[ label, values => [ value => label ] ]. */ public static function traits() { return array( 'channel' => array( 'paid', 'search', 'social', 'email', 'referral', 'ai', 'direct', 'unknown' ), 'visits' => array( '1', '2-3', '4+' ), 'intent' => array( '0', '1', '2+' ), 'asked' => array( 'yes', 'no' ), 'phone' => array( 'yes', 'no' ), 'company' => array( 'yes', 'no' ), 'news' => array( 'yes', 'no' ), 'clicked' => array( 'yes', 'no' ), ); } /** * Starting values: share of buyers and of others with each trait value, from how small businesses usually * sell. [ buyers, others ]. */ private static function defaults() { return array( 'channel' => array( 'paid' => array( .24, .14 ), 'search' => array( .30, .30 ), 'social' => array( .08, .16 ), 'email' => array( .09, .04 ), 'referral' => array( .11, .08 ), 'ai' => array( .04, .02 ), 'direct' => array( .11, .14 ), 'unknown' => array( .03, .12 ), ), 'visits' => array( '1' => array( .25, .58 ), '2-3' => array( .40, .28 ), '4+' => array( .35, .14 ), ), 'intent' => array( '0' => array( .25, .66 ), '1' => array( .30, .20 ), '2+' => array( .45, .14 ), ), 'asked' => array( 'yes' => array( .70, .35 ), 'no' => array( .30, .65 ), ), 'phone' => array( 'yes' => array( .60, .30 ), 'no' => array( .40, .70 ), ), 'company' => array( 'yes' => array( .35, .25 ), 'no' => array( .65, .75 ), ), 'news' => array( 'yes' => array( .35, .20 ), 'no' => array( .65, .80 ), ), 'clicked' => array( 'yes' => array( .30, .08 ), 'no' => array( .70, .92 ), ), ); } /** Where someone first came from, as a broad channel. */ public static function channel( $source, $medium ) { $m = strtolower( (string) $medium ); $s = strtolower( (string) $source ); if ( '' === $s && '' === $m ) { return 'unknown'; } if ( preg_match( '/cpc|ppc|paid|display|cpm|ads?$/', $m ) ) { return 'paid'; } if ( 'organic' === $m ) { return 'search'; } if ( false !== strpos( $m, 'social' ) ) { return 'social'; } if ( false !== strpos( $m, 'mail' ) || 'newsletter' === $m ) { return 'email'; } if ( 'ai' === $m ) { return 'ai'; } if ( 'referral' === $m ) { return 'referral'; } if ( '(direct)' === $s || '(none)' === $m || 'direct' === $s ) { return 'direct'; } return '' !== $m ? 'referral' : 'direct'; } /** * Traits of contacts, from their activity up to a moment (for buyers: before they bought, so the purchase * itself does not explain the purchase). * * @param array $contacts Rows with id, phone, company_id, email_status, first_source, first_medium, last_inquiry_at. * @param array $cutoff Contact ID => GMT datetime (activity after it is ignored); missing = now. * @return array Contact ID => [ trait => value ] plus counts under '_n'. */ public static function features( array $contacts, array $cutoff = array() ) { global $wpdb; $out = array(); $ids = array(); foreach ( $contacts as $c ) { $ids[] = (int) $c['id']; } $counts = array_fill_keys( $ids, array() ); foreach ( array_chunk( $ids, 200 ) as $chunk ) { $ph = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the plugin's own table; $ph is a list of %d. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, type, created_at, data FROM %i WHERE contact_id IN ($ph) AND type IN ('visit','pageview','form','click','subscription') ORDER BY id ASC", array_merge( array( Nodebook_Activities::table() ), $chunk ) ), ARRAY_A ); foreach ( $rows as $r ) { $cid = (int) $r['contact_id']; if ( isset( $cutoff[ $cid ] ) && $r['created_at'] >= $cutoff[ $cid ] ) { continue; } $t = $r['type']; if ( 'pageview' === $t ) { if ( false === strpos( (string) $r['data'], '"intent":true' ) ) { continue; } $t = 'intent'; } $counts[ $cid ][ $t ] = ( $counts[ $cid ][ $t ] ?? 0 ) + 1; } } foreach ( $contacts as $c ) { $id = (int) $c['id']; $n = $counts[ $id ]; $visits = (int) ( $n['visit'] ?? 0 ); $intent = (int) ( $n['intent'] ?? 0 ); $asked = ! empty( $n['form'] ) || ( ! isset( $cutoff[ $id ] ) && ! empty( $c['last_inquiry_at'] ) ); $out[ $id ] = array( 'channel' => self::channel( $c['first_source'] ?? '', $c['first_medium'] ?? '' ), 'visits' => $visits >= 4 ? '4+' : ( $visits >= 2 ? '2-3' : '1' ), 'intent' => $intent >= 2 ? '2+' : ( 1 === $intent ? '1' : '0' ), 'asked' => $asked ? 'yes' : 'no', 'phone' => '' !== trim( (string) ( $c['phone'] ?? '' ) ) ? 'yes' : 'no', 'company' => ! empty( $c['company_id'] ) ? 'yes' : 'no', 'news' => 'subscribed' === (string) ( $c['email_status'] ?? '' ) || ! empty( $n['subscription'] ) ? 'yes' : 'no', 'clicked' => ! empty( $n['click'] ) ? 'yes' : 'no', '_n' => array( 'visits' => $visits, 'intent' => $intent, ), ); } return $out; } /* ------------------------------------------------------------------ * * Learning * ------------------------------------------------------------------ */ /** * Learn from who became a customer: per trait value, how much more (or less) common it is among buyers. * * @return array The model. */ public static function train() { global $wpdb; $ct = Nodebook_Contacts::table(); $at = Nodebook_Activities::table(); $dt = Nodebook_Deals::table(); // Buyers and the moment they first bought (order, booking, won deal or became a customer). // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- the plugin's own tables. $first = array(); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, MIN(created_at) AS t FROM %i WHERE contact_id > 0 AND type IN ('order','booking','appointment') GROUP BY contact_id", $at ), ARRAY_A ) as $r ) { $first[ (int) $r['contact_id'] ] = (string) $r['t']; } foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, MIN(closed_at) AS t FROM %i WHERE contact_id > 0 AND outcome = 'won' AND closed_at IS NOT NULL GROUP BY contact_id", $dt ), ARRAY_A ) as $r ) { $cid = (int) $r['contact_id']; $first[ $cid ] = isset( $first[ $cid ] ) ? min( $first[ $cid ], (string) $r['t'] ) : (string) $r['t']; } foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, COALESCE(status_at, updated_at) AS t FROM %i WHERE status = 'customer' LIMIT 5000", $ct ), ARRAY_A ) as $r ) { $cid = (int) $r['id']; if ( ! isset( $first[ $cid ] ) ) { $first[ $cid ] = (string) $r['t']; } } // Sample data teaches nothing about this business. $sample = class_exists( 'Nodebook_Sample' ) ? array_flip( Nodebook_Sample::ids() ) : array(); $first = array_diff_key( $first, $sample ); arsort( $first ); $first = array_slice( $first, 0, 600, true ); $buyers = array(); foreach ( array_chunk( array_keys( $first ), 300 ) as $chunk ) { $ph = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $ph is a list of %d. $buyers = array_merge( $buyers, (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, phone, company_id, email_status, first_source, first_medium, last_inquiry_at, status, status_at, created_at FROM %i WHERE id IN ($ph)", array_merge( array( $ct ), $chunk ) ), ARRAY_A ) ); } // Others: people who had a month to buy and did not. $month = gmdate( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ); $others = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, phone, company_id, email_status, first_source, first_medium, last_inquiry_at, status, status_at, created_at FROM %i WHERE status <> 'customer' AND created_at < %s ORDER BY id DESC LIMIT 2000", $ct, $month ), ARRAY_A ); // phpcs:enable $others = array_values( array_filter( $others, static function ( $c ) use ( $first, $sample ) { return ! isset( $first[ (int) $c['id'] ] ) && ! isset( $sample[ (int) $c['id'] ] ); } ) ); $fb = $buyers ? self::features( $buyers, $first ) : array(); $fo = $others ? self::features( $others ) : array(); $p = count( $fb ); $n = count( $fo ); $m = self::PRIOR; $model = array( 'at' => time(), 'buyers' => $p, 'others' => $n, 'learned' => $p >= self::LEARNED, 'lr' => array(), 'share' => array(), ); foreach ( self::defaults() as $trait => $values ) { foreach ( $values as $v => $d ) { $cp = 0; $cn = 0; foreach ( $fb as $f ) { $cp += $f[ $trait ] === (string) $v ? 1 : 0; } foreach ( $fo as $f ) { $cn += $f[ $trait ] === (string) $v ? 1 : 0; } $sp = ( $cp + $m * $d[0] ) / ( $p + $m ); $sn = ( $cn + $m * $d[1] ) / ( $n + $m ); $model['lr'][ $trait ][ (string) $v ] = round( log( max( 1e-4, $sp ) / max( 1e-4, $sn ) ), 4 ); $model['share'][ $trait ][ (string) $v ] = array( round( $sp, 3 ), round( $sn, 3 ) ); } } // 50 means "a typical lead here": the middle of the open leads right now, so the score always tells // apart the best of your current pipeline. With few open leads: the average of those who did not buy, // or what a typical lead looks like by the starting values. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- the plugin's own table. $open = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, phone, company_id, email_status, first_source, first_medium, last_inquiry_at, status, status_at, created_at FROM %i WHERE status NOT IN ('customer','lost','archived') ORDER BY id DESC LIMIT 2000", $ct ), ARRAY_A ); if ( count( $open ) >= 15 ) { $raws = array(); foreach ( self::features( $open ) as $f ) { $raws[] = self::raw( $f, $model ); } sort( $raws ); $mid = (int) floor( count( $raws ) / 2 ); $model['center'] = round( count( $raws ) % 2 ? $raws[ $mid ] : ( $raws[ $mid - 1 ] + $raws[ $mid ] ) / 2, 4 ); } elseif ( $n >= 20 ) { $sum = 0.0; foreach ( $fo as $f ) { $sum += self::raw( $f, $model ); } $model['center'] = round( $sum / $n, 4 ); } else { $center = 0.0; foreach ( self::defaults() as $trait => $values ) { foreach ( $values as $v => $d ) { $center += $d[1] * $model['lr'][ $trait ][ (string) $v ]; } } $model['center'] = round( $center, 4 ); } update_option( self::MODEL, $model, false ); return $model; } public static function model() { $m = get_option( self::MODEL ); if ( ! is_array( $m ) || empty( $m['lr'] ) ) { $m = self::train(); } return $m; } /* ------------------------------------------------------------------ * * Scoring * ------------------------------------------------------------------ */ /** How warm someone is now: recent visits and high-intent pages weigh more. */ private static function warmth( array $c ) { $seen = ! empty( $c['last_seen'] ) ? ( time() - strtotime( $c['last_seen'] . ' UTC' ) ) / DAY_IN_SECONDS : 9999; $w = $seen < 3 ? 2.0 : ( $seen < 14 ? 1.4 : ( $seen < 60 ? 1.0 : ( $seen < 180 ? .7 : .5 ) ) ); if ( 9999 === $seen && ! empty( $c['created_at'] ) ) { $age = ( time() - strtotime( $c['created_at'] . ' UTC' ) ) / DAY_IN_SECONDS; $w = $age < 7 ? 1.4 : ( $age < 60 ? 1.0 : .6 ); } $intent = ! empty( $c['last_intent_at'] ) ? ( time() - strtotime( $c['last_intent_at'] . ' UTC' ) ) / DAY_IN_SECONDS : 9999; if ( $intent < 7 ) { $w *= 1.5; } return $w; } /** * Score one contact from its traits: 50 is a typical lead, every doubling of the odds adds 14. * * @param array $c Contact row. * @param array $f Traits from features(). * @param array $m Model. */ public static function score_of( array $c, array $f, array $m ) { $logit = max( -3.0, min( 3.0, self::raw( $f, $m ) - (float) ( $m['center'] ?? 0 ) ) ); $lift = exp( $logit ) * self::warmth( $c ); // Twice as likely as a typical lead ≈ 64, four times ≈ 78, eight times ≈ 92. $x = max( -2.5, min( 3.5, log( $lift, 2 ) ) ); return (int) max( 1, min( 99, round( 50 + 14 * $x ) ) ); } /** Sum of the evidence of all traits (before centring). */ private static function raw( array $f, array $m ) { $sum = 0.0; foreach ( self::traits() as $trait => $vals ) { $sum += (float) ( $m['lr'][ $trait ][ $f[ $trait ] ] ?? 0 ); } return $sum; } /** Contacts that get a score: everyone who has not bought (customers get "due to reorder" instead). */ private static function scorable( array $c ) { return ! in_array( (string) $c['status'], array( 'customer', 'lost', 'archived' ), true ); } /** Score some contacts and store it. */ public static function score_ids( array $ids ) { global $wpdb; $ids = array_values( array_filter( array_map( 'absint', $ids ) ) ); if ( ! $ids ) { return 0; } $m = self::model(); $ph = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the plugin's own table; $ph is a list of %d. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE id IN ($ph)", array_merge( array( Nodebook_Contacts::table() ), $ids ) ), ARRAY_A ); $feat = self::features( $rows ); $now = current_time( 'mysql', true ); $n = 0; foreach ( $rows as $c ) { $score = self::scorable( $c ) ? self::score_of( $c, $feat[ (int) $c['id'] ], $m ) : null; // Straight to the table: a score is not an edit (no "updated", no hooks). $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. Nodebook_Contacts::table(), array( 'score' => $score, 'score_at' => $now, ), array( 'id' => (int) $c['id'] ) ); ++$n; } return $n; } /** Nightly: learn, then score everyone (in batches), and find who is due to reorder. */ public static function nightly() { self::train(); self::reorder_scan(); update_option( 'nodebook_insights_cursor', 0, false ); self::score_batch(); } /** One batch of scoring; schedules the next until everyone is done. */ public static function score_batch() { global $wpdb; $after = (int) get_option( 'nodebook_insights_cursor', 0 ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $ids = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE id > %d ORDER BY id ASC LIMIT %d', Nodebook_Contacts::table(), $after, self::BATCH ) ) ); if ( ! $ids ) { return 0; } self::score_ids( $ids ); update_option( 'nodebook_insights_cursor', end( $ids ), false ); if ( count( $ids ) === self::BATCH && ! wp_next_scheduled( self::RUN ) ) { wp_schedule_single_event( time() + 10, self::RUN ); } return count( $ids ); } /** Something happened: score again (at most once a minute per contact for visits). */ public static function on_change( $contact_id ) { self::score_ids( array( (int) $contact_id ) ); } public static function on_visit( $contact_id ) { $key = 'nodebook_scored_' . (int) $contact_id; if ( get_transient( $key ) ) { return; } set_transient( $key, 1, MINUTE_IN_SECONDS ); self::score_ids( array( (int) $contact_id ) ); } public static function on_conversion( $contact_id, $type ) { self::score_ids( array( (int) $contact_id ) ); if ( in_array( $type, array( 'order', 'booking', 'appointment' ), true ) ) { self::reorder_forget( (int) $contact_id ); } } /** Sample data: score it straight away so the screens show what scores look like. */ public static function after_sample( $made = array() ) { $ids = class_exists( 'Nodebook_Sample' ) ? Nodebook_Sample::ids() : array(); self::score_ids( $ids ); self::reorder_scan(); } /** * Why a contact scores what it does: the strongest reasons, in words. * * @param array $c Contact. * @return array{score:int|null, label:string, tone:string, reasons:string[], learned:bool} */ public static function explain( array $c ) { $score = isset( $c['score'] ) && null !== $c['score'] && '' !== $c['score'] ? (int) $c['score'] : null; $m = self::model(); $out = array( 'score' => $score, 'label' => '', 'tone' => '', 'reasons' => array(), 'learned' => ! empty( $m['learned'] ), ); if ( null === $score ) { return $out; } $out['label'] = $score >= 75 ? __( 'Very likely', 'nodebook' ) : ( $score >= 60 ? __( 'Likely', 'nodebook' ) : ( $score >= 40 ? __( 'Maybe', 'nodebook' ) : __( 'Unlikely', 'nodebook' ) ) ); $out['tone'] = $score >= 75 ? 'hot' : ( $score >= 60 ? 'warm' : ( $score >= 40 ? 'mild' : 'cold' ) ); $f = self::features( array( $c ) )[ (int) $c['id'] ]; $lines = array(); foreach ( self::traits() as $trait => $vals ) { $lr = (float) ( $m['lr'][ $trait ][ $f[ $trait ] ] ?? 0 ); if ( $lr < .25 ) { continue; } $text = self::reason_text( $trait, $f, $c ); if ( '' === $text ) { continue; } if ( ! empty( $m['learned'] ) ) { $sh = $m['share'][ $trait ][ $f[ $trait ] ] ?? null; if ( $sh && $sh[1] > 0 ) { /* translators: 1: reason, 2: how many times more common, like "2.4" */ $text = sprintf( __( '%1$s (%2$s× more common among your buyers)', 'nodebook' ), $text, number_format_i18n( $sh[0] / $sh[1], 1 ) ); } } $lines[ $text ] = $lr; } arsort( $lines ); $out['reasons'] = array_slice( array_keys( $lines ), 0, 3 ); $seen = ! empty( $c['last_seen'] ) ? ( time() - strtotime( $c['last_seen'] . ' UTC' ) ) / DAY_IN_SECONDS : 9999; if ( $seen < 3 ) { /* translators: %s: time ago */ $out['reasons'][] = sprintf( __( 'on your site %s ago', 'nodebook' ), human_time_diff( strtotime( $c['last_seen'] . ' UTC' ) ) ); } elseif ( $seen > 180 && 9999 !== $seen ) { $out['reasons'][] = __( 'not seen in over half a year', 'nodebook' ); } return $out; } private static function reason_text( $trait, array $f, array $c ) { switch ( $trait ) { case 'channel': /* translators: %s: where they came from, like "Google · paid" */ return sprintf( __( 'came from %s', 'nodebook' ), Nodebook_Attribution::label( (string) $c['first_source'], (string) $c['first_medium'] ) ); case 'visits': /* translators: %s: number of visits */ return sprintf( _n( 'came back %s time', 'came back %s times', max( 1, $f['_n']['visits'] - 1 ), 'nodebook' ), number_format_i18n( max( 1, $f['_n']['visits'] - 1 ) ) ); case 'intent': /* translators: %s: number of page views */ return sprintf( _n( 'read a pricing or booking page (%s view)', 'read pricing or booking pages (%s views)', $f['_n']['intent'], 'nodebook' ), number_format_i18n( $f['_n']['intent'] ) ); case 'asked': return 'yes' === $f['asked'] ? __( 'asked you something', 'nodebook' ) : ''; case 'phone': return 'yes' === $f['phone'] ? __( 'left a phone number', 'nodebook' ) : ''; case 'company': return 'yes' === $f['company'] ? __( 'works at a company', 'nodebook' ) : ''; case 'news': return 'yes' === $f['news'] ? __( 'subscribed to your emails', 'nodebook' ) : ''; case 'clicked': return 'yes' === $f['clicked'] ? __( 'clicked to call, message or email you', 'nodebook' ) : ''; } return ''; } /** A small pill with the score, for lists. */ public static function pill( $score, $title = '' ) { if ( null === $score || '' === $score ) { return ''; } $s = (int) $score; $tone = $s >= 75 ? 'hot' : ( $s >= 60 ? 'warm' : ( $s >= 40 ? 'mild' : 'cold' ) ); /* translators: %s: score */ $t = '' !== $title ? $title : sprintf( __( 'Likely to buy: %s out of 100', 'nodebook' ), $s ); return '' . esc_html( (string) $s ) . ''; } /* ------------------------------------------------------------------ * * Best time to reach someone * ------------------------------------------------------------------ */ /** * When someone is usually around, from their own visits, forms and clicks (site time). * * @param int $contact_id Contact. * @return array|null from (hour), to (hour), days (weekdays|weekends|any), text, now (bool: inside the window now). */ public static function best_time( $contact_id ) { global $wpdb; $key = 'nodebook_besttime_' . (int) $contact_id; $hit = wp_cache_get( $key, 'nodebook' ); if ( false !== $hit ) { return $hit ? $hit : null; } $since = gmdate( 'Y-m-d H:i:s', time() - 180 * DAY_IN_SECONDS ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $times = (array) $wpdb->get_col( $wpdb->prepare( "SELECT created_at FROM %i WHERE contact_id = %d AND type IN ('visit','form','click','order','booking','appointment','subscription') AND created_at >= %s ORDER BY id DESC LIMIT 300", Nodebook_Activities::table(), (int) $contact_id, $since ) ); $res = self::window( $times ); wp_cache_set( $key, $res ? $res : 0, 'nodebook', 300 ); return $res; } /** * The busiest three-hour stretch in a list of GMT times, if there is a clear one. * * @param string[] $times GMT datetimes. */ public static function window( array $times ) { $tz = wp_timezone(); $hours = array_fill( 0, 24, 0 ); $days = array(); $week = 0; foreach ( $times as $t ) { $d = ( new DateTimeImmutable( $t, new DateTimeZone( 'UTC' ) ) )->setTimezone( $tz ); ++$hours[ (int) $d->format( 'G' ) ]; $days[ $d->format( 'Y-m-d' ) ] = true; $week += (int) $d->format( 'N' ) >= 6 ? 0 : 1; } $n = count( $times ); if ( $n < 5 || count( $days ) < 2 ) { return null; } $best = 0; $from = 0; for ( $h = 0; $h < 24; $h++ ) { $sum = $hours[ $h ] + $hours[ ( $h + 1 ) % 24 ] + $hours[ ( $h + 2 ) % 24 ]; if ( $sum > $best ) { $best = $sum; $from = $h; } } // Only when it is a real pattern: the window holds at least 40% (a flat day would hold 12.5%). if ( $best / $n < .4 ) { return null; } $to = ( $from + 3 ) % 24; $share = $week / $n; $which = $share >= .8 ? 'weekdays' : ( $share <= .3 ? 'weekends' : 'any' ); $part = $from >= 5 && $from < 11 ? __( 'mornings', 'nodebook' ) : ( $from >= 11 && $from < 14 ? __( 'around lunch', 'nodebook' ) : ( $from >= 14 && $from < 17 ? __( 'afternoons', 'nodebook' ) : ( $from >= 17 && $from < 22 ? __( 'evenings', 'nodebook' ) : __( 'late at night', 'nodebook' ) ) ) ); $range = sprintf( '%02d:00–%02d:00', $from, $to ); if ( 'weekdays' === $which ) { /* translators: 1: part of the day, like "evenings", 2: hours */ $text = sprintf( __( 'Weekday %1$s (%2$s)', 'nodebook' ), $part, $range ); } elseif ( 'weekends' === $which ) { /* translators: 1: part of the day, 2: hours */ $text = sprintf( __( 'Weekend %1$s (%2$s)', 'nodebook' ), $part, $range ); } else { /* translators: 1: part of the day, 2: hours */ $text = sprintf( __( 'Usually %1$s (%2$s)', 'nodebook' ), $part, $range ); } $now = (int) wp_date( 'G' ); $in = $from < $to ? ( $now >= $from && $now < $to ) : ( $now >= $from || $now < $to ); $wday = (int) wp_date( 'N' ) < 6; $in = $in && ( 'any' === $which || ( 'weekdays' === $which ) === $wday ); return array( 'from' => $from, 'to' => $to, 'days' => $which, 'text' => mb_strtoupper( mb_substr( $text, 0, 1 ) ) . mb_substr( $text, 1 ), 'now' => $in, ); } /* ------------------------------------------------------------------ * * Due to reorder * ------------------------------------------------------------------ */ /** Customers who buy regularly and are past their usual interval: contact ID => [ every (days), last (GMT), due (GMT), count ]. */ public static function reorder_scan() { global $wpdb; $at = Nodebook_Activities::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $ids = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT contact_id FROM %i WHERE contact_id > 0 AND type IN ('order','booking','appointment') GROUP BY contact_id HAVING COUNT(*) >= 3 LIMIT 5000", $at ) ) ); $out = array(); foreach ( array_chunk( $ids, 200 ) as $chunk ) { $ph = implode( ',', array_fill( 0, count( $chunk ), '%d' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $ph is a list of %d. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, created_at FROM %i WHERE contact_id IN ($ph) AND type IN ('order','booking','appointment') ORDER BY created_at ASC", array_merge( array( $at ), $chunk ) ), ARRAY_A ); $by = array(); foreach ( $rows as $r ) { $by[ (int) $r['contact_id'] ][] = strtotime( $r['created_at'] . ' UTC' ); } foreach ( $by as $cid => $ts ) { $r = self::interval( $ts ); if ( $r ) { $out[ $cid ] = $r; } } } // phpcs:enable update_option( self::REORDER, $out, false ); return $out; } /** * From purchase moments: the usual gap and whether they are now overdue. * * @param int[] $ts Unix times, oldest first. */ public static function interval( array $ts ) { sort( $ts ); // Two orders on the same day are one shopping trip. $days = array(); foreach ( $ts as $t ) { $days[ gmdate( 'Y-m-d', $t ) ] = $t; } $ts = array_values( $days ); if ( count( $ts ) < 3 ) { return null; } $gaps = array(); for ( $i = 1; $i < count( $ts ); $i++ ) { $gaps[] = ( $ts[ $i ] - $ts[ $i - 1 ] ) / DAY_IN_SECONDS; } sort( $gaps ); $mid = (int) floor( count( $gaps ) / 2 ); $every = count( $gaps ) % 2 ? $gaps[ $mid ] : ( $gaps[ $mid - 1 ] + $gaps[ $mid ] ) / 2; if ( $every < 7 ) { return null; // Daily buyers do not need a nudge. } // Regular enough: most gaps within half to twice the usual one. $regular = 0; foreach ( $gaps as $g ) { $regular += $g >= $every / 2 && $g <= $every * 2 ? 1 : 0; } if ( $regular / count( $gaps ) < .6 ) { return null; } $last = end( $ts ); $since = ( time() - $last ) / DAY_IN_SECONDS; if ( $since < $every * 1.25 || $since > $every * 4 ) { return null; } return array( 'every' => (int) round( $every ), 'last' => gmdate( 'Y-m-d H:i:s', $last ), 'since' => (int) floor( $since ), 'count' => count( $ts ), ); } /** Who is due to reorder now (most overdue first), for those this user may see. */ public static function reorder_due( $owner = 0, $limit = 20 ) { $all = get_option( self::REORDER ); if ( ! is_array( $all ) ) { $all = self::reorder_scan(); } // Most overdue first, then load only as many contacts as needed. foreach ( $all as $cid => $r ) { $all[ $cid ]['since'] = (int) floor( ( time() - strtotime( $r['last'] . ' UTC' ) ) / DAY_IN_SECONDS ); $all[ $cid ]['late'] = $all[ $cid ]['since'] / max( 1, $r['every'] ); } uasort( $all, static function ( $a, $b ) { return $b['late'] <=> $a['late']; } ); $out = array(); foreach ( $all as $cid => $r ) { if ( count( $out ) >= $limit ) { break; } $c = Nodebook_Contacts::get( (int) $cid ); if ( ! $c || ! Nodebook_Team::can_see( $c ) || ( $owner && (int) $c['owner_id'] && (int) $c['owner_id'] !== (int) $owner ) ) { continue; } // Already in touch since the last purchase: nothing to nudge. if ( ! empty( $c['followed_up_at'] ) && $c['followed_up_at'] > $r['last'] ) { continue; } $out[ (int) $cid ] = array( 'contact' => $c ) + $r; } return $out; } public static function reorder_of( $contact_id ) { $all = get_option( self::REORDER ); return is_array( $all ) && isset( $all[ (int) $contact_id ] ) ? $all[ (int) $contact_id ] : null; } private static function reorder_forget( $contact_id ) { $all = get_option( self::REORDER ); if ( is_array( $all ) && isset( $all[ (int) $contact_id ] ) ) { unset( $all[ (int) $contact_id ] ); update_option( self::REORDER, $all, false ); } } /** "every 6 weeks", "every 10 days", "every 3 months". */ public static function every( $days ) { $days = (int) $days; if ( $days >= 60 ) { $n = (int) round( $days / 30 ); /* translators: %s: number of months */ return 1 === $n ? __( 'every month', 'nodebook' ) : sprintf( _n( 'every %s month', 'every %s months', $n, 'nodebook' ), number_format_i18n( $n ) ); } if ( $days >= 14 ) { $n = (int) round( $days / 7 ); /* translators: %s: number of weeks */ return 1 === $n ? __( 'every week', 'nodebook' ) : sprintf( _n( 'every %s week', 'every %s weeks', $n, 'nodebook' ), number_format_i18n( $n ) ); } /* translators: %s: number of days */ return 1 === $days ? __( 'every day', 'nodebook' ) : sprintf( _n( 'every %s day', 'every %s days', $days, 'nodebook' ), number_format_i18n( $days ) ); } /** "9 weeks", "12 days". */ public static function span( $days ) { $days = (int) $days; if ( $days >= 60 ) { $n = (int) round( $days / 30 ); /* translators: %s: number of months */ return sprintf( _n( '%s month', '%s months', $n, 'nodebook' ), number_format_i18n( $n ) ); } if ( $days >= 14 ) { $n = (int) round( $days / 7 ); /* translators: %s: number of weeks */ return sprintf( _n( '%s week', '%s weeks', $n, 'nodebook' ), number_format_i18n( $n ) ); } /* translators: %s: number of days */ return sprintf( _n( '%s day', '%s days', $days, 'nodebook' ), number_format_i18n( $days ) ); } }