Schema::date(), 'end_date' => Schema::date(), 'code' => array( 'type' => 'string', 'maxLength' => 100, ), 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 25, 'default' => 10, ), ), array( 'start_date', 'end_date' ) ); } /** * Runs the data function. * * @param array $args Validated arguments. * @return array */ public function run( array $args ): array { $period = Schema::period( $args ); $limit = (int) ( $args['limit'] ?? 10 ); $code = isset( $args['code'] ) ? wc_format_coupon_code( (string) $args['code'] ) : ''; $params = array( 'after' => $period->after(), 'before' => $period->before(), 'orderby' => 'orders_count', 'order' => 'desc', 'per_page' => $limit, 'extended_info' => true, ); if ( '' !== $code ) { $coupon_id = wc_get_coupon_id_by_code( $code ); if ( ! $coupon_id ) { return array( 'period' => $period->to_array(), 'coupons' => array(), 'rows_read' => 0, 'notes' => array( sprintf( 'No coupon with the code "%s" exists in this store.', $code ) ), ); } $params['coupons'] = array( $coupon_id ); } $response = Analytics::get( '/reports/coupons', $params ); $coupons = array(); $read = 0; foreach ( is_array( $response['data'] ) ? $response['data'] : array() as $row ) { $coupon_id = (int) $row['coupon_id']; $orders = Analytics::get( '/reports/orders/stats', array( 'after' => $period->after(), 'before' => $period->before(), 'coupon_includes' => array( $coupon_id ), 'interval' => 'year', ) ); $totals = is_array( $orders['data'] ) && is_array( $orders['data']['totals'] ?? null ) ? $orders['data']['totals'] : array(); $coupons[] = array( 'code' => (string) ( $row['extended_info']['code'] ?? '' ), 'discount_type' => (string) ( $row['extended_info']['discount_type'] ?? '' ), 'orders' => (int) $row['orders_count'], 'discount_given' => Analytics::money( $row['amount'] ), 'net_sales_of_orders' => Analytics::money( $totals['net_revenue'] ?? 0 ), 'average_order' => (int) $row['orders_count'] > 0 ? Analytics::money( (float) ( $totals['net_revenue'] ?? 0 ) / (int) $row['orders_count'] ) : 0.0, ); $read += (int) $row['orders_count']; }//end foreach return array( 'period' => $period->to_array(), 'coupons' => $coupons, 'rows_read' => $read, 'notes' => array( 'Net sales are after discounts and refunds, before tax and shipping, as in WooCommerce Analytics.' ), 'chart' => array( 'type' => 'bar', 'title' => __( 'Orders by coupon', 'askshelf' ), 'format' => 'number', 'points' => array_map( static fn( array $c ): array => array( 'label' => $c['code'], 'value' => $c['orders'], ), $coupons ), ), ); } }