Merge pull request woocommerce/woocommerce-admin#1144 from woocommerce/add/916-customers-report-endpoint
Add `/reports/customers` endpoint
This commit is contained in:
commit
43517940fb
|
@ -39,25 +39,30 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
*/
|
||||
protected function prepare_reports_query( $request ) {
|
||||
$args = array();
|
||||
$args['before'] = $request['before'];
|
||||
$args['after'] = $request['after'];
|
||||
$args['registered_before'] = $request['registered_before'];
|
||||
$args['registered_after'] = $request['registered_after'];
|
||||
$args['page'] = $request['page'];
|
||||
$args['per_page'] = $request['per_page'];
|
||||
$args['order'] = $request['order'];
|
||||
$args['orderby'] = $request['orderby'];
|
||||
$args['match'] = $request['match'];
|
||||
$args['name'] = $request['name'];
|
||||
$args['username'] = $request['username'];
|
||||
$args['email'] = $request['email'];
|
||||
$args['country'] = $request['country'];
|
||||
$args['last_active_before'] = $request['last_active_before'];
|
||||
$args['last_active_after'] = $request['last_active_after'];
|
||||
$args['order_count_min'] = $request['order_count_min'];
|
||||
$args['order_count_max'] = $request['order_count_max'];
|
||||
$args['order_count_between'] = $request['order_count_between'];
|
||||
$args['orders_count_min'] = $request['orders_count_min'];
|
||||
$args['orders_count_max'] = $request['orders_count_max'];
|
||||
$args['orders_count_between'] = $request['orders_count_between'];
|
||||
$args['total_spend_min'] = $request['total_spend_min'];
|
||||
$args['total_spend_max'] = $request['total_spend_max'];
|
||||
$args['total_spend_between'] = $request['total_spend_between'];
|
||||
$args['avg_order_value_min'] = $request['avg_order_value_min'];
|
||||
$args['avg_order_value_max'] = $request['avg_order_value_max'];
|
||||
$args['avg_order_value_between'] = $request['avg_order_value_between'];
|
||||
$args['last_order_before'] = $request['last_order_before'];
|
||||
$args['last_order_after'] = $request['last_order_after'];
|
||||
return $args;
|
||||
}
|
||||
|
||||
|
@ -69,19 +74,20 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
*/
|
||||
public function get_items( $request ) {
|
||||
$query_args = $this->prepare_reports_query( $request );
|
||||
$customers_query = new WC_Reports_Orders_Stats_Query( $query_args ); // @todo change to correct class.
|
||||
$customers_query = new WC_Admin_Reports_Customers_Query( $query_args );
|
||||
$report_data = $customers_query->get_data();
|
||||
$out_data = array(
|
||||
'totals' => get_object_vars( $report_data->totals ),
|
||||
'customers' => array(),
|
||||
);
|
||||
foreach ( $report_data->customers as $customer_data ) {
|
||||
$item_data = $this->prepare_item_for_response( (object) $customer_data, $request );
|
||||
$out_data['customers'][] = $item_data;
|
||||
|
||||
$data = array();
|
||||
|
||||
foreach ( $report_data->data as $customer_data ) {
|
||||
$item = $this->prepare_item_for_response( $customer_data, $request );
|
||||
$data[] = $this->prepare_response_for_collection( $item );
|
||||
}
|
||||
$response = rest_ensure_response( $out_data );
|
||||
|
||||
$response = rest_ensure_response( $data );
|
||||
$response->header( 'X-WP-Total', (int) $report_data->total );
|
||||
$response->header( 'X-WP-TotalPages', (int) $report_data->pages );
|
||||
|
||||
$page = $report_data->page_no;
|
||||
$max_pages = $report_data->pages;
|
||||
$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
|
||||
|
@ -98,21 +104,26 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
$next_link = add_query_arg( 'page', $next_page, $base );
|
||||
$response->link_header( 'next', $next_link );
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a report object for serialization.
|
||||
*
|
||||
* @param stdClass $report Report data.
|
||||
* @param array $report Report data.
|
||||
* @param WP_REST_Request $request Request object.
|
||||
* @return WP_REST_Response
|
||||
*/
|
||||
public function prepare_item_for_response( $report, $request ) {
|
||||
$data = get_object_vars( $report );
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $data, $request );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
|
||||
$data = $this->add_additional_fields_to_object( $report, $request );
|
||||
$data['date_registered_gmt'] = wc_rest_prepare_date_response( $data['date_registered'] );
|
||||
$data['date_registered'] = wc_rest_prepare_date_response( $data['date_registered'], false );
|
||||
$data['date_last_active_gmt'] = wc_rest_prepare_date_response( $data['date_last_active'] );
|
||||
$data['date_last_active'] = wc_rest_prepare_date_response( $data['date_last_active'], false );
|
||||
$data = $this->filter_response_by_context( $data, $context );
|
||||
|
||||
// Wrap the data in a response object.
|
||||
$response = rest_ensure_response( $data );
|
||||
$response->add_links( $this->prepare_links( $report ) );
|
||||
|
@ -131,16 +142,19 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
/**
|
||||
* Prepare links for the request.
|
||||
*
|
||||
* @param WC_Reports_Query $object Object data.
|
||||
* @param array $object Object data.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_links( $object ) {
|
||||
$links = array(
|
||||
if ( empty( $object['user_id'] ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array(
|
||||
'customer' => array(
|
||||
'href' => rest_url( sprintf( '/%s/customers/%d', $this->namespace, $object->customer_id ) ),
|
||||
'href' => rest_url( sprintf( '/%s/customers/%d', $this->namespace, $object['user_id'] ) ),
|
||||
),
|
||||
);
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -154,18 +168,60 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'title' => 'report_customers',
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'id' => array(
|
||||
'description' => __( 'ID.', 'wc-admin' ),
|
||||
'customer_id' => array(
|
||||
'description' => __( 'Customer ID.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'customer_id' => array(
|
||||
'description' => __( 'Customer ID.', 'wc-admin' ),
|
||||
'user_id' => array(
|
||||
'description' => __( 'User ID.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'name' => array(
|
||||
'description' => __( 'Name.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'username' => array(
|
||||
'description' => __( 'Username.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'country' => array(
|
||||
'description' => __( 'Country.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'city' => array(
|
||||
'description' => __( 'City.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'postcode' => array(
|
||||
'description' => __( 'Postal code.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_registered' => array(
|
||||
'description' => __( 'Date registered.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_registered_gmt' => array(
|
||||
'description' => __( 'Date registered GMT.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
'context' => array( 'view', 'edit' ),
|
||||
'readonly' => true,
|
||||
),
|
||||
'date_last_active' => array(
|
||||
'description' => __( 'Date last active.', 'wc-admin' ),
|
||||
'type' => 'date-time',
|
||||
|
@ -209,14 +265,14 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
public function get_collection_params() {
|
||||
$params = array();
|
||||
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
|
||||
$params['before'] = array(
|
||||
'description' => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
$params['registered_before'] = array(
|
||||
'description' => __( 'Limit response to objects registered before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['after'] = array(
|
||||
'description' => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'wc-admin' ),
|
||||
$params['registered_after'] = array(
|
||||
'description' => __( 'Limit response to objects registered after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
@ -238,7 +294,42 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['name'] = array(
|
||||
$params['order'] = array(
|
||||
'description' => __( 'Order sort attribute ascending or descending.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'desc',
|
||||
'enum' => array( 'asc', 'desc' ),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['orderby'] = array(
|
||||
'description' => __( 'Sort collection by object attribute.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'date_registered',
|
||||
'enum' => array(
|
||||
'username',
|
||||
'name',
|
||||
'country',
|
||||
'city',
|
||||
'postcode',
|
||||
'date_registered',
|
||||
'date_last_active',
|
||||
'orders_count',
|
||||
'total_spend',
|
||||
'avg_order_value',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['match'] = array(
|
||||
'description' => __( 'Indicates whether all the conditions should be true for the resulting set, or if any one of them is sufficient. Match affects the following parameters: status_is, status_is_not, product_includes, product_excludes, coupon_includes, coupon_excludes, customer, categories', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'default' => 'all',
|
||||
'enum' => array(
|
||||
'all',
|
||||
'any',
|
||||
),
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['name'] = array(
|
||||
'description' => __( 'Limit response to objects with a specfic customer name.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
@ -270,19 +361,31 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_min'] = array(
|
||||
$params['registered_before'] = array(
|
||||
'description' => __( 'Limit response to objects registered before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['registered_after'] = array(
|
||||
'description' => __( 'Limit response to objects registered after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['orders_count_min'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count greater than or equal to given integer.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_max'] = array(
|
||||
$params['orders_count_max'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count less than or equal to given integer.', 'wc-admin' ),
|
||||
'type' => 'integer',
|
||||
'sanitize_callback' => 'absint',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['order_count_between'] = array(
|
||||
$params['orders_count_between'] = array(
|
||||
'description' => __( 'Limit response to objects with an order count between two given integers.', 'wc-admin' ),
|
||||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
|
@ -317,6 +420,18 @@ class WC_Admin_REST_Reports_Customers_Controller extends WC_REST_Reports_Control
|
|||
'type' => 'array',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['last_order_before'] = array(
|
||||
'description' => __( 'Limit response to objects with last order before (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
$params['last_order_after'] = array(
|
||||
'description' => __( 'Limit response to objects with last order after (or at) a given ISO8601 compliant datetime.', 'wc-admin' ),
|
||||
'type' => 'string',
|
||||
'format' => 'date-time',
|
||||
'validate_callback' => 'rest_validate_request_arg',
|
||||
);
|
||||
return $params;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,6 +29,10 @@ class WC_Admin_Api_Init {
|
|||
|
||||
// Initialize Orders data store class's static vars.
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'orders_data_store_init' ), 20 );
|
||||
// Initialize Customers Report data store sync hooks.
|
||||
// Note: we need to hook into 'wp' before `wc_current_user_is_active`.
|
||||
// See: https://github.com/woocommerce/woocommerce/blob/942615101ba00c939c107c3a4820c3d466864872/includes/wc-user-functions.php#L749.
|
||||
add_action( 'wp', array( 'WC_Admin_Api_Init', 'customers_report_data_store_init' ), 9 );
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -55,6 +59,7 @@ class WC_Admin_Api_Init {
|
|||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-stats-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-downloads-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-downloads-stats-query.php';
|
||||
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-customers-query.php';
|
||||
|
||||
// Data stores.
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-data-store.php';
|
||||
|
@ -69,6 +74,7 @@ class WC_Admin_Api_Init {
|
|||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-coupons-stats-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-downloads-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-downloads-stats-data-store.php';
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-customers-data-store.php';
|
||||
|
||||
// Data triggers.
|
||||
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-notes-data-store.php';
|
||||
|
@ -130,6 +136,7 @@ class WC_Admin_Api_Init {
|
|||
'WC_Admin_REST_Reports_Stock_Controller',
|
||||
'WC_Admin_REST_Reports_Downloads_Controller',
|
||||
'WC_Admin_REST_Reports_Downloads_Stats_Controller',
|
||||
'WC_Admin_REST_Reports_Customers_Controller',
|
||||
);
|
||||
|
||||
foreach ( $controllers as $controller ) {
|
||||
|
@ -260,6 +267,9 @@ class WC_Admin_Api_Init {
|
|||
* Regenerate data for reports.
|
||||
*/
|
||||
public static function regenerate_report_data() {
|
||||
// Add registered customers to the lookup table before updating order stats
|
||||
// so that the orders can be associated with the `customer_id` column.
|
||||
self::customer_lookup_store_init();
|
||||
WC_Admin_Reports_Orders_Data_Store::queue_order_stats_repopulate_database();
|
||||
self::order_product_lookup_store_init();
|
||||
}
|
||||
|
@ -330,6 +340,59 @@ class WC_Admin_Api_Init {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Init customers report data store.
|
||||
*/
|
||||
public static function customers_report_data_store_init() {
|
||||
WC_Admin_Reports_Customers_Data_Store::init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Init customer lookup store.
|
||||
*
|
||||
* @param WC_Background_Updater|null $updater Updater instance.
|
||||
* @return bool
|
||||
*/
|
||||
public static function customer_lookup_store_init( $updater = null ) {
|
||||
// TODO: this needs to be updated a bit, as it no longer runs as a part of WC_Install, there is no bg updater.
|
||||
global $wpdb;
|
||||
|
||||
// Backfill customer lookup table with registered customers.
|
||||
$customer_ids = get_transient( 'wc_update_350_all_customers' );
|
||||
|
||||
if ( false === $customer_ids ) {
|
||||
$customer_query = new WP_User_Query(
|
||||
array(
|
||||
'fields' => 'ID',
|
||||
'role' => 'customer',
|
||||
'number' => -1,
|
||||
)
|
||||
);
|
||||
|
||||
$customer_ids = $customer_query->get_results();
|
||||
|
||||
set_transient( 'wc_update_350_all_customers', $customer_ids, DAY_IN_SECONDS );
|
||||
}
|
||||
|
||||
// Process customers until close to running out of memory timeouts on large sites then requeue.
|
||||
foreach ( $customer_ids as $customer_id ) {
|
||||
$result = WC_Admin_Reports_Customers_Data_Store::update_registered_customer( $customer_id );
|
||||
|
||||
if ( $result ) {
|
||||
// Pop the customer ID from the array for updating the transient later should we near memory exhaustion.
|
||||
unset( $customer_ids[ $customer_id ] );
|
||||
}
|
||||
|
||||
if ( $updater instanceof WC_Background_Updater && $updater->is_memory_exceeded() ) {
|
||||
// Update the transient for the next run to avoid processing the same orders again.
|
||||
set_transient( 'wc_update_350_all_customers', $customer_ids, DAY_IN_SECONDS );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds data stores.
|
||||
*
|
||||
|
@ -353,6 +416,7 @@ class WC_Admin_Api_Init {
|
|||
'report-downloads' => 'WC_Admin_Reports_Downloads_Data_Store',
|
||||
'report-downloads-stats' => 'WC_Admin_Reports_Downloads_Stats_Data_Store',
|
||||
'admin-note' => 'WC_Admin_Notes_Data_Store',
|
||||
'report-customers' => 'WC_Admin_Reports_Customers_Data_Store',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -376,6 +440,7 @@ class WC_Admin_Api_Init {
|
|||
"{$wpdb->prefix}wc_order_coupon_lookup",
|
||||
"{$wpdb->prefix}woocommerce_admin_notes",
|
||||
"{$wpdb->prefix}woocommerce_admin_note_actions",
|
||||
"{$wpdb->prefix}wc_customer_lookup",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -405,6 +470,7 @@ class WC_Admin_Api_Init {
|
|||
net_total double DEFAULT 0 NOT NULL,
|
||||
returning_customer boolean DEFAULT 0 NOT NULL,
|
||||
status varchar(200) NOT NULL,
|
||||
customer_id BIGINT UNSIGNED NOT NULL,
|
||||
PRIMARY KEY (order_id),
|
||||
KEY date_created (date_created)
|
||||
) $collate;
|
||||
|
@ -467,6 +533,22 @@ class WC_Admin_Api_Init {
|
|||
PRIMARY KEY (action_id),
|
||||
KEY note_id (note_id)
|
||||
) $collate;
|
||||
CREATE TABLE {$wpdb->prefix}wc_customer_lookup (
|
||||
customer_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
user_id BIGINT UNSIGNED DEFAULT NULL,
|
||||
username varchar(60) DEFAULT '' NOT NULL,
|
||||
first_name varchar(255) NOT NULL,
|
||||
last_name varchar(255) NOT NULL,
|
||||
email varchar(100) NOT NULL,
|
||||
date_last_active timestamp DEFAULT '0000-00-00 00:00:00' NOT NULL,
|
||||
date_registered timestamp NULL default null,
|
||||
country char(2) DEFAULT '' NOT NULL,
|
||||
postcode varchar(20) DEFAULT '' NOT NULL,
|
||||
city varchar(100) DEFAULT '' NOT NULL,
|
||||
PRIMARY KEY (customer_id),
|
||||
UNIQUE KEY user_id (user_id),
|
||||
KEY email (email)
|
||||
) $collate;
|
||||
";
|
||||
|
||||
return $tables;
|
||||
|
@ -490,6 +572,7 @@ class WC_Admin_Api_Init {
|
|||
|
||||
// Initialize report tables.
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'order_product_lookup_store_init' ), 20 );
|
||||
add_action( 'woocommerce_after_register_post_type', array( 'WC_Admin_Api_Init', 'customer_lookup_store_init' ), 20 );
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
/**
|
||||
* Class for parameter-based Customers Report querying
|
||||
*
|
||||
* Example usage:
|
||||
* $args = array(
|
||||
* 'registered_before' => '2018-07-19 00:00:00',
|
||||
* 'registered_after' => '2018-07-05 00:00:00',
|
||||
* 'page' => 2,
|
||||
* 'avg_order_value_min' => 100,
|
||||
* 'country' => 'GB',
|
||||
* );
|
||||
* $report = new WC_Admin_Reports_Customers_Query( $args );
|
||||
* $mydata = $report->get_data();
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Query
|
||||
*/
|
||||
class WC_Admin_Reports_Customers_Query extends WC_Admin_Reports_Query {
|
||||
|
||||
/**
|
||||
* Valid fields for Customers report.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_default_query_vars() {
|
||||
return array(
|
||||
'per_page' => get_option( 'posts_per_page' ), // not sure if this should be the default.
|
||||
'page' => 1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'date_registered',
|
||||
'fields' => '*',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get product data based on the current query vars.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_data() {
|
||||
$args = apply_filters( 'woocommerce_reports_customers_query_args', $this->get_query_vars() );
|
||||
|
||||
$data_store = WC_Data_Store::load( 'report-customers' );
|
||||
$results = $data_store->get_data( $args );
|
||||
return apply_filters( 'woocommerce_reports_customers_select_query', $results, $args );
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,572 @@
|
|||
<?php
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Data_Store class file.
|
||||
*
|
||||
* @package WooCommerce Admin/Classes
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* WC_Admin_Reports_Customers_Data_Store.
|
||||
*/
|
||||
class WC_Admin_Reports_Customers_Data_Store extends WC_Admin_Reports_Data_Store implements WC_Admin_Reports_Data_Store_Interface {
|
||||
|
||||
/**
|
||||
* Table used to get the data.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const TABLE_NAME = 'wc_customer_lookup';
|
||||
|
||||
/**
|
||||
* Mapping columns to data type to return correct response types.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $column_types = array(
|
||||
'customer_id' => 'intval',
|
||||
'user_id' => 'intval',
|
||||
'orders_count' => 'intval',
|
||||
'total_spend' => 'floatval',
|
||||
'avg_order_value' => 'floatval',
|
||||
);
|
||||
|
||||
/**
|
||||
* SQL columns to select in the db query and their mapping to SQL code.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $report_columns = array(
|
||||
'customer_id' => 'customer_id',
|
||||
'user_id' => 'user_id',
|
||||
'username' => 'username',
|
||||
'name' => "CONCAT_WS( ' ', first_name, last_name ) as name", // TODO: what does this mean for RTL?
|
||||
'email' => 'email',
|
||||
'country' => 'country',
|
||||
'city' => 'city',
|
||||
'postcode' => 'postcode',
|
||||
'date_registered' => 'date_registered',
|
||||
'date_last_active' => 'date_last_active',
|
||||
'orders_count' => 'COUNT( order_id ) as orders_count',
|
||||
'total_spend' => 'SUM( gross_total ) as total_spend',
|
||||
'avg_order_value' => '( SUM( gross_total ) / COUNT( order_id ) ) as avg_order_value',
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
global $wpdb;
|
||||
|
||||
// Initialize some report columns that need disambiguation.
|
||||
$this->report_columns['customer_id'] = $wpdb->prefix . self::TABLE_NAME . '.customer_id';
|
||||
$this->report_columns['date_last_order'] = "MAX( {$wpdb->prefix}wc_order_stats.date_created ) as date_last_order";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up all the hooks for maintaining and populating table data.
|
||||
*/
|
||||
public static function init() {
|
||||
add_action( 'woocommerce_new_customer', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'woocommerce_update_customer', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'edit_user_profile_update', array( __CLASS__, 'update_registered_customer' ) );
|
||||
add_action( 'updated_user_meta', array( __CLASS__, 'update_registered_customer_via_last_active' ), 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a customer update if their "last active" meta value was changed.
|
||||
* Function expects to be hooked into the `updated_user_meta` action.
|
||||
*
|
||||
* @param int $meta_id ID of updated metadata entry.
|
||||
* @param int $user_id ID of the user being updated.
|
||||
* @param string $meta_key Meta key being updated.
|
||||
*/
|
||||
public static function update_registered_customer_via_last_active( $meta_id, $user_id, $meta_key ) {
|
||||
if ( 'wc_last_active' === $meta_key ) {
|
||||
self::update_registered_customer( $user_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps ordering specified by the user to columns in the database/fields in the data.
|
||||
*
|
||||
* @param string $order_by Sorting criterion.
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize_order_by( $order_by ) {
|
||||
if ( 'name' === $order_by ) {
|
||||
return "CONCAT_WS( ' ', first_name, last_name )";
|
||||
}
|
||||
|
||||
return $order_by;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills ORDER BY clause of SQL request based on user supplied parameters.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_order_by_sql_params( $query_args ) {
|
||||
$sql_query['order_by_clause'] = '';
|
||||
|
||||
if ( isset( $query_args['orderby'] ) ) {
|
||||
$sql_query['order_by_clause'] = $this->normalize_order_by( $query_args['orderby'] );
|
||||
}
|
||||
|
||||
if ( isset( $query_args['order'] ) ) {
|
||||
$sql_query['order_by_clause'] .= ' ' . $query_args['order'];
|
||||
} else {
|
||||
$sql_query['order_by_clause'] .= ' DESC';
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills WHERE clause of SQL request with date-related constraints.
|
||||
*
|
||||
* @param array $query_args Parameters supplied by the user.
|
||||
* @param string $table_name Name of the db table relevant for the date constraint.
|
||||
* @return array
|
||||
*/
|
||||
protected function get_time_period_sql_params( $query_args, $table_name ) {
|
||||
global $wpdb;
|
||||
|
||||
$sql_query = array(
|
||||
'where_time_clause' => '',
|
||||
'where_clause' => '',
|
||||
'having_clause' => '',
|
||||
);
|
||||
$date_param_mapping = array(
|
||||
'registered' => array(
|
||||
'clause' => 'where',
|
||||
'column' => $table_name . '.date_registered',
|
||||
),
|
||||
'last_active' => array(
|
||||
'clause' => 'where',
|
||||
'column' => $table_name . '.date_last_active',
|
||||
),
|
||||
'last_order' => array(
|
||||
'clause' => 'having',
|
||||
'column' => "MAX( {$wpdb->prefix}wc_order_stats.date_created )",
|
||||
),
|
||||
);
|
||||
$match_operator = $this->get_match_operator( $query_args );
|
||||
$where_time_clauses = array();
|
||||
$having_time_clauses = array();
|
||||
|
||||
foreach ( $date_param_mapping as $query_param => $param_info ) {
|
||||
$subclauses = array();
|
||||
$before_arg = $query_param . '_before';
|
||||
$after_arg = $query_param . '_after';
|
||||
$column_name = $param_info['column'];
|
||||
|
||||
if ( ! empty( $query_args[ $before_arg ] ) ) {
|
||||
$datetime = new DateTime( $query_args[ $before_arg ] );
|
||||
$datetime_str = $datetime->format( WC_Admin_Reports_Interval::$sql_datetime_format );
|
||||
$subclauses[] = "{$column_name} <= '$datetime_str'";
|
||||
}
|
||||
|
||||
if ( ! empty( $query_args[ $after_arg ] ) ) {
|
||||
$datetime = new DateTime( $query_args[ $after_arg ] );
|
||||
$datetime_str = $datetime->format( WC_Admin_Reports_Interval::$sql_datetime_format );
|
||||
$subclauses[] = "{$column_name} >= '$datetime_str'";
|
||||
}
|
||||
|
||||
if ( $subclauses && ( 'where' === $param_info['clause'] ) ) {
|
||||
$where_time_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
|
||||
if ( $subclauses && ( 'having' === $param_info['clause'] ) ) {
|
||||
$having_time_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
if ( $where_time_clauses ) {
|
||||
$sql_query['where_time_clause'] = ' AND ' . implode( " {$match_operator} ", $where_time_clauses );
|
||||
}
|
||||
|
||||
if ( $having_time_clauses ) {
|
||||
$sql_query['having_clause'] = ' AND ' . implode( " {$match_operator} ", $having_time_clauses );
|
||||
}
|
||||
|
||||
return $sql_query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the database query with parameters used for Customers report: categories and order status.
|
||||
*
|
||||
* @param array $query_args Query arguments supplied by the user.
|
||||
* @return array Array of parameters used for SQL query.
|
||||
*/
|
||||
protected function get_sql_query_params( $query_args ) {
|
||||
global $wpdb;
|
||||
$customer_lookup_table = $wpdb->prefix . self::TABLE_NAME;
|
||||
|
||||
$sql_query_params = $this->get_time_period_sql_params( $query_args, $customer_lookup_table );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_limit_sql_params( $query_args ) );
|
||||
$sql_query_params = array_merge( $sql_query_params, $this->get_order_by_sql_params( $query_args ) );
|
||||
|
||||
$match_operator = $this->get_match_operator( $query_args );
|
||||
$where_clauses = array();
|
||||
$having_clauses = array();
|
||||
|
||||
$exact_match_params = array(
|
||||
'username',
|
||||
'email',
|
||||
'country',
|
||||
);
|
||||
|
||||
foreach ( $exact_match_params as $exact_match_param ) {
|
||||
if ( ! empty( $query_args[ $exact_match_param ] ) ) {
|
||||
$where_clauses[] = $wpdb->prepare(
|
||||
"{$customer_lookup_table}.{$exact_match_param} = %s",
|
||||
$query_args[ $exact_match_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $query_args['name'] ) ) {
|
||||
$where_clauses[] = $wpdb->prepare( "CONCAT_WS( ' ', first_name, last_name ) = %s", $query_args['name'] );
|
||||
}
|
||||
|
||||
$numeric_params = array(
|
||||
'orders_count' => array(
|
||||
'column' => 'COUNT( order_id )',
|
||||
'format' => '%d',
|
||||
),
|
||||
'total_spend' => array(
|
||||
'column' => 'SUM( gross_total )',
|
||||
'format' => '%f',
|
||||
),
|
||||
'avg_order_value' => array(
|
||||
'column' => '( SUM( gross_total ) / COUNT( order_id ) )',
|
||||
'format' => '%f',
|
||||
),
|
||||
);
|
||||
|
||||
foreach ( $numeric_params as $numeric_param => $param_info ) {
|
||||
$subclauses = array();
|
||||
$min_param = $numeric_param . '_min';
|
||||
$max_param = $numeric_param . '_max';
|
||||
|
||||
if ( isset( $query_args[ $min_param ] ) ) {
|
||||
$subclauses[] = $wpdb->prepare(
|
||||
"{$param_info['column']} >= {$param_info['format']}",
|
||||
$query_args[ $min_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
|
||||
if ( isset( $query_args[ $max_param ] ) ) {
|
||||
$subclauses[] = $wpdb->prepare(
|
||||
"{$param_info['column']} <= {$param_info['format']}",
|
||||
$query_args[ $max_param ]
|
||||
); // WPCS: unprepared SQL ok.
|
||||
}
|
||||
|
||||
if ( $subclauses ) {
|
||||
$having_clauses[] = '(' . implode( ' AND ', $subclauses ) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
if ( $where_clauses ) {
|
||||
$preceding_match = empty( $sql_query_params['where_time_clause'] ) ? ' AND ' : " {$match_operator} ";
|
||||
$sql_query_params['where_clause'] = $preceding_match . implode( " {$match_operator} ", $where_clauses );
|
||||
}
|
||||
|
||||
if ( $having_clauses ) {
|
||||
$preceding_match = empty( $sql_query_params['having_clause'] ) ? ' AND ' : " {$match_operator} ";
|
||||
$sql_query_params['having_clause'] .= $preceding_match . implode( " {$match_operator} ", $having_clauses );
|
||||
}
|
||||
|
||||
return $sql_query_params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the report data based on parameters supplied by the user.
|
||||
*
|
||||
* @param array $query_args Query parameters.
|
||||
* @return stdClass|WP_Error Data.
|
||||
*/
|
||||
public function get_data( $query_args ) {
|
||||
global $wpdb;
|
||||
|
||||
$customers_table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$order_stats_table_name = $wpdb->prefix . 'wc_order_stats';
|
||||
|
||||
// These defaults are only partially applied when used via REST API, as that has its own defaults.
|
||||
$defaults = array(
|
||||
'per_page' => get_option( 'posts_per_page' ),
|
||||
'page' => 1,
|
||||
'order' => 'DESC',
|
||||
'orderby' => 'date_registered',
|
||||
'fields' => '*',
|
||||
);
|
||||
$query_args = wp_parse_args( $query_args, $defaults );
|
||||
|
||||
$cache_key = $this->get_cache_key( $query_args );
|
||||
$data = wp_cache_get( $cache_key, $this->cache_group );
|
||||
|
||||
if ( false === $data ) {
|
||||
$data = (object) array(
|
||||
'data' => array(),
|
||||
'total' => 0,
|
||||
'pages' => 0,
|
||||
'page_no' => 0,
|
||||
);
|
||||
|
||||
$selections = $this->selected_columns( $query_args );
|
||||
$sql_query_params = $this->get_sql_query_params( $query_args );
|
||||
|
||||
$db_records_count = (int) $wpdb->get_var(
|
||||
"SELECT COUNT(*) FROM (
|
||||
SELECT {$customers_table_name}.customer_id
|
||||
FROM
|
||||
{$customers_table_name}
|
||||
LEFT JOIN
|
||||
{$order_stats_table_name}
|
||||
ON
|
||||
{$customers_table_name}.customer_id = {$order_stats_table_name}.customer_id
|
||||
WHERE
|
||||
1=1
|
||||
{$sql_query_params['where_time_clause']}
|
||||
{$sql_query_params['where_clause']}
|
||||
GROUP BY
|
||||
{$customers_table_name}.customer_id
|
||||
HAVING
|
||||
1=1
|
||||
{$sql_query_params['having_clause']}
|
||||
) as tt
|
||||
"
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
$total_pages = (int) ceil( $db_records_count / $sql_query_params['per_page'] );
|
||||
if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$customer_data = $wpdb->get_results(
|
||||
"SELECT
|
||||
{$selections}
|
||||
FROM
|
||||
{$customers_table_name}
|
||||
LEFT JOIN
|
||||
{$order_stats_table_name}
|
||||
ON
|
||||
{$customers_table_name}.customer_id = {$order_stats_table_name}.customer_id
|
||||
WHERE
|
||||
1=1
|
||||
{$sql_query_params['where_time_clause']}
|
||||
{$sql_query_params['where_clause']}
|
||||
GROUP BY
|
||||
{$customers_table_name}.customer_id
|
||||
HAVING
|
||||
1=1
|
||||
{$sql_query_params['having_clause']}
|
||||
ORDER BY
|
||||
{$sql_query_params['order_by_clause']}
|
||||
{$sql_query_params['limit']}
|
||||
",
|
||||
ARRAY_A
|
||||
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
|
||||
|
||||
if ( null === $customer_data ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$customer_data = array_map( array( $this, 'cast_numbers' ), $customer_data );
|
||||
$data = (object) array(
|
||||
'data' => $customer_data,
|
||||
'total' => $db_records_count,
|
||||
'pages' => $total_pages,
|
||||
'page_no' => (int) $query_args['page'],
|
||||
);
|
||||
|
||||
wp_cache_set( $cache_key, $data, $this->cache_group );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the guest (no user_id) customer ID or creates a new one for
|
||||
* the corresponding billing email in the provided WC_Order
|
||||
*
|
||||
* @param WC_Order $order Order to get/create guest customer data with.
|
||||
* @return int|false The ID of the retrieved/created customer, or false on error.
|
||||
*/
|
||||
public function get_or_create_guest_customer_from_order( $order ) {
|
||||
global $wpdb;
|
||||
|
||||
$email = $order->get_billing_email( 'edit' );
|
||||
|
||||
if ( empty( $email ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$existing_guest = $this->get_guest_by_email( $email );
|
||||
|
||||
if ( $existing_guest ) {
|
||||
return $existing_guest['customer_id'];
|
||||
}
|
||||
|
||||
$result = $wpdb->insert(
|
||||
$wpdb->prefix . self::TABLE_NAME,
|
||||
array(
|
||||
'first_name' => $order->get_billing_first_name( 'edit' ),
|
||||
'last_name' => $order->get_billing_last_name( 'edit' ),
|
||||
'email' => $email,
|
||||
'city' => $order->get_billing_city( 'edit' ),
|
||||
'postcode' => $order->get_billing_postcode( 'edit' ),
|
||||
'country' => $order->get_billing_country( 'edit' ),
|
||||
'date_last_active' => date( 'Y-m-d H:i:s', $order->get_date_created( 'edit' )->getTimestamp() ),
|
||||
),
|
||||
array(
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
)
|
||||
);
|
||||
|
||||
return $result ? $wpdb->insert_id : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a guest (no user_id) customer row by email.
|
||||
*
|
||||
* @param string $email Email address.
|
||||
* @returns false|array Customer array if found, boolean false if not.
|
||||
*/
|
||||
public function get_guest_by_email( $email ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$guest_row = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table_name} WHERE email = %s AND user_id IS NULL LIMIT 1",
|
||||
$email
|
||||
),
|
||||
ARRAY_A
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
if ( $guest_row ) {
|
||||
return $this->cast_numbers( $guest_row );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a registered customer row by user_id.
|
||||
*
|
||||
* @param string|int $user_id User ID.
|
||||
* @returns false|array Customer array if found, boolean false if not.
|
||||
*/
|
||||
public function get_customer_by_user_id( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$customer = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM {$table_name} WHERE user_id = %d LIMIT 1",
|
||||
$user_id
|
||||
),
|
||||
ARRAY_A
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
if ( $customer ) {
|
||||
return $this->cast_numbers( $customer );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a registered customer row id by user_id.
|
||||
*
|
||||
* @param string|int $user_id User ID.
|
||||
* @returns false|int Customer ID if found, boolean false if not.
|
||||
*/
|
||||
public static function get_customer_id_by_user_id( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$table_name = $wpdb->prefix . self::TABLE_NAME;
|
||||
$customer_id = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT customer_id FROM {$table_name} WHERE user_id = %d LIMIT 1",
|
||||
$user_id
|
||||
)
|
||||
); // WPCS: unprepared SQL ok.
|
||||
|
||||
return $customer_id ? (int) $customer_id : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the database with customer data.
|
||||
*
|
||||
* @param int $user_id WP User ID to update customer data for.
|
||||
* @return int|bool|null Number or rows modified or false on failure.
|
||||
*/
|
||||
public static function update_registered_customer( $user_id ) {
|
||||
global $wpdb;
|
||||
|
||||
$customer = new WC_Customer( $user_id );
|
||||
|
||||
if ( $customer->get_id() != $user_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$last_active = $customer->get_meta( 'wc_last_active', true, 'edit' );
|
||||
$data = array(
|
||||
'user_id' => $user_id,
|
||||
'username' => $customer->get_username( 'edit' ),
|
||||
'first_name' => $customer->get_first_name( 'edit' ),
|
||||
'last_name' => $customer->get_last_name( 'edit' ),
|
||||
'email' => $customer->get_email( 'edit' ),
|
||||
'city' => $customer->get_billing_city( 'edit' ),
|
||||
'postcode' => $customer->get_billing_postcode( 'edit' ),
|
||||
'country' => $customer->get_billing_country( 'edit' ),
|
||||
'date_registered' => date( 'Y-m-d H:i:s', $customer->get_date_created( 'edit' )->getTimestamp() ),
|
||||
'date_last_active' => $last_active ? date( 'Y-m-d H:i:s', $last_active ) : '',
|
||||
);
|
||||
$format = array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
'%s',
|
||||
);
|
||||
|
||||
$customer_id = self::get_customer_id_by_user_id( $user_id );
|
||||
|
||||
if ( $customer_id ) {
|
||||
// Preserve customer_id for existing user_id.
|
||||
$data['customer_id'] = $customer_id;
|
||||
$format[] = '%d';
|
||||
}
|
||||
|
||||
return $wpdb->replace( $wpdb->prefix . self::TABLE_NAME, $data, $format );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns string to be used as cache key for the data.
|
||||
*
|
||||
* @param array $params Query parameters.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_cache_key( $params ) {
|
||||
return 'woocommerce_' . self::TABLE_NAME . '_' . md5( wp_json_encode( $params ) );
|
||||
}
|
||||
|
||||
}
|
|
@ -447,7 +447,7 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
|
|||
return;
|
||||
}
|
||||
|
||||
$data = array(
|
||||
$data = array(
|
||||
'order_id' => $order->get_id(),
|
||||
'date_created' => $order->get_date_created()->date( 'Y-m-d H:i:s' ),
|
||||
'num_items_sold' => self::get_num_items_sold( $order ),
|
||||
|
@ -460,25 +460,46 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
|
|||
'returning_customer' => self::is_returning_customer( $order ),
|
||||
'status' => self::normalize_order_status( $order->get_status() ),
|
||||
);
|
||||
$format = array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%d',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%d',
|
||||
'%s',
|
||||
);
|
||||
|
||||
// Ensure we're associating this order with a Customer in the lookup table.
|
||||
$order_user_id = $order->get_customer_id();
|
||||
$customers_data_store = new WC_Admin_Reports_Customers_Data_Store();
|
||||
|
||||
if ( 0 === $order_user_id ) {
|
||||
$email = $order->get_billing_email( 'edit' );
|
||||
|
||||
if ( $email ) {
|
||||
$customer_id = $customers_data_store->get_or_create_guest_customer_from_order( $order );
|
||||
|
||||
if ( $customer_id ) {
|
||||
$data['customer_id'] = $customer_id;
|
||||
$format[] = '%d';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$customer = $customers_data_store->get_customer_by_user_id( $order_user_id );
|
||||
|
||||
if ( $customer && $customer['customer_id'] ) {
|
||||
$data['customer_id'] = $customer['customer_id'];
|
||||
$format[] = '%d';
|
||||
}
|
||||
}
|
||||
|
||||
// Update or add the information to the DB.
|
||||
return $wpdb->replace(
|
||||
$table_name,
|
||||
$data,
|
||||
array(
|
||||
'%d',
|
||||
'%s',
|
||||
'%d',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%f',
|
||||
'%d',
|
||||
'%s',
|
||||
)
|
||||
);
|
||||
return $wpdb->replace( $table_name, $data, $format );
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -0,0 +1,193 @@
|
|||
<?php
|
||||
/**
|
||||
* Reports Customers REST API Test
|
||||
*
|
||||
* @package WooCommerce\Tests\API
|
||||
* @since 3.5.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reports Customers REST API Test Class
|
||||
*
|
||||
* @package WooCommerce\Tests\API
|
||||
* @since 3.5.0
|
||||
*/
|
||||
class WC_Tests_API_Reports_Customers extends WC_REST_Unit_Test_Case {
|
||||
/**
|
||||
* Endpoint.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $endpoint = '/wc/v3/reports/customers';
|
||||
|
||||
/**
|
||||
* Setup test reports products data.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->user = $this->factory->user->create(
|
||||
array(
|
||||
'role' => 'administrator',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test route registration.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function test_register_routes() {
|
||||
$routes = $this->server->get_routes();
|
||||
|
||||
$this->assertArrayHasKey( $this->endpoint, $routes );
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the report item schema is correct.
|
||||
*
|
||||
* @param array $schema Item to check schema.
|
||||
*/
|
||||
public function assert_report_item_schema( $schema ) {
|
||||
$this->assertArrayHasKey( 'customer_id', $schema );
|
||||
$this->assertArrayHasKey( 'user_id', $schema );
|
||||
$this->assertArrayHasKey( 'name', $schema );
|
||||
$this->assertArrayHasKey( 'username', $schema );
|
||||
$this->assertArrayHasKey( 'country', $schema );
|
||||
$this->assertArrayHasKey( 'city', $schema );
|
||||
$this->assertArrayHasKey( 'postcode', $schema );
|
||||
$this->assertArrayHasKey( 'date_registered', $schema );
|
||||
$this->assertArrayHasKey( 'date_registered_gmt', $schema );
|
||||
$this->assertArrayHasKey( 'date_last_active', $schema );
|
||||
$this->assertArrayHasKey( 'date_last_active_gmt', $schema );
|
||||
$this->assertArrayHasKey( 'orders_count', $schema );
|
||||
$this->assertArrayHasKey( 'total_spend', $schema );
|
||||
$this->assertArrayHasKey( 'avg_order_value', $schema );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test reports schema.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function test_reports_schema() {
|
||||
wp_set_current_user( $this->user );
|
||||
|
||||
$request = new WP_REST_Request( 'OPTIONS', $this->endpoint );
|
||||
$response = $this->server->dispatch( $request );
|
||||
$data = $response->get_data();
|
||||
$properties = $data['schema']['properties'];
|
||||
|
||||
$this->assertCount( 14, $properties );
|
||||
$this->assert_report_item_schema( $properties );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test getting reports without valid permissions.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function test_get_reports_without_permission() {
|
||||
wp_set_current_user( 0 );
|
||||
$response = $this->server->dispatch( new WP_REST_Request( 'GET', $this->endpoint ) );
|
||||
$this->assertEquals( 401, $response->get_status() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test calling update_registered_customer() with a bad user id.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function test_update_registered_customer_with_bad_user_id() {
|
||||
$result = WC_Admin_Reports_Customers_Data_Store::update_registered_customer( 2 );
|
||||
$this->assertFalse( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test getting reports.
|
||||
*
|
||||
* @since 3.5.0
|
||||
*/
|
||||
public function test_get_reports() {
|
||||
wp_set_current_user( $this->user );
|
||||
WC_Helper_Reports::reset_stats_dbs();
|
||||
|
||||
$test_customers = array();
|
||||
|
||||
// Create 10 test customers.
|
||||
for ( $i = 1; $i <= 10; $i++ ) {
|
||||
$test_customers[] = WC_Helper_Customer::create_customer( "customer{$i}", 'password', "customer{$i}@example.com" );
|
||||
}
|
||||
|
||||
// Initialize the report lookup table.
|
||||
delete_transient( 'wc_update_350_all_customers' );
|
||||
WC_Admin_Api_Init::customer_lookup_store_init();
|
||||
|
||||
// Create a test product for use in an order.
|
||||
$product = new WC_Product_Simple();
|
||||
$product->set_name( 'Test Product' );
|
||||
$product->set_regular_price( 25 );
|
||||
$product->save();
|
||||
|
||||
// Place an order for the first test customer.
|
||||
$order = WC_Helper_Order::create_order( $test_customers[0]->get_id(), $product );
|
||||
$order->set_status( 'processing' );
|
||||
$order->set_total( 100 );
|
||||
$order->save();
|
||||
|
||||
$request = new WP_REST_Request( 'GET', $this->endpoint );
|
||||
$request->set_query_params(
|
||||
array(
|
||||
'per_page' => 5,
|
||||
'order' => 'asc',
|
||||
'orderby' => 'username',
|
||||
)
|
||||
);
|
||||
|
||||
$response = $this->server->dispatch( $request );
|
||||
$reports = $response->get_data();
|
||||
$headers = $response->get_headers();
|
||||
|
||||
$this->assertEquals( 200, $response->get_status() );
|
||||
$this->assertCount( 5, $reports );
|
||||
$this->assertArrayHasKey( 'X-WP-Total', $headers );
|
||||
$this->assertEquals( 10, $headers['X-WP-Total'] );
|
||||
$this->assertArrayHasKey( 'X-WP-TotalPages', $headers );
|
||||
$this->assertEquals( 2, $headers['X-WP-TotalPages'] );
|
||||
$this->assertEquals( $test_customers[0]->get_id(), $reports[0]['user_id'] );
|
||||
$this->assertEquals( 1, $reports[0]['orders_count'] );
|
||||
$this->assertEquals( 100, $reports[0]['total_spend'] );
|
||||
$this->assert_report_item_schema( $reports[0] );
|
||||
|
||||
// Test name parameter (case with no matches).
|
||||
$request->set_query_params(
|
||||
array(
|
||||
'name' => 'Nota Customername',
|
||||
)
|
||||
);
|
||||
$response = $this->server->dispatch( $request );
|
||||
$reports = $response->get_data();
|
||||
|
||||
$this->assertEquals( 200, $response->get_status() );
|
||||
$this->assertCount( 0, $reports );
|
||||
|
||||
// Test name and last_order parameters.
|
||||
$request->set_query_params(
|
||||
array(
|
||||
'name' => 'Justin',
|
||||
'last_order_after' => date( 'Y-m-d' ) . 'T00:00:00Z',
|
||||
)
|
||||
);
|
||||
$response = $this->server->dispatch( $request );
|
||||
$reports = $response->get_data();
|
||||
|
||||
$this->assertEquals( 200, $response->get_status() );
|
||||
$this->assertCount( 1, $reports );
|
||||
$this->assertEquals( $test_customers[0]->get_id(), $reports[0]['user_id'] );
|
||||
$this->assertEquals( 1, $reports[0]['orders_count'] );
|
||||
$this->assertEquals( 100, $reports[0]['total_spend'] );
|
||||
}
|
||||
}
|
|
@ -20,5 +20,6 @@ class WC_Helper_Reports {
|
|||
$wpdb->query( "DELETE FROM $wpdb->prefix" . WC_Admin_Reports_Orders_Data_Store::TABLE_NAME ); // @codingStandardsIgnoreLine.
|
||||
$wpdb->query( "DELETE FROM $wpdb->prefix" . WC_Admin_Reports_Products_Data_Store::TABLE_NAME ); // @codingStandardsIgnoreLine.
|
||||
$wpdb->query( "DELETE FROM $wpdb->prefix" . WC_Admin_Reports_Coupons_Data_Store::TABLE_NAME ); // @codingStandardsIgnoreLine.
|
||||
$wpdb->query( "DELETE FROM $wpdb->prefix" . WC_Admin_Reports_Customers_Data_Store::TABLE_NAME ); // @codingStandardsIgnoreLine.
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue