prefix . 'loyaltypress_'; $since = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * $days ); // phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $members = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(DISTINCT user_id) FROM %i', $l ) ); $new_members = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM (SELECT user_id, MIN(created_at) first_at FROM %i GROUP BY user_id) x WHERE x.first_at >= %s', $l, $since ) ); $order_ids = array_map( 'intval', $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT order_id FROM %i WHERE type = 'earn' AND order_id > 0 AND created_at >= %s ORDER BY order_id DESC LIMIT 3000", $l, $since ) ) ); $buyers = array_map( 'intval', $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT user_id FROM %i WHERE type = 'earn' AND order_id > 0 AND created_at >= %s", $l, $since ) ) ); $repeaters = 0; if ( $buyers ) { $in = implode( ',', array_fill( 0, count( $buyers ), '%d' ) ); $repeaters = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM (SELECT user_id FROM %i WHERE type = 'earn' AND order_id > 0 AND user_id IN ({$in}) GROUP BY user_id HAVING COUNT(DISTINCT order_id) > 1) r", array_merge( array( $l ), $buyers ) ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare } $redeemed = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COALESCE(-SUM(amount),0) FROM %i WHERE type = 'redeem' AND created_at >= %s", $l, $since ) ) - (int) $wpdb->get_var( $wpdb->prepare( "SELECT COALESCE(SUM(amount),0) FROM %i WHERE type = 'refund' AND created_at >= %s", $l, $since ) ); $issued = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COALESCE(SUM(amount),0) FROM %i WHERE amount > 0 AND type IN ('earn','prize','adjust') AND created_at >= %s", $l, $since ) ); $spins = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE created_at >= %s', $p . 'spin_results', $since ) ); // phpcs:enable $sales = 0.0; $tier = 0.0; foreach ( $order_ids as $id ) { $order = wc_get_order( $id ); if ( ! $order ) { continue; } $sales += (float) $order->get_total() - (float) $order->get_total_refunded(); foreach ( $order->get_fees() as $fee ) { if ( 'tier' === $fee->get_meta( '_loyaltypress_fee' ) ) { $tier += abs( (float) $fee->get_total() ); } } } $customers = new \WP_User_Query( array( 'role' => 'customer', 'number' => 1, 'fields' => 'ID', 'count_total' => true, ) ); $coins_val = Redeem::value_of( max( 0, $redeemed ) ); $cost = $coins_val + $tier; return array( 'days' => $days, 'members' => $members, 'customers' => (int) $customers->get_total(), 'new_members' => $new_members, 'orders' => count( $order_ids ), 'sales' => $sales, 'buyers' => count( $buyers ), 'repeat_rate' => $buyers ? round( $repeaters / count( $buyers ) * 100 ) : 0, 'coins_issued' => $issued, 'coins_used' => max( 0, $redeemed ), 'coins_value' => $coins_val, 'tier_discount' => $tier, 'cost' => $cost, 'cost_pct' => $sales > 0 ? round( $cost / $sales * 100, 1 ) : 0, 'spins' => $spins, 'at' => time(), ); } }