* Add taxes endpoint and data store

* Add sorting options and normalize orderby param

* Add report taxes unit tests

* Add tax rate to response

* Add country, state, priority, and name to response

* Fix tax codes query param

* Add class comment

* Add missing  to record query

* Add comment about ambiguous column
This commit is contained in:
Joshua T Flowers 2018-12-11 08:58:05 +08:00 committed by GitHub
parent 557cec57cb
commit 04d3ce6eb1
5 changed files with 504 additions and 34 deletions

View File

@ -31,6 +31,25 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
*/
protected $rest_base = 'reports/taxes';
/**
* 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['page'] = $request['page'];
$args['per_page'] = $request['per_page'];
$args['orderby'] = $request['orderby'];
$args['order'] = $request['order'];
$args['taxes'] = $request['taxes'];
return $args;
}
/**
* Get all reports.
*
@ -39,20 +58,17 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
*/
public function get_items( $request ) {
$query_args = $this->prepare_reports_query( $request );
$taxes_query = new WC_Reports_Orders_Stats_Query( $query_args ); // @todo change to correct class.
$taxes_query = new WC_Admin_Reports_Taxes_Query( $query_args );
$report_data = $taxes_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 $tax_data ) {
$item = $this->prepare_item_for_response( (object) $tax_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 );
@ -84,14 +100,12 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
* @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 );
$report = $this->add_additional_fields_to_object( $report, $request );
$report = $this->filter_response_by_context( $report, $context );
// Wrap the data in a response object.
$response = rest_ensure_response( $data );
$response = rest_ensure_response( $report );
$response->add_links( $this->prepare_links( $report ) );
/**
@ -115,7 +129,7 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
protected function prepare_links( $object ) {
$links = array(
'tax' => array(
'href' => rest_url( sprintf( '/%s/taxes/%d', $this->namespace, $object->category_id ) ),
'href' => rest_url( sprintf( '/%s/taxes/%d', $this->namespace, $object->tax_rate_id ) ),
),
);
@ -139,6 +153,36 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'Tax rate name.', 'wc-admin' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'tax_rate' => array(
'description' => __( 'Tax rate.', 'wc-admin' ),
'type' => 'number',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'country' => array(
'description' => __( 'Country.', 'wc-admin' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'state' => array(
'description' => __( 'State.', 'wc-admin' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'priority' => array(
'description' => __( 'Priority.', 'wc-admin' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'total_tax' => array(
'description' => __( 'Total tax.', 'wc-admin' ),
'type' => 'number',
@ -216,33 +260,22 @@ class WC_Admin_REST_Reports_Taxes_Controller extends WC_REST_Reports_Controller
$params['orderby'] = array(
'description' => __( 'Sort collection by object attribute.', 'wc-admin' ),
'type' => 'string',
'default' => 'date',
'default' => 'tax_rate_id',
'enum' => array(
'date',
'name',
'tax_rate_id',
'rate',
'order_tax',
'total_tax',
'shipping_tax',
'orders_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['code'] = array(
'description' => __( 'Limit result set to items assigned one or more code.', 'wc-admin' ),
$params['taxes'] = array(
'description' => __( 'Limit result set to items assigned one or more tax rates.', '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',

View File

@ -49,6 +49,7 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-variations-query.php';
require_once dirname( __FILE__ ) . '/class-wc-admin-reports-products-stats-query.php';
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';
// Data stores.
@ -58,6 +59,7 @@ class WC_Admin_Api_Init {
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-variations-data-store.php';
require_once dirname( __FILE__ ) . '/data-stores/class-wc-admin-reports-products-stats-data-store.php';
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';
// Data triggers.
@ -266,6 +268,7 @@ class WC_Admin_Api_Init {
'report-variations' => 'WC_Admin_Reports_Variations_Data_Store',
'report-products-stats' => 'WC_Admin_Reports_Products_Stats_Data_Store',
'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',
'admin-note' => 'WC_Admin_Notes_Data_Store',
)

View File

@ -0,0 +1,47 @@
<?php
/**
* Class for parameter-based Taxes Report querying
*
* Example usage:
* $args = array(
* 'before' => '2018-07-19 00:00:00',
* 'after' => '2018-07-05 00:00:00',
* 'page' => 2,
* 'taxes' => array(1,2,3)
* );
* $report = new WC_Admin_Reports_Taxes_Query( $args );
* $mydata = $report->get_data();
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Taxes_Query
*/
class WC_Admin_Reports_Taxes_Query extends WC_Admin_Reports_Query {
/**
* Valid fields for Taxes 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_taxes_query_args', $this->get_query_vars() );
$data_store = WC_Data_Store::load( 'report-taxes' );
$results = $data_store->get_data( $args );
return apply_filters( 'woocommerce_reports_taxes_select_query', $results, $args );
}
}

View File

@ -0,0 +1,238 @@
<?php
/**
* WC_Admin_Reports_Taxes_Data_Store class file.
*
* @package WooCommerce Admin/Classes
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Admin_Reports_Taxes_Data_Store.
*/
class WC_Admin_Reports_Taxes_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_tax_lookup';
/**
* Mapping columns to data type to return correct response types.
*
* @var array
*/
protected $column_types = array(
'tax_rate_id' => 'intval',
'name' => 'strval',
'tax_rate' => 'floatval',
'country' => 'strval',
'state' => 'strval',
'priority' => 'intval',
'total_tax' => 'floatval',
'order_tax' => 'floatval',
'shipping_tax' => 'floatval',
'orders_count' => 'intval',
);
/**
* SQL columns to select in the db query and their mapping to SQL code.
*
* @var array
*/
protected $report_columns = array(
'tax_rate_id' => 'tax_rate_id',
'name' => 'tax_rate_name as name',
'tax_rate' => 'tax_rate',
'country' => 'tax_rate_country as country',
'state' => 'tax_rate_state as state',
'priority' => 'tax_rate_priority as priority',
'total_tax' => 'SUM(total_tax) as total_tax',
'order_tax' => 'SUM(order_tax) as order_tax',
'shipping_tax' => 'SUM(shipping_tax) as shipping_tax',
'orders_count' => 'COUNT(DISTINCT order_id) as orders_count',
);
/**
* Constructor
*/
public function __construct() {
global $wpdb;
$table_name = $wpdb->prefix . self::TABLE_NAME;
// Avoid ambigious column tax_rate_id in SQL query.
$this->report_columns['tax_rate_id'] = $table_name . '.' . $this->report_columns['tax_rate_id'];
}
/**
* Updates the database query with parameters used for Taxes 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_tax_lookup_table = $wpdb->prefix . self::TABLE_NAME;
$sql_query_params = $this->get_time_period_sql_params( $query_args, $order_tax_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 ) );
if ( isset( $query_args['taxes'] ) && ! empty( $query_args['taxes'] ) ) {
$allowed_taxes = implode( ',', $query_args['taxes'] );
$sql_query_params['where_clause'] .= " AND {$order_tax_lookup_table}.tax_rate_id IN ({$allowed_taxes})";
}
$sql_query_params['from_clause'] .= " JOIN {$wpdb->prefix}woocommerce_tax_rates ON {$order_tax_lookup_table}.tax_rate_id = {$wpdb->prefix}woocommerce_tax_rates.tax_rate_id";
return $sql_query_params;
}
/**
* 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;
}
/**
* 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' => 'tax_rate_id',
'before' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $now ),
'after' => date( WC_Admin_Reports_Interval::$iso_datetime_format, $week_back ),
'fields' => '*',
'taxes' => array(),
);
$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
{$table_name}.tax_rate_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
{$table_name}.tax_rate_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;
}
$tax_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
{$table_name}.tax_rate_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 === $tax_data ) {
return $data;
}
$tax_data = array_map( array( $this, 'cast_numbers' ), $tax_data );
$data = (object) array(
'data' => $tax_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 ) );
}
/**
* 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 ) {
global $wpdb;
if ( 'rate' === $order_by ) {
return $wpdb->prefix . 'woocommerce_tax_rates.tax_rate';
}
return $order_by;
}
}

View File

@ -0,0 +1,149 @@
<?php
/**
* Reports Taxes REST API Test
*
* @package WooCommerce\Tests\API
* @since 3.5.0
*/
/**
* WC_Tests_API_Reports_Taxes
*/
class WC_Tests_API_Reports_Taxes extends WC_REST_Unit_Test_Case {
/**
* Endpoints.
*
* @var string
*/
protected $endpoint = '/wc/v3/reports/taxes';
/**
* Setup test reports taxes 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 );
}
/**
* Test getting reports.
*
* @since 3.5.0
*/
public function test_get_reports() {
global $wpdb;
wp_set_current_user( $this->user );
WC_Helper_Reports::reset_stats_dbs();
// Populate all of the data.
$product = new WC_Product_Simple();
$product->set_name( 'Test Product' );
$product->set_regular_price( 25 );
$product->save();
$wpdb->insert(
$wpdb->prefix . 'woocommerce_tax_rates',
array(
'tax_rate_id' => 1,
'tax_rate' => '7',
'tax_rate_country' => 'US',
'tax_rate_state' => 'GA',
'tax_rate_name' => 'TestTax',
'tax_rate_priority' => 1,
'tax_rate_order' => 1,
)
);
$order = WC_Helper_Order::create_order( 1, $product );
$order->set_status( 'completed' );
$order->set_total( 100 ); // $25 x 4.
$order->save();
// @todo Remove this once order data is synced to wc_order_tax_lookup
$wpdb->insert(
$wpdb->prefix . 'wc_order_tax_lookup',
array(
'order_id' => 1,
'tax_rate_id' => 1,
'date_created' => date( 'Y-m-d H:i:s' ),
'shipping_tax' => 2,
'order_tax' => 5,
'total_tax' => 7,
)
);
$response = $this->server->dispatch( new WP_REST_Request( 'GET', $this->endpoint ) );
$reports = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( 1, count( $reports ) );
$tax_report = reset( $reports );
$this->assertEquals( 1, $tax_report['tax_rate_id'] );
$this->assertEquals( 'TestTax', $tax_report['name'] );
$this->assertEquals( 7, $tax_report['tax_rate'] );
$this->assertEquals( 'US', $tax_report['country'] );
$this->assertEquals( 'GA', $tax_report['state'] );
$this->assertEquals( 7, $tax_report['total_tax'] );
$this->assertEquals( 5, $tax_report['order_tax'] );
$this->assertEquals( 2, $tax_report['shipping_tax'] );
$this->assertEquals( 1, $tax_report['orders_count'] );
}
/**
* 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 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->assertEquals( 10, count( $properties ) );
$this->assertArrayHasKey( 'tax_rate_id', $properties );
$this->assertArrayHasKey( 'name', $properties );
$this->assertArrayHasKey( 'tax_rate', $properties );
$this->assertArrayHasKey( 'country', $properties );
$this->assertArrayHasKey( 'state', $properties );
$this->assertArrayHasKey( 'priority', $properties );
$this->assertArrayHasKey( 'total_tax', $properties );
$this->assertArrayHasKey( 'order_tax', $properties );
$this->assertArrayHasKey( 'shipping_tax', $properties );
$this->assertArrayHasKey( 'orders_count', $properties );
}
}