can( 'floorplans' ); $payments = $this->can( 'payments' ); $settings = $this->can( 'settings' ); // ---- Public --------------------------------------------------------- register_rest_route( self::NS, '/availability/days', array( 'methods' => 'GET', 'callback' => array( $this, 'days' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/availability/slots', array( 'methods' => 'GET', 'callback' => array( $this, 'slots' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/availability/tables', array( 'methods' => 'GET', 'callback' => array( $this, 'tables' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/reservations', array( 'methods' => 'POST', 'callback' => array( $this, 'create' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/reservations/(?PTB-[A-Z0-9]+)', array( 'methods' => 'GET', 'callback' => array( $this, 'show' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/reservations/(?PTB-[A-Z0-9]+)/verify', array( 'methods' => 'POST', 'callback' => array( $this, 'verify' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/reservations/(?PTB-[A-Z0-9]+)/cancel', array( 'methods' => 'POST', 'callback' => array( $this, 'guest_cancel' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/reservations/(?PTB-[A-Z0-9]+)/ics', array( 'methods' => 'GET', 'callback' => array( $this, 'ics' ), 'permission_callback' => $public ) ); register_rest_route( self::NS, '/stripe/webhook', array( 'methods' => 'POST', 'callback' => array( 'TableEngine\\Stripe', 'handle_webhook' ), 'permission_callback' => $public ) ); // ---- Admin ---------------------------------------------------------- register_rest_route( self::NS, '/admin/floorplans', array( array( 'methods' => 'GET', 'callback' => array( $this, 'plans_list' ), 'permission_callback' => $admin ), array( 'methods' => 'POST', 'callback' => array( $this, 'plans_save' ), 'permission_callback' => $rooms ), ) ); register_rest_route( self::NS, '/admin/floorplans/(?P\d+)', array( array( 'methods' => 'PUT,POST', 'callback' => array( $this, 'plans_save' ), 'permission_callback' => $rooms ), array( 'methods' => 'DELETE', 'callback' => array( $this, 'plans_delete' ), 'permission_callback' => $rooms ), ) ); register_rest_route( self::NS, '/admin/reservations', array( array( 'methods' => 'GET', 'callback' => array( $this, 'admin_list' ), 'permission_callback' => $admin ), array( 'methods' => 'POST', 'callback' => array( $this, 'admin_create' ), 'permission_callback' => $admin ), ) ); register_rest_route( self::NS, '/admin/reservations/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( $this, 'admin_get' ), 'permission_callback' => $admin ), array( 'methods' => 'PATCH,PUT,POST', 'callback' => array( $this, 'admin_update' ), 'permission_callback' => $admin ), array( 'methods' => 'DELETE', 'callback' => array( $this, 'admin_delete' ), 'permission_callback' => $payments ), ) ); register_rest_route( self::NS, '/admin/reservations/(?P\d+)/refund', array( 'methods' => 'POST', 'callback' => array( $this, 'admin_refund' ), 'permission_callback' => $payments ) ); register_rest_route( self::NS, '/admin/reservations/(?P\d+)/resend', array( 'methods' => 'POST', 'callback' => array( $this, 'admin_resend' ), 'permission_callback' => $admin ) ); register_rest_route( self::NS, '/admin/tables', array( 'methods' => 'GET', 'callback' => array( $this, 'admin_tables' ), 'permission_callback' => $admin ) ); register_rest_route( self::NS, '/admin/stats', array( 'methods' => 'GET', 'callback' => array( $this, 'admin_stats' ), 'permission_callback' => $admin ) ); register_rest_route( self::NS, '/admin/stripe/test', array( 'methods' => 'POST', 'callback' => array( $this, 'admin_stripe_test' ), 'permission_callback' => $settings ) ); /** * Register extra routes. Use the passed namespace; admin routes should use * `array( $rest, 'can_manage' )` as their permission callback. */ do_action( 'tableengine_rest_routes', self::NS, $this ); } // ===================================================================== // Helpers // ===================================================================== private function err( $code, $message, $status = 400 ) { return new \WP_Error( $code, $message, array( 'status' => $status ) ); } private function party( \WP_REST_Request $r ) { return max( 1, min( 500, (int) $r->get_param( 'party' ) ) ); } private function time_param( $time ) { return is_string( $time ) && preg_match( '/^([01]\d|2[0-3]):[0-5]\d$/', $time ) ? $time : ''; } private function client_ip() { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; return apply_filters( 'tableengine_client_ip', $ip ); } private function rate_limited() { $limit = (int) Settings::get( 'rate_limit' ); if ( $limit <= 0 ) { return false; } $key = 'tableengine_rl_' . md5( $this->client_ip() ); $count = (int) get_transient( $key ); if ( $count >= $limit ) { return true; } set_transient( $key, $count + 1, HOUR_IN_SECONDS ); return false; } private function lock() { global $wpdb; return (bool) $wpdb->get_var( "SELECT GET_LOCK('tableengine_booking', 10)" ); // phpcs:ignore WordPress.DB -- MySQL named lock that serialises bookings; no table and no input. } private function unlock() { global $wpdb; $wpdb->query( "SELECT RELEASE_LOCK('tableengine_booking')" ); // phpcs:ignore WordPress.DB -- MySQL named lock that serialises bookings; no table and no input. } private function guest_row( \WP_REST_Request $r ) { $row = Reservations::get_by_reference( $r['ref'] ); if ( ! Reservations::check_token( $row, (string) $r->get_param( 'token' ) ) ) { return $this->err( 'tableengine_not_found', __( 'Booking not found.', 'tableengine' ), 404 ); } return $row; } private function public_plans() { $out = array(); foreach ( Floorplans::all( true ) as $plan ) { $out[] = array( 'id' => $plan['id'], 'name' => $plan['name'], 'data' => $plan['data'], ); } return apply_filters( 'tableengine_public_plans', $out ); } /** * Store a bookable unit on a reservation: primary table plus all member tables. */ private function table_columns( $unit ) { if ( ! $unit ) { return array( 'floorplan_id' => 0, 'table_id' => '', 'table_ids' => '', 'table_label' => '', ); } $members = Availability::members( $unit ); return array( 'floorplan_id' => (int) $unit['plan_id'], 'table_id' => $members[0], 'table_ids' => implode( ',', $members ), 'table_label' => $unit['label'], ); } // ===================================================================== // Public endpoints // ===================================================================== public function days( \WP_REST_Request $r ) { $from = (string) $r->get_param( 'from' ); if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $from ) ) { $from = wp_date( 'Y-m-d' ); } $days = max( 1, min( 62, (int) $r->get_param( 'days' ) ? (int) $r->get_param( 'days' ) : 42 ) ); return rest_ensure_response( array( 'days' => Availability::open_days( $from, $days ) ) ); } public function slots( \WP_REST_Request $r ) { $date = (string) $r->get_param( 'date' ); $party = $this->party( $r ); if ( ! Availability::valid_date( $date ) ) { return $this->err( 'tableengine_date', __( 'Please choose a date within the booking window.', 'tableengine' ) ); } $ranges = Availability::ranges_for( $date ); return rest_ensure_response( array( 'date' => $date, 'closed' => empty( $ranges ), 'slots' => Availability::slots( $date, $party ), ) ); } public function tables( \WP_REST_Request $r ) { $date = (string) $r->get_param( 'date' ); $time = $this->time_param( $r->get_param( 'time' ) ); $party = $this->party( $r ); if ( ! Availability::valid_date( $date ) || ! $time ) { return $this->err( 'tableengine_params', __( 'Invalid date or time.', 'tableengine' ) ); } return rest_ensure_response( apply_filters( 'tableengine_availability_tables_response', array( 'plans' => $this->public_plans(), 'states' => Availability::table_states( $date, $time, $party ), ), $date, $time, $party ) ); } public function create( \WP_REST_Request $r ) { // Honeypot: a hidden, non-semantic field that humans and autofill never fill. if ( Settings::get( 'honeypot' ) && '' !== trim( (string) $r->get_param( 'tf_hp' ) ) ) { return $this->err( 'tableengine_spam', __( 'We couldn’t verify this submission. If you use an autofill or form-filler extension, please disable it for this page and try again.', 'tableengine' ) ); } if ( $this->rate_limited() ) { return $this->err( 'tableengine_rate', __( 'Too many attempts. Please try again later.', 'tableengine' ), 429 ); } $date = (string) $r->get_param( 'date' ); $time = $this->time_param( $r->get_param( 'time' ) ); $party = $this->party( $r ); $name = sanitize_text_field( (string) $r->get_param( 'name' ) ); $email = sanitize_email( (string) $r->get_param( 'email' ) ); $phone = sanitize_text_field( (string) $r->get_param( 'phone' ) ); $notes = sanitize_textarea_field( (string) $r->get_param( 'notes' ) ); $occasion = sanitize_text_field( (string) $r->get_param( 'occasion' ) ); $plan_id = (int) $r->get_param( 'plan_id' ); $table_id = preg_replace( '/[^A-Za-z0-9_\-]/', '', (string) $r->get_param( 'table_id' ) ); // Field validation. $errors = array(); if ( mb_strlen( $name ) < 2 ) { $errors['name'] = __( 'Please enter your name.', 'tableengine' ); } /** Channels that identify the guest another way (e.g. the AI phone agent, by caller number) may leave email out. */ $email_optional = '' === $email && strlen( preg_replace( '/\D/', '', $phone ) ) >= 6 && (bool) apply_filters( 'tableengine_booking_email_optional', false, $r ); if ( ! is_email( $email ) && ! $email_optional ) { $errors['email'] = __( 'Please enter a valid email address.', 'tableengine' ); } $phone_mode = Settings::get( 'phone_field' ); if ( 'required' === $phone_mode && strlen( preg_replace( '/\D/', '', $phone ) ) < 6 ) { $errors['phone'] = __( 'Please enter a valid phone number.', 'tableengine' ); } if ( 'required' === Settings::get( 'notes_field' ) && '' === trim( $notes ) ) { $errors['notes'] = __( 'This field is required.', 'tableengine' ); } if ( Settings::get( 'terms_required' ) && ! $r->get_param( 'terms' ) ) { $errors['terms'] = __( 'Please accept the terms to continue.', 'tableengine' ); } /** Add field errors (field key => message), e.g. for custom booking fields. */ $errors = (array) apply_filters( 'tableengine_validate_booking', $errors, $r ); if ( $errors ) { return new \WP_Error( 'tableengine_validation', __( 'Please check the highlighted fields.', 'tableengine' ), array( 'status' => 422, 'fields' => $errors ) ); } if ( 'hidden' === $phone_mode ) { $phone = ''; } if ( 'hidden' === Settings::get( 'notes_field' ) ) { $notes = ''; } if ( ! $this->lock() ) { return $this->err( 'tableengine_busy', __( 'We’re handling a lot of bookings right now — please try again.', 'tableengine' ), 503 ); } try { $valid = Availability::validate_slot( $date, $time, $party ); if ( is_wp_error( $valid ) ) { $valid->add_data( array( 'status' => 409 ) ); return $valid; } $mode = Settings::get( 'table_selection' ); $table = null; if ( 'auto' !== $mode && $plan_id && $table_id ) { $table = Availability::find_candidate( $plan_id, $table_id, $party, $date, $time ); $states = Availability::table_states( $date, $time, $party ); if ( ! $table || 'available' !== ( $states[ $plan_id . ':' . $table_id ] ?? '' ) ) { return $this->err( 'tableengine_table_taken', __( 'Sorry, that table was just booked. Please pick another.', 'tableengine' ), 409 ); } } elseif ( 'required' === $mode ) { return $this->err( 'tableengine_table_required', __( 'Please choose a table.', 'tableengine' ) ); } else { $table = Availability::auto_assign( $date, $time, $party, $plan_id ); if ( ! $table ) { return $this->err( 'tableengine_full', __( 'Sorry, we’re fully booked at that time.', 'tableengine' ), 409 ); } } $tz = wp_timezone(); $start = new \DateTimeImmutable( $date . ' ' . $time . ':00', $tz ); $end = $start->modify( '+' . Availability::duration_for( $party, $date, $time ) . ' minutes' ); $context = array( 'date' => $date, 'time' => $time, 'plan_id' => (int) $table['plan_id'], 'table' => $table, ); $gateway = Payments::active(); $amount = Payments::deposit_for( $party, $context ); $pay = $gateway && Payments::required( $amount, $party, $context ); /** * Last chance to stop before the booking is saved, e.g. a channel that can't take a payment * (the chat assistant) hands the guest over to the booking form instead. Return a WP_Error to stop. */ $stop = apply_filters( 'tableengine_booking_pre_insert', null, $pay ? $amount : 0, $context, $r ); if ( is_wp_error( $stop ) ) { return $stop; } $status = $pay ? 'pending_payment' : ( Settings::get( 'auto_confirm' ) ? 'confirmed' : 'pending' ); /** Adjust the new reservation's columns (e.g. location_id, shift_id). */ $data = apply_filters( 'tableengine_booking_data', array_merge( $this->table_columns( $table ), array( 'party_size' => $party, 'start_at' => $start->format( 'Y-m-d H:i:s' ), 'end_at' => $end->format( 'Y-m-d H:i:s' ), 'status' => $status, 'name' => $name, 'email' => $email, 'phone' => $phone, 'occasion' => mb_substr( $occasion, 0, 120 ), 'notes' => mb_substr( $notes, 0, 2000 ), 'amount' => $pay ? $amount : 0, 'currency' => Settings::get( 'currency' ), 'payment_status' => $pay ? 'unpaid' : 'none', 'gateway' => $pay ? $gateway->id() : '', 'hold_expires_gmt' => $pay ? gmdate( 'Y-m-d H:i:s', time() + 60 * (int) Settings::get( 'hold_minutes' ) ) : null, 'marketing_optin' => $r->get_param( 'marketing' ) ? 1 : 0, 'source' => 'web', 'ip' => $this->client_ip(), ) ), $r, $table ); $row = Reservations::insert( $data ); } finally { $this->unlock(); } if ( ! $row ) { return $this->err( 'tableengine_db', __( 'Could not save your booking. Please try again.', 'tableengine' ), 500 ); } /** Save extra submitted data (custom fields, add-ons…) against the new reservation. */ do_action( 'tableengine_booking_submitted', $row, $r ); $payment = null; if ( $pay ) { $client = $gateway->start( $row ); if ( is_wp_error( $client ) ) { Reservations::delete( $row['id'] ); return $this->err( 'tableengine_payment', __( 'We couldn’t start the payment. Please try again in a moment.', 'tableengine' ) . ' (' . $client->get_error_message() . ')', 502 ); } $row = Reservations::get( $row['id'] ); $payment = array_merge( array( 'gateway' => $gateway->id(), 'amount' => (int) $row['amount'], 'amountLabel' => Reservations::format_money( $row['amount'], $row['currency'] ), 'expiresIn' => 60 * (int) Settings::get( 'hold_minutes' ), ), (array) $client ); } else { Notifications::dispatch( 'confirmed' === $row['status'] ? 'confirm' : 'pending', $row ); Notifications::dispatch( 'admin_new', $row ); } return rest_ensure_response( apply_filters( 'tableengine_booking_response', array( 'reservation' => Reservations::format_public( $row ), 'token' => $row['token'], 'payment' => $payment, ), $row, $r ) ); } public function show( \WP_REST_Request $r ) { $row = $this->guest_row( $r ); return is_wp_error( $row ) ? $row : rest_ensure_response( Reservations::format_public( $row ) ); } /** * Client-side fallback: pull the PaymentIntent from Stripe and sync, so the * guest sees the confirmed state even if the webhook is delayed. */ public function verify( \WP_REST_Request $r ) { $row = $this->guest_row( $r ); if ( is_wp_error( $row ) ) { return $row; } $gateway = Payments::for_reservation( $row ); if ( $gateway ) { $gateway->verify( $row ); } return rest_ensure_response( Reservations::format_public( Reservations::get( $row['id'] ) ) ); } public function guest_cancel( \WP_REST_Request $r ) { $row = $this->guest_row( $r ); if ( is_wp_error( $row ) ) { return $row; } // Abandoned checkout: release the hold silently. if ( 'pending_payment' === $row['status'] ) { $gateway = Payments::for_reservation( $row ); if ( $gateway ) { $gateway->cancel( $row ); } Reservations::update( $row['id'], array( 'payment_status' => 'cancelled' ) ); Reservations::set_status( $row['id'], 'expired', false ); return rest_ensure_response( Reservations::format_public( Reservations::get( $row['id'] ) ) ); } if ( ! Reservations::guest_can_cancel( $row ) ) { return $this->err( 'tableengine_cancel', __( 'This booking can no longer be cancelled online. Please contact us.', 'tableengine' ), 403 ); } $refunded = false; if ( Reservations::qualifies_for_refund( $row ) ) { /** Minor units to refund when a guest cancels; 0 = all of it. */ $amount = (int) apply_filters( 'tableengine_guest_refund_amount', 0, $row ); $refunded = ! is_wp_error( Payments::refund( $row, $amount ) ); } $row = Reservations::set_status( $row['id'], 'cancelled' ); $out = Reservations::format_public( $row ); $out['refunded'] = $refunded; return rest_ensure_response( $out ); } public function ics( \WP_REST_Request $r ) { $row = $this->guest_row( $r ); if ( is_wp_error( $row ) ) { return $row; } $tz = wp_timezone(); $utc = new \DateTimeZone( 'UTC' ); $start = ( new \DateTimeImmutable( $row['start_at'], $tz ) )->setTimezone( $utc ); $end = ( new \DateTimeImmutable( $row['end_at'], $tz ) )->setTimezone( $utc ); // iCalendar (RFC 5545) text escaping: tags and control characters removed, then \ ; , and newlines escaped. $esc = function ( $s ) { $s = wp_strip_all_tags( (string) $s ); $s = str_replace( array( '\\', ';', ',', "\r\n", "\r", "\n" ), array( '\\\\', '\;', '\,', '\n', '\n', '\n' ), $s ); return (string) preg_replace( '/[\x00-\x1F\x7F]/', '', $s ); }; $ref = preg_replace( '/[^A-Za-z0-9-]/', '', (string) $row['reference'] ); $name = Settings::get( 'restaurant_name' ); $lines = array( 'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//' . preg_replace( '/[^A-Za-z0-9 ]/', '', (string) apply_filters( 'tableengine_brand_name', 'TableEngine' ) ) . '//Reservations//EN', 'CALSCALE:GREGORIAN', 'METHOD:PUBLISH', 'BEGIN:VEVENT', 'UID:' . $ref . '@' . $esc( wp_parse_url( home_url(), PHP_URL_HOST ) ), 'DTSTAMP:' . gmdate( 'Ymd\THis\Z' ), 'DTSTART:' . $start->format( 'Ymd\THis\Z' ), 'DTEND:' . $end->format( 'Ymd\THis\Z' ), /* translators: %s restaurant */ 'SUMMARY:' . $esc( sprintf( __( 'Table at %s', 'tableengine' ), $name ) ), 'DESCRIPTION:' . $esc( sprintf( '%s · %d guests · %s', $ref, (int) $row['party_size'], $row['table_label'] ) ), 'LOCATION:' . $esc( Settings::get( 'restaurant_address' ) ), 'STATUS:' . ( 'cancelled' === $row['status'] ? 'CANCELLED' : 'CONFIRMED' ), 'END:VEVENT', 'END:VCALENDAR', ); nocache_headers(); header( 'Content-Type: text/calendar; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( ( '' !== $ref ? $ref : 'booking' ) . '.ics' ) . '"' ); // A text/calendar file, not HTML: HTML escaping would corrupt it. Every value above went through $esc() (iCalendar escaping). echo implode( "\r\n", $lines ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- text/calendar body; each value is iCalendar-escaped by $esc(). exit; } // ===================================================================== // Admin endpoints // ===================================================================== public function plans_list() { return rest_ensure_response( Floorplans::all() ); } public function plans_save( \WP_REST_Request $r ) { $body = $r->get_json_params(); if ( ! is_array( $body ) ) { return $this->err( 'tableengine_body', __( 'Invalid payload.', 'tableengine' ) ); } if ( isset( $r['id'] ) ) { $body['id'] = (int) $r['id']; } $plan = Floorplans::save( $body ); return $plan ? rest_ensure_response( $plan ) : $this->err( 'tableengine_save', __( 'Could not save the floor plan.', 'tableengine' ), 500 ); } public function plans_delete( \WP_REST_Request $r ) { if ( Floorplans::count() <= 1 ) { return $this->err( 'tableengine_last', __( 'You need at least one room.', 'tableengine' ) ); } return rest_ensure_response( array( 'deleted' => Floorplans::delete( (int) $r['id'] ) ) ); } public function admin_list( \WP_REST_Request $r ) { $result = Reservations::query( array( 'from' => preg_match( '/^\d{4}-\d{2}-\d{2}$/', (string) $r['from'] ) ? $r['from'] : '', 'to' => preg_match( '/^\d{4}-\d{2}-\d{2}$/', (string) $r['to'] ) ? $r['to'] : '', 'status' => sanitize_text_field( (string) $r['status'] ), 'search' => sanitize_text_field( (string) $r['search'] ), 'page' => (int) $r['page'], 'per_page' => (int) $r['per_page'] ? (int) $r['per_page'] : 100, 'order' => (string) $r['order'], 'location' => (int) $r['location'], 'guest' => (int) $r['guest'], ) ); return rest_ensure_response( $result ); } public function admin_get( \WP_REST_Request $r ) { $row = Reservations::get( (int) $r['id'] ); if ( ! $row ) { return $this->err( 'tableengine_not_found', __( 'Not found.', 'tableengine' ), 404 ); } $out = Reservations::format_admin( $row ); $out['events'] = Stripe::recent_events( 50, $row['id'] ); return rest_ensure_response( $out ); } /** * Shared field extraction for admin create/update. */ private function admin_fields( \WP_REST_Request $r, $existing = null ) { $data = array(); foreach ( array( 'name', 'phone', 'occasion' ) as $f ) { if ( null !== $r->get_param( $f ) ) { $data[ $f ] = sanitize_text_field( (string) $r->get_param( $f ) ); } } if ( null !== $r->get_param( 'email' ) ) { $data['email'] = sanitize_email( (string) $r->get_param( 'email' ) ); } foreach ( array( 'notes', 'internal_notes' ) as $f ) { if ( null !== $r->get_param( $f ) ) { $data[ $f ] = sanitize_textarea_field( (string) $r->get_param( $f ) ); } } if ( null !== $r->get_param( 'party_size' ) ) { $data['party_size'] = max( 1, min( 500, (int) $r->get_param( 'party_size' ) ) ); } $date = $r->get_param( 'date' ); $time = $r->get_param( 'time' ); $plan_id = $r->get_param( 'floorplan_id' ); $table_id = $r->get_param( 'table_id' ); $date_changed = null !== $date || null !== $time || isset( $data['party_size'] ); $table_changed = null !== $plan_id || null !== $table_id; if ( $date_changed || ! $existing ) { $date = $date ? (string) $date : ( $existing ? substr( $existing['start_at'], 0, 10 ) : '' ); $time = $this->time_param( $time ? (string) $time : ( $existing ? substr( $existing['start_at'], 11, 5 ) : '' ) ); if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) || ! $time ) { return $this->err( 'tableengine_params', __( 'Please provide a valid date and time.', 'tableengine' ) ); } $party = isset( $data['party_size'] ) ? $data['party_size'] : ( $existing ? (int) $existing['party_size'] : 2 ); $duration = (int) $r->get_param( 'duration' ) ? (int) $r->get_param( 'duration' ) : Availability::duration_for( $party, $date, $time ); $start = new \DateTimeImmutable( $date . ' ' . $time . ':00', wp_timezone() ); $data['start_at'] = $start->format( 'Y-m-d H:i:s' ); $data['end_at'] = $start->modify( '+' . $duration . ' minutes' )->format( 'Y-m-d H:i:s' ); } if ( $table_changed ) { $plan_id = (int) $plan_id; $table_id = preg_replace( '/[^A-Za-z0-9_\-]/', '', (string) $table_id ); $table = null; if ( $plan_id && $table_id ) { $party = isset( $data['party_size'] ) ? $data['party_size'] : ( $existing ? (int) $existing['party_size'] : 2 ); $table = Availability::find_candidate( $plan_id, $table_id, $party, '', '', 'admin' ); if ( ! $table ) { return $this->err( 'tableengine_table', __( 'Table not found.', 'tableengine' ) ); } } $data = array_merge( $data, $this->table_columns( $table ) ); } /** Adjust columns saved from the admin editor; return a WP_Error to reject. */ return apply_filters( 'tableengine_admin_fields', $data, $r, $existing ); } private function check_conflict( array $data, $existing, $force ) { if ( $force ) { return true; } $probe = array_merge( $existing ? $existing : array( 'id' => 0 ), $data ); if ( empty( $probe['table_id'] ) ) { return true; } if ( ! Availability::reservation_table_free( $probe ) ) { return $this->err( 'tableengine_conflict', __( 'That table is already booked for this time. Choose another table or enable “override”.', 'tableengine' ), 409 ); } return true; } public function admin_create( \WP_REST_Request $r ) { $data = $this->admin_fields( $r ); if ( is_wp_error( $data ) ) { return $data; } if ( empty( $data['name'] ) ) { return $this->err( 'tableengine_name', __( 'Guest name is required.', 'tableengine' ) ); } $conflict = $this->check_conflict( $data, null, (bool) $r->get_param( 'force' ) ); if ( is_wp_error( $conflict ) ) { return $conflict; } $status = (string) $r->get_param( 'status' ); $data += array( 'status' => isset( Reservations::statuses()[ $status ] ) ? $status : 'confirmed', 'currency' => Settings::get( 'currency' ), 'payment_status' => 'none', 'source' => sanitize_key( (string) ( $r->get_param( 'source' ) ? $r->get_param( 'source' ) : 'admin' ) ), 'party_size' => 2, ); $row = Reservations::insert( $data ); if ( ! $row ) { return $this->err( 'tableengine_db', __( 'Could not save.', 'tableengine' ), 500 ); } if ( $r->get_param( 'notify' ) && $row['email'] ) { Notifications::dispatch( 'confirmed' === $row['status'] ? 'confirm' : 'pending', $row ); } do_action( 'tableengine_admin_saved', $row, $r, true ); return rest_ensure_response( Reservations::format_admin( Reservations::get( $row['id'] ) ) ); } public function admin_update( \WP_REST_Request $r ) { $row = Reservations::get( (int) $r['id'] ); if ( ! $row ) { return $this->err( 'tableengine_not_found', __( 'Not found.', 'tableengine' ), 404 ); } // Refunding moves money: it needs the payments permission, not just bookings. Checked before anything is changed. if ( $r->get_param( 'refund' ) && ! Plugin::can( 'payments' ) ) { return $this->err( 'tableengine_forbidden', __( 'You are not allowed to refund payments.', 'tableengine' ), 403 ); } $data = $this->admin_fields( $r, $row ); if ( is_wp_error( $data ) ) { return $data; } if ( isset( $data['start_at'] ) || isset( $data['table_id'] ) ) { $conflict = $this->check_conflict( $data, $row, (bool) $r->get_param( 'force' ) ); if ( is_wp_error( $conflict ) ) { return $conflict; } } if ( $data ) { $row = Reservations::update( $row['id'], $data ); } $status = (string) $r->get_param( 'status' ); if ( $status && isset( Reservations::statuses()[ $status ] ) ) { $notify = null === $r->get_param( 'notify' ) ? true : (bool) $r->get_param( 'notify' ); if ( 'cancelled' === $status && $r->get_param( 'refund' ) && 'paid' === $row['payment_status'] ) { $refund = Payments::refund( $row ); if ( is_wp_error( $refund ) ) { return $refund; } } // Approving a pending request sends the confirmation email via the status transition. $row = Reservations::set_status( $row['id'], $status, $notify ); } do_action( 'tableengine_admin_saved', $row, $r, false ); return rest_ensure_response( Reservations::format_admin( Reservations::get( $row['id'] ) ) ); } public function admin_delete( \WP_REST_Request $r ) { return rest_ensure_response( array( 'deleted' => Reservations::delete( (int) $r['id'] ) ) ); } public function admin_refund( \WP_REST_Request $r ) { $row = Reservations::get( (int) $r['id'] ); if ( ! $row ) { return $this->err( 'tableengine_not_found', __( 'Not found.', 'tableengine' ), 404 ); } if ( ! in_array( $row['payment_status'], array( 'paid', 'partially_refunded' ), true ) ) { return $this->err( 'tableengine_refund', __( 'This booking has no captured payment to refund.', 'tableengine' ) ); } $amount = (int) $r->get_param( 'amount' ); $result = Payments::refund( $row, $amount ); if ( is_wp_error( $result ) ) { return $result; } return rest_ensure_response( Reservations::format_admin( Reservations::get( $row['id'] ) ) ); } public function admin_resend( \WP_REST_Request $r ) { $row = Reservations::get( (int) $r['id'] ); if ( ! $row ) { return $this->err( 'tableengine_not_found', __( 'Not found.', 'tableengine' ), 404 ); } $map = array( 'confirmed' => 'confirm', 'pending' => 'pending', 'cancelled' => 'cancel', 'seated' => 'confirm' ); $type = isset( $map[ $row['status'] ] ) ? $map[ $row['status'] ] : 'confirm'; $result = Notifications::dispatch( $type, $row, array( 'resend' => true ), array( 'email' ) ); return rest_ensure_response( array( 'sent' => ! empty( $result['email'] ) ) ); } public function admin_tables( \WP_REST_Request $r ) { $date = (string) $r['date']; $time = $this->time_param( $r['time'] ); $party = $this->party( $r ); $exclude = (int) $r['exclude']; if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) || ! $time ) { return $this->err( 'tableengine_params', __( 'Invalid date or time.', 'tableengine' ) ); } $start = new \DateTimeImmutable( $date . ' ' . $time . ':00', wp_timezone() ); $end = $start->modify( '+' . Availability::duration_for( $party, $date, $time ) . ' minutes' ); $out = array(); foreach ( Availability::candidates( $party, $date, $time, 'admin' ) as $t ) { $members = Availability::members( $t ); $free = Availability::reservation_table_free( array( 'id' => $exclude ), $start->format( 'Y-m-d H:i:s' ), $end->format( 'Y-m-d H:i:s' ), $t['plan_id'], $members ); $out[] = array( 'plan_id' => $t['plan_id'], 'plan' => isset( $t['plan_name'] ) ? $t['plan_name'] : '', 'id' => $t['id'], 'label' => $t['label'], 'seatsMin' => $t['seatsMin'], 'seatsMax' => $t['seatsMax'], 'members' => $members, 'free' => $free, 'fits' => $party <= $t['seatsMax'], ); } return rest_ensure_response( $out ); } public function admin_stats( \WP_REST_Request $r ) { global $wpdb; $date = preg_match( '/^\d{4}-\d{2}-\d{2}$/', (string) $r['date'] ) ? $r['date'] : wp_date( 'Y-m-d' ); $t = Install::table( 'reservations' ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT status, payment_status, party_size, amount FROM {$t} WHERE start_at BETWEEN %s AND %s" . Reservations::scope_sql(), $date . ' 00:00:00', $date . ' 23:59:59' ), 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. $stats = array( 'bookings' => 0, 'covers' => 0, 'pending' => 0, 'seated' => 0, 'deposits' => 0, 'cancelled' => 0, ); foreach ( $rows as $row ) { if ( in_array( $row['status'], array( 'cancelled', 'expired', 'no_show' ), true ) ) { if ( 'cancelled' === $row['status'] ) { $stats['cancelled']++; } continue; } if ( in_array( $row['status'], Reservations::non_booking_statuses(), true ) ) { continue; } $stats['bookings']++; $stats['covers'] += (int) $row['party_size']; if ( 'pending' === $row['status'] ) { $stats['pending']++; } if ( 'seated' === $row['status'] ) { $stats['seated'] += (int) $row['party_size']; } if ( 'paid' === $row['payment_status'] ) { $stats['deposits'] += (int) $row['amount']; } } $stats['deposits_label'] = Reservations::format_money( $stats['deposits'], Settings::get( 'currency' ) ); $stats['seats_total'] = array_sum( array_map( function ( $t ) { return (int) $t['seatsMax']; }, Floorplans::all_tables() ) ); // phpcs:ignore return rest_ensure_response( $stats ); } public function admin_stripe_test() { if ( ! Stripe::secret_key() ) { return $this->err( 'tableengine_stripe_key', __( 'Add your secret key and save first.', 'tableengine' ) ); } $res = Stripe::request( 'GET', 'balance' ); if ( is_wp_error( $res ) ) { return $res; } return rest_ensure_response( array( 'ok' => true, 'mode' => empty( $res['livemode'] ) ? 'test' : 'live', 'webhook' => (bool) Stripe::webhook_secret(), ) ); } }