prepare(). /** * The headline figures between two times. * * @param int $from_ts From (timestamp). * @param int $to_ts To (timestamp). * @return array visitors, baskets, checkouts, orders, revenue, abandoned, abandoned_value, reminders, recovered, recovered_value. */ function brai_period_stats( $from_ts, $to_ts ) { global $wpdb; $e = brai_table( 'events' ); $from = gmdate( 'Y-m-d H:i:s', (int) $from_ts ); $to = gmdate( 'Y-m-d H:i:s', (int) $to_ts ); /* A basket only counts as abandoned once it has been quiet for the "abandoned after" time. */ $quiet = gmdate( 'Y-m-d H:i:s', min( (int) $to_ts, time() - brai_abandon_mins() * 60 ) ); $out = array( 'visitors' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT vid) FROM %i WHERE ts >= %s AND ts < %s AND type IN ('visit','view','cat')", $e, $from, $to ) ), 'baskets' => 0, 'checkouts' => 0, 'orders' => 0, 'revenue' => 0.0, 'abandoned' => 0, 'abandoned_value' => 0.0, 'reminders' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE ts >= %s AND ts < %s AND type = 'reminder'", $e, $from, $to ) ), 'recovered' => 0, 'recovered_value' => 0.0, ); $stage = $wpdb->get_results( $wpdb->prepare( "SELECT type, COUNT(DISTINCT vid) n FROM %i WHERE ts >= %s AND ts < %s AND type IN ('add','checkout') GROUP BY type", $e, $from, $to ), OBJECT_K ); $out['baskets'] = isset( $stage['add'] ) ? (int) $stage['add']->n : 0; $out['checkouts'] = isset( $stage['checkout'] ) ? (int) $stage['checkout']->n : 0; $orders = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) n, COALESCE(SUM(value),0) v FROM %i WHERE type = 'order' AND ts >= %s AND ts < %s", $e, $from, $to ) ); if ( $orders ) { $out['orders'] = (int) $orders->n; $out['revenue'] = (float) $orders->v; } $left = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) n, COALESCE(SUM(cart_value),0) v FROM %i WHERE status IN ('basket','checkout') AND cart_value > 0 AND last_seen >= %s AND last_seen < %s", brai_table( 'visitors' ), $from, $quiet ) ); if ( $left ) { $out['abandoned'] = (int) $left->n; $out['abandoned_value'] = (float) $left->v; } /* Orders placed by someone who had been sent a reminder first. */ $won = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) n, COALESCE(SUM(o.value),0) v FROM %i o WHERE o.type = 'order' AND o.ts >= %s AND o.ts < %s AND EXISTS ( SELECT 1 FROM %i r WHERE r.vid = o.vid AND r.type = 'reminder' AND r.ts < o.ts )", $e, $from, $to, $e ) ); if ( $won ) { $out['recovered'] = (int) $won->n; $out['recovered_value'] = (float) $won->v; } return $out; } /** * How each reminder email is doing: sent, clicked, orders and order value. * * A click or an order is credited to the last reminder that customer was sent before it. * * @param int $since_ts Only count reminders sent since (timestamp). * @return array Email number => sent, clicked, orders, value. */ function brai_reminder_stats( $since_ts ) { global $wpdb; $e = brai_table( 'events' ); $since = gmdate( 'Y-m-d H:i:s', (int) $since_ts ); $out = array(); for ( $i = 1; $i <= 3; $i++ ) { $out[ $i ] = array( 'sent' => 0, 'clicked' => 0, 'orders' => 0, 'value' => 0.0, ); } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT vid, type, qty, value FROM %i WHERE ts >= %s AND type IN ('reminder','restore','order') AND vid IN ( SELECT vid FROM %i WHERE type = 'reminder' AND ts >= %s ) ORDER BY vid ASC, id ASC LIMIT 50000", $e, $since, $e, $since ) ); $vid = ''; $last = 0; $clicked = false; foreach ( $rows as $r ) { if ( $r->vid !== $vid ) { $vid = $r->vid; $last = 0; $clicked = false; } if ( 'reminder' === $r->type ) { $last = min( 3, max( 1, (int) $r->qty ) ); $clicked = false; ++$out[ $last ]['sent']; } elseif ( $last && 'restore' === $r->type ) { if ( ! $clicked ) { ++$out[ $last ]['clicked']; $clicked = true; } } elseif ( $last && 'order' === $r->type ) { ++$out[ $last ]['orders']; $out[ $last ]['value'] += (float) $r->value; $last = 0; } } return $out; } /** * How the single-use discount codes in reminder emails are doing. * * @param int $since_ts Only count codes sent since (timestamp). * @return array sent, used, orders, value. */ function brai_coupon_stats( $since_ts ) { global $wpdb; $e = brai_table( 'events' ); $out = array( 'sent' => 0, 'used' => 0, 'orders' => 0, 'value' => 0.0, ); $sent = $wpdb->get_results( $wpdb->prepare( "SELECT id, vid, object_id FROM %i WHERE type = 'coupon' AND ts >= %s ORDER BY id DESC LIMIT 500", $e, gmdate( 'Y-m-d H:i:s', (int) $since_ts ) ) ); if ( ! $sent ) { return $out; } $out['sent'] = count( $sent ); /* A code counts as used once WooCommerce has recorded it on an order. */ $used = get_posts( array( 'post_type' => 'shop_coupon', 'post_status' => 'any', 'post__in' => array_map( 'intval', wp_list_pluck( $sent, 'object_id' ) ), 'posts_per_page' => 500, // phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_posts_per_page -- one lookup of this plugin's own coupons, capped by the query above. 'fields' => 'ids', 'no_found_rows' => true, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- limited to this plugin's own coupons by post__in. 'meta_query' => array( array( 'key' => 'usage_count', 'value' => 0, 'compare' => '>', 'type' => 'NUMERIC', ), ), ) ); $out['used'] = count( $used ); if ( ! $used ) { return $out; } /* The orders those customers placed after being sent their code. */ $used = array_flip( array_map( 'intval', $used ) ); $first = array(); foreach ( $sent as $c ) { if ( isset( $used[ (int) $c->object_id ] ) ) { $first[ $c->vid ] = isset( $first[ $c->vid ] ) ? min( $first[ $c->vid ], (int) $c->id ) : (int) $c->id; } } $vids = array_keys( $first ); $in = implode( ',', array_fill( 0, count( $vids ), '%s' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $in is only a list of %s placeholders, and the values are passed as one array. foreach ( $wpdb->get_results( $wpdb->prepare( "SELECT id, vid, value FROM %i WHERE type = 'order' AND vid IN ($in) ORDER BY id ASC", array_merge( array( $e ), $vids ) ) ) as $o ) { if ( isset( $first[ $o->vid ] ) && (int) $o->id > $first[ $o->vid ] ) { ++$out['orders']; $out['value'] += (float) $o->value; unset( $first[ $o->vid ] ); // One order for each code. } } return $out; } /** * How a figure has moved against the period before, as a small coloured label. * * @param float $now This period. * @param float $before The period before. * @param bool|null $up_good True if a rise is good news, false if bad, null if neither. * @param string $title Tooltip. * @return string HTML, or '' when there is nothing to compare with. */ function brai_delta_html( $now, $before, $up_good = true, $title = '' ) { $now = (float) $now; $before = (float) $before; if ( $before <= 0 ) { return ''; } $pc = (int) round( 100 * ( $now - $before ) / $before ); $class = 'flat'; if ( 0 !== $pc && null !== $up_good ) { $class = ( $pc > 0 ) === $up_good ? 'up' : 'down'; } return '' . esc_html( ( $pc > 0 ? '+' : '' ) . $pc . '%' ) . ''; } /** * Is this basket ready for a reminder to be sent by hand? * * @param array $r Visitor row. * @return int|string The number of the email that would be sent, or the reason none can be. */ function brai_next_reminder( $r ) { $s = brai_mail_settings(); if ( empty( $r['email'] ) ) { return __( 'This visitor has not left an email address.', 'basketwise' ); } if ( ! in_array( $r['status'], array( 'basket', 'checkout' ), true ) || (float) $r['cart_value'] <= 0 || empty( $r['cart'] ) ) { return __( 'There is nothing in this visitor\'s basket.', 'basketwise' ); } if ( brai_unsubscribed( $r['email'] ) ) { return __( 'This customer has unsubscribed from basket reminders.', 'basketwise' ); } if ( (int) $r['reminders'] >= (int) $s['count'] ) { return __( 'This customer has already been sent every reminder in the sequence.', 'basketwise' ); } if ( brai_has_ordered( $r['email'], strtotime( $r['last_seen'] . ' UTC' ) ) ) { return __( 'This customer has placed an order since leaving this basket.', 'basketwise' ); } return (int) $r['reminders'] + 1; } /* ---------- Weekly summary email to the shop ---------- */ /** Next weekly summary: Monday at the summary time (site time zone), as a timestamp. */ function brai_weekly_next() { $s = brai_mail_settings(); $t = new DateTime( 'now', wp_timezone() ); $t->setTime( (int) $s['digest_hour'], 0, 0 ); while ( 1 !== (int) $t->format( 'N' ) || $t->getTimestamp() <= time() ) { $t->modify( '+1 day' ); } return $t->getTimestamp(); } /** Keeps the weekly summary scheduled while it is switched on, and unscheduled while it is off. */ function brai_weekly_schedule() { $s = brai_mail_settings(); $on = ! empty( $s['weekly'] ) && ! empty( $s['digest_to'] ); $next = wp_next_scheduled( 'brai_weekly' ); if ( $on && ! $next ) { wp_schedule_single_event( brai_weekly_next(), 'brai_weekly' ); } elseif ( ! $on && $next ) { wp_clear_scheduled_hook( 'brai_weekly' ); } } add_action( 'init', 'brai_weekly_schedule' ); /** * The weekly summary email body: the last seven days beside the seven before. * * @param int $to_ts End of the week covered (timestamp). * @return string */ function brai_weekly_html( $to_ts ) { $to_ts = (int) $to_ts; $now = brai_period_stats( $to_ts - WEEK_IN_SECONDS, $to_ts ); $then = brai_period_stats( $to_ts - 2 * WEEK_IN_SECONDS, $to_ts - WEEK_IN_SECONDS ); $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $rows = array( array( __( 'Visitors', 'basketwise' ), 'visitors', false, true ), array( __( 'Added to basket', 'basketwise' ), 'baskets', false, true ), array( __( 'Reached checkout', 'basketwise' ), 'checkouts', false, true ), array( __( 'Orders', 'basketwise' ), 'orders', false, true ), array( __( 'Order value', 'basketwise' ), 'revenue', true, true ), array( __( 'Abandoned baskets', 'basketwise' ), 'abandoned', false, false ), array( __( 'Left in abandoned baskets', 'basketwise' ), 'abandoned_value', true, false ), array( __( 'Reminder emails sent', 'basketwise' ), 'reminders', false, null ), array( __( 'Orders recovered by reminders', 'basketwise' ), 'recovered', false, true ), array( __( 'Value recovered by reminders', 'basketwise' ), 'recovered_value', true, true ), ); $cell = 'padding:10px 12px;border-bottom:1px solid #e4e7ec;font-size:14px;line-height:1.45'; $num = $cell . ';text-align:right;white-space:nowrap'; $fmt = 'D j M'; /* translators: %s: shop name. */ $h = '

' . esc_html( sprintf( __( 'Your week on %s', 'basketwise' ), $site ) ) . '

'; $h .= '

' . esc_html( wp_date( $fmt, $to_ts - WEEK_IN_SECONDS ) . ' to ' . wp_date( $fmt, $to_ts ) ) . ', ' . esc_html__( 'beside the week before.', 'basketwise' ) . '

'; $h .= ''; $h .= ''; foreach ( $rows as $row ) { list( $label, $key, $money, $up_is_good ) = $row; $a = (float) $now[ $key ]; $b = (float) $then[ $key ]; $change = '–'; $color = '#667085'; if ( $b > 0 ) { $pc = round( 100 * ( $a - $b ) / $b ); $change = ( $pc > 0 ? '+' : '' ) . $pc . '%'; if ( 0 !== (int) $pc && null !== $up_is_good ) { $color = ( $pc > 0 ) === $up_is_good ? '#067647' : '#b42318'; } } $h .= '' . '' . '' . ''; } $h .= '
' . esc_html__( 'This week', 'basketwise' ) . '' . esc_html__( 'Week before', 'basketwise' ) . '' . esc_html__( 'Change', 'basketwise' ) . '
' . esc_html( $label ) . '' . esc_html( $money ? brai_money( $a ) : number_format_i18n( $a ) ) . '' . esc_html( $money ? brai_money( $b ) : number_format_i18n( $b ) ) . '' . esc_html( $change ) . '
'; /* translators: %s: shop name. */ $h .= '

' . esc_html( sprintf( __( 'Open Basketwise on %s', 'basketwise' ), $site ) ) . '

'; return $h; } add_action( 'brai_weekly', function () { $s = brai_mail_settings(); if ( ! empty( $s['weekly'] ) && ! empty( $s['digest_to'] ) ) { $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); wp_mail( $s['digest_to'], /* translators: %s: shop name. */ sprintf( __( '%s: your week in baskets', 'basketwise' ), $site ), brai_weekly_html( time() ), array( 'Content-Type: text/html; charset=UTF-8' ) ); } wp_clear_scheduled_hook( 'brai_weekly' ); brai_weekly_schedule(); } );