query( $wpdb->prepare( 'UPDATE %i SET last_inquiry_at = %s WHERE id = %d AND ( last_inquiry_at IS NULL OR last_inquiry_at < %s )', Nodebook_Contacts::table(), $row['created_at'], (int) $row['contact_id'], $row['created_at'] ) ); self::clear_badge(); } /** Whether new interest (a visit, a high-intent page) brings a snoozed contact back before the date. */ public static function snooze_strict() { return 'strict' === Nodebook_Settings::get( 'snooze' ); } /** * "Gone quiet" thresholds in days: an open lead with no status change, contact or visit; * a customer not back on the site; someone who came back several times and then stopped. * Each person surfaces once, for WINDOW days after crossing the line, so the list never floods. */ public static function quiet_days() { return apply_filters( 'nodebook_quiet_days', array( 'stalled' => 30, 'customer' => 90, 'cooling' => 14, ) ); } /** Statuses that are still "in play" (not yet customer, inactive or subscriber). */ public static function open_statuses() { return (array) apply_filters( 'nodebook_open_statuses', array( 'lead', 'prospect' ) ); } public static function quiet_on() { return (bool) Nodebook_Settings::get( 'quiet' ); } /** * The three "gone quiet" lookups, each on one indexed column, as a condition-style pair: * array( fixed SQL with placeholders, values ). $own is the fixed owner/visibility filter with its values. */ private static function quiet_union( array $own ) { $t = Nodebook_Contacts::table(); $d = self::quiet_days(); $ago = static function ( $days ) { return gmdate( 'Y-m-d H:i:s', time() - (int) $days * DAY_IN_SECONDS ); }; $open = array_values( array_map( 'strval', self::open_statuses() ) ); $sql = array(); $args = array(); if ( $open ) { $in = Nodebook_Sql::list_of( count( $open ), '%s' ); $sql[] = 'SELECT id FROM %i WHERE status_at >= %s AND status_at < %s AND status IN (' . $in . ') AND remind_at IS NULL AND ( last_seen IS NULL OR last_seen < %s ) AND ( followed_up_at IS NULL OR followed_up_at < %s )' . $own[0]; $args = array_merge( $args, array( $t, $ago( $d['stalled'] + self::WINDOW ), $ago( $d['stalled'] ) ), $open, array( $ago( $d['stalled'] ), $ago( $d['stalled'] ) ), $own[1] ); $sql[] = 'SELECT id FROM %i WHERE last_seen >= %s AND last_seen < %s AND status IN (' . $in . ') AND visits_count >= 3 AND remind_at IS NULL AND ( followed_up_at IS NULL OR followed_up_at < last_seen )' . $own[0]; $args = array_merge( $args, array( $t, $ago( $d['cooling'] + self::WINDOW ), $ago( $d['cooling'] ) ), $open, $own[1] ); } $sql[] = "SELECT id FROM %i WHERE last_seen >= %s AND last_seen < %s AND status = 'customer' AND remind_at IS NULL AND ( followed_up_at IS NULL OR followed_up_at < last_seen )" . $own[0]; $args = array_merge( $args, array( $t, $ago( $d['customer'] + self::WINDOW ), $ago( $d['customer'] ) ), $own[1] ); return array( implode( ' UNION ', $sql ), $args ); } /** * Why a contact is on the list because they went quiet: stalled | customer | cooling | ''. */ public static function quiet_kind( array $c ) { if ( ! self::quiet_on() || ! empty( $c['remind_at'] ) ) { return ''; } $d = self::quiet_days(); $now = time(); $ts = static function ( $v ) { return $v ? strtotime( $v . ' UTC' ) : 0; }; $seen = $ts( $c['last_seen'] ); $done = $ts( $c['followed_up_at'] ); $open = in_array( $c['status'], self::open_statuses(), true ); $in = static function ( $t, $days ) use ( $now ) { return $t && $t < $now - $days * DAY_IN_SECONDS && $t >= $now - ( $days + self::WINDOW ) * DAY_IN_SECONDS; }; $st = $ts( $c['status_at'] ?? '' ); if ( $open && $in( $st, $d['stalled'] ) && ( ! $seen || $seen < $now - $d['stalled'] * DAY_IN_SECONDS ) && ( ! $done || $done < $now - $d['stalled'] * DAY_IN_SECONDS ) ) { return 'stalled'; } if ( $open && (int) $c['visits_count'] >= 3 && $in( $seen, $d['cooling'] ) && $done < $seen ) { return 'cooling'; } if ( 'customer' === $c['status'] && $in( $seen, $d['customer'] ) && $done < $seen ) { return 'customer'; } return ''; } /** Plain-language reason for a quiet contact. */ public static function quiet_reason( array $c, $kind ) { $d = self::quiet_days(); switch ( $kind ) { case 'stalled': /* translators: %d: days */ return sprintf( __( 'Gone quiet: no change, contact or visit in %d days', 'nodebook' ), $d['stalled'] ); case 'cooling': /* translators: %d: number of visits */ return sprintf( __( 'Came back %d times, then stopped', 'nodebook' ), (int) $c['visits_count'] ); case 'customer': /* translators: %d: days */ return sprintf( __( 'Customer not back in %d days', 'nodebook' ), $d['customer'] ); } return ''; } /** * IDs that are due, as a UNION of index-friendly lookups (fast on 100k+ contacts): an unanswered inquiry, * a fresh intent signal, a watched contact who came back, a reminder that came due, or (optionally) gone quiet. * * @return array{0:string,1:array} Fixed SQL with placeholders, and their values. */ private static function due_ids( $owner = 0 ) { $t = Nodebook_Contacts::table(); $since = gmdate( 'Y-m-d H:i:s', time() - self::WINDOW * DAY_IN_SECONDS ); $now = current_time( 'mysql', true ); // Mine = assigned to me, or nobody's yet (so unassigned leads are never lost); plus who may see what. $own = array( ' AND ( %d = 0 OR owner_id IN (0, %d) ) AND ( %d = 0 OR owner_id = %d OR ( %d = 1 AND owner_id = 0 ) )', array_merge( array( (int) $owner, (int) $owner ), Nodebook_Team::scope_args() ), ); // Snoozed (a reminder still ahead) and the site keeps snoozes: new interest waits for the date. $strict = self::snooze_strict() ? 1 : 0; $sql = 'SELECT id FROM %i WHERE last_inquiry_at >= %s AND ( followed_up_at IS NULL OR followed_up_at < last_inquiry_at )' . $own[0] . ' UNION SELECT id FROM %i WHERE last_intent_at >= %s AND ( followed_up_at IS NULL OR followed_up_at < last_intent_at ) AND ( %d = 0 OR remind_at IS NULL OR remind_at <= %s )' . $own[0] . ' UNION SELECT id FROM %i WHERE last_seen >= %s AND watched = 1 AND ( followed_up_at IS NULL OR followed_up_at < last_seen ) AND ( %d = 0 OR remind_at IS NULL OR remind_at <= %s )' . $own[0] . ' UNION SELECT id FROM %i WHERE remind_at <= %s' . $own[0]; $args = array_merge( array( $t, gmdate( 'Y-m-d H:i:s', time() - self::INQUIRY_WINDOW * DAY_IN_SECONDS ) ), $own[1], array( $t, $since, $strict, $now ), $own[1], array( $t, $since, $strict, $now ), $own[1], array( $t, $now ), $own[1] ); if ( self::quiet_on() ) { $quiet = self::quiet_union( $own ); $sql .= ' UNION ' . $quiet[0]; $args = array_merge( $args, $quiet[1] ); } return array( $sql, $args ); } /** * Contacts to follow up, newest signal first. Reminders that came due sort to the top. * * @param int $limit Max rows. * @param int $owner User ID to show "mine" (plus unassigned); 0 = everyone. * @return array[] */ public static function due( $limit = 8, $owner = 0 ) { global $wpdb; list( $ids, $args ) = self::due_ids( $owner ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $ids is fixed SQL with placeholders; every value is passed to prepare(). $rows = $wpdb->get_results( $wpdb->prepare( "SELECT c.* FROM %i c INNER JOIN ( " . $ids . " ) d ON d.id = c.id ORDER BY ( c.last_inquiry_at IS NOT NULL AND ( c.followed_up_at IS NULL OR c.followed_up_at < c.last_inquiry_at ) ) DESC, CASE WHEN c.last_inquiry_at IS NOT NULL AND ( c.followed_up_at IS NULL OR c.followed_up_at < c.last_inquiry_at ) THEN 0 WHEN c.remind_at IS NOT NULL AND c.remind_at <= %s THEN 1 ELSE 0 END DESC, COALESCE( c.score, 50 ) DESC, GREATEST( COALESCE( c.last_inquiry_at, '1970-01-01' ), COALESCE( c.last_intent_at, '1970-01-01' ), COALESCE( c.last_seen, '1970-01-01' ), COALESCE( c.remind_at, '1970-01-01' ) ) DESC, c.id DESC LIMIT %d", array_merge( array( Nodebook_Contacts::table() ), $args, array( current_time( 'mysql', true ), (int) $limit ) ) ), ARRAY_A ); return array_map( array( 'Nodebook_Contacts', 'hydrate' ), (array) $rows ); } /** Menu badge: cached 2 minutes per user; cleared when that user acts on a follow-up. */ public static function badge( $owner = 0 ) { $key = 'nodebook_due_' . (int) get_current_user_id() . '_' . (int) $owner; $count = get_transient( $key ); if ( false === $count ) { $count = self::count_due( $owner ); set_transient( $key, $count, 2 * MINUTE_IN_SECONDS ); } return (int) $count; } public static function clear_badge() { $uid = (int) get_current_user_id(); delete_transient( 'nodebook_due_' . $uid . '_0' ); delete_transient( 'nodebook_due_' . $uid . '_' . $uid ); } public static function count_due( $owner = 0 ) { global $wpdb; list( $ids, $args ) = self::due_ids( $owner ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $ids is fixed SQL with placeholders; every value is passed to prepare(). return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ( ' . $ids . ' ) d', $args ) ); } public static function is_due( array $c ) { $remind = ! empty( $c['remind_at'] ) ? strtotime( $c['remind_at'] . ' UTC' ) : 0; return self::unanswered( $c ) || self::fresh_signal( $c ) || ( $remind && $remind <= time() ) || '' !== self::quiet_kind( $c ); } /** An inquiry (form, webhook) nobody has followed up on yet, from the last 30 days. */ public static function unanswered( array $c ) { $asked = ! empty( $c['last_inquiry_at'] ) ? strtotime( $c['last_inquiry_at'] . ' UTC' ) : 0; $done = ! empty( $c['followed_up_at'] ) ? strtotime( $c['followed_up_at'] . ' UTC' ) : 0; return $asked >= time() - self::INQUIRY_WINDOW * DAY_IN_SECONDS && $done < $asked; } /** Snooze presets in days. */ public static function snoozes() { return array( 3 => __( '3 days', 'nodebook' ), 7 => __( '1 week', 'nodebook' ), 30 => __( '1 month', 'nodebook' ), ); } /** * Off the list now, back on it in N days (as a reminder), whatever they do meanwhile. */ public static function snooze( $contact_id, $days, $user_id = 0 ) { $days = (int) $days; if ( ! isset( self::snoozes()[ $days ] ) || ! Nodebook_Contacts::get( $contact_id ) ) { return false; } self::clear_badge(); $ts = ( new DateTimeImmutable( 'now', wp_timezone() ) )->modify( '+' . $days . ' days' )->setTime( 9, 0 )->getTimestamp(); Nodebook_Contacts::update( $contact_id, array( 'followed_up_at' => current_time( 'mysql', true ), 'remind_at' => gmdate( 'Y-m-d H:i:s', $ts ), ) ); Nodebook_Activities::add( $contact_id, 'note', /* translators: %s: date */ sprintf( __( 'Snoozed until %s', 'nodebook' ), wp_date( get_option( 'date_format' ), $ts ) ), array( 'user_id' => (int) $user_id, 'data' => array( 'text' => __( 'Snoozed follow-up', 'nodebook' ), 'reminder' => gmdate( 'Y-m-d H:i:s', $ts ), ), ) ); return true; } /** Set (or clear with '') a reminder; logs it on the timeline. */ public static function remind( $contact_id, $when, $note = '', $user_id = 0 ) { self::clear_badge(); $contact_id = absint( $contact_id ); if ( ! Nodebook_Contacts::get( $contact_id ) ) { return false; } if ( '' === (string) $when ) { Nodebook_Contacts::update( $contact_id, array( 'remind_at' => null ) ); return true; } $ts = is_numeric( $when ) ? (int) $when : strtotime( (string) $when ); if ( ! $ts ) { return false; } Nodebook_Contacts::update( $contact_id, array( 'remind_at' => gmdate( 'Y-m-d H:i:s', $ts ) ) ); $note = mb_substr( sanitize_text_field( (string) $note ), 0, 200 ); Nodebook_Activities::add( $contact_id, 'note', /* translators: %s: date */ sprintf( __( 'Reminder set for %s', 'nodebook' ), wp_date( get_option( 'date_format' ), $ts ) ), array( 'user_id' => (int) $user_id, 'data' => array( 'text' => $note, 'reminder' => gmdate( 'Y-m-d H:i:s', $ts ), ), ) ); return true; } /** Reminder presets → timestamp (local 9:00). */ public static function preset( $key ) { $days = array( 'tomorrow' => 1, '3days' => 3, 'week' => 7, '2weeks' => 14, 'month' => 30, ); if ( ! isset( $days[ $key ] ) ) { return 0; } $tz = wp_timezone(); $day = new DateTimeImmutable( 'now', $tz ); return $day->modify( '+' . $days[ $key ] . ' days' )->setTime( 9, 0 )->getTimestamp(); } /** Channels for a logged contact moment. */ public static function channels() { return array( 'call' => __( 'Call', 'nodebook' ), 'whatsapp' => __( 'WhatsApp', 'nodebook' ), 'email' => __( 'Email', 'nodebook' ), 'meeting' => __( 'Meeting', 'nodebook' ), ); } /** Log that someone reached out (or met). Counts as a follow-up and clears a due reminder. */ /** Saved reply templates: [ [ name, text ] ]. */ public static function templates() { $t = Nodebook_Settings::get( 'templates' ); return is_array( $t ) ? array_values( $t ) : array(); } /** How a call, message or meeting went. */ public static function outcomes() { return array( 'spoke' => __( 'Spoke', 'nodebook' ), 'no_answer' => __( 'No answer', 'nodebook' ), 'left_message' => __( 'Left a message', 'nodebook' ), 'quote_sent' => __( 'Sent a quote or proposal', 'nodebook' ), 'not_interested' => __( 'Not interested', 'nodebook' ), 'yes' => __( 'Said yes', 'nodebook' ), ); } public static function log_touch( $contact_id, $channel, $text = '', $user_id = 0, $outcome = '' ) { self::clear_badge(); $contact_id = absint( $contact_id ); $channels = self::channels(); if ( ! isset( $channels[ $channel ] ) || ! Nodebook_Contacts::get( $contact_id ) ) { return false; } $titles = array( 'call' => __( 'Called', 'nodebook' ), 'whatsapp' => __( 'WhatsApp message', 'nodebook' ), 'email' => __( 'Emailed', 'nodebook' ), 'meeting' => __( 'Meeting', 'nodebook' ), ); $text = sanitize_textarea_field( (string) $text ); $outcomes = self::outcomes(); $outcome = isset( $outcomes[ $outcome ] ) ? $outcome : ''; $title = $titles[ $channel ] . ( '' !== $outcome ? ' · ' . $outcomes[ $outcome ] : '' ) . ( '' !== trim( $text ) ? ': ' . wp_trim_words( $text, 10, '…' ) : '' ); Nodebook_Activities::add( $contact_id, 'touch', $title, array( 'user_id' => (int) $user_id, 'data' => array_filter( array( 'channel' => $channel, 'outcome' => $outcome, 'text' => mb_substr( $text, 0, 5000 ), ) ), ) ); $c = Nodebook_Contacts::get( $contact_id ); $update = array( 'followed_up_at' => current_time( 'mysql', true ) ); if ( ! empty( $c['remind_at'] ) && strtotime( $c['remind_at'] . ' UTC' ) <= time() ) { $update['remind_at'] = null; } Nodebook_Contacts::update( $contact_id, $update ); return true; } /** Why they are on the list: the latest high-intent page view or click. */ public static function reason( $contact_id ) { global $wpdb; $c = Nodebook_Contacts::get( $contact_id ); // Someone asked something and nobody answered yet: that comes first. if ( $c && self::unanswered( $c ) ) { $row = $wpdb->get_row( $wpdb->prepare( "SELECT type, title, url, created_at FROM %i WHERE contact_id = %d AND type = 'form' AND user_id = 0 ORDER BY created_at DESC, id DESC LIMIT 1", Nodebook_Activities::table(), $contact_id ), ARRAY_A ); if ( $row ) { return array( 'type' => 'inquiry', /* translators: %s: what they sent, e.g. "Viewing request: Villa 26" */ 'title' => sprintf( __( 'Waiting for an answer: %s', 'nodebook' ), $row['title'] ), 'url' => $row['url'], 'created_at' => $row['created_at'], ); } } if ( $c && ! empty( $c['remind_at'] ) && strtotime( $c['remind_at'] . ' UTC' ) <= time() ) { $note = $wpdb->get_var( $wpdb->prepare( "SELECT data FROM %i WHERE contact_id = %d AND type = 'note' AND data LIKE %s ORDER BY id DESC LIMIT 1", Nodebook_Activities::table(), $contact_id, '%' . $wpdb->esc_like( '"reminder"' ) . '%' ) ); $d = $note ? json_decode( (string) $note, true ) : array(); return array( 'type' => 'reminder', 'title' => ! empty( $d['text'] ) ? sprintf( /* translators: %s: reminder note */ __( 'Reminder: %s', 'nodebook' ), $d['text'] ) : __( 'Reminder', 'nodebook' ), 'url' => '', 'created_at' => $c['remind_at'], ); } if ( $c && ! self::fresh_signal( $c ) ) { $kind = self::quiet_kind( $c ); if ( $kind ) { return array( 'type' => 'quiet', 'kind' => $kind, 'title' => self::quiet_reason( $c, $kind ), 'url' => '', 'created_at' => 'stalled' === $kind ? ( $c['last_seen'] && $c['last_seen'] > (string) $c['status_at'] ? $c['last_seen'] : $c['status_at'] ) : $c['last_seen'], ); } } $row = $wpdb->get_row( $wpdb->prepare( "SELECT type, title, url, created_at FROM %i WHERE contact_id = %d AND type IN ('pageview','click') AND data LIKE %s ORDER BY id DESC LIMIT 1", Nodebook_Activities::table(), $contact_id, '%' . $wpdb->esc_like( '"intent":true' ) . '%' ), ARRAY_A ); if ( ! $row ) { $row = $wpdb->get_row( $wpdb->prepare( "SELECT type, title, url, created_at FROM %i WHERE contact_id = %d AND type IN ('visit','pageview') ORDER BY id DESC LIMIT 1", Nodebook_Activities::table(), $contact_id ), ARRAY_A ); } return $row ? $row : null; } /** A fresh intent or watched-return signal (those explain themselves better than "gone quiet"). */ private static function fresh_signal( array $c ) { $remind = ! empty( $c['remind_at'] ) ? strtotime( $c['remind_at'] . ' UTC' ) : 0; if ( $remind > time() && self::snooze_strict() ) { return false; } $since = time() - self::WINDOW * DAY_IN_SECONDS; $done = $c['followed_up_at'] ? strtotime( $c['followed_up_at'] . ' UTC' ) : 0; $hot = $c['last_intent_at'] ? strtotime( $c['last_intent_at'] . ' UTC' ) : 0; $seen = $c['last_seen'] ? strtotime( $c['last_seen'] . ' UTC' ) : 0; return ( $hot >= $since && $done < $hot ) || ( ! empty( $c['watched'] ) && $seen >= $since && $done < $seen ); } /** The one thing they looked at most: what the message should be about. */ public static function topic( $contact_id ) { static $cache = array(); $contact_id = (int) $contact_id; if ( ! array_key_exists( $contact_id, $cache ) ) { $items = Nodebook_Interests::for_contact( $contact_id, 1 ); $cache[ $contact_id ] = $items ? $items[0] : null; } return $cache[ $contact_id ]; } /** Prefilled message text, in the site's niche wording. */ public static function message( array $c, $light = false ) { $topic = $light ? null : self::topic( (int) $c['id'] ); $name = '' !== trim( (string) $c['first_name'] ) ? trim( (string) $c['first_name'] ) : __( 'there', 'nodebook' ); $what = $topic ? $topic['title'] : get_bloginfo( 'name' ); $text = sprintf( (string) Nodebook_Niche::get( 'followup' ), $name, $what ); return (string) apply_filters( 'nodebook_followup_message', $text, $c, $topic ); } /** * One-tap actions: label, url, kind. Only the ones that can work for this contact. * * @return array[] */ public static function actions( array $c, $light = false ) { $out = array(); $text = self::message( $c, $light ); $phone = (string) $c['phone']; $intl = Nodebook_Phone::international( $phone, isset( $c['country'] ) ? $c['country'] : '' ); $local = preg_replace( '/[^0-9+]/', '', $phone ); if ( $intl || strlen( preg_replace( '/\D/', '', $local ) ) >= 6 ) { $out[] = array( 'label' => __( 'Call', 'nodebook' ), 'url' => 'tel:' . ( $intl ? '+' . $intl : $local ), 'kind' => 'call', ); } // WhatsApp needs the country code; without one we would open the wrong chat, so no button. if ( $intl ) { $out[] = array( 'label' => __( 'WhatsApp', 'nodebook' ), 'url' => 'https://wa.me/' . $intl . '?text=' . rawurlencode( $text ), 'kind' => 'whatsapp', ); } if ( is_email( (string) $c['email'] ) ) { $topic = $light ? null : self::topic( (int) $c['id'] ); $out[] = array( 'label' => __( 'Email', 'nodebook' ), 'url' => 'mailto:' . rawurlencode( (string) $c['email'] ) . '?subject=' . rawurlencode( $topic ? $topic['title'] : get_bloginfo( 'name' ) ) . '&body=' . rawurlencode( $text ), 'kind' => 'email', ); } return apply_filters( 'nodebook_followup_actions', $out, $c ); } public static function mark_done( $contact_id, $user_id = 0 ) { self::clear_badge(); $contact_id = absint( $contact_id ); if ( ! Nodebook_Contacts::get( $contact_id ) ) { return false; } $c = Nodebook_Contacts::get( $contact_id ); $update = array( 'followed_up_at' => current_time( 'mysql', true ) ); if ( ! empty( $c['remind_at'] ) && strtotime( $c['remind_at'] . ' UTC' ) <= time() ) { $update['remind_at'] = null; } Nodebook_Contacts::update( $contact_id, $update ); $user = $user_id ? get_userdata( $user_id ) : null; Nodebook_Activities::add( $contact_id, 'followup', $user /* translators: %s: user display name */ ? sprintf( __( 'Followed up by %s', 'nodebook' ), $user->display_name ) : __( 'Followed up', 'nodebook' ), array( 'user_id' => (int) $user_id ) ); return true; } }