500 ) ). * * @package Nodebook */ defined( 'ABSPATH' ) || exit; final class Nodebook_Gatherings { const MODULE = 'gatherings'; const STATUSES = array( 'interested', 'reserved', 'waitlist', 'cancelled' ); /** @var bool True while this class changes a deal, so the deal hooks do not echo back. */ private static $syncing = false; /* ------------------------------------------------------------------ * * Setup * ------------------------------------------------------------------ */ public static function on() { return class_exists( 'Nodebook_Modules' ) && Nodebook_Modules::is_active( self::MODULE ); } public static function events_table() { global $wpdb; return $wpdb->prefix . 'nodebook_gatherings_events'; } public static function people_table() { global $wpdb; return $wpdb->prefix . 'nodebook_gatherings_people'; } /** Hooks, once the module is booted. */ public static function boot() { add_action( 'nodebook_contact_before_delete', array( __CLASS__, 'on_contact_delete' ) ); add_action( 'nodebook_contacts_merged', array( __CLASS__, 'on_merge' ), 10, 2 ); add_action( 'nodebook_deal_closed', array( __CLASS__, 'on_deal_closed' ), 10, 2 ); add_action( 'nodebook_conversion', array( __CLASS__, 'on_conversion' ), 10, 4 ); add_action( 'nodebook_activity_added', array( __CLASS__, 'on_activity' ), 10, 2 ); add_action( 'nodebook_gathering_join', array( __CLASS__, 'join' ), 10, 3 ); add_filter( 'nodebook_node_items', array( __CLASS__, 'node_items' ), 10, 2 ); foreach ( array( 'woocommerce_order_status_processing', 'woocommerce_order_status_completed', 'woocommerce_payment_complete' ) as $hook ) { add_action( $hook, array( __CLASS__, 'woo_paid' ), 30 ); } foreach ( array( 'woocommerce_order_status_cancelled', 'woocommerce_order_status_refunded' ) as $hook ) { add_action( $hook, array( __CLASS__, 'woo_cancelled' ), 30 ); } } /* ------------------------------------------------------------------ * * Gatherings * ------------------------------------------------------------------ */ public static function get( $id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::events_table(), $id ), ARRAY_A ); return $row ? $row : null; } /** * Gatherings, upcoming first (soonest), then the ones without dates, then past ones (latest first). * * @param array $args when: '' (all) | 'upcoming' (not ended) | 'past'. */ public static function all( array $args = array() ) { global $wpdb; $today = wp_date( 'Y-m-d' ); $when = $args['when'] ?? ''; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. if ( 'upcoming' === $when ) { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE COALESCE(ends_on, starts_on) IS NULL OR COALESCE(ends_on, starts_on) >= %s ORDER BY starts_on IS NULL, starts_on ASC, id ASC LIMIT 200', self::events_table(), $today ), ARRAY_A ); } elseif ( 'past' === $when ) { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE COALESCE(ends_on, starts_on) < %s ORDER BY starts_on DESC, id ASC LIMIT 200', self::events_table(), $today ), ARRAY_A ); } else { $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY starts_on IS NULL, starts_on ASC, id ASC LIMIT 200', self::events_table() ), ARRAY_A ); } // phpcs:enable return (array) $rows; } /** Clean incoming gathering fields. */ private static function prepare( array $in ) { $out = array(); if ( isset( $in['title'] ) ) { $out['title'] = mb_substr( trim( sanitize_text_field( (string) $in['title'] ) ), 0, 190 ); } foreach ( array( 'starts_on', 'ends_on' ) as $k ) { if ( array_key_exists( $k, $in ) ) { $d = trim( (string) $in[ $k ] ); $out[ $k ] = preg_match( '/^\d{4}-\d{2}-\d{2}$/', $d ) && checkdate( (int) substr( $d, 5, 2 ), (int) substr( $d, 8, 2 ), (int) substr( $d, 0, 4 ) ) ? $d : null; } } if ( isset( $in['location'] ) ) { $out['location'] = mb_substr( trim( sanitize_text_field( (string) $in['location'] ) ), 0, 190 ); } if ( isset( $in['match_text'] ) ) { $out['match_text'] = mb_substr( trim( sanitize_text_field( (string) $in['match_text'] ) ), 0, 190 ); } foreach ( array( 'capacity', 'page_id', 'product_id' ) as $k ) { if ( isset( $in[ $k ] ) ) { $out[ $k ] = absint( $in[ $k ] ); } } if ( isset( $in['balance_days'] ) ) { $out['balance_days'] = min( 365, absint( $in['balance_days'] ) ); } foreach ( array( 'price', 'deposit' ) as $k ) { if ( isset( $in[ $k ] ) ) { $v = Nodebook_Props::to_number( $in[ $k ] ); $out[ $k ] = null === $v ? 0 : max( 0, round( (float) $v, 2 ) ); } } if ( isset( $in['currency'] ) ) { $c = strtoupper( trim( (string) $in['currency'] ) ); $out['currency'] = preg_match( '/^[A-Z]{3}$/', $c ) ? $c : ''; } if ( isset( $in['status'] ) ) { $out['status'] = 'closed' === $in['status'] ? 'closed' : 'open'; } if ( isset( $in['notes'] ) ) { $out['notes'] = mb_substr( sanitize_textarea_field( (string) $in['notes'] ), 0, 5000 ); } if ( isset( $out['starts_on'], $out['ends_on'] ) && $out['starts_on'] && $out['ends_on'] && $out['ends_on'] < $out['starts_on'] ) { $out['ends_on'] = $out['starts_on']; } return $out; } /** * Create or update a gathering. * * @return int ID, or 0. */ public static function save( array $in, $id = 0 ) { global $wpdb; $row = self::prepare( $in ); $now = current_time( 'mysql', true ); if ( $id ) { if ( ! self::get( $id ) ) { return 0; } if ( isset( $row['title'] ) && '' === $row['title'] ) { unset( $row['title'] ); } $row['updated_at'] = $now; $wpdb->update( self::events_table(), $row, array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. return (int) $id; } if ( empty( $row['title'] ) ) { return 0; } $row += array( 'currency' => Nodebook_Conversions::currency(), 'balance_days' => 30, 'status' => 'open', ); $row['created_at'] = $now; $row['updated_at'] = $now; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- module table. return false === $wpdb->insert( self::events_table(), $row ) ? 0 : (int) $wpdb->insert_id; } /** Delete a gathering and its roster. Deals stay (they are the history of the sale). */ public static function delete( $id ) { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module tables. $wpdb->delete( self::people_table(), array( 'event_id' => (int) $id ) ); return (bool) $wpdb->delete( self::events_table(), array( 'id' => (int) $id ) ); // phpcs:enable } /** upcoming | running | past | undated */ public static function phase( array $g ) { $today = wp_date( 'Y-m-d' ); $start = (string) $g['starts_on']; $end = (string) ( $g['ends_on'] ? $g['ends_on'] : $g['starts_on'] ); if ( '' === $start ) { return 'undated'; } if ( $end < $today ) { return 'past'; } return $start <= $today ? 'running' : 'upcoming'; } /** The day the balance is due (Y-m-d), or ''. */ public static function balance_due( array $g ) { if ( empty( $g['starts_on'] ) ) { return ''; } return wp_date( 'Y-m-d', strtotime( $g['starts_on'] . ' 12:00:00 UTC' ) - (int) $g['balance_days'] * DAY_IN_SECONDS, new DateTimeZone( 'UTC' ) ); } /** "12–16 May 2027", "12 May – 3 Jun 2027", or ''. */ public static function dates_label( array $g ) { return Nodebook_Conversions::range_label( (string) $g['starts_on'], (string) ( $g['ends_on'] && $g['ends_on'] !== $g['starts_on'] ? $g['ends_on'] : '' ) ); } /** * Numbers for one gathering. * * @return array taken (seats reserved), left (null without a limit), interested, waitlist, cancelled, * people (not cancelled), expected (owed by reserved people), paid, owed, owing (people who * still owe), unpaid_due (owing after the balance date), unmarked (reserved, gathering over, * attendance not marked). */ public static function stats( array $g, $people = null ) { $people = null === $people ? self::people( (int) $g['id'] ) : $people; $s = array_fill_keys( array( 'taken', 'interested', 'waitlist', 'cancelled', 'people', 'expected', 'paid', 'owed', 'owing', 'attended' ), 0 ); foreach ( $people as $p ) { if ( 'cancelled' === $p['status'] ) { ++$s['cancelled']; continue; } ++$s['people']; $s['paid'] += (float) $p['paid']; if ( 'reserved' === $p['status'] ) { $s['taken'] += max( 1, (int) $p['seats'] ); $s['expected'] += (float) $p['amount']; $owe = max( 0, (float) $p['amount'] - (float) $p['paid'] ); $s['owed'] += $owe; $s['owing'] += $owe > 0.009 ? 1 : 0; $s['attended'] += (int) $p['attended']; } elseif ( 'interested' === $p['status'] ) { ++$s['interested']; } else { ++$s['waitlist']; } } $s['left'] = (int) $g['capacity'] > 0 ? max( 0, (int) $g['capacity'] - $s['taken'] ) : null; return $s; } /* ------------------------------------------------------------------ * * Roster * ------------------------------------------------------------------ */ /** Roster of a gathering with the contact's name, email and phone; reserved first, then by name. */ public static function people( $event_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table joined with the contacts table. return (array) $wpdb->get_results( $wpdb->prepare( "SELECT p.*, c.first_name, c.last_name, c.email, c.phone, c.owner_id FROM %i p LEFT JOIN %i c ON c.id = p.contact_id WHERE p.event_id = %d ORDER BY CASE p.status WHEN 'reserved' THEN 0 WHEN 'interested' THEN 1 WHEN 'waitlist' THEN 2 ELSE 3 END, p.created_at ASC, p.id ASC", self::people_table(), Nodebook_Contacts::table(), $event_id ), ARRAY_A ); } public static function person( $id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::people_table(), $id ), ARRAY_A ); return $row ? $row : null; } public static function find( $event_id, $contact_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE event_id = %d AND contact_id = %d', self::people_table(), $event_id, $contact_id ), ARRAY_A ); return $row ? $row : null; } /** A contact's gatherings (newest first), with the gathering's title and dates. */ public static function for_contact( $contact_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module tables. return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT p.*, e.title, e.starts_on, e.ends_on, e.currency, e.balance_days FROM %i p JOIN %i e ON e.id = p.event_id WHERE p.contact_id = %d ORDER BY e.starts_on IS NULL, e.starts_on DESC, p.id DESC', self::people_table(), self::events_table(), $contact_id ), ARRAY_A ); } /** none | deposit | paid | free */ public static function payment( array $p ) { if ( (float) $p['amount'] <= 0 ) { return (float) $p['paid'] > 0 ? 'paid' : 'free'; } if ( (float) $p['paid'] + 0.009 >= (float) $p['amount'] ) { return 'paid'; } return (float) $p['paid'] > 0 ? 'deposit' : 'none'; } public static function status_labels() { return array( 'interested' => __( 'Interested', 'nodebook' ), 'reserved' => __( 'Reserved', 'nodebook' ), 'waitlist' => __( 'Waitlist', 'nodebook' ), 'cancelled' => __( 'Cancelled', 'nodebook' ), ); } /** Whether a new reservation of $seats fits. */ public static function fits( array $g, $seats, $except = 0 ) { if ( (int) $g['capacity'] <= 0 ) { return true; } $taken = 0; foreach ( self::people( (int) $g['id'] ) as $p ) { if ( 'reserved' === $p['status'] && (int) $p['id'] !== (int) $except ) { $taken += max( 1, (int) $p['seats'] ); } } return $taken + max( 1, (int) $seats ) <= (int) $g['capacity']; } /** * Put a contact on a gathering's roster (or update them when they are on it already). * * @param array $args status (interested|reserved|waitlist), seats, amount, source, paid (a payment to record now), * note (shown with the payment). A reservation that does not fit goes on the waitlist. * @return int Roster ID, or 0. */ public static function add( $event_id, $contact_id, array $args = array() ) { global $wpdb; $g = self::get( $event_id ); if ( ! $g || ! $contact_id || ! Nodebook_Contacts::get( $contact_id ) ) { return 0; } $seats = max( 1, min( 99, (int) ( $args['seats'] ?? 1 ) ) ); $status = isset( $args['status'] ) && in_array( $args['status'], self::STATUSES, true ) ? $args['status'] : 'interested'; $pay = isset( $args['paid'] ) ? (float) $args['paid'] : 0.0; if ( $pay > 0 && 'interested' === $status ) { $status = 'reserved'; } $have = self::find( $event_id, $contact_id ); if ( $have ) { $changes = array(); // Only move forward: interested → reserved; never undo a reservation from an automatic source. $rank = array( 'cancelled' => 0, 'interested' => 1, 'waitlist' => 2, 'reserved' => 3, ); if ( $rank[ $status ] > $rank[ $have['status'] ] || ( 'cancelled' === $have['status'] && 'cancelled' !== $status ) ) { $changes['status'] = $status; } if ( isset( $args['seats'] ) && $seats !== (int) $have['seats'] ) { $changes['seats'] = $seats; $changes['amount'] = round( (float) $g['price'] * $seats, 2 ); } if ( $changes ) { self::update( (int) $have['id'], $changes ); } if ( $pay ) { self::pay( (int) $have['id'], $pay, (string) ( $args['note'] ?? '' ) ); } return (int) $have['id']; } if ( 'reserved' === $status && ! self::fits( $g, $seats ) && $pay <= 0 ) { $status = 'waitlist'; } $amount = isset( $args['amount'] ) && is_numeric( $args['amount'] ) ? max( 0, round( (float) $args['amount'], 2 ) ) : round( (float) $g['price'] * $seats, 2 ); $now = current_time( 'mysql', true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- module table. $ok = $wpdb->insert( self::people_table(), array( 'event_id' => (int) $event_id, 'contact_id' => (int) $contact_id, 'seats' => $seats, 'amount' => $amount, 'paid' => 0, 'status' => $status, 'source' => mb_substr( sanitize_text_field( (string) ( $args['source'] ?? '' ) ), 0, 100 ), 'created_at' => $now, 'updated_at' => $now, ) ); if ( ! $ok ) { return 0; } $pid = (int) $wpdb->insert_id; $labels = self::status_labels(); Nodebook_Activities::add( (int) $contact_id, 'gathering', /* translators: 1: status, e.g. "Reserved", 2: gathering */ sprintf( __( '%1$s: %2$s', 'nodebook' ), $labels[ $status ], $g['title'] ) . ( '' !== (string) ( $args['source'] ?? '' ) ? ' · ' . $args['source'] : '' ), array( 'object_id' => (int) $event_id, 'user_id' => get_current_user_id(), ) ); if ( self::deals_on() ) { self::make_deal( $pid ); } if ( $pay ) { self::pay( $pid, $pay, (string) ( $args['note'] ?? '' ) ); } else { self::sync_deal( $pid ); } Nodebook_Node::flush(); /** * Someone was added to a gathering's roster. * * @param int $person_id Roster ID. * @param int $event_id Gathering. * @param int $contact_id Contact. * @param string $status interested|reserved|waitlist. */ do_action( 'nodebook_gathering_added', $pid, (int) $event_id, (int) $contact_id, $status ); return $pid; } /** Change status, seats, amount or attendance of a roster entry. */ public static function update( $id, array $in ) { global $wpdb; $p = self::person( $id ); if ( ! $p ) { return false; } $row = array(); if ( isset( $in['status'] ) && in_array( $in['status'], self::STATUSES, true ) ) { $row['status'] = $in['status']; } if ( isset( $in['seats'] ) ) { $row['seats'] = max( 1, min( 99, (int) $in['seats'] ) ); } if ( isset( $in['amount'] ) && is_numeric( $in['amount'] ) ) { $row['amount'] = max( 0, round( (float) $in['amount'], 2 ) ); } if ( isset( $in['attended'] ) ) { $row['attended'] = $in['attended'] ? 1 : 0; } if ( ! $row ) { return true; } $row['updated_at'] = current_time( 'mysql', true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->update( self::people_table(), $row, array( 'id' => (int) $id ) ); if ( isset( $row['status'] ) && $row['status'] !== $p['status'] ) { $g = self::get( (int) $p['event_id'] ); $labels = self::status_labels(); Nodebook_Activities::add( (int) $p['contact_id'], 'gathering', /* translators: 1: status, 2: gathering */ sprintf( __( '%1$s: %2$s', 'nodebook' ), $labels[ $row['status'] ], $g ? $g['title'] : '' ), array( 'object_id' => (int) $p['event_id'], 'user_id' => get_current_user_id(), ) ); } if ( isset( $row['attended'] ) && $row['attended'] && ! (int) $p['attended'] ) { $g = self::get( (int) $p['event_id'] ); /* translators: %s: gathering */ Nodebook_Activities::add( (int) $p['contact_id'], 'gathering', sprintf( __( 'Came to %s', 'nodebook' ), $g ? $g['title'] : '' ), array( 'object_id' => (int) $p['event_id'] ) ); } self::sync_deal( (int) $id ); Nodebook_Node::flush(); return true; } /** * Record a payment (negative for a refund). Paying makes someone reserved. * * @return bool */ public static function pay( $id, $amount, $note = '' ) { global $wpdb; $p = self::person( $id ); $amount = round( (float) $amount, 2 ); if ( ! $p || 0.0 === $amount ) { return false; } $g = self::get( (int) $p['event_id'] ); $paid = max( 0, round( (float) $p['paid'] + $amount, 2 ) ); $row = array( 'paid' => $paid, 'updated_at' => current_time( 'mysql', true ), ); if ( $amount > 0 ) { $row['paid_at'] = current_time( 'mysql', true ); if ( in_array( $p['status'], array( 'interested', 'waitlist', 'cancelled' ), true ) ) { $row['status'] = 'reserved'; } } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->update( self::people_table(), $row, array( 'id' => (int) $id ) ); $cur = $g ? (string) $g['currency'] : ''; $after = array_merge( $p, $row ); if ( $amount < 0 ) { /* translators: 1: amount, 2: gathering */ $title = sprintf( __( 'Refunded %1$s for %2$s', 'nodebook' ), Nodebook_Admin::money( -$amount, $cur ), $g ? $g['title'] : '' ); } elseif ( 'paid' === self::payment( $after ) ) { /* translators: 1: amount, 2: gathering */ $title = (float) $p['paid'] > 0 ? sprintf( __( 'Paid the balance, %1$s, for %2$s', 'nodebook' ), Nodebook_Admin::money( $amount, $cur ), $g ? $g['title'] : '' ) : sprintf( __( 'Paid %1$s in full for %2$s', 'nodebook' ), Nodebook_Admin::money( $amount, $cur ), $g ? $g['title'] : '' ); } else { /* translators: 1: amount, 2: gathering */ $title = sprintf( __( 'Paid a deposit of %1$s for %2$s', 'nodebook' ), Nodebook_Admin::money( $amount, $cur ), $g ? $g['title'] : '' ); } Nodebook_Activities::add( (int) $p['contact_id'], 'gathering', $title . ( '' !== trim( (string) $note ) ? ' · ' . mb_substr( sanitize_text_field( (string) $note ), 0, 120 ) : '' ), array( 'object_id' => (int) $p['event_id'], 'user_id' => get_current_user_id(), 'data' => array( 'value' => $amount, 'currency' => $cur, ), ) ); self::sync_deal( (int) $id ); Nodebook_Node::flush(); /** * A payment (or refund) was recorded for a roster entry. * * @param int $person_id Roster ID. * @param float $amount Amount (negative for a refund). * @param float $paid Total paid now. */ do_action( 'nodebook_gathering_paid', (int) $id, $amount, $paid ); return true; } /** Take someone off the roster (their deal and timeline stay). */ public static function remove( $id ) { global $wpdb; $p = self::person( $id ); if ( ! $p ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->delete( self::people_table(), array( 'id' => (int) $id ) ); Nodebook_Node::flush(); return true; } /** * Public way in for other plugins and add-ons: put someone on a gathering, optionally with a payment. * * @param int $event_id Gathering. * @param int|string $who Contact ID or email address (a new email becomes a contact). * @param array $args status, seats, paid, source, note; first_name, last_name, phone for new people. */ public static function join( $event_id, $who, $args = array() ) { $args = (array) $args; $cid = 0; if ( is_numeric( $who ) ) { $cid = Nodebook_Contacts::get( (int) $who ) ? (int) $who : 0; } elseif ( is_email( (string) $who ) ) { $cid = (int) Nodebook_Capture::capture( array_filter( array( 'email' => (string) $who, 'first_name' => (string) ( $args['first_name'] ?? '' ), 'last_name' => (string) ( $args['last_name'] ?? '' ), 'phone' => (string) ( $args['phone'] ?? '' ), ) ), (string) ( $args['source'] ?? '' ), array( 'activity' => false ) ); } return $cid ? self::add( (int) $event_id, $cid, $args ) : 0; } /* ------------------------------------------------------------------ * * Deals * ------------------------------------------------------------------ */ public static function deals_on() { return Nodebook_Deals::on() && '0' !== (string) get_option( 'nodebook_mod_gatherings_deals', '1' ); } private static function make_deal( $pid ) { global $wpdb; $p = self::person( $pid ); $g = $p ? self::get( (int) $p['event_id'] ) : null; $c = $p ? Nodebook_Contacts::get( (int) $p['contact_id'] ) : null; if ( ! $p || ! $g || ! $c || (int) $p['deal_id'] ) { return 0; } self::$syncing = true; $deal = Nodebook_Deals::add( array( /* translators: 1: gathering, 2: person */ 'title' => sprintf( __( '%1$s: %2$s', 'nodebook' ), $g['title'], Nodebook_Contacts::display_name( $c ) ), 'contact_id' => (int) $c['id'], 'value' => (float) $p['amount'], 'currency' => (string) $g['currency'], 'expected_close' => (string) ( $g['starts_on'] ? $g['starts_on'] : '' ), 'owner_id' => (int) $c['owner_id'] ? (int) $c['owner_id'] : get_current_user_id(), ) ); self::$syncing = false; if ( $deal ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->update( self::people_table(), array( 'deal_id' => $deal ), array( 'id' => (int) $pid ) ); } return $deal; } /** Let the person's deal follow the roster: value, "Deposit paid", won when paid in full, lost when cancelled. */ public static function sync_deal( $pid ) { $p = self::person( $pid ); if ( ! $p || ! (int) $p['deal_id'] ) { return; } $d = Nodebook_Deals::get( (int) $p['deal_id'] ); if ( ! $d ) { return; } self::$syncing = true; if ( abs( (float) $d['value'] - (float) $p['amount'] ) > 0.009 && (float) $p['amount'] > 0 ) { Nodebook_Deals::update( (int) $d['id'], array( 'value' => (float) $p['amount'] ) ); } $pay = self::payment( $p ); if ( 'cancelled' === $p['status'] ) { if ( 'lost' !== $d['outcome'] ) { if ( 'won' === $d['outcome'] ) { Nodebook_Deals::close( (int) $d['id'], '' ); } Nodebook_Deals::close( (int) $d['id'], 'lost', __( 'Cancelled', 'nodebook' ) ); } } elseif ( 'paid' === $pay && (float) $p['amount'] > 0 ) { if ( 'won' !== $d['outcome'] ) { if ( 'lost' === $d['outcome'] ) { Nodebook_Deals::close( (int) $d['id'], '' ); } Nodebook_Deals::close( (int) $d['id'], 'won' ); } } else { if ( '' !== $d['outcome'] ) { Nodebook_Deals::close( (int) $d['id'], '' ); } $stages = Nodebook_Deals::stages( (int) $d['pipeline_id'] ); if ( 'deposit' === $pay && isset( $stages['deposit'] ) && 'deposit' !== $d['stage'] ) { Nodebook_Deals::update( (int) $d['id'], array( 'stage' => 'deposit' ) ); } } self::$syncing = false; } /** A deal closed by hand: won means a spot, lost means cancelled. */ public static function on_deal_closed( $deal_id, $outcome ) { global $wpdb; if ( self::$syncing || '' === $outcome ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $pid = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE deal_id = %d', self::people_table(), $deal_id ) ); if ( ! $pid ) { return; } $p = self::person( $pid ); self::$syncing = true; if ( 'won' === $outcome && in_array( $p['status'], array( 'interested', 'waitlist' ), true ) ) { self::update( $pid, array( 'status' => 'reserved' ) ); } elseif ( 'lost' === $outcome && 'cancelled' !== $p['status'] ) { self::update( $pid, array( 'status' => 'cancelled' ) ); } self::$syncing = false; } /* ------------------------------------------------------------------ * * Where people come from * ------------------------------------------------------------------ */ /** A form sent from a gathering's own page: interested. */ public static function on_activity( $activity_id, $row ) { if ( 'form' !== ( $row['type'] ?? '' ) || empty( $row['contact_id'] ) ) { return; } $data = json_decode( (string) ( $row['data'] ?? '' ), true ); $item = is_array( $data ) ? (int) ( $data['item'] ?? 0 ) : 0; $url = (string) ( $row['url'] ?? '' ); foreach ( self::all( array( 'when' => 'upcoming' ) ) as $g ) { if ( ! (int) $g['page_id'] || 'closed' === $g['status'] ) { continue; } if ( $item === (int) $g['page_id'] || ( '' !== $url && self::same_page( $url, (int) $g['page_id'] ) ) ) { self::add( (int) $g['id'], (int) $row['contact_id'], array( 'status' => 'interested', 'source' => __( 'Form on its page', 'nodebook' ), ) ); } } } /** Bookings and appointments whose name contains a gathering's booking name. */ public static function on_conversion( $cid, $type, $title, $data ) { $data = (array) $data; if ( ! in_array( $type, array( 'booking', 'appointment' ), true ) ) { return; } foreach ( self::all( array( 'when' => 'upcoming' ) ) as $g ) { $match = trim( (string) $g['match_text'] ); if ( '' === $match || false === mb_stripos( (string) $title, $match ) ) { continue; } $status = isset( $data['status'] ) ? (string) $data['status'] : ''; if ( Nodebook_Conversions::is_cancelled( $status ) ) { continue; } $settled = Nodebook_Conversions::is_settled( $status ); self::add( (int) $g['id'], (int) $cid, array( 'status' => $settled ? 'reserved' : 'interested', 'paid' => $settled && ! empty( $data['value'] ) ? (float) $data['value'] : 0, 'source' => (string) ( $data['source'] ?? '' ), 'note' => (string) ( $data['source'] ?? '' ), ) ); } } /** Whether a URL points at a page (by its path). */ private static function same_page( $url, $page_id ) { $link = get_permalink( $page_id ); if ( ! $link ) { return false; } $a = untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) ); $b = untrailingslashit( (string) wp_parse_url( $link, PHP_URL_PATH ) ); if ( '' !== $a && $a === $b ) { return true; } parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $q ); return (int) ( $q['page_id'] ?? ( $q['p'] ?? 0 ) ) === (int) $page_id; } /** WooCommerce: a paid order with a gathering's product reserves the spot and records the payment (once per order). */ public static function woo_paid( $order_id ) { if ( ! function_exists( 'wc_get_order' ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order || ! $order->get_billing_email() ) { return; } $events = self::by_product(); if ( ! $events ) { return; } $done = (array) $order->get_meta( '_nodebook_gatherings' ); $new = false; foreach ( $order->get_items() as $item ) { if ( ! is_a( $item, 'WC_Order_Item_Product' ) ) { continue; } $ids = array( (int) $item->get_product_id(), (int) $item->get_variation_id() ); foreach ( $ids as $product ) { if ( ! $product || ! isset( $events[ $product ] ) ) { continue; } $g = $events[ $product ]; if ( isset( $done[ $g['id'] ] ) ) { continue 2; } $paid = round( (float) $item->get_total() + (float) $item->get_total_tax(), 2 ); $pid = self::join( (int) $g['id'], $order->get_billing_email(), array( 'status' => 'reserved', 'seats' => max( 1, (int) $item->get_quantity() ), 'paid' => $paid, /* translators: %s: order number */ 'source' => sprintf( __( 'WooCommerce order #%s', 'nodebook' ), $order->get_order_number() ), /* translators: %s: order number */ 'note' => sprintf( __( 'order #%s', 'nodebook' ), $order->get_order_number() ), 'first_name' => $order->get_billing_first_name(), 'last_name' => $order->get_billing_last_name(), 'phone' => $order->get_billing_phone(), ) ); if ( $pid ) { $done[ $g['id'] ] = array( $pid, $paid ); $new = true; } continue 2; } } if ( $new ) { $order->update_meta_data( '_nodebook_gatherings', $done ); $order->save_meta_data(); } } /** WooCommerce: a cancelled or refunded order takes its payment back and cancels the spot when nothing is left. */ public static function woo_cancelled( $order_id ) { if ( ! function_exists( 'wc_get_order' ) ) { return; } $order = wc_get_order( $order_id ); $done = $order ? (array) $order->get_meta( '_nodebook_gatherings' ) : array(); if ( ! $done ) { return; } foreach ( $done as $pair ) { list( $pid, $paid ) = array_pad( (array) $pair, 2, 0 ); $p = self::person( (int) $pid ); if ( ! $p ) { continue; } if ( (float) $paid > 0 ) { /* translators: %s: order number */ self::pay( (int) $pid, -(float) $paid, sprintf( __( 'order #%s', 'nodebook' ), $order->get_order_number() ) ); } $p = self::person( (int) $pid ); if ( $p && (float) $p['paid'] <= 0 ) { self::update( (int) $pid, array( 'status' => 'cancelled' ) ); } } $order->delete_meta_data( '_nodebook_gatherings' ); $order->save_meta_data(); } /** Upcoming gatherings with a product: product ID => gathering. */ private static function by_product() { $out = array(); foreach ( self::all( array( 'when' => 'upcoming' ) ) as $g ) { if ( (int) $g['product_id'] ) { $out[ (int) $g['product_id'] ] = $g; } } return $out; } /* ------------------------------------------------------------------ * * Contacts * ------------------------------------------------------------------ */ public static function on_contact_delete( $contact_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->delete( self::people_table(), array( 'contact_id' => (int) $contact_id ) ); } /** Merged contacts: the roster entries move over; where both were on one gathering, the furthest one stays. */ public static function on_merge( $keep_id, $merge_id ) { global $wpdb; foreach ( self::for_contact( (int) $merge_id ) as $p ) { $have = self::find( (int) $p['event_id'], (int) $keep_id ); if ( $have ) { $rank = array_flip( array( 'cancelled', 'interested', 'waitlist', 'reserved' ) ); if ( $rank[ $p['status'] ] > $rank[ $have['status'] ] || (float) $p['paid'] > (float) $have['paid'] ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->delete( self::people_table(), array( 'id' => (int) $have['id'] ) ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->delete( self::people_table(), array( 'id' => (int) $p['id'] ) ); continue; } } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module table. $wpdb->update( self::people_table(), array( 'contact_id' => (int) $keep_id ), array( 'id' => (int) $p['id'] ) ); } } /** People who came to (or reserved) past gatherings and are not on this one yet: contact ID => name. */ public static function alumni( array $g ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- module tables. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT DISTINCT p.contact_id, c.first_name, c.last_name, c.email FROM %i p JOIN %i e ON e.id = p.event_id JOIN %i c ON c.id = p.contact_id WHERE p.status = 'reserved' AND p.event_id <> %d AND COALESCE(e.ends_on, e.starts_on) < %s AND p.contact_id NOT IN ( SELECT contact_id FROM %i WHERE event_id = %d ) ORDER BY c.first_name, c.last_name LIMIT 500", self::people_table(), self::events_table(), Nodebook_Contacts::table(), (int) $g['id'], wp_date( 'Y-m-d' ), self::people_table(), (int) $g['id'] ), ARRAY_A ); $out = array(); foreach ( $rows as $r ) { if ( Nodebook_Team::can_see( (int) $r['contact_id'] ) ) { $out[ (int) $r['contact_id'] ] = Nodebook_Contacts::display_name( $r ); } } return $out; } /* ------------------------------------------------------------------ * * Node * ------------------------------------------------------------------ */ /** What Node points out: balances due, spots that opened up, interest to follow up, past guests to invite. */ public static function node_items( $items, $user_id = 0 ) { if ( ! current_user_can( 'manage_options' ) && ! user_can( (int) $user_id, 'manage_options' ) ) { return $items; } $today = wp_date( 'Y-m-d' ); $upcoming = self::all( array( 'when' => 'upcoming' ) ); foreach ( $upcoming as $g ) { $people = self::people( (int) $g['id'] ); $s = self::stats( $g, $people ); $url = self::url( (int) $g['id'] ); $due = self::balance_due( $g ); $days = $due ? (int) round( ( strtotime( $due . ' 12:00:00' ) - strtotime( $today . ' 12:00:00' ) ) / DAY_IN_SECONDS ) : 999; if ( $s['owing'] && $days <= 14 ) { $items[] = array( 'key' => 'gbal:' . (int) $g['id'] . ':' . wp_date( 'Y-W' ), 'kind' => 'gathering', 'score' => $days < 0 ? 88 : 78, 'text' => $days < 0 ? Nodebook_Node::say( /* translators: 1: number of people, 2: gathering, 3: money */ sprintf( _n( '%1$d person still owes for %2$s (%3$s). The balance was due already 💸', '%1$d people still owe for %2$s (%3$s). The balance was due already 💸', $s['owing'], 'nodebook' ), $s['owing'], $g['title'], Nodebook_Admin::money( $s['owed'], $g['currency'] ) ), /* translators: 1: number of people, 2: gathering, 3: money */ sprintf( _n( '%1$d person owes for %2$s (%3$s), past the balance date.', '%1$d people owe for %2$s (%3$s), past the balance date.', $s['owing'], 'nodebook' ), $s['owing'], $g['title'], Nodebook_Admin::money( $s['owed'], $g['currency'] ) ) ) : Nodebook_Node::say( /* translators: 1: number of people, 2: gathering, 3: number of days */ sprintf( _n( '%1$d person still owes their balance for %2$s, due in %3$d days.', '%1$d people still owe their balance for %2$s, due in %3$d days.', $s['owing'], 'nodebook' ), $s['owing'], $g['title'], max( 0, $days ) ), /* translators: 1: number of people, 2: gathering, 3: number of days */ sprintf( _n( '%2$s: %1$d balance due in %3$d days.', '%2$s: %1$d balances due in %3$d days.', $s['owing'], 'nodebook' ), $s['owing'], $g['title'], max( 0, $days ) ) ), 'action' => array( __( 'See who owes', 'nodebook' ), $url . '#nb-roster' ), 'who' => 0, ); } if ( $s['waitlist'] && null !== $s['left'] && $s['left'] > 0 ) { $items[] = array( 'key' => 'gwait:' . (int) $g['id'] . ':' . $s['left'], 'kind' => 'gathering', 'score' => 76, 'text' => Nodebook_Node::say( /* translators: 1: spots, 2: gathering, 3: people waiting */ sprintf( _n( '%1$d spot opened up for %2$s, and the waitlist has %3$d. Good news to share!', '%1$d spots opened up for %2$s, and the waitlist has %3$d. Good news to share!', $s['left'], 'nodebook' ), $s['left'], $g['title'], $s['waitlist'] ), /* translators: 1: spots, 2: gathering, 3: people waiting */ sprintf( _n( '%2$s: %1$d spot free, waitlist %3$d.', '%2$s: %1$d spots free, waitlist %3$d.', $s['left'], 'nodebook' ), $s['left'], $g['title'], $s['waitlist'] ) ), 'action' => array( __( 'Open the waitlist', 'nodebook' ), $url . '#nb-roster' ), 'who' => 0, ); } if ( $s['interested'] && 'closed' !== $g['status'] && ( null === $s['left'] || $s['left'] > 0 ) ) { $items[] = array( 'key' => 'gint:' . (int) $g['id'] . ':' . $s['interested'], 'kind' => 'gathering', 'score' => 62, 'text' => Nodebook_Node::say( /* translators: 1: number, 2: gathering, 3: spots left text */ sprintf( _n( '%1$d person is interested in %2$s but has not reserved yet.%3$s', '%1$d people are interested in %2$s but have not reserved yet.%3$s', $s['interested'], 'nodebook' ), $s['interested'], $g['title'], null !== $s['left'] ? ' ' . sprintf( /* translators: %d: spots */ _n( 'Only %d spot left 🔥', '%d spots left.', $s['left'], 'nodebook' ), $s['left'] ) : '' ), /* translators: 1: number, 2: gathering */ sprintf( _n( '%2$s: %1$d interested, not reserved.', '%2$s: %1$d interested, not reserved.', $s['interested'], 'nodebook' ), $s['interested'], $g['title'] ) ), 'action' => array( __( 'See who', 'nodebook' ), $url . '#nb-roster' ), 'who' => 0, ); } } // A gathering that just ended: mark who came, then invite them to the next one. foreach ( self::all( array( 'when' => 'past' ) ) as $g ) { $end = (string) ( $g['ends_on'] ? $g['ends_on'] : $g['starts_on'] ); if ( $end < wp_date( 'Y-m-d', time() - 30 * DAY_IN_SECONDS ) ) { break; } $s = self::stats( $g ); if ( $s['taken'] && ! $s['attended'] ) { $items[] = array( 'key' => 'gcame:' . (int) $g['id'], 'kind' => 'gathering', 'score' => 45, /* translators: %s: gathering */ 'text' => Nodebook_Node::say( sprintf( __( '%s is done. Tick who came, so they get invited next time 🙌', 'nodebook' ), $g['title'] ), sprintf( __( '%s is over: mark who came.', 'nodebook' ), $g['title'] ) ), 'action' => array( __( 'Mark who came', 'nodebook' ), self::url( (int) $g['id'] ) . '#nb-roster' ), 'who' => 0, ); } foreach ( $upcoming as $next ) { if ( 'closed' === $next['status'] || ! $next['starts_on'] ) { continue; } $n = count( self::alumni( $next ) ); if ( $n ) { $items[] = array( 'key' => 'ginv:' . (int) $next['id'] . ':' . (int) $g['id'], 'kind' => 'gathering', 'score' => 55, 'text' => Nodebook_Node::say( /* translators: 1: number of people, 2: next gathering */ sprintf( _n( '%1$d past guest is not on %2$s yet. Invite them back?', '%1$d past guests are not on %2$s yet. Invite them back?', $n, 'nodebook' ), $n, $next['title'] ), /* translators: 1: number of people, 2: next gathering */ sprintf( _n( '%1$d past guest to invite to %2$s.', '%1$d past guests to invite to %2$s.', $n, 'nodebook' ), $n, $next['title'] ) ), 'action' => array( __( 'Invite past guests', 'nodebook' ), self::url( (int) $next['id'] ) . '#nb-invite' ), 'who' => 0, ); } break; } break; } return $items; } public static function url( $id = 0, array $args = array() ) { return Nodebook_Admin::url( 'nodebook-gatherings', $id ? array_merge( array( 'id' => (int) $id ), $args ) : $args ); } }