woocommerce/includes/legacy/api/v2/class-wc-api-reports.php

330 lines
9.6 KiB
PHP
Raw Normal View History

<?php
/**
* WooCommerce API Reports Class
*
* Handles requests to the /reports endpoint
*
* @author WooThemes
* @category API
* @package WooCommerce\RestApi
* @since 2.1
*/
2014-09-20 19:24:20 +00:00
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
2013-11-09 21:20:23 +00:00
class WC_API_Reports extends WC_API_Resource {
/** @var string $base the route base */
protected $base = '/reports';
/** @var WC_Admin_Report instance */
private $report;
/**
* Register the routes for this class
*
* GET /reports
* GET /reports/sales
*
* @since 2.1
* @param array $routes
* @return array
*/
public function register_routes( $routes ) {
# GET /reports
$routes[ $this->base ] = array(
array( array( $this, 'get_reports' ), WC_API_Server::READABLE ),
);
# GET /reports/sales
$routes[ $this->base . '/sales' ] = array(
array( array( $this, 'get_sales_report' ), WC_API_Server::READABLE ),
);
# GET /reports/sales/top_sellers
$routes[ $this->base . '/sales/top_sellers' ] = array(
array( array( $this, 'get_top_sellers_report' ), WC_API_Server::READABLE ),
);
return $routes;
}
/**
* Get a simple listing of available reports
*
* @since 2.1
* @return array
*/
public function get_reports() {
return array( 'reports' => array( 'sales', 'sales/top_sellers' ) );
}
/**
* Get the sales report
*
* @since 2.1
* @param string $fields fields to include in response
* @param array $filter date filtering
* @return array|WP_Error
*/
public function get_sales_report( $fields = null, $filter = array() ) {
// check user permissions
$check = $this->validate_request();
2015-01-30 13:28:53 +00:00
// check for WP_Error
if ( is_wp_error( $check ) ) {
return $check;
2015-01-30 13:28:53 +00:00
}
// set date filtering
$this->setup_report( $filter );
// new customers
$users_query = new WP_User_Query(
array(
'fields' => array( 'user_registered' ),
'role' => 'customer',
)
);
$customers = $users_query->get_results();
foreach ( $customers as $key => $customer ) {
if ( strtotime( $customer->user_registered ) < $this->report->start_date || strtotime( $customer->user_registered ) > $this->report->end_date ) {
unset( $customers[ $key ] );
}
}
$total_customers = count( $customers );
$report_data = $this->report->get_report_data();
$period_totals = array();
// setup period totals by ensuring each period in the interval has data
for ( $i = 0; $i <= $this->report->chart_interval; $i ++ ) {
switch ( $this->report->chart_groupby ) {
case 'day' :
$time = date( 'Y-m-d', strtotime( "+{$i} DAY", $this->report->start_date ) );
break;
2015-02-03 14:44:53 +00:00
default :
$time = date( 'Y-m', strtotime( "+{$i} MONTH", $this->report->start_date ) );
break;
}
// set the customer signups for each period
$customer_count = 0;
foreach ( $customers as $customer ) {
if ( date( ( 'day' == $this->report->chart_groupby ) ? 'Y-m-d' : 'Y-m', strtotime( $customer->user_registered ) ) == $time ) {
$customer_count++;
}
}
$period_totals[ $time ] = array(
2014-01-21 19:07:22 +00:00
'sales' => wc_format_decimal( 0.00, 2 ),
'orders' => 0,
'items' => 0,
'tax' => wc_format_decimal( 0.00, 2 ),
'shipping' => wc_format_decimal( 0.00, 2 ),
'discount' => wc_format_decimal( 0.00, 2 ),
'customers' => $customer_count,
);
}
// add total sales, total order count, total tax and total shipping for each period
foreach ( $report_data->orders as $order ) {
$time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order->post_date ) ) : date( 'Y-m', strtotime( $order->post_date ) );
2015-01-30 13:28:53 +00:00
if ( ! isset( $period_totals[ $time ] ) ) {
continue;
2015-01-30 13:28:53 +00:00
}
$period_totals[ $time ]['sales'] = wc_format_decimal( $order->total_sales, 2 );
$period_totals[ $time ]['tax'] = wc_format_decimal( $order->total_tax + $order->total_shipping_tax, 2 );
$period_totals[ $time ]['shipping'] = wc_format_decimal( $order->total_shipping, 2 );
}
foreach ( $report_data->order_counts as $order ) {
$time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order->post_date ) ) : date( 'Y-m', strtotime( $order->post_date ) );
if ( ! isset( $period_totals[ $time ] ) ) {
continue;
}
$period_totals[ $time ]['orders'] = (int) $order->count;
}
// add total order items for each period
foreach ( $report_data->order_items as $order_item ) {
$time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order_item->post_date ) ) : date( 'Y-m', strtotime( $order_item->post_date ) );
2015-01-30 13:28:53 +00:00
if ( ! isset( $period_totals[ $time ] ) ) {
continue;
2015-01-30 13:28:53 +00:00
}
$period_totals[ $time ]['items'] = (int) $order_item->order_item_count;
}
// add total discount for each period
foreach ( $report_data->coupons as $discount ) {
$time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $discount->post_date ) ) : date( 'Y-m', strtotime( $discount->post_date ) );
if ( ! isset( $period_totals[ $time ] ) ) {
continue;
}
$period_totals[ $time ]['discount'] = wc_format_decimal( $discount->discount_amount, 2 );
}
$sales_data = array(
'total_sales' => $report_data->total_sales,
'net_sales' => $report_data->net_sales,
'average_sales' => $report_data->average_sales,
'total_orders' => $report_data->total_orders,
'total_items' => $report_data->total_items,
'total_tax' => wc_format_decimal( $report_data->total_tax + $report_data->total_shipping_tax, 2 ),
'total_shipping' => $report_data->total_shipping,
'total_refunds' => $report_data->total_refunds,
'total_discount' => $report_data->total_coupons,
'totals_grouped_by' => $this->report->chart_groupby,
'totals' => $period_totals,
'total_customers' => $total_customers,
);
return array( 'sales' => apply_filters( 'woocommerce_api_report_response', $sales_data, $this->report, $fields, $this->server ) );
}
/**
* Get the top sellers report
*
* @since 2.1
* @param string $fields fields to include in response
* @param array $filter date filtering
* @return array|WP_Error
*/
public function get_top_sellers_report( $fields = null, $filter = array() ) {
// check user permissions
$check = $this->validate_request();
if ( is_wp_error( $check ) ) {
return $check;
}
// set date filtering
$this->setup_report( $filter );
$top_sellers = $this->report->get_order_report_data( array(
'data' => array(
'_product_id' => array(
'type' => 'order_item_meta',
'order_item_type' => 'line_item',
'function' => '',
'name' => 'product_id',
),
'_qty' => array(
'type' => 'order_item_meta',
'order_item_type' => 'line_item',
'function' => 'SUM',
'name' => 'order_item_qty',
),
),
'order_by' => 'order_item_qty DESC',
'group_by' => 'product_id',
'limit' => isset( $filter['limit'] ) ? absint( $filter['limit'] ) : 12,
'query_type' => 'get_results',
'filter_range' => true,
) );
$top_sellers_data = array();
foreach ( $top_sellers as $top_seller ) {
$product = wc_get_product( $top_seller->product_id );
if ( $product ) {
$top_sellers_data[] = array(
WIP - Product CRUD (#12065) * Created function to get the catalog visibility options * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Add related product functions and deprecate those in class. * No need to exclude ID * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Sanitize ids later * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Bump template version * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * Made abstract function useful * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * Allow WP_Query to preload post data, and meta in wc_get_products() Allow WP_Query to bulk query for post data and meta if more than just IDs are requested from wc_get_products(). Reduces query count significantly. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * First methods for WP_Product crud * Product set methods * Fixed several erros while setting data * Hardcode the get_type per product class * Initial look through getters and setters and abstract data * Missing var * Fixed coding standards and improved the docblocks * Get cached terms from wc_get_related_terms() * Fixed wrong variable in wc_get_related_terms * Use count() instead of sizeof() * Add related product functions and deprecate those in class. * No need to exclude ID * Sanitize ids later * Clean up the abstract product class a bit, deprecate two functions we have renamed, make update & create work properly, and add some tests for it. * Remove unneeded comments * wc_get_product_term_ids instead of related wording and use in other places. get_the_terms is used here and also handles caching, something wp_get_post_terms does not. * Handle PR feedback: Remove duplicate regular_price update, allow changing of post status for products, remove deprecation for get_title since we might still offer it as a function * External Product CRUD * _virtual meta should be 'no', not taxable, in product unit test helper * Bump template version * Made abstract function useful * Grouped product class * Tests * Move children to meta and update test * Use get_upsell_ids * Spacing in query * Moving and refactoring methods * Availability html * Tidy/add todos * Rename method * Put back review functions (still todo) * missing $this * get_price_including_tax/excluding_tax functions * wc_get_price_to_display * Price handling * [Product CRUD] Variable (#12146) * [Product CRUD] Variable Products * Handle PR feedback. * [Product CRUD] Grouped Handling (#12151) * Handle grouped product saving * Update routine * [Product CRUD] Product crud terms (#12149) * Category and tag id handling * Replace template functions * Remove todo * Handle default name in save function * Product crud admin save routine (#12174) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Spacing * Fix comment * wc_implode_text_attributes helper function * [Product CRUD] Product crud admin use getters (#12196) * Initial props * Work on admin saving * Set/get attributes * Atom was moaning about this before but no longer. * Update get_shipping_class * WC_Product_Attribute * Use getter in admin panel * Fix attribute saving * Move settings into new files * Refactor panels and use getters * Use getters for variation panel * Revert save variation changes for now * Add todos * Fix downloads * REST API CRUD Updates * Additional API updates/fixes. Added some todos * Fix final failing tests and implementing setters/getters and attributes functionality. * Fix comparison for is_on_sale and remove download_type from WC_Product. * Add a wc_get_products wrapper. * Remove the download type input from the product data metabox for downloadable products. (#12221) * [Product CRUD] Variations - setters, getters and admin. (#12228) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * Feedback fixes * Implement CRUD in the legacy REST API * Handle PR feedback * [Product CRUD] Getter setter proxy methods (#12236) * Started on variation changes * Stock functions * Variation class * Bulk change ->id to get_id() to fix variation form display * Missing status * Fix add to cart * Start on stored data save * save variation * Save_variations * Variation edit panel * Save variations code works. * Remove stored data code and fix save * Improve legacy class * wc_bool_to_string * prepare_set_attributes * Use wc_get_products * More feedback fixes * get_prop implementation in abstract and data classes * Implement set_prop * Change handling * Array key exists * set_object_read * Use get_the_terms() instead of wp_get_post_terms() wp_get_post_terms() is a wrapper around wp_get_object_terms() which does not use the object cache, and generates a database query every time it is used. get_the_terms() however can use data from the object cache if present. * [Product CRUD] Variable, variation, notices, and stock handling (#12277) * No longer needed * Remove old todos * Use getters in admin list * Related and upsells update for CRUD * Fix notice in gallery * Variable fixes and todos * Context * Price sync * Revert variation attributes change * Return parent data in view context * Defer term counting * wc_find_matching_product_variation * Stock manage tweaks * Stock fixes * Correct id * correct id * Better sync * Data logic setter fix * feedback * Prevent notices * Handle image_id from parent * Fix error * Remove _wc_save_product_price * Remove todo * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * [Product CRUD] Abstract todos (#12305) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Revert "[Product CRUD] Abstract todos (#12305)" This reverts commit 9a6136fcf88fec16f97457b7c8a4388f7587bfa2. * Remove deprecated get_variation_id() * New default attributes method * [Product CRUD] Product Datastore (#12317) * Fix up tests in the product/* folder. * Handle data store updates for grouped, variable, external, simple, and general data store updates for products. * Variations & variable changes. * Update -functions.php calls to use data store. * Add an interface for the public product data store methods. * Finished product factory tests * Correctly delete in the api, fix up some comments, and implement an interface for the public variable methods. * Fix up delete in all versions of the api * Handle feedback * Match protected decloration to parent * Product crud abstract todos (#12316) * Get dimensions and weights, with soft deprecation * Product attributes * Ratings * Fix read method * Downloads * Feedback * Fix up store * Fixed method returning in write context * Fix error in variation admin * Check for parent value - fixes tax class * Remove old/complete todos * Allow set tax class as "parent" * Removed duplicated sync * Fixed wrong variation URLs * Fixed undefined $image_id in WC_Product_Variation::get_image_id() * Allow wc_rest_prepare_date_response() handle timestamps * Updated get methods on REST API for variations * Use variations CRUD to save variations metadata * Remove deprecated get_variation_id() * New default attributes method * Fixed method returning in write context * Allow set tax class as "parent" * Removed duplicated sync * Fixed coding standards * TODO is not accurate. * Should pass WC_Product instancies to WC_Comments methods (#12327) * Use new method in abstract order class to prevent headers sent issue in tests * Fixed variable description in REST API * Updated how create initial product variation * Fixed a few fatal errors and warnings in Products CRUD (#12329) * Fixed a few fatal errors and warnings in Products CRUD * Fixed sync functions * Add variations CRUD to legacy API (#12331) * Apply crud to variable products in legacy API v1 * New REST API do not need fallback for default attributes * Apply variations CRUD to legacy API v2 * Legacy v2 - save default attributes * Variations in legacy API v2 do not have descriptions * Fixed legacy API v2 variations params * Applied variations CRUD to legacy API v3 * Sync before save in legacy apis * Punc * Removed API todos * Removed test * Products endpoint tweaks (#12354) * Var type already normalized on CRUD * Let Product CRUD handle with validation, sanitization and conditional checks * Set downloads using WC_Product_Download * Stop try catch exceptions more than one time * Handle WC_Data_Exception in legacy API * Complete remove products when fails on creating * On creating I mean! * Already have a method to complete delete products * Fixed standards using WP CodeSniffer * get_the_terms() returns false when empty * get_manage_stock returns boolean @claudiosanches * Merge conflict * Variations API endpoint fixes * Product CRUD improvements (#12359) * args is not used any more - remove todo * Added test for attributes * wc_get_price_excluding_tax usage * parent usage * Fix rating counts * Test fixes * Cleanup after tests * Make sure status transition code runs even during API calls, not just in admin. * Default visibility * Fix attribute setting in API * Use get name instead of get title * variation id usage * Improved cross sell templates * variation_data * Grouped product sync * Notices * Sync is not needed in API * Delete * Rename interfaces * Update counts in data store
2016-11-16 12:38:24 +00:00
'title' => $product->get_name(),
'product_id' => $top_seller->product_id,
'quantity' => $top_seller->order_item_qty,
);
}
}
return array( 'top_sellers' => apply_filters( 'woocommerce_api_report_response', $top_sellers_data, $this->report, $fields, $this->server ) );
}
/**
* Setup the report object and parse any date filtering
*
* @since 2.1
* @param array $filter date filtering
*/
private function setup_report( $filter ) {
include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-admin-report.php' );
include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-report-sales-by-date.php' );
$this->report = new WC_Report_Sales_By_Date();
if ( empty( $filter['period'] ) ) {
// custom date range
$filter['period'] = 'custom';
if ( ! empty( $filter['date_min'] ) || ! empty( $filter['date_max'] ) ) {
// overwrite _GET to make use of WC_Admin_Report::calculate_current_range() for custom date ranges
$_GET['start_date'] = $this->server->parse_datetime( $filter['date_min'] );
$_GET['end_date'] = isset( $filter['date_max'] ) ? $this->server->parse_datetime( $filter['date_max'] ) : null;
} else {
// default custom range to today
$_GET['start_date'] = $_GET['end_date'] = date( 'Y-m-d', current_time( 'timestamp' ) );
}
} else {
// ensure period is valid
if ( ! in_array( $filter['period'], array( 'week', 'month', 'last_month', 'year' ) ) ) {
$filter['period'] = 'week';
}
// TODO: change WC_Admin_Report class to use "week" instead, as it's more consistent with other periods
// allow "week" for period instead of "7day"
if ( 'week' === $filter['period'] ) {
$filter['period'] = '7day';
}
}
$this->report->calculate_current_range( $filter['period'] );
}
/**
* Verify that the current user has permission to view reports
*
* @since 2.1
* @see WC_API_Resource::validate_request()
*
* @param null $id unused
* @param null $type unused
* @param null $context unused
*
* @return bool|WP_Error
*/
protected function validate_request( $id = null, $type = null, $context = null ) {
if ( ! current_user_can( 'view_woocommerce_reports' ) ) {
return new WP_Error( 'woocommerce_api_user_cannot_read_report', __( 'You do not have permission to read this report', 'woocommerce' ), array( 'status' => 401 ) );
} else {
return true;
}
}
}