Add `reports/downloads/stats` REST API Endpoint (https://github.com/woocommerce/woocommerce-admin/pull/1142)

* First pass at downloads REST API

* Add reports/downloads/stats endpoint.

* Add tests

* Update cache key
This commit is contained in:
Justin Shreve 2019-01-03 13:00:48 -05:00 committed by GitHub
parent f5e2c8c5f9
commit e3e9ccb6a4
8 changed files with 819 additions and 5 deletions

View File

@ -292,7 +292,6 @@ class WC_Admin_REST_Reports_Downloads_Controller extends WC_REST_Reports_Control
'default' => array(),
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
);
$params['product_excludes'] = array(
'description' => __( 'Limit result set to items that don\'t have the specified product(s) assigned.', 'wc-admin' ),

View File

@ -30,4 +30,340 @@ class WC_Admin_REST_Reports_Downloads_Stats_Controller extends WC_REST_Reports_C
* @var string
*/
protected $rest_base = 'reports/downloads/stats';
/**
* Maps query arguments from the REST request.
*
* @param array $request Request array.
* @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['match'] = $request['match'];
$args['product_includes'] = (array) $request['product_includes'];
$args['product_excludes'] = (array) $request['product_excludes'];
$args['order_includes'] = (array) $request['order_includes'];
$args['order_excludes'] = (array) $request['order_excludes'];
$args['ip_address_includes'] = (array) $request['ip_address_includes'];
$args['ip_address_excludes'] = (array) $request['ip_address_excludes'];
return $args;
}
/**
* Get all reports.
*
* @param WP_REST_Request $request Request data.
* @return array|WP_Error
*/
public function get_items( $request ) {
$query_args = $this->prepare_reports_query( $request );
$downloads_query = new WC_Admin_Reports_Downloads_Stats_Query( $query_args );
$report_data = $downloads_query->get_data();
$out_data = array(
'totals' => get_object_vars( $report_data->totals ),
'intervals' => array(),
);
foreach ( $report_data->intervals as $interval_data ) {
$item = $this->prepare_item_for_response( $interval_data, $request );
$out_data['intervals'][] = $this->prepare_response_for_collection( $item );
}
$response = rest_ensure_response( $out_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 ) ) );
if ( $page > 1 ) {
$prev_page = $page - 1;
if ( $prev_page > $max_pages ) {
$prev_page = $max_pages;
}
$prev_link = add_query_arg( 'page', $prev_page, $base );
$response->link_header( 'prev', $prev_link );
}
if ( $max_pages > $page ) {
$next_page = $page + 1;
$next_link = add_query_arg( 'page', $next_page, $base );
$response->link_header( 'next', $next_link );
}
return $response;
}
/**
* Prepare a report object for serialization.
*
* @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 = $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 );
// Wrap the data in a response object.
$response = rest_ensure_response( $data );
/**
* Filter a report returned from the API.
*
* Allows modification of the report data right before it is returned.
*
* @param WP_REST_Response $response The response object.
* @param object $report The original report object.
* @param WP_REST_Request $request Request used to generate the response.
*/
return apply_filters( 'woocommerce_rest_prepare_report_downloads_stats', $response, $report, $request );
}
/**
* Get the Report's schema, conforming to JSON Schema.
*
* @return array
*/
public function get_item_schema() {
$totals = array(
'downloads_count' => array(
'description' => __( 'Number of downloads.', 'wc-admin' ),
'type' => 'number',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
);
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'report_orders_stats',
'type' => 'object',
'properties' => array(
'totals' => array(
'description' => __( 'Totals data.', 'wc-admin' ),
'type' => 'object',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'properties' => $totals,
),
'intervals' => array(
'description' => __( 'Reports data grouped by intervals.', 'wc-admin' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'items' => array(
'type' => 'object',
'properties' => array(
'interval' => array(
'description' => __( 'Type of interval.', 'wc-admin' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'enum' => array( 'day', 'week', 'month', 'year' ),
),
'date_start' => array(
'description' => __( "The date the report start, in the site's timezone.", 'wc-admin' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'date_start_gmt' => array(
'description' => __( 'The date the report start, as GMT.', 'wc-admin' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'date_end' => array(
'description' => __( "The date the report end, in the site's timezone.", 'wc-admin' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'date_end_gmt' => array(
'description' => __( 'The date the report end, as GMT.', 'wc-admin' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'subtotals' => array(
'description' => __( 'Interval subtotals.', 'wc-admin' ),
'type' => 'object',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'properties' => $totals,
),
),
),
),
),
);
return $this->add_additional_fields_schema( $schema );
}
/**
* Get the query params for collections.
*
* @return array
*/
public function get_collection_params() {
$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,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
'minimum' => 1,
);
$params['per_page'] = array(
'description' => __( 'Maximum number of items to be returned in result set.', 'wc-admin' ),
'type' => 'integer',
'default' => 10,
'minimum' => 1,
'maximum' => 100,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
$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(
'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(
'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',
'enum' => array(
'date',
'downloads_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['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['product_includes'] = array(
'description' => __( 'Limit result set to items that have the specified product(s) assigned.', 'wc-admin' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
'sanitize_callback' => 'wp_parse_id_list',
);
$params['product_excludes'] = array(
'description' => __( 'Limit result set to items that don\'t have the specified product(s) assigned.', 'wc-admin' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
'sanitize_callback' => 'wp_parse_id_list',
);
$params['order_includes'] = array(
'description' => __( 'Limit result set to items that have the specified order ids.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'integer',
),
);
$params['order_excludes'] = array(
'description' => __( 'Limit result set to items that don\'t have the specified order ids.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'integer',
),
);
$params['user_includes'] = array(
'description' => __( 'Limit response to objects that have the specified user ids.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'integer',
),
);
$params['user_excludes'] = array(
'description' => __( 'Limit response to objects that don\'t have the specified user ids.', 'wc-admin' ),
'type' => 'array',
'sanitize_callback' => 'wp_parse_id_list',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'integer',
),
);
$params['ip_address_includes'] = array(
'description' => __( 'Limit response to objects that have a specified ip address.', 'wc-admin' ),
'type' => 'array',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'string',
),
);
$params['ip_address_excludes'] = array(
'description' => __( 'Limit response to objects that don\'t have a specified ip address.', 'wc-admin' ),
'type' => 'array',
'validate_callback' => 'rest_validate_request_arg',
'items' => array(
'type' => 'string',
),
);
return $params;
}
}

View File

@ -54,6 +54,7 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-coupons-query.php';
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';
// Data stores.
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-data-store.php';
@ -67,6 +68,7 @@ class WC_Admin_Api_Init {
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';
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';
// Data triggers.
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-notes-data-store.php';
@ -104,7 +106,6 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-taxes-controller.php';
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-taxes-stats-controller.php';
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-stock-controller.php';
require_once dirname( __FILE__ ) . '/api/class-wc-admin-rest-reports-downloads-controller.php';
$controllers = array(
'WC_Admin_REST_Admin_Notes_Controller',
@ -128,6 +129,7 @@ class WC_Admin_Api_Init {
'WC_Admin_REST_Reports_Coupons_Stats_Controller',
'WC_Admin_REST_Reports_Stock_Controller',
'WC_Admin_REST_Reports_Downloads_Controller',
'WC_Admin_REST_Reports_Downloads_Stats_Controller',
);
foreach ( $controllers as $controller ) {
@ -349,6 +351,7 @@ class WC_Admin_Api_Init {
'report-coupons' => 'WC_Admin_Reports_Coupons_Data_Store',
'report-coupons-stats' => 'WC_Admin_Reports_Coupons_Stats_Data_Store',
'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',
)
);

View File

@ -0,0 +1,37 @@
<?php
/**
* Class for parameter-based downloads Reports querying
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Downloads_Stats_Query
*/
class WC_Admin_Reports_Downloads_Stats_Query extends WC_Admin_Reports_Query {
/**
* Valid fields for Orders report.
*
* @return array
*/
protected function get_default_query_vars() {
return array();
}
/**
* Get revenue data based on the current query vars.
*
* @return array
*/
public function get_data() {
$args = apply_filters( 'woocommerce_reports_downloads_stats_query_args', $this->get_query_vars() );
$data_store = WC_Data_Store::load( 'report-downloads-stats' );
$results = $data_store->get_data( $args );
return apply_filters( 'woocommerce_reports_downloads_stats_select_query', $results, $args );
}
}

View File

@ -180,6 +180,71 @@ class WC_Admin_Reports_Data_Store {
$data->intervals = array_slice( $data->intervals, $offset, $count );
}
/**
* 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 LIMIT query part for Intervals query of the report.
*

View File

@ -0,0 +1,218 @@
<?php
/**
* WC_Admin_Reports_Downloads_Data_Store class file.
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Downloads_Data_Store.
*/
class WC_Admin_Reports_Downloads_Stats_Data_Store extends WC_Admin_Reports_Downloads_Data_Store implements WC_Admin_Reports_Data_Store_Interface {
/**
* SQL columns to select in the db query and their mapping to SQL code.
*
* @var array
*/
protected $report_columns = array(
'download_count' => 'COUNT(DISTINCT download_log_id) as download_count',
);
/**
* Constructor
*/
public function __construct() {
global $wpdb;
}
/**
* 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' => 'date',
'fields' => '*',
'interval' => 'week',
);
$query_args = wp_parse_args( $query_args, $defaults );
if ( empty( $query_args['before'] ) ) {
$query_args['before'] = date( WC_Admin_Reports_Interval::$iso_datetime_format, $now );
}
if ( empty( $query_args['after'] ) ) {
$query_args['after'] = date( WC_Admin_Reports_Interval::$iso_datetime_format, $week_back );
}
$cache_key = $this->get_cache_key( $query_args );
$data = wp_cache_get( $cache_key, $this->cache_group );
if ( false === $data ) {
$selections = $this->selected_columns( $query_args );
$sql_query_params = $this->get_sql_query_params( $query_args );
$totals_query = array_merge( array(), $this->get_time_period_sql_params( $query_args, $table_name ) );
$intervals_query = array_merge( array(), $this->get_intervals_sql_params( $query_args, $table_name ) );
$totals_query['where_clause'] .= $sql_query_params['where_clause'];
$totals_query['from_clause'] .= $sql_query_params['from_clause'];
$intervals_query['where_clause'] .= $sql_query_params['where_clause'];
$intervals_query['from_clause'] .= $sql_query_params['from_clause'];
$intervals_query['select_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['select_clause'] );
$intervals_query['where_time_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['where_time_clause'] );
$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_records_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 array();
}
$this->update_intervals_sql_params( $intervals_query, $query_args, $db_records_count, $expected_interval_count );
$intervals_query['where_time_clause'] = str_replace( 'date_created', 'timestamp', $intervals_query['where_time_clause'] );
$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 new WP_Error( 'woocommerce_reports_downloads_stats_result_failed', __( 'Sorry, fetching downloads data failed.', 'wc-admin' ) );
}
if ( '' !== $selections ) {
$selections = ', ' . $selections;
}
$intervals = $wpdb->get_results(
"SELECT
MAX(timestamp) 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 new WP_Error( 'woocommerce_reports_downloads_stats_result_failed', __( 'Sorry, fetching downloads data failed.', 'wc-admin' ) );
}
$totals = (object) $this->cast_numbers( $totals[0] );
$data = (object) array(
'totals' => $totals,
'intervals' => $intervals,
'total' => $expected_interval_count,
'pages' => $total_pages,
'page_no' => (int) $query_args['page'],
);
if ( $this->intervals_missing( $expected_interval_count, $db_records_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_records_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 ) );
}
/**
* Sorts intervals according to user's request.
*
* They are pre-sorted in SQL, but after adding gaps, they need to be sorted including the added ones.
*
* @param stdClass $data Data object, must contain an array under $data->intervals.
* @param string $sort_by Ordering property.
* @param string $direction DESC/ASC.
*/
protected function sort_intervals( &$data, $sort_by, $direction ) {
$this->order_by = 'time_interval';
$this->order = $direction;
usort( $data->intervals, array( $this, 'interval_cmp' ) );
}
/**
* Compares two report data objects by pre-defined object property and ASC/DESC ordering.
*
* @param stdClass $a Object a.
* @param stdClass $b Object b.
* @return string
*/
protected function interval_cmp( $a, $b ) {
if ( '' === $this->order_by || '' === $this->order ) {
return 0;
}
if ( $a[ $this->order_by ] === $b[ $this->order_by ] ) {
return 0;
} elseif ( $a[ $this->order_by ] > $b[ $this->order_by ] ) {
return strtolower( $this->order ) === 'desc' ? -1 : 1;
} elseif ( $a[ $this->order_by ] < $b[ $this->order_by ] ) {
return strtolower( $this->order ) === 'desc' ? 1 : -1;
}
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* Reports Downloads Stats REST API Test
*
* @package WooCommerce Admin\Tests\API.
*/
/**
* WC_Tests_API_Reports_Downloads_Stats
*/
class WC_Tests_API_Reports_Downloads_Stats extends WC_REST_Unit_Test_Case {
/**
* Endpoints.
*
* @var string
*/
protected $endpoint = '/wc/v3/reports/downloads/stats';
/**
* Setup test reports downloads 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 report.
*/
public function test_get_report() {
global $wpdb;
wp_set_current_user( $this->user );
WC_Helper_Reports::reset_stats_dbs();
// Populate all of the data.
$prod_download = new WC_Product_Download();
$prod_download->set_file( plugin_dir_url( __FILE__ ) . '/assets/images/help.png' );
$prod_download->set_id( 1 );
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_downloadable( 'yes' );
$product->set_downloads( array( $prod_download ) );
$product->set_regular_price( 25 );
$product->save();
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 );
$order->save();
$download = new WC_Customer_Download();
$download->set_user_id( $this->user );
$download->set_order_id( $order->get_id() );
$download->set_product_id( $product->get_id() );
$download->set_download_id( $prod_download->get_id() );
$download->save();
$object = new WC_Customer_Download_Log();
$object->set_permission_id( $download->get_id() );
$object->set_user_id( $this->user );
$object->set_user_ip_address( '1.2.3.4' );
$id = $object->save();
$time = time();
$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 H:00:00', $time - ( 7 * DAY_IN_SECONDS ) ),
'interval' => 'day',
)
);
$response = $this->server->dispatch( $request );
$reports = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$totals = array(
'download_count' => 1,
);
$this->assertEquals( $totals, $reports['totals'] );
$today_interval = 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(
'download_count' => 1,
),
);
$this->assertEquals( $today_interval, $reports['intervals'][0] );
$this->assertEquals( 8, count( $reports['intervals'] ) );
$this->assertEquals( 0, $reports['intervals'][1]['subtotals']->download_count );
}
/**
* 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( 1, count( $totals ) );
$this->assertArrayHasKey( 'downloads_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( 1, count( $subtotals ) );
$this->assertArrayHasKey( 'downloads_count', $subtotals );
}
}

View File

@ -156,8 +156,8 @@ class WC_Tests_API_Reports_Products_Stats extends WC_REST_Unit_Test_Case {
$subtotals = $properties['intervals']['items']['properties']['subtotals']['properties'];
$this->assertEquals( 3, count( $subtotals ) );
$this->assertArrayHasKey( 'net_revenue', $totals );
$this->assertArrayHasKey( 'items_sold', $totals );
$this->assertArrayHasKey( 'orders_count', $totals );
$this->assertArrayHasKey( 'net_revenue', $subtotals );
$this->assertArrayHasKey( 'items_sold', $subtotals );
$this->assertArrayHasKey( 'orders_count', $subtotals );
}
}