class-wc-api-reports.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. /**
  3. * WooCommerce API Reports Class
  4. *
  5. * Handles requests to the /reports endpoint
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 2.1
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. class WC_API_Reports extends WC_API_Resource {
  16. /** @var string $base the route base */
  17. protected $base = '/reports';
  18. /** @var WC_Admin_Report instance */
  19. private $report;
  20. /**
  21. * Register the routes for this class
  22. *
  23. * GET /reports
  24. * GET /reports/sales
  25. *
  26. * @since 2.1
  27. * @param array $routes
  28. * @return array
  29. */
  30. public function register_routes( $routes ) {
  31. # GET /reports
  32. $routes[ $this->base ] = array(
  33. array( array( $this, 'get_reports' ), WC_API_Server::READABLE ),
  34. );
  35. # GET /reports/sales
  36. $routes[ $this->base . '/sales' ] = array(
  37. array( array( $this, 'get_sales_report' ), WC_API_Server::READABLE ),
  38. );
  39. # GET /reports/sales/top_sellers
  40. $routes[ $this->base . '/sales/top_sellers' ] = array(
  41. array( array( $this, 'get_top_sellers_report' ), WC_API_Server::READABLE ),
  42. );
  43. return $routes;
  44. }
  45. /**
  46. * Get a simple listing of available reports
  47. *
  48. * @since 2.1
  49. * @return array
  50. */
  51. public function get_reports() {
  52. return array( 'reports' => array( 'sales', 'sales/top_sellers' ) );
  53. }
  54. /**
  55. * Get the sales report
  56. *
  57. * @since 2.1
  58. * @param string $fields fields to include in response
  59. * @param array $filter date filtering
  60. * @return array|WP_Error
  61. */
  62. public function get_sales_report( $fields = null, $filter = array() ) {
  63. // check user permissions
  64. $check = $this->validate_request();
  65. // check for WP_Error
  66. if ( is_wp_error( $check ) ) {
  67. return $check;
  68. }
  69. // set date filtering
  70. $this->setup_report( $filter );
  71. // new customers
  72. $users_query = new WP_User_Query(
  73. array(
  74. 'fields' => array( 'user_registered' ),
  75. 'role' => 'customer',
  76. )
  77. );
  78. $customers = $users_query->get_results();
  79. foreach ( $customers as $key => $customer ) {
  80. if ( strtotime( $customer->user_registered ) < $this->report->start_date || strtotime( $customer->user_registered ) > $this->report->end_date ) {
  81. unset( $customers[ $key ] );
  82. }
  83. }
  84. $total_customers = count( $customers );
  85. $report_data = $this->report->get_report_data();
  86. $period_totals = array();
  87. // setup period totals by ensuring each period in the interval has data
  88. for ( $i = 0; $i <= $this->report->chart_interval; $i ++ ) {
  89. switch ( $this->report->chart_groupby ) {
  90. case 'day' :
  91. $time = date( 'Y-m-d', strtotime( "+{$i} DAY", $this->report->start_date ) );
  92. break;
  93. default :
  94. $time = date( 'Y-m', strtotime( "+{$i} MONTH", $this->report->start_date ) );
  95. break;
  96. }
  97. // set the customer signups for each period
  98. $customer_count = 0;
  99. foreach ( $customers as $customer ) {
  100. if ( date( ( 'day' == $this->report->chart_groupby ) ? 'Y-m-d' : 'Y-m', strtotime( $customer->user_registered ) ) == $time ) {
  101. $customer_count++;
  102. }
  103. }
  104. $period_totals[ $time ] = array(
  105. 'sales' => wc_format_decimal( 0.00, 2 ),
  106. 'orders' => 0,
  107. 'items' => 0,
  108. 'tax' => wc_format_decimal( 0.00, 2 ),
  109. 'shipping' => wc_format_decimal( 0.00, 2 ),
  110. 'discount' => wc_format_decimal( 0.00, 2 ),
  111. 'customers' => $customer_count,
  112. );
  113. }
  114. // add total sales, total order count, total tax and total shipping for each period
  115. foreach ( $report_data->orders as $order ) {
  116. $time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order->post_date ) ) : date( 'Y-m', strtotime( $order->post_date ) );
  117. if ( ! isset( $period_totals[ $time ] ) ) {
  118. continue;
  119. }
  120. $period_totals[ $time ]['sales'] = wc_format_decimal( $order->total_sales, 2 );
  121. $period_totals[ $time ]['tax'] = wc_format_decimal( $order->total_tax + $order->total_shipping_tax, 2 );
  122. $period_totals[ $time ]['shipping'] = wc_format_decimal( $order->total_shipping, 2 );
  123. }
  124. foreach ( $report_data->order_counts as $order ) {
  125. $time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order->post_date ) ) : date( 'Y-m', strtotime( $order->post_date ) );
  126. if ( ! isset( $period_totals[ $time ] ) ) {
  127. continue;
  128. }
  129. $period_totals[ $time ]['orders'] = (int) $order->count;
  130. }
  131. // add total order items for each period
  132. foreach ( $report_data->order_items as $order_item ) {
  133. $time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $order_item->post_date ) ) : date( 'Y-m', strtotime( $order_item->post_date ) );
  134. if ( ! isset( $period_totals[ $time ] ) ) {
  135. continue;
  136. }
  137. $period_totals[ $time ]['items'] = (int) $order_item->order_item_count;
  138. }
  139. // add total discount for each period
  140. foreach ( $report_data->coupons as $discount ) {
  141. $time = ( 'day' === $this->report->chart_groupby ) ? date( 'Y-m-d', strtotime( $discount->post_date ) ) : date( 'Y-m', strtotime( $discount->post_date ) );
  142. if ( ! isset( $period_totals[ $time ] ) ) {
  143. continue;
  144. }
  145. $period_totals[ $time ]['discount'] = wc_format_decimal( $discount->discount_amount, 2 );
  146. }
  147. $sales_data = array(
  148. 'total_sales' => $report_data->total_sales,
  149. 'net_sales' => $report_data->net_sales,
  150. 'average_sales' => $report_data->average_sales,
  151. 'total_orders' => $report_data->total_orders,
  152. 'total_items' => $report_data->total_items,
  153. 'total_tax' => wc_format_decimal( $report_data->total_tax + $report_data->total_shipping_tax, 2 ),
  154. 'total_shipping' => $report_data->total_shipping,
  155. 'total_refunds' => $report_data->total_refunds,
  156. 'total_discount' => $report_data->total_coupons,
  157. 'totals_grouped_by' => $this->report->chart_groupby,
  158. 'totals' => $period_totals,
  159. 'total_customers' => $total_customers,
  160. );
  161. return array( 'sales' => apply_filters( 'woocommerce_api_report_response', $sales_data, $this->report, $fields, $this->server ) );
  162. }
  163. /**
  164. * Get the top sellers report
  165. *
  166. * @since 2.1
  167. * @param string $fields fields to include in response
  168. * @param array $filter date filtering
  169. * @return array|WP_Error
  170. */
  171. public function get_top_sellers_report( $fields = null, $filter = array() ) {
  172. // check user permissions
  173. $check = $this->validate_request();
  174. if ( is_wp_error( $check ) ) {
  175. return $check;
  176. }
  177. // set date filtering
  178. $this->setup_report( $filter );
  179. $top_sellers = $this->report->get_order_report_data( array(
  180. 'data' => array(
  181. '_product_id' => array(
  182. 'type' => 'order_item_meta',
  183. 'order_item_type' => 'line_item',
  184. 'function' => '',
  185. 'name' => 'product_id',
  186. ),
  187. '_qty' => array(
  188. 'type' => 'order_item_meta',
  189. 'order_item_type' => 'line_item',
  190. 'function' => 'SUM',
  191. 'name' => 'order_item_qty',
  192. ),
  193. ),
  194. 'order_by' => 'order_item_qty DESC',
  195. 'group_by' => 'product_id',
  196. 'limit' => isset( $filter['limit'] ) ? absint( $filter['limit'] ) : 12,
  197. 'query_type' => 'get_results',
  198. 'filter_range' => true,
  199. ) );
  200. $top_sellers_data = array();
  201. foreach ( $top_sellers as $top_seller ) {
  202. $product = wc_get_product( $top_seller->product_id );
  203. if ( $product ) {
  204. $top_sellers_data[] = array(
  205. 'title' => $product->get_name(),
  206. 'product_id' => $top_seller->product_id,
  207. 'quantity' => $top_seller->order_item_qty,
  208. );
  209. }
  210. }
  211. return array( 'top_sellers' => apply_filters( 'woocommerce_api_report_response', $top_sellers_data, $this->report, $fields, $this->server ) );
  212. }
  213. /**
  214. * Setup the report object and parse any date filtering
  215. *
  216. * @since 2.1
  217. * @param array $filter date filtering
  218. */
  219. private function setup_report( $filter ) {
  220. include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-admin-report.php' );
  221. include_once( WC()->plugin_path() . '/includes/admin/reports/class-wc-report-sales-by-date.php' );
  222. $this->report = new WC_Report_Sales_By_Date();
  223. if ( empty( $filter['period'] ) ) {
  224. // custom date range
  225. $filter['period'] = 'custom';
  226. if ( ! empty( $filter['date_min'] ) || ! empty( $filter['date_max'] ) ) {
  227. // overwrite _GET to make use of WC_Admin_Report::calculate_current_range() for custom date ranges
  228. $_GET['start_date'] = $this->server->parse_datetime( $filter['date_min'] );
  229. $_GET['end_date'] = isset( $filter['date_max'] ) ? $this->server->parse_datetime( $filter['date_max'] ) : null;
  230. } else {
  231. // default custom range to today
  232. $_GET['start_date'] = $_GET['end_date'] = date( 'Y-m-d', current_time( 'timestamp' ) );
  233. }
  234. } else {
  235. // ensure period is valid
  236. if ( ! in_array( $filter['period'], array( 'week', 'month', 'last_month', 'year' ) ) ) {
  237. $filter['period'] = 'week';
  238. }
  239. // TODO: change WC_Admin_Report class to use "week" instead, as it's more consistent with other periods
  240. // allow "week" for period instead of "7day"
  241. if ( 'week' === $filter['period'] ) {
  242. $filter['period'] = '7day';
  243. }
  244. }
  245. $this->report->calculate_current_range( $filter['period'] );
  246. }
  247. /**
  248. * Verify that the current user has permission to view reports
  249. *
  250. * @since 2.1
  251. * @see WC_API_Resource::validate_request()
  252. *
  253. * @param null $id unused
  254. * @param null $type unused
  255. * @param null $context unused
  256. *
  257. * @return bool|WP_Error
  258. */
  259. protected function validate_request( $id = null, $type = null, $context = null ) {
  260. if ( ! current_user_can( 'view_woocommerce_reports' ) ) {
  261. return new WP_Error( 'woocommerce_api_user_cannot_read_report', __( 'You do not have permission to read this report', 'woocommerce' ), array( 'status' => 401 ) );
  262. } else {
  263. return true;
  264. }
  265. }
  266. }