__( 'Awaiting payment', 'tableengine' ), 'pending' => __( 'Pending', 'tableengine' ), 'confirmed' => __( 'Confirmed', 'tableengine' ), 'seated' => __( 'Seated', 'tableengine' ), 'completed' => __( 'Completed', 'tableengine' ), 'cancelled' => __( 'Cancelled', 'tableengine' ), 'no_show' => __( 'No-show', 'tableengine' ), 'expired' => __( 'Expired', 'tableengine' ), ) ); } /** * Statuses that aren't bookings: left out of guest stats, dashboard totals and reports * (unfinished checkouts; extensions add e.g. waitlist entries). */ public static function non_booking_statuses() { return array_values( (array) apply_filters( 'tableengine_non_booking_statuses', array( 'pending_payment', 'expired' ) ) ); } /** * Extra SQL condition (starting with " AND ") that scopes admin views and * totals, e.g. to the current location. Empty by default. */ /** * Extra condition limiting admin views and totals to the locations in scope. * Built here from integers only; extensions return location ids, never SQL. * * @return string '' or " AND location_id IN (…)". */ public static function scope_sql() { /** Location ids the admin views and totals are limited to; null = no limit. */ $ids = apply_filters( 'tableengine_reservations_scope', null ); if ( ! is_array( $ids ) ) { return ''; } $ids = array_values( array_unique( array_map( 'absint', $ids ) ) ); return $ids ? ' AND location_id IN (' . implode( ',', $ids ) . ')' : ' AND 1 = 0'; } public static function payment_statuses() { return apply_filters( 'tableengine_payment_statuses', array( 'none' => __( 'Not required', 'tableengine' ), 'unpaid' => __( 'Unpaid', 'tableengine' ), 'processing' => __( 'Processing', 'tableengine' ), 'paid' => __( 'Paid', 'tableengine' ), 'authorized' => __( 'Authorised (on hold)', 'tableengine' ), 'released' => __( 'Hold released', 'tableengine' ), 'failed' => __( 'Failed', 'tableengine' ), 'refunded' => __( 'Refunded', 'tableengine' ), 'partially_refunded' => __( 'Partially refunded', 'tableengine' ), 'cancelled' => __( 'Cancelled', 'tableengine' ), ) ); } private static function table() { return Install::table( 'reservations' ); } public static function generate_reference() { global $wpdb; $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; do { $ref = 'TB-'; for ( $i = 0; $i < 6; $i++ ) { $ref .= $alphabet[ random_int( 0, strlen( $alphabet ) - 1 ) ]; } $exists = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM ' . self::table() . ' WHERE reference = %s', $ref ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } while ( $exists ); return $ref; } public static function get( $id ) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE id = %d', $id ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } public static function get_by_reference( $ref ) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE reference = %s', strtoupper( $ref ) ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } public static function get_by_intent( $intent_id ) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE stripe_intent = %s', $intent_id ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. } /** * Verify a guest access token (constant-time). */ public static function check_token( $row, $token ) { return $row && is_string( $token ) && '' !== $token && hash_equals( $row['token'], $token ); } public static function insert( array $data ) { global $wpdb; $data = apply_filters( 'tableengine_reservation_insert_data', $data ); $now = current_time( 'mysql', true ); if ( ! isset( $data['table_ids'] ) && ! empty( $data['table_id'] ) ) { $data['table_ids'] = $data['table_id']; } $data['guest_id'] = Guests::resolve( $data ); $data['reference'] = self::generate_reference(); $data['token'] = bin2hex( random_bytes( 20 ) ); $data['created_gmt'] = $now; $data['updated_gmt'] = $now; $wpdb->insert( self::table(), $data ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $id = (int) $wpdb->insert_id; if ( ! $id ) { return null; } $row = self::get( $id ); Guests::refresh_stats( $row['guest_id'] ); do_action( 'tableengine_reservation_created', $id, $row ); return $row; } /** Columns whose change affects guest linking or guest statistics. */ const GUEST_FIELDS = array( 'email', 'phone', 'name', 'status', 'payment_status', 'party_size', 'start_at', 'amount' ); public static function update( $id, array $data ) { global $wpdb; $before = array_intersect_key( $data, array_flip( self::GUEST_FIELDS ) ) ? self::get( $id ) : null; if ( isset( $data['table_id'] ) && ! isset( $data['table_ids'] ) ) { $data['table_ids'] = $data['table_id']; } $data['updated_gmt'] = current_time( 'mysql', true ); $wpdb->update( self::table(), $data, array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $row = self::get( $id ); if ( $before && $row ) { // Contact details changed: re-link to the right guest. if ( isset( $data['email'] ) || isset( $data['phone'] ) ) { $gid = Guests::resolve( $row ); if ( $gid !== (int) $row['guest_id'] ) { $wpdb->update( self::table(), array( 'guest_id' => $gid ), array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $row['guest_id'] = $gid; } } Guests::refresh_stats( $row['guest_id'] ); if ( (int) $before['guest_id'] !== (int) $row['guest_id'] ) { Guests::refresh_stats( $before['guest_id'] ); } } if ( $row ) { do_action( 'tableengine_reservation_updated', $row, $data, $before ); } return $row; } public static function delete( $id ) { global $wpdb; $row = self::get( $id ); if ( ! $row ) { return false; } do_action( 'tableengine_reservation_before_delete', $row ); $deleted = (bool) $wpdb->delete( self::table(), array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. if ( $deleted ) { // delete_metadata() needs a key, so remove all of this reservation's meta directly. $wpdb->delete( Install::table( 'reservationmeta' ), array( 'tableengine_reservation_id' => (int) $id ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. wp_cache_delete( (int) $id, 'tableengine_reservation_meta' ); Guests::refresh_stats( $row['guest_id'] ); do_action( 'tableengine_reservation_deleted', $row ); } return $deleted; } // --------------------------------------------------------------------- // Meta (WordPress metadata API on the reservationmeta table) // --------------------------------------------------------------------- public static function get_meta( $id, $key = '', $single = true ) { return get_metadata( 'tableengine_reservation', (int) $id, $key, $single ); } public static function update_meta( $id, $key, $value ) { return update_metadata( 'tableengine_reservation', (int) $id, $key, $value ); } public static function delete_meta( $id, $key ) { return delete_metadata( 'tableengine_reservation', (int) $id, $key ); } /** * All table ids a reservation occupies (one, or several for combined tables). * * @return string[] */ public static function table_ids( array $row ) { $ids = isset( $row['table_ids'] ) && '' !== $row['table_ids'] ? explode( ',', $row['table_ids'] ) : array(); if ( ! $ids && ! empty( $row['table_id'] ) ) { $ids = array( $row['table_id'] ); } return array_values( array_filter( array_map( 'trim', $ids ) ) ); } /** * Change status and fire notifications for meaningful transitions. */ public static function set_status( $id, $status, $notify = true ) { $row = self::get( $id ); if ( ! $row || ! isset( self::statuses()[ $status ] ) ) { return $row; } $old = $row['status']; if ( $old === $status ) { return $row; } $update = array( 'status' => $status ); if ( 'pending_payment' !== $status ) { $update['hold_expires_gmt'] = null; } $row = self::update( $id, $update ); do_action( 'tableengine_status_changed', $row, $old, $status ); if ( $notify ) { if ( 'confirmed' === $status && in_array( $old, array( 'pending', 'pending_payment' ), true ) ) { Notifications::dispatch( 'confirm', $row ); if ( 'pending_payment' === $old ) { Notifications::dispatch( 'admin_new', $row ); } } elseif ( 'pending' === $status && 'pending_payment' === $old ) { Notifications::dispatch( 'pending', $row ); Notifications::dispatch( 'admin_new', $row ); } elseif ( 'cancelled' === $status && 'pending_payment' !== $old ) { Notifications::dispatch( 'cancel', $row ); Notifications::dispatch( 'admin_cancel', $row ); } } return $row; } /** * Admin listing query. */ public static function query( array $args ) { global $wpdb; $args = wp_parse_args( $args, array( 'from' => '', 'to' => '', 'status' => '', 'search' => '', 'page' => 1, 'per_page' => 50, 'order' => 'ASC', 'location' => 0, 'guest' => 0, ) ); $where = array( '1=1' ); $params = array(); if ( $args['from'] ) { $where[] = 'start_at >= %s'; $params[] = $args['from'] . ' 00:00:00'; } if ( $args['to'] ) { $where[] = 'start_at <= %s'; $params[] = $args['to'] . ' 23:59:59'; } if ( $args['status'] ) { $statuses = array_intersect( explode( ',', $args['status'] ), array_keys( self::statuses() ) ); if ( $statuses ) { $where[] = 'status IN (' . implode( ',', array_fill( 0, count( $statuses ), '%s' ) ) . ')'; $params = array_merge( $params, array_values( $statuses ) ); } } if ( $args['search'] ) { $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; $where[] = '(name LIKE %s OR email LIKE %s OR phone LIKE %s OR reference LIKE %s OR table_label LIKE %s)'; $params = array_merge( $params, array( $like, $like, $like, $like, $like ) ); } if ( $args['location'] ) { $where[] = 'location_id = %d'; $params[] = (int) $args['location']; } if ( $args['guest'] ) { $where[] = 'guest_id = %d'; $params[] = (int) $args['guest']; } if ( empty( $args['unscoped'] ) && self::scope_sql() ) { $where[] = '1=1' . self::scope_sql(); } list( $where, $params ) = apply_filters( 'tableengine_reservations_query_where', array( $where, $params ), $args ); $order = 'DESC' === strtoupper( $args['order'] ) ? 'DESC' : 'ASC'; $per_page = max( 1, min( 500, (int) $args['per_page'] ) ); $offset = ( max( 1, (int) $args['page'] ) - 1 ) * $per_page; $sql_w = implode( ' AND ', $where ); $count_sql = 'SELECT COUNT(*) FROM ' . self::table() . " WHERE {$sql_w}"; $list_sql = 'SELECT * FROM ' . self::table() . " WHERE {$sql_w} ORDER BY start_at {$order}, id ASC LIMIT {$per_page} OFFSET {$offset}"; $total = (int) ( $params ? $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) ) : $wpdb->get_var( $count_sql ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. $rows = $params ? $wpdb->get_results( $wpdb->prepare( $list_sql, $params ), ARRAY_A ) : $wpdb->get_results( $list_sql, ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. return array( 'total' => $total, 'items' => array_map( array( __CLASS__, 'format_admin' ), $rows ? $rows : array() ), ); } /** * Reservations that overlap a window and still occupy a table. */ public static function blocking_between( $start, $end, $exclude_id = 0 ) { global $wpdb; $now = current_time( 'mysql', true ); $sql = 'SELECT id, floorplan_id, table_id, table_ids, location_id, party_size, start_at, end_at, status FROM ' . self::table() . " WHERE start_at < %s AND end_at > %s AND id <> %d AND ( status IN ('pending','confirmed','seated') OR ( status = 'pending_payment' AND hold_expires_gmt > %s ) )"; $rows = $wpdb->get_results( $wpdb->prepare( $sql, $end, $start, (int) $exclude_id, $now ), ARRAY_A ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB -- Plugin's own custom table: the name is $wpdb->prefix plus a fixed suffix and values are prepared, so there is no core API or cache to use. return apply_filters( 'tableengine_blocking_reservations', $rows ? $rows : array(), $start, $end, $exclude_id ); } public static function format_public( $row ) { if ( ! $row ) { return null; } $tz = wp_timezone(); $start = new \DateTimeImmutable( $row['start_at'], $tz ); $plan = $row['floorplan_id'] ? Floorplans::get( $row['floorplan_id'] ) : null; $out = array( 'reference' => $row['reference'], 'status' => $row['status'], 'statusLabel' => self::statuses()[ $row['status'] ] ?? $row['status'], 'paymentStatus' => $row['payment_status'], 'name' => $row['name'], 'email' => $row['email'], 'party' => (int) $row['party_size'], 'date' => $start->format( 'Y-m-d' ), 'time' => $start->format( 'H:i' ), 'dateLabel' => self::format_date( $row['start_at'] ), 'timeLabel' => self::format_time( $row['start_at'] ), 'endLabel' => self::format_time( $row['end_at'] ), 'table' => $row['table_label'], 'room' => $plan ? $plan['name'] : '', 'amount' => (int) $row['amount'], 'amountLabel' => $row['amount'] ? self::format_money( $row['amount'], $row['currency'] ) : '', 'currency' => $row['currency'], 'occasion' => $row['occasion'], 'notes' => $row['notes'], 'canCancel' => self::guest_can_cancel( $row ), 'manageUrl' => self::manage_url( $row ), 'icsUrl' => self::ics_url( $row ), 'googleUrl' => self::google_calendar_url( $row ), ); return apply_filters( 'tableengine_format_public', $out, $row ); } public static function format_admin( $row ) { $out = $row; foreach ( array( 'id', 'floorplan_id', 'location_id', 'shift_id', 'guest_id', 'party_size', 'amount', 'reminder_sent', 'marketing_optin' ) as $k ) { $out[ $k ] = (int) $row[ $k ]; } unset( $out['token'] ); $out['table_ids'] = self::table_ids( $row ); $out['date'] = substr( $row['start_at'], 0, 10 ); $out['time'] = substr( $row['start_at'], 11, 5 ); $out['end_time'] = substr( $row['end_at'], 11, 5 ); $out['time_label'] = self::format_time( $row['start_at'] ); $out['end_label'] = self::format_time( $row['end_at'] ); $out['date_label'] = self::format_date( $row['start_at'] ); $out['amount_label'] = $row['amount'] ? self::format_money( $row['amount'], $row['currency'] ) : ''; $out['status_label'] = self::statuses()[ $row['status'] ] ?? $row['status']; $out['payment_label'] = self::payment_statuses()[ $row['payment_status'] ] ?? $row['payment_status']; $out['manage_url'] = self::manage_url( $row ); $gateway = Payments::for_reservation( $row ); $out['payment_url'] = $gateway ? $gateway->admin_url( $row ) : ''; $out['gateway_label'] = $gateway ? $gateway->label() : ''; $out['guest'] = Guests::summary( $row['guest_id'] ); return apply_filters( 'tableengine_format_admin', $out, $row ); } public static function guest_can_cancel( $row ) { $start = new \DateTimeImmutable( $row['start_at'], wp_timezone() ); $cutoff = $start->getTimestamp() - HOUR_IN_SECONDS * (int) Settings::get( 'cancel_cutoff_hours' ); $ok = Settings::get( 'allow_cancel' ) && in_array( $row['status'], array( 'pending', 'confirmed' ), true ) && time() <= $cutoff; /** Runs for every status, so extensions can allow e.g. leaving a waitlist. */ return (bool) apply_filters( 'tableengine_guest_can_cancel', $ok, $row ); } public static function qualifies_for_refund( $row ) { if ( 'paid' !== $row['payment_status'] || ! Settings::get( 'refund_on_cancel' ) ) { return false; } $start = new \DateTimeImmutable( $row['start_at'], wp_timezone() ); $ok = time() <= $start->getTimestamp() - HOUR_IN_SECONDS * (int) Settings::get( 'refund_cutoff_hours' ); return (bool) apply_filters( 'tableengine_qualifies_for_refund', $ok, $row ); } public static function manage_url( $row ) { $page = (int) Settings::get( 'booking_page' ); /** Page that hosts the manage view for this booking (e.g. its translation). */ $base = (string) apply_filters( 'tableengine_manage_base_url', $page ? get_permalink( $page ) : home_url( '/' ), $row ); return add_query_arg( array( 'tableengine_ref' => $row['reference'], 'tableengine_token' => $row['token'], ), $base ); } public static function ics_url( $row ) { return add_query_arg( 'token', $row['token'], rest_url( 'tableengine/v1/reservations/' . $row['reference'] . '/ics' ) ); } public static function google_calendar_url( $row ) { $tz = wp_timezone(); $start = ( new \DateTimeImmutable( $row['start_at'], $tz ) )->setTimezone( new \DateTimeZone( 'UTC' ) ); $end = ( new \DateTimeImmutable( $row['end_at'], $tz ) )->setTimezone( new \DateTimeZone( 'UTC' ) ); return add_query_arg( array( 'action' => 'TEMPLATE', 'text' => rawurlencode( sprintf( /* translators: %s restaurant */ __( 'Table at %s', 'tableengine' ), Settings::get( 'restaurant_name' ) ) ), 'dates' => $start->format( 'Ymd\THis\Z' ) . '/' . $end->format( 'Ymd\THis\Z' ), 'details' => rawurlencode( sprintf( /* translators: 1: ref 2: party */ __( 'Booking %1$s · %2$d guests', 'tableengine' ), $row['reference'], $row['party_size'] ) ), 'location' => rawurlencode( (string) Settings::get( 'restaurant_address' ) ), ), 'https://calendar.google.com/calendar/render' ); } public static function format_date( $mysql ) { $d = new \DateTimeImmutable( $mysql, wp_timezone() ); return wp_date( 'l, j F Y', $d->getTimestamp() ); } public static function format_time( $mysql ) { $d = new \DateTimeImmutable( $mysql, wp_timezone() ); return wp_date( '24' === Settings::get( 'time_format' ) ? 'H:i' : 'g:i A', $d->getTimestamp() ); } public static function format_money( $minor, $currency ) { $zero = Payments::is_zero_decimal( $currency ); $val = $zero ? (int) $minor : $minor / 100; $sym = array( 'USD' => '$', 'EUR' => '€', 'GBP' => '£', 'AUD' => 'A$', 'CAD' => 'C$', 'NZD' => 'NZ$', 'JPY' => '¥', 'INR' => '₹', 'NPR' => 'Rs ', 'KRW' => '₩', ); $num = number_format_i18n( $val, $zero ? 0 : 2 ); return isset( $sym[ $currency ] ) ? $sym[ $currency ] . $num : $num . ' ' . $currency; } }