Merge pull request woocommerce/woocommerce-admin#1010 from woocommerce/fix/845

Added /reports/coupons and /reports/coupons/stats endpoints
This commit is contained in:
Peter Fabian 2018-12-19 13:55:28 +01:00 committed by GitHub
commit dff8b63271
18 changed files with 1480 additions and 189 deletions

View File

@ -38,16 +38,15 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
* @return array
*/
protected function prepare_reports_query( $request ) {
$args = array();
$args['before'] = $request['before'];
$args['after'] = $request['after'];
$args['interval'] = $request['interval'];
$args['page'] = $request['page'];
$args['per_page'] = $request['per_page'];
$args['orderby'] = $request['orderby'];
$args['order'] = $request['order'];
$args['code'] = (array) $request['code'];
$args = array();
$args['before'] = $request['before'];
$args['after'] = $request['after'];
$args['page'] = $request['page'];
$args['per_page'] = $request['per_page'];
$args['orderby'] = $request['orderby'];
$args['order'] = $request['order'];
$args['coupons'] = (array) $request['coupons'];
$args['extended_info'] = $request['extended_info'];
return $args;
}
@ -59,20 +58,17 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
*/
public function get_items( $request ) {
$query_args = $this->prepare_reports_query( $request );
$coupons_query = new WC_Reports_Orders_Stats_Query( $query_args ); // @todo change to correct class.
$coupons_query = new WC_Admin_Reports_Coupons_Query( $query_args );
$report_data = $coupons_query->get_data();
$out_data = array(
'totals' => get_object_vars( $report_data->totals ),
'intervals' => array(),
);
$data = array();
foreach ( $report_data->intervals as $interval_data ) {
$item = $this->prepare_item_for_response( (object) $interval_data, $request );
$out_data['intervals'][] = $this->prepare_response_for_collection( $item );
foreach ( $report_data->data as $coupons_data ) {
$item = $this->prepare_item_for_response( $coupons_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 );
@ -104,7 +100,7 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
* @return WP_REST_Response
*/
public function prepare_item_for_response( $report, $request ) {
$data = get_object_vars( $report );
$data = $report;
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
@ -135,7 +131,7 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
protected function prepare_links( $object ) {
$links = array(
'coupon' => array(
'href' => rest_url( sprintf( '/%s/coupons/%d', $this->namespace, $object->coupon_id ) ),
'href' => rest_url( sprintf( '/%s/coupons/%d', $this->namespace, $object['coupon_id'] ) ),
),
);
@ -153,24 +149,63 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
'title' => 'report_coupons',
'type' => 'object',
'properties' => array(
'coupon_id' => array(
'coupon_id' => array(
'description' => __( 'Coupon ID.', 'wc-admin' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'gross_discount' => array(
'description' => __( 'Gross discount.', 'wc-admin' ),
'amount' => array(
'description' => __( 'Net discount amount.', 'wc-admin' ),
'type' => 'number',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'orders_count' => array(
'orders_count' => array(
'description' => __( 'Amount of orders.', 'wc-admin' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'extended_info' => array(
'code' => array(
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'description' => __( 'Coupon code.', 'wc-admin' ),
),
'date_created' => array(
'type' => 'date-time',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'description' => __( 'Coupon creation date.', 'wc-admin' ),
),
'date_created_gmt' => array(
'type' => 'date-time',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'description' => __( 'Coupon creation date in GMT.', 'wc-admin' ),
),
'date_expires' => array(
'type' => 'date-time',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'description' => __( 'Coupon expiration date.', 'wc-admin' ),
),
'date_expires_gmt' => array(
'type' => 'date-time',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'description' => __( 'Coupon expiration date in GMT.', 'wc-admin' ),
),
'discount_type' => array(
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit' ),
'enum' => array_keys( wc_get_coupon_types() ),
'description' => __( 'Coupon discount type.', 'wc-admin' ),
),
),
),
);
@ -183,9 +218,9 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
* @return array
*/
public function get_collection_params() {
$params = array();
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
$params['page'] = array(
$params = array();
$params['context'] = $this->get_context_param( array( 'default' => 'view' ) );
$params['page'] = array(
'description' => __( 'Current page of the collection.', 'wc-admin' ),
'type' => 'integer',
'default' => 1,
@ -193,7 +228,7 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
'validate_callback' => 'rest_validate_request_arg',
'minimum' => 1,
);
$params['per_page'] = array(
$params['per_page'] = array(
'description' => __( 'Maximum number of items to be returned in result set.', 'wc-admin' ),
'type' => 'integer',
'default' => 10,
@ -202,61 +237,52 @@ class WC_Admin_REST_Reports_Coupons_Controller extends WC_REST_Reports_Controlle
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
$params['after'] = array(
$params['after'] = array(
'description' => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'wc-admin' ),
'type' => 'string',
'format' => 'date-time',
'validate_callback' => 'rest_validate_request_arg',
);
$params['before'] = array(
$params['before'] = array(
'description' => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'wc-admin' ),
'type' => 'string',
'format' => 'date-time',
'validate_callback' => 'rest_validate_request_arg',
);
$params['order'] = 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(
$params['orderby'] = array(
'description' => __( 'Sort collection by object attribute.', 'wc-admin' ),
'type' => 'string',
'default' => 'date',
'default' => 'coupon_id',
'enum' => array(
'date',
'items_sold',
'gross_revenue',
'coupon_id',
'amount',
'orders_count',
'products_count',
),
'validate_callback' => 'rest_validate_request_arg',
);
$params['interval'] = array(
'description' => __( 'Time interval to use for buckets in the returned data.', 'wc-admin' ),
'type' => 'string',
'default' => 'week',
'enum' => array(
'hour',
'day',
'week',
'month',
'quarter',
'year',
),
'validate_callback' => 'rest_validate_request_arg',
);
$params['coupons'] = array(
'description' => __( 'Limit result set to items assigned one or more code.', 'wc-admin' ),
$params['coupons'] = array(
'description' => __( 'Limit result set to coupons assigned specific coupon IDs.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_slug_list',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'string',
'type' => 'integer',
),
);
$params['extended_info'] = array(
'description' => __( 'Add additional piece of info about each coupon to the report.', 'wc-admin' ),
'type' => 'boolean',
'default' => false,
'sanitize_callback' => 'wc_string_to_bool',
'validate_callback' => 'rest_validate_request_arg',
);
return $params;
}

View File

@ -47,7 +47,7 @@ class WC_Admin_REST_Reports_Coupons_Stats_Controller extends WC_REST_Reports_Con
$args['per_page'] = $request['per_page'];
$args['orderby'] = $request['orderby'];
$args['order'] = $request['order'];
$args['code'] = (array) $request['code'];
$args['coupons'] = (array) $request['coupons'];
return $args;
}
@ -60,7 +60,7 @@ class WC_Admin_REST_Reports_Coupons_Stats_Controller extends WC_REST_Reports_Con
*/
public function get_items( $request ) {
$query_args = $this->prepare_reports_query( $request );
$coupons_query = new WC_Reports_Orders_Stats_Query( $query_args ); // @todo change to correct class.
$coupons_query = new WC_Admin_Reports_Coupons_Stats_Query( $query_args );
$report_data = $coupons_query->get_data();
$out_data = array(
@ -133,19 +133,19 @@ class WC_Admin_REST_Reports_Coupons_Stats_Controller extends WC_REST_Reports_Con
*/
public function get_item_schema() {
$totals = array(
'gross_discount' => array(
'description' => __( 'Gross discount.', 'wc-admin' ),
'amount' => array(
'description' => __( 'Net discount amount.', 'wc-admin' ),
'type' => 'number',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'coupons_count' => array(
'coupons_count' => array(
'description' => __( 'Amount of coupons.', 'wc-admin' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'orders_count' => array(
'orders_count' => array(
'description' => __( 'Amount of orders.', 'wc-admin' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
@ -270,10 +270,9 @@ class WC_Admin_REST_Reports_Coupons_Stats_Controller extends WC_REST_Reports_Con
'default' => 'date',
'enum' => array(
'date',
'items_sold',
'gross_revenue',
'amount',
'coupons_count',
'orders_count',
'products_count',
),
'validate_callback' => 'rest_validate_request_arg',
);
@ -292,12 +291,12 @@ class WC_Admin_REST_Reports_Coupons_Stats_Controller extends WC_REST_Reports_Con
'validate_callback' => 'rest_validate_request_arg',
);
$params['coupons'] = array(
'description' => __( 'Limit result set to items assigned one or more code.', 'wc-admin' ),
'description' => __( 'Limit result set to coupons assigned specific coupon IDs.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_slug_list',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'string',
'type' => 'integer',
),
);

View File

@ -51,6 +51,8 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-categories-query.php';
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-taxes-query.php';
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-taxes-stats-query.php';
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-query.php';
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-stats-query.php';
// Data stores.
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-data-store.php';
@ -61,6 +63,8 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-categories-data-store.php';
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-taxes-data-store.php';
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-taxes-stats-data-store.php';
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-coupons-data-store.php';
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-coupons-stats-data-store.php';
// Data triggers.
require_once dirname( __FILE__ ) . '/wc-admin-order-functions.php';
@ -325,6 +329,8 @@ class WC_Admin_Api_Init {
'report-categories' => 'WC_Admin_Reports_Categories_Data_Store',
'report-taxes' => 'WC_Admin_Reports_Taxes_Data_Store',
'report-taxes-stats' => 'WC_Admin_Reports_Taxes_Stats_Data_Store',
'report-coupons' => 'WC_Admin_Reports_Coupons_Data_Store',
'report-coupons-stats' => 'WC_Admin_Reports_Coupons_Stats_Data_Store',
'admin-note' => 'WC_Admin_Notes_Data_Store',
)
);
@ -410,7 +416,7 @@ class WC_Admin_Api_Init {
order_id BIGINT UNSIGNED NOT NULL,
coupon_id BIGINT UNSIGNED NOT NULL,
date_created timestamp DEFAULT '0000-00-00 00:00:00' NOT NULL,
coupon_gross_discount double DEFAULT 0 NOT NULL,
discount_amount double DEFAULT 0 NOT NULL,
PRIMARY KEY (order_id, coupon_id),
KEY coupon_id (coupon_id),
KEY date_created (date_created)

View File

@ -0,0 +1,47 @@
<?php
/**
* Class for parameter-based Coupons Report querying
*
* Example usage:
* $args = array(
* 'before' => '2018-07-19 00:00:00',
* 'after' => '2018-07-05 00:00:00',
* 'page' => 2,
* 'coupons' => array(5, 120),
* );
* $report = new WC_Admin_Reports_Coupons_Query( $args );
* $mydata = $report->get_data();
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Products_Query
*/
class WC_Admin_Reports_Coupons_Query extends WC_Admin_Reports_Query {
/**
* Valid fields for Products report.
*
* @return array
*/
protected function get_default_query_vars() {
return array();
}
/**
* Get product data based on the current query vars.
*
* @return array
*/
public function get_data() {
$args = apply_filters( 'woocommerce_reports_coupons_query_args', $this->get_query_vars() );
$data_store = WC_Data_Store::load( 'report-coupons' );
$results = $data_store->get_data( $args );
return apply_filters( 'woocommerce_reports_coupons_select_query', $results, $args );
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* Class for parameter-based Products Report querying
*
* Example usage:
* $args = array(
* 'before' => '2018-07-19 00:00:00',
* 'after' => '2018-07-05 00:00:00',
* 'page' => 2,
* 'coupons' => array(5, 120),
* );
* $report = new WC_Admin_Reports_Coupons_Stats_Query( $args );
* $mydata = $report->get_data();
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Products_Query
*/
class WC_Admin_Reports_Coupons_Stats_Query extends WC_Admin_Reports_Query {
/**
* Valid fields for Products report.
*
* @return array
*/
protected function get_default_query_vars() {
return array();
}
/**
* Get product data based on the current query vars.
*
* @return array
*/
public function get_data() {
$args = apply_filters( 'woocommerce_reports_coupons_query_args', $this->get_query_vars() );
$data_store = WC_Data_Store::load( 'report-coupons-stats' );
$results = $data_store->get_data( $args );
return apply_filters( 'woocommerce_reports_coupons_select_query', $results, $args );
}
}

View File

@ -17,7 +17,7 @@ class WC_Admin_Reports_Interval {
*
* @var string
*/
public static $iso_datetime_format = 'Y-m-d\TH:i:s\Z';
public static $iso_datetime_format = 'Y-m-d\TH:i:s';
/**
* Format string for use in SQL queries.
@ -409,4 +409,69 @@ class WC_Admin_Reports_Interval {
return call_user_func( array( __CLASS__, "next_{$time_interval}_start" ), $datetime, $reversed );
}
/**
* Returns expected number of items on the page in case of date ordering.
*
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
*
* @return float|int
*/
public static function expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ) {
$total_pages = (int) ceil( $expected_interval_count / $items_per_page );
if ( $page_no < $total_pages ) {
return $items_per_page;
} elseif ( $page_no === $total_pages ) {
return $expected_interval_count - ( $page_no - 1 ) * $items_per_page;
} else {
return 0;
}
}
/**
* Returns true if there are any intervals that need to be filled in the response.
*
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $db_records Total number of records for given period in the database.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
* @param string $order asc or desc.
* @param string $order_by Column by which the result will be sorted.
* @param int $intervals_count Number of records for given (possibly shortened) time interval.
*
* @return bool
*/
public static function intervals_missing( $expected_interval_count, $db_records, $items_per_page, $page_no, $order, $order_by, $intervals_count ) {
if ( $expected_interval_count > $db_records ) {
if ( 'date' === $order_by ) {
$expected_intervals_on_page = self::expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no );
if ( $intervals_count < $expected_intervals_on_page ) {
return true;
} else {
return false;
}
} else {
if ( 'desc' === $order ) {
if ( $page_no > floor( $db_records / $items_per_page ) ) {
return true;
} else {
return false;
}
} elseif ( 'asc' === $order ) {
if ( $page_no <= ceil( ( $expected_interval_count - $db_records ) / $items_per_page ) ) {
return true;
} else {
return false;
}
} else {
// Invalid ordering.
return false;
}
}
} else {
return false;
}
}
}

View File

@ -0,0 +1,252 @@
<?php
/**
* WC_Admin_Reports_Copons_Data_Store class file.
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Coupons_Data_Store.
*/
class WC_Admin_Reports_Coupons_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_order_coupon_lookup';
/**
* Mapping columns to data type to return correct response types.
*
* @var array
*/
protected $column_types = array(
'coupon_id' => 'intval',
'amount' => 'floatval',
'orders_count' => 'intval',
);
/**
* SQL columns to select in the db query and their mapping to SQL code.
*
* @var array
*/
protected $report_columns = array(
'coupon_id' => 'coupon_id',
'amount' => 'SUM(discount_amount) as amount',
'orders_count' => 'COUNT(DISTINCT order_id) as orders_count',
);
/**
* Returns comma separated ids of included coupons, based on query arguments from the user.
*
* @param array $query_args Parameters supplied by the user.
* @return string
*/
protected function get_included_coupons( $query_args ) {
$included_coupons_str = '';
if ( isset( $query_args['coupons'] ) && is_array( $query_args['coupons'] ) && count( $query_args['coupons'] ) > 0 ) {
$included_coupons_str = implode( ',', $query_args['coupons'] );
}
return $included_coupons_str;
}
/**
* Updates the database query with parameters used for Products 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;
$order_coupon_lookup_table = $wpdb->prefix . self::TABLE_NAME;
$sql_query_params = $this->get_time_period_sql_params( $query_args, $order_coupon_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 ) );
$included_coupons = $this->get_included_coupons( $query_args );
if ( $included_coupons ) {
$sql_query_params['where_clause'] .= " AND {$order_coupon_lookup_table}.coupon_id IN ({$included_coupons})";
}
// TODO: questionable, I think we need order status filters, even though it's not specified.
$order_status_filter = $this->get_status_subquery( $query_args );
if ( $order_status_filter ) {
$sql_query_params['from_clause'] .= " JOIN {$wpdb->prefix}posts ON {$order_coupon_lookup_table}.order_id = {$wpdb->prefix}posts.ID";
$sql_query_params['where_clause'] .= " AND ( {$order_status_filter} )";
}
return $sql_query_params;
}
/**
* Enriches the coupon data with extra attributes.
*
* @param array $coupon_data Coupon data.
* @param array $query_args Query parameters.
*/
protected function include_extended_info( &$coupon_data, $query_args ) {
foreach ( $coupon_data as $idx => $coupon_datum ) {
$extended_info = new ArrayObject();
if ( $query_args['extended_info'] ) {
$coupon_id = $coupon_datum['coupon_id'];
$coupon = new WC_Coupon( $coupon_id );
$gmt_timzone = new DateTimeZone( 'UTC' );
$date_expires = $coupon->get_date_expires();
if ( null === $date_expires ) {
$date_expires = '';
$date_expires_gmt = '';
} else {
$date_expires = $date_expires->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$date_expires_gmt = new DateTime( $date_expires );
$date_expires_gmt->setTimezone( $gmt_timzone );
$date_expires_gmt = $date_expires_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$date_created = $coupon->get_date_created();
if ( null === $date_created ) {
$date_created = '';
$date_created_gmt = '';
} else {
$date_created = $date_created->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$date_created_gmt = new DateTime( $date_created );
$date_created_gmt->setTimezone( $gmt_timzone );
$date_created_gmt = $date_created_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$extended_info = array(
'code' => $coupon->get_code(),
'date_created' => $date_created,
'date_created_gmt' => $date_created_gmt,
'date_expires' => $date_expires,
'date_expires_gmt' => $date_expires_gmt,
'discount_type' => $coupon->get_discount_type(),
);
}
$coupon_data[ $idx ]['extended_info'] = $extended_info;
}
}
/**
* 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;
$table_name = $wpdb->prefix . self::TABLE_NAME;
$now = time();
$week_back = $now - WEEK_IN_SECONDS;
// 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' => 'coupon_id',
'before' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $now ),
'after' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $week_back ),
'fields' => '*',
'coupons' => array(),
'extended_info' => false,
// This is not a parameter for coupons reports per se, but we want to only take into account selected order types.
'order_status' => parent::get_report_order_statuses(),
);
$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
coupon_id
FROM
{$table_name}
{$sql_query_params['from_clause']}
WHERE
1=1
{$sql_query_params['where_time_clause']}
{$sql_query_params['where_clause']}
GROUP BY
coupon_id
) 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;
}
$coupon_data = $wpdb->get_results(
"SELECT
{$selections}
FROM
{$table_name}
{$sql_query_params['from_clause']}
WHERE
1=1
{$sql_query_params['where_time_clause']}
{$sql_query_params['where_clause']}
GROUP BY
coupon_id
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 === $coupon_data ) {
return $data;
}
$this->include_extended_info( $coupon_data, $query_args );
$coupon_data = array_map( array( $this, 'cast_numbers' ), $coupon_data );
$data = (object) array(
'data' => $coupon_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;
}
/**
* 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 ) );
}
}

View File

@ -0,0 +1,225 @@
<?php
/**
* WC_Admin_Reports_Coupons_Stats_Data_Store class file.
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Reports_Coupons_Stats_Data_Store.
*/
class WC_Admin_Reports_Coupons_Stats_Data_Store extends WC_Admin_Reports_Coupons_Data_Store implements WC_Admin_Reports_Data_Store_Interface {
/**
* Mapping columns to data type to return correct response types.
*
* @var array
*/
protected $column_types = array(
'date_start' => 'strval',
'date_end' => 'strval',
'date_start_gmt' => 'strval',
'date_end_gmt' => 'strval',
'amount' => 'floatval',
'coupons_count' => 'intval',
'orders_count' => 'intval',
);
/**
* SQL columns to select in the db query.
*
* @var array
*/
protected $report_columns = array(
'amount' => 'SUM(discount_amount) as amount',
'coupons_count' => 'COUNT(DISTINCT coupon_id) as coupons_count',
'orders_count' => 'COUNT(DISTINCT order_id) as orders_count',
);
/**
* Updates the database query with parameters used for Products Stats report: categories and order status.
*
* @param array $query_args Query arguments supplied by the user.
* @param array $totals_params SQL parameters for the totals query.
* @param array $intervals_params SQL parameters for the intervals query.
*/
protected function update_sql_query_params( $query_args, &$totals_params, &$intervals_params ) {
global $wpdb;
$coupons_where_clause = '';
$coupons_from_clause = '';
$order_coupon_lookup_table = $wpdb->prefix . self::TABLE_NAME;
$included_coupons = $this->get_included_coupons( $query_args );
if ( $included_coupons ) {
$coupons_where_clause .= " AND {$order_coupon_lookup_table}.coupon_id IN ({$included_coupons})";
}
$order_status_filter = $this->get_status_subquery( $query_args );
if ( $order_status_filter ) {
$coupons_from_clause .= " JOIN {$wpdb->prefix}posts ON {$order_coupon_lookup_table}.order_id = {$wpdb->prefix}posts.ID";
$coupons_where_clause .= " AND ( {$order_status_filter} )";
}
$totals_params = array_merge( $totals_params, $this->get_time_period_sql_params( $query_args, $order_coupon_lookup_table ) );
$totals_params['where_clause'] .= $coupons_where_clause;
$totals_params['from_clause'] .= $coupons_from_clause;
$intervals_params = array_merge( $intervals_params, $this->get_intervals_sql_params( $query_args, $order_coupon_lookup_table ) );
$intervals_params['where_clause'] .= $coupons_where_clause;
$intervals_params['from_clause'] .= $coupons_from_clause;
}
/**
* Returns the report data based on parameters supplied by the user.
*
* @since 3.5.0
* @param array $query_args Query parameters.
* @return stdClass|WP_Error Data.
*/
public function get_data( $query_args ) {
global $wpdb;
$table_name = $wpdb->prefix . self::TABLE_NAME;
$now = time();
$week_back = $now - WEEK_IN_SECONDS;
// 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',
'before' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $now ),
'after' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $week_back ),
'fields' => '*',
'interval' => 'week',
'coupons' => array(),
// This is not a parameter for products reports per se, but we should probably restricts order statuses here, too.
'order_status' => parent::get_report_order_statuses(),
);
$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 );
$totals_query = array();
$intervals_query = array();
$this->update_sql_query_params( $query_args, $totals_query, $intervals_query );
$db_intervals = $wpdb->get_col(
"SELECT
{$intervals_query['select_clause']} AS time_interval
FROM
{$table_name}
{$intervals_query['from_clause']}
WHERE
1=1
{$intervals_query['where_time_clause']}
{$intervals_query['where_clause']}
GROUP BY
time_interval"
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
$db_interval_count = count( $db_intervals );
$expected_interval_count = WC_Admin_Reports_Interval::intervals_between( $query_args['after'], $query_args['before'], $query_args['interval'] );
$total_pages = (int) ceil( $expected_interval_count / $intervals_query['per_page'] );
if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
return $data;
}
$totals = $wpdb->get_results(
"SELECT
{$selections}
FROM
{$table_name}
{$totals_query['from_clause']}
WHERE
1=1
{$totals_query['where_time_clause']}
{$totals_query['where_clause']}",
ARRAY_A
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
if ( null === $totals ) {
return $data;
}
$totals = (object) $this->cast_numbers( $totals[0] );
// Intervals.
$this->update_intervals_sql_params( $intervals_query, $query_args, $db_interval_count, $expected_interval_count );
if ( '' !== $selections ) {
$selections = ', ' . $selections;
}
$intervals = $wpdb->get_results(
"SELECT
MAX(date_created) AS datetime_anchor,
{$intervals_query['select_clause']} AS time_interval
{$selections}
FROM
{$table_name}
{$intervals_query['from_clause']}
WHERE
1=1
{$intervals_query['where_time_clause']}
{$intervals_query['where_clause']}
GROUP BY
time_interval
ORDER BY
{$intervals_query['order_by_clause']}
{$intervals_query['limit']}",
ARRAY_A
); // WPCS: cache ok, DB call ok, unprepared SQL ok.
if ( null === $intervals ) {
return $data;
}
$data = (object) array(
'totals' => $totals,
'intervals' => $intervals,
'total' => $expected_interval_count,
'pages' => $total_pages,
'page_no' => (int) $query_args['page'],
);
if ( WC_Admin_Reports_Interval::intervals_missing( $expected_interval_count, $db_interval_count, $intervals_query['per_page'], $query_args['page'], $query_args['order'], $query_args['orderby'], count( $intervals ) ) ) {
$this->fill_in_missing_intervals( $db_intervals, $query_args['adj_after'], $query_args['adj_before'], $query_args['interval'], $data );
$this->sort_intervals( $data, $query_args['orderby'], $query_args['order'] );
$this->remove_extra_records( $data, $query_args['page'], $intervals_query['per_page'], $db_interval_count, $expected_interval_count, $query_args['orderby'] );
} else {
$this->update_interval_boundary_dates( $query_args['after'], $query_args['before'], $query_args['interval'], $data->intervals );
}
$this->create_interval_subtotals( $data->intervals );
wp_cache_set( $cache_key, $data, $this->cache_group );
}
return $data;
}
/**
* 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 . '_stats_' . md5( wp_json_encode( $params ) );
}
}

View File

@ -294,6 +294,10 @@ class WC_Admin_Reports_Data_Store {
$retyped_array = array();
$column_types = apply_filters( 'woocommerce_rest_reports_column_types', $this->column_types, $array );
foreach ( $array as $column_name => $value ) {
if ( is_array( $value ) ) {
$value = $this->cast_numbers( $value );
}
if ( isset( $column_types[ $column_name ] ) ) {
$retyped_array[ $column_name ] = $column_types[ $column_name ]( $value );
} else {

View File

@ -101,71 +101,6 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
}
}
/**
* Returns expected number of items on the page in case of date ordering.
*
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
*
* @return float|int
*/
protected function expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ) {
$total_pages = (int) ceil( $expected_interval_count / $items_per_page );
if ( $page_no < $total_pages ) {
return $items_per_page;
} elseif ( $page_no === $total_pages ) {
return $expected_interval_count - ( $page_no - 1 ) * $items_per_page;
} else {
return 0;
}
}
/**
* Returns true if there are any intervals that need to be filled in the response.
*
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $db_records Total number of records for given period in the database.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
* @param string $order asc or desc.
* @param string $order_by Column by which the result will be sorted.
* @param int $intervals_count Number of records for given (possibly shortened) time interval.
*
* @return bool
*/
protected function intervals_missing( $expected_interval_count, $db_records, $items_per_page, $page_no, $order, $order_by, $intervals_count ) {
if ( $expected_interval_count > $db_records ) {
if ( 'date' === $order_by ) {
$expected_intervals_on_page = $this->expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no );
if ( $intervals_count < $expected_intervals_on_page ) {
return true;
} else {
return false;
}
} else {
if ( 'desc' === $order ) {
if ( $page_no > floor( $db_records / $items_per_page ) ) {
return true;
} else {
return false;
}
} elseif ( 'asc' === $order ) {
if ( $page_no <= ceil( ( $expected_interval_count - $db_records ) / $items_per_page ) ) {
return true;
} else {
return false;
}
} else {
// Invalid ordering.
return false;
}
}
} else {
return false;
}
}
/**
* Updates the totals and intervals database queries with parameters used for Orders report: categories, coupons and order status.
*
@ -394,7 +329,7 @@ class WC_Admin_Reports_Orders_Data_Store extends WC_Admin_Reports_Data_Store imp
'page_no' => (int) $query_args['page'],
);
if ( $this->intervals_missing( $expected_interval_count, $db_interval_count, $intervals_query['per_page'], $query_args['page'], $query_args['order'], $query_args['orderby'], count( $intervals ) ) ) {
if ( WC_Admin_Reports_Interval::intervals_missing( $expected_interval_count, $db_interval_count, $intervals_query['per_page'], $query_args['page'], $query_args['order'], $query_args['orderby'], count( $intervals ) ) ) {
$this->fill_in_missing_intervals( $db_intervals, $query_args['adj_after'], $query_args['adj_before'], $query_args['interval'], $data );
$this->sort_intervals( $data, $query_args['orderby'], $query_args['order'] );
$this->remove_extra_records( $data, $query_args['page'], $intervals_query['per_page'], $db_interval_count, $expected_interval_count, $query_args['orderby'] );

View File

@ -108,10 +108,10 @@ function wc_order_coupon_lookup_entry( $order_id ) {
$wpdb->replace(
$wpdb->prefix . 'wc_order_coupon_lookup',
array(
'order_id' => $order_id,
'coupon_id' => wc_get_coupon_id_by_code( $coupon_item->get_code() ),
'coupon_gross_discount' => $coupon_item->get_discount(),
'date_created' => date( 'Y-m-d H:i:s', $order->get_date_created( 'edit' )->getTimestamp() ),
'order_id' => $order_id,
'coupon_id' => wc_get_coupon_id_by_code( $coupon_item->get_code() ),
'discount_amount' => $coupon_item->get_discount(),
'date_created' => date( 'Y-m-d H:i:s', $order->get_date_created( 'edit' )->getTimestamp() ),
),
array(
'%d',

View File

@ -3,7 +3,10 @@
* Admin notes REST API Test
*
* @package WooCommerce\Tests\API
* @since 3.5.0
*/
/**
* Class WC_Tests_API_Admin_Notes
*/
class WC_Tests_API_Admin_Notes extends WC_REST_Unit_Test_Case {

View File

@ -0,0 +1,173 @@
<?php
/**
* Reports Coupons Stats REST API Test
*
* @package WooCommerce\Tests\API
*/
/**
* Class WC_Tests_API_Reports_Coupons_Stats
*/
class WC_Tests_API_Reports_Coupons_Stats extends WC_REST_Unit_Test_Case {
/**
* Endpoints.
*
* @var string
*/
protected $endpoint = '/wc/v3/reports/coupons/stats';
/**
* Setup test reports products stats data.
*/
public function setUp() {
parent::setUp();
$this->user = $this->factory->user->create(
array(
'role' => 'administrator',
)
);
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$this->assertArrayHasKey( $this->endpoint, $routes );
}
/**
* Test getting reports.
*/
public function test_get_reports() {
WC_Helper_Reports::reset_stats_dbs();
wp_set_current_user( $this->user );
// Populate all of the data.
// Simple product.
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_regular_price( 25 );
$product->save();
// Coupons.
$coupon_1_amount = 1; // by default in create_coupon.
$coupon_1 = WC_Helper_Coupon::create_coupon( 'coupon_1' );
$coupon_2_amount = 2;
$coupon_2 = WC_Helper_Coupon::create_coupon( 'coupon_2' );
$coupon_2->set_amount( $coupon_2_amount );
$coupon_2->save();
// Order without coupon.
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 ); // $25 x 4.
$order->save();
$time = time();
// Order with 1 coupon.
$order_1c = WC_Helper_Order::create_order( 1, $product );
$order_1c->set_status( 'completed' );
$order_1c->apply_coupon( $coupon_1 );
$order_1c->calculate_totals();
$order_1c->set_date_created( $time );
$order_1c->save();
// Order with 2 coupons.
$order_2c = WC_Helper_Order::create_order( 1, $product );
$order_2c->set_status( 'completed' );
$order_2c->apply_coupon( $coupon_1 );
$order_2c->apply_coupon( $coupon_2 );
$order_2c->calculate_totals();
$order_2c->set_date_created( $time );
$order_2c->save();
$request = new WP_REST_Request( 'GET', $this->endpoint );
$request->set_query_params(
array(
'before' => date( 'Y-m-d 23:59:59', $time ),
'after' => date( 'Y-m-d 00:00:00', $time ),
'interval' => 'day',
)
);
$response = $this->server->dispatch( $request );
$reports = $response->get_data();
$expected_reports = array(
'totals' => array(
'amount' => 4,
'coupons_count' => 2,
'orders_count' => 2,
),
'intervals' => array(
array(
'interval' => date( 'Y-m-d', $time ),
'date_start' => date( 'Y-m-d 00:00:00', $time ),
'date_start_gmt' => date( 'Y-m-d 00:00:00', $time ),
'date_end' => date( 'Y-m-d 23:59:59', $time ),
'date_end_gmt' => date( 'Y-m-d 23:59:59', $time ),
'subtotals' => (object) array(
'amount' => 4,
'coupons_count' => 2,
'orders_count' => 2,
),
),
),
);
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( $expected_reports, $reports );
}
/**
* Test getting reports without valid permissions.
*/
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 reports schema.
*/
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->assertEquals( 2, count( $properties ) );
$this->assertArrayHasKey( 'totals', $properties );
$this->assertArrayHasKey( 'intervals', $properties );
$totals = $properties['totals']['properties'];
$this->assertEquals( 3, count( $totals ) );
$this->assertArrayHasKey( 'amount', $totals );
$this->assertArrayHasKey( 'coupons_count', $totals );
$this->assertArrayHasKey( 'orders_count', $totals );
$intervals = $properties['intervals']['items']['properties'];
$this->assertEquals( 6, count( $intervals ) );
$this->assertArrayHasKey( 'interval', $intervals );
$this->assertArrayHasKey( 'date_start', $intervals );
$this->assertArrayHasKey( 'date_start_gmt', $intervals );
$this->assertArrayHasKey( 'date_end', $intervals );
$this->assertArrayHasKey( 'date_end_gmt', $intervals );
$this->assertArrayHasKey( 'subtotals', $intervals );
$subtotals = $properties['intervals']['items']['properties']['subtotals']['properties'];
$this->assertEquals( 3, count( $subtotals ) );
$this->assertArrayHasKey( 'amount', $totals );
$this->assertArrayHasKey( 'coupons_count', $totals );
$this->assertArrayHasKey( 'orders_count', $totals );
}
}

View File

@ -0,0 +1,130 @@
<?php
/**
* Reports Coupons REST API Test
*
* @package WooCommerce\Tests\API
*/
/**
* Class WC_Tests_API_Reports_Coupons
*/
class WC_Tests_API_Reports_Coupons extends WC_REST_Unit_Test_Case {
/**
* Endpoints.
*
* @var string
*/
protected $endpoint = '/wc/v3/reports/coupons';
/**
* Setup test reports products data.
*/
public function setUp() {
parent::setUp();
$this->user = $this->factory->user->create(
array(
'role' => 'administrator',
)
);
}
/**
* Test route registration.
*/
public function test_register_routes() {
$routes = $this->server->get_routes();
$this->assertArrayHasKey( $this->endpoint, $routes );
}
/**
* Test getting basic reports.
*/
public function test_get_reports() {
wp_set_current_user( $this->user );
WC_Helper_Reports::reset_stats_dbs();
// Simple product.
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_regular_price( 25 );
$product->save();
// Coupons.
$coupon_1_amount = 1; // by default in create_coupon.
$coupon_1 = WC_Helper_Coupon::create_coupon( 'coupon_1' );
$coupon_2_amount = 2;
$coupon_2 = WC_Helper_Coupon::create_coupon( 'coupon_2' );
$coupon_2->set_amount( $coupon_2_amount );
$coupon_2->save();
// Order without coupon.
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 ); // $25 x 4.
$order->save();
// Order with 1 coupon.
$order_1c = WC_Helper_Order::create_order( 1, $product );
$order_1c->set_status( 'completed' );
$order_1c->apply_coupon( $coupon_1 );
$order_1c->calculate_totals();
$order_1c->save();
// Order with 2 coupons.
$order_2c = WC_Helper_Order::create_order( 1, $product );
$order_2c->set_status( 'completed' );
$order_2c->apply_coupon( $coupon_1 );
$order_2c->apply_coupon( $coupon_2 );
$order_2c->calculate_totals();
$order_2c->save();
$response = $this->server->dispatch( new WP_REST_Request( 'GET', $this->endpoint ) );
$coupon_reports = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( 2, count( $coupon_reports ) );
$this->assertEquals( $coupon_2->get_id(), $coupon_reports[0]['coupon_id'] );
$this->assertEquals( 1 * $coupon_2_amount, $coupon_reports[0]['amount'] );
$this->assertEquals( 1, $coupon_reports[0]['orders_count'] );
$this->assertArrayHasKey( '_links', $coupon_reports[0] );
$this->assertArrayHasKey( 'coupon', $coupon_reports[0]['_links'] );
$this->assertEquals( $coupon_1->get_id(), $coupon_reports[1]['coupon_id'] );
$this->assertEquals( 2 * $coupon_1_amount, $coupon_reports[1]['amount'] );
$this->assertEquals( 2, $coupon_reports[1]['orders_count'] );
$this->assertArrayHasKey( '_links', $coupon_reports[1] );
$this->assertArrayHasKey( 'coupon', $coupon_reports[1]['_links'] );
}
/**
* Test getting reports without valid permissions.
*/
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 reports schema.
*/
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->assertEquals( 4, count( $properties ) );
$this->assertArrayHasKey( 'coupon_id', $properties );
$this->assertArrayHasKey( 'amount', $properties );
$this->assertArrayHasKey( 'orders_count', $properties );
$this->assertArrayHasKey( 'extended_info', $properties );
}
}

View File

@ -5,6 +5,10 @@
* @package WC Admin
* @since x.x.0
*/
/**
* Class WC_Tests_Reports_Interval_Stats
*/
class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
/**
@ -594,12 +598,12 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
public function test_next_hour_start() {
$settings = array(
'2017-12-30T00:00:00Z' => array(
0 => '2017-12-30T01:00:00Z',
1 => '2017-12-29T23:59:59Z',
0 => '2017-12-30T01:00:00',
1 => '2017-12-29T23:59:59',
),
'2017-12-30T10:00:00Z' => array(
0 => '2017-12-30T11:00:00Z',
1 => '2017-12-30T09:59:59Z',
0 => '2017-12-30T11:00:00',
1 => '2017-12-30T09:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -617,12 +621,12 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
public function test_next_day_start() {
$settings = array(
'2017-12-30T00:00:00Z' => array(
0 => '2017-12-31T00:00:00Z',
1 => '2017-12-29T23:59:59Z',
0 => '2017-12-31T00:00:00',
1 => '2017-12-29T23:59:59',
),
'2017-12-30T10:00:00Z' => array(
0 => '2017-12-31T00:00:00Z',
1 => '2017-12-29T23:59:59Z',
0 => '2017-12-31T00:00:00',
1 => '2017-12-29T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -641,36 +645,36 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
update_option( 'start_of_week', 1 );
$settings = array(
'2017-12-30T00:00:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2017-12-24T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2017-12-24T23:59:59',
),
'2017-12-30T10:00:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2017-12-24T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2017-12-24T23:59:59',
),
'2010-12-25T10:00:00Z' => array(
0 => '2010-12-27T00:00:00Z',
1 => '2010-12-19T23:59:59Z',
0 => '2010-12-27T00:00:00',
1 => '2010-12-19T23:59:59',
),
'2010-12-26T10:00:00Z' => array(
0 => '2010-12-27T00:00:00Z',
1 => '2010-12-19T23:59:59Z',
0 => '2010-12-27T00:00:00',
1 => '2010-12-19T23:59:59',
),
'2010-12-27T00:00:00Z' => array(
0 => '2011-01-03T00:00:00Z',
1 => '2010-12-26T23:59:59Z',
0 => '2011-01-03T00:00:00',
1 => '2010-12-26T23:59:59',
),
'2010-12-31T00:00:00Z' => array(
0 => '2011-01-03T00:00:00Z',
1 => '2010-12-26T23:59:59Z',
0 => '2011-01-03T00:00:00',
1 => '2010-12-26T23:59:59',
),
'2011-01-01T00:00:00Z' => array(
0 => '2011-01-03T00:00:00Z',
1 => '2010-12-26T23:59:59Z',
0 => '2011-01-03T00:00:00',
1 => '2010-12-26T23:59:59',
),
'2011-01-03T00:00:00Z' => array(
0 => '2011-01-10T00:00:00Z',
1 => '2011-01-02T23:59:59Z',
0 => '2011-01-10T00:00:00',
1 => '2011-01-02T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -689,20 +693,20 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
update_option( 'start_of_week', 7 );
$settings = array(
'2010-12-25T10:00:00Z' => array(
0 => '2010-12-26T00:00:00Z',
1 => '2010-12-18T23:59:59Z',
0 => '2010-12-26T00:00:00',
1 => '2010-12-18T23:59:59',
),
'2010-12-26T10:00:00Z' => array(
0 => '2011-01-01T00:00:00Z',
1 => '2010-12-25T23:59:59Z',
0 => '2011-01-01T00:00:00',
1 => '2010-12-25T23:59:59',
),
'2011-01-01T00:00:00Z' => array(
0 => '2011-01-02T00:00:00Z',
1 => '2010-12-31T23:59:59Z',
0 => '2011-01-02T00:00:00',
1 => '2010-12-31T23:59:59',
),
'2011-01-02T00:00:00Z' => array(
0 => '2011-01-09T00:00:00Z',
1 => '2011-01-01T23:59:59Z',
0 => '2011-01-09T00:00:00',
1 => '2011-01-01T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -720,13 +724,13 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
public function test_next_month_start() {
$settings = array(
'2017-12-30T00:00:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2017-11-30T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2017-11-30T23:59:59',
),
// Leap year reversed test.
'2016-03-05T10:00:00Z' => array(
0 => '2016-04-01T00:00:00Z',
1 => '2016-02-29T23:59:59Z',
0 => '2016-04-01T00:00:00',
1 => '2016-02-29T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -744,16 +748,16 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
public function test_next_quarter_start() {
$settings = array(
'2017-12-31T00:00:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2017-09-30T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2017-09-30T23:59:59',
),
'2018-01-01T10:00:00Z' => array(
0 => '2018-04-01T00:00:00Z',
1 => '2017-12-31T23:59:59Z',
0 => '2018-04-01T00:00:00',
1 => '2017-12-31T23:59:59',
),
'2018-02-14T10:00:00Z' => array(
0 => '2018-04-01T00:00:00Z',
1 => '2017-12-31T23:59:59Z',
0 => '2018-04-01T00:00:00',
1 => '2017-12-31T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {
@ -771,16 +775,16 @@ class WC_Tests_Reports_Interval_Stats extends WC_Unit_Test_Case {
public function test_next_year_start() {
$settings = array(
'2017-12-31T23:59:59Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2016-12-31T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2016-12-31T23:59:59',
),
'2017-01-01T00:00:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2016-12-31T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2016-12-31T23:59:59',
),
'2017-04-23T14:53:00Z' => array(
0 => '2018-01-01T00:00:00Z',
1 => '2016-12-31T23:59:59Z',
0 => '2018-01-01T00:00:00',
1 => '2016-12-31T23:59:59',
),
);
foreach ( $settings as $datetime_s => $setting ) {

View File

@ -1,4 +1,9 @@
<?php
/**
* Helper code for wc-admin unit tests.
*
* @package WooCommerce\Tests\Framework\Helpers
*/
/**
* Class WC_Helper_Reports.
@ -14,5 +19,6 @@ class WC_Helper_Reports {
global $wpdb;
$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.
}
}

View File

@ -0,0 +1,100 @@
<?php
/**
* Reports coupons stats tests.
*
* @package WooCommerce\Tests\Coupons-stats
*/
/**
* Class WC_Tests_Reports_Coupons_Stats
*/
class WC_Tests_Reports_Coupons_Stats extends WC_Unit_Test_Case {
/**
* Test the for the basic cases.
*/
public function test_populate_and_query() {
WC_Helper_Reports::reset_stats_dbs();
// Simple product.
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_regular_price( 25 );
$product->save();
// Coupons.
$coupon_1_amount = 3; // by default in create_coupon.
$coupon_1 = WC_Helper_Coupon::create_coupon( 'coupon_1' );
$coupon_1->set_amount( $coupon_1_amount );
$coupon_1->save();
$coupon_2_amount = 7;
$coupon_2 = WC_Helper_Coupon::create_coupon( 'coupon_2' );
$coupon_2->set_amount( $coupon_2_amount );
$coupon_2->save();
// Order without coupon.
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 ); // $25 x 4.
$order->save();
// Order with 1 coupon.
$order_1c = WC_Helper_Order::create_order( 1, $product );
$order_1c->set_status( 'completed' );
$order_1c->apply_coupon( $coupon_1 );
$order_1c->calculate_totals();
$order_1c->save();
// Order with 2 coupons.
$order_2c = WC_Helper_Order::create_order( 1, $product );
$order_2c->set_status( 'completed' );
$order_2c->apply_coupon( $coupon_1 );
$order_2c->apply_coupon( $coupon_2 );
$order_2c->calculate_totals();
$order_2c->save();
$data_store = new WC_Admin_Reports_Coupons_Stats_Data_Store();
$start_time = date( 'Y-m-d 00:00:00', $order->get_date_created()->getOffsetTimestamp() );
$end_time = date( 'Y-m-d 23:59:59', $order->get_date_created()->getOffsetTimestamp() );
$args = array(
'after' => $start_time,
'before' => $end_time,
'interval' => 'day',
);
// Test retrieving the stats through the data store.
$start_datetime = new DateTime( $start_time );
$end_datetime = new DateTime( $end_time );
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 1,
'pages' => 1,
'page_no' => 1,
'totals' => (object) array(
'amount' => 2 * $coupon_1_amount + $coupon_2_amount,
'coupons_count' => 2,
'orders_count' => 2,
),
'intervals' => array(
array(
'interval' => $start_datetime->format( 'Y-m-d' ),
'date_start' => $start_datetime->format( 'Y-m-d H:i:s' ),
'date_start_gmt' => $start_datetime->format( 'Y-m-d H:i:s' ),
'date_end' => $end_datetime->format( 'Y-m-d H:i:s' ),
'date_end_gmt' => $end_datetime->format( 'Y-m-d H:i:s' ),
'subtotals' => (object) array(
'amount' => 2 * $coupon_1_amount + $coupon_2_amount,
'coupons_count' => 2,
'orders_count' => 2,
),
),
),
);
$this->assertEquals( $expected_data, $data );
// Test retrieving the stats through the query class.
$query = new WC_Admin_Reports_Coupons_Stats_Query( $args );
$this->assertEquals( $expected_data, $query->get_data() );
}
}

View File

@ -0,0 +1,269 @@
<?php
/**
* Reports coupons tests.
*
* @package WooCommerce\Tests\Coupons
*/
/**
* Class WC_Tests_Reports_Coupons
*/
class WC_Tests_Reports_Coupons extends WC_Unit_Test_Case {
/**
* Test the calculations and querying works correctly for the base case of 1 product.
*/
public function test_populate_and_query() {
WC_Helper_Reports::reset_stats_dbs();
// Simple product.
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_regular_price( 25 );
$product->save();
// Coupons.
$coupon_1_amount = 3; // by default in create_coupon.
$coupon_1 = WC_Helper_Coupon::create_coupon( 'coupon_1' );
$coupon_1->set_amount( $coupon_1_amount );
$coupon_1->save();
$coupon_2_amount = 7;
$coupon_2 = WC_Helper_Coupon::create_coupon( 'coupon_2' );
$coupon_2->set_amount( $coupon_2_amount );
$coupon_2->save();
// Order without coupon.
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 ); // $25 x 4.
$order->save();
// Order with 1 coupon.
$order_1c = WC_Helper_Order::create_order( 1, $product );
$order_1c->set_status( 'completed' );
$order_1c->apply_coupon( $coupon_1 );
$order_1c->calculate_totals();
$order_1c->save();
// Order with 2 coupons.
$order_2c = WC_Helper_Order::create_order( 1, $product );
$order_2c->set_status( 'completed' );
$order_2c->apply_coupon( $coupon_1 );
$order_2c->apply_coupon( $coupon_2 );
$order_2c->calculate_totals();
$order_2c->save();
$data_store = new WC_Admin_Reports_Coupons_Data_Store();
$start_time = date( 'Y-m-d 00:00:00', $order->get_date_created()->getOffsetTimestamp() );
$end_time = date( 'Y-m-d 23:59:59', $order->get_date_created()->getOffsetTimestamp() );
$args = array(
'after' => $start_time,
'before' => $end_time,
);
// Test retrieving the stats through the data store.
$coupon_1_response = array(
'coupon_id' => $coupon_1->get_id(),
'amount' => floatval( $coupon_1_amount * 2 ),
'orders_count' => 2,
'extended_info' => new ArrayObject(),
);
$coupon_2_response = array(
'coupon_id' => $coupon_2->get_id(),
'amount' => floatval( $coupon_2_amount ),
'orders_count' => 1,
'extended_info' => new ArrayObject(),
);
// Order by coupon id DESC is the default.
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 2,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_2_response,
1 => $coupon_1_response,
),
);
$this->assertEquals( $expected_data, $data );
// Test retrieving the stats through the query class.
$query = new WC_Admin_Reports_Coupons_Query( $args );
$this->assertEquals( $expected_data, $query->get_data() );
// Test order by orders_count DESC.
$args = array(
'after' => $start_time,
'before' => $end_time,
'orderby' => 'orders_count',
'order' => 'desc',
);
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 2,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_1_response,
1 => $coupon_2_response,
),
);
$this->assertEquals( $expected_data, $data );
// Test order by amount ASC.
$args = array(
'after' => $start_time,
'before' => $end_time,
'orderby' => 'amount',
'order' => 'asc',
);
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 2,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_1_response,
1 => $coupon_2_response,
),
);
$this->assertEquals( $expected_data, $data );
// Test filtering by coupon id: coupon_1.
$args = array(
'after' => $start_time,
'before' => $end_time,
'coupons' => array( $coupon_1->get_id() ),
);
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 1,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_1_response,
),
);
$this->assertEquals( $expected_data, $data );
// Test filtering by coupon id: coupon_1 & coupon_2.
$args = array(
'after' => $start_time,
'before' => $end_time,
'coupons' => array( $coupon_1->get_id(), $coupon_2->get_id() ),
);
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 2,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_2_response,
1 => $coupon_1_response,
),
);
$this->assertEquals( $expected_data, $data );
// Test extended info.
$gmt_timezone = new DateTimeZone( 'UTC' );
$c1_date_created = $coupon_1->get_date_created();
if ( null === $c1_date_created ) {
$c1_date_created = '';
$c1_date_created_gmt = '';
} else {
$c1_date_created_gmt = new DateTime( $c1_date_created );
$c1_date_created_gmt->setTimezone( $gmt_timezone );
$c1_date_created = $c1_date_created->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$c1_date_created_gmt = $c1_date_created_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$c1_date_expires = $coupon_1->get_date_expires();
if ( null === $c1_date_expires ) {
$c1_date_expires = '';
$c1_date_expires_gmt = '';
} else {
$c1_date_expires_gmt = new DateTime( $c1_date_expires );
$c1_date_expires_gmt->setTimezone( $gmt_timezone );
$c1_date_expires = $c1_date_expires->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$c1_date_expires_gmt = $c1_date_expires_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$coupon_1_response = array(
'coupon_id' => $coupon_1->get_id(),
'amount' => $coupon_1_amount * 2,
'orders_count' => 2,
'extended_info' => array(
'code' => $coupon_1->get_code(),
'date_created' => $c1_date_created,
'date_created_gmt' => $c1_date_created_gmt,
'date_expires' => $c1_date_expires,
'date_expires_gmt' => $c1_date_expires_gmt,
'discount_type' => $coupon_1->get_discount_type(),
),
);
$c2_date_created = $coupon_2->get_date_created();
if ( null === $c2_date_created ) {
$c2_date_created = '';
$c2_date_created_gmt = '';
} else {
$c2_date_created_gmt = new DateTime( $c2_date_created );
$c2_date_created_gmt->setTimezone( $gmt_timezone );
$c2_date_created = $c2_date_created->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$c2_date_created_gmt = $c2_date_created_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$c2_date_expires = $coupon_2->get_date_expires();
if ( null === $c2_date_expires ) {
$c2_date_expires = '';
$c2_date_expires_gmt = '';
} else {
$c2_date_expires_gmt = new DateTime( $c2_date_expires );
$c2_date_expires_gmt->setTimezone( $gmt_timezone );
$c2_date_expires = $c2_date_expires->format( WC_Admin_Reports_Interval::$iso_datetime_format );
$c2_date_expires_gmt = $c2_date_expires_gmt->format( WC_Admin_Reports_Interval::$iso_datetime_format );
}
$coupon_2_response = array(
'coupon_id' => $coupon_2->get_id(),
'amount' => $coupon_2_amount,
'orders_count' => 1,
'extended_info' => array(
'code' => $coupon_2->get_code(),
'date_created' => $c2_date_created,
'date_created_gmt' => $c2_date_created_gmt,
'date_expires' => $c2_date_expires,
'date_expires_gmt' => $c2_date_expires_gmt,
'discount_type' => $coupon_2->get_discount_type(),
),
);
$args = array(
'after' => $start_time,
'before' => $end_time,
'extended_info' => true,
);
$data = $data_store->get_data( $args );
$expected_data = (object) array(
'total' => 2,
'pages' => 1,
'page_no' => 1,
'data' => array(
0 => $coupon_2_response,
1 => $coupon_1_response,
),
);
$this->assertEquals( $expected_data, $data );
}
}