route( '/admin/bookings', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'search' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create' ), 'permission' => $enter, ), ) ); $this->route( '/admin/bookings/export', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'export' ), 'permission' => array( $this, 'can_desk' ), ), ) ); $this->route( '/admin/bookings/(?P\d+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'show' ), 'permission' => $enter, 'args' => self::id_arg(), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update' ), 'permission' => $enter, 'args' => self::id_arg(), ), ) ); foreach ( array( 'reschedule', 'cancel', 'payments', 'check-in', 'resend' ) as $action ) { $this->route( '/admin/bookings/(?P\d+)/' . $action, array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, str_replace( '-', '_', $action ) ), 'permission' => $enter, 'args' => self::id_arg(), ), ) ); } $this->route( '/admin/calendar', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'calendar' ), 'permission' => $enter, ), ) ); $this->route( '/admin/availability', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'availability' ), 'permission' => $enter, ), ) ); $this->route( '/admin/dashboard', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'dashboard' ), 'permission' => $enter, ), ) ); } /** * Search bookings. * * @param WP_REST_Request $request Request. * @return array */ public function search( WP_REST_Request $request ): array { $filters = $this->filters( $request ); $result = Services::bookings()->search( $filters ); return array( 'items' => array_map( array( $this, 'row' ), $result['items'] ), 'total' => $result['total'], ); } /** * Book for a customer. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When staff may not book for others. */ public function create( WP_REST_Request $request ): array { $body = self::body( $request ); if ( ! Capabilities::can_desk() ) { // Staff book only themselves. $own = Capabilities::own_staff_id(); foreach ( (array) ( $body['items'] ?? array() ) as $i => $item ) { $body['items'][ $i ]['staff_id'] = $own; } } $booking = Services::checkout()->book_by_staff( $body ); return $this->full( $booking ); } /** * One booking in full. * * @param WP_REST_Request $request Request. * @return array */ public function show( WP_REST_Request $request ): array { return $this->full( $this->booking( $request ) ); } /** * Change notes or status. * * @param WP_REST_Request $request Request. * @return array */ public function update( WP_REST_Request $request ): array { $booking = $this->booking( $request ); $body = self::body( $request ); $data = array(); if ( isset( $body['staff_notes'] ) ) { $data['staff_notes'] = mb_substr( sanitize_textarea_field( (string) $body['staff_notes'] ), 0, 5000 ); } if ( isset( $body['notes'] ) ) { $data['notes'] = mb_substr( sanitize_textarea_field( (string) $body['notes'] ), 0, 2000 ); } if ( isset( $body['meeting_url'] ) ) { $data['meeting_url'] = esc_url_raw( (string) $body['meeting_url'] ); } if ( array() !== $data ) { Services::bookings()->update( $booking['id'], $data ); Services::activity()->record( $booking['id'], 'edited', array( 'fields' => array_keys( $data ) ) ); } if ( isset( $body['status'] ) && $body['status'] !== $booking['status'] ) { Services::checkout()->set_status( $booking['id'], (string) $body['status'] ); } return $this->full( (array) Services::bookings()->find( $booking['id'] ) ); } /** * Move a booking. * * @param WP_REST_Request $request Request. * @return array */ public function reschedule( WP_REST_Request $request ): array { $booking = $this->booking( $request ); $body = self::body( $request ); if ( ! Capabilities::can_desk() ) { unset( $body['staff_id'] ); foreach ( (array) ( $body['items'] ?? array() ) as $i => $item ) { unset( $body['items'][ $i ]['staff_id'] ); } } return $this->full( Services::checkout()->reschedule( $booking['id'], $body, 'staff', ! empty( $body['force'] ) ) ); } /** * Cancel a booking. * * @param WP_REST_Request $request Request. * @return array */ public function cancel( WP_REST_Request $request ): array { $booking = $this->booking( $request ); $body = self::body( $request ); $refund = isset( $body['refund'] ) && is_numeric( $body['refund'] ) ? (int) $body['refund'] : null; $by = ! empty( $body['business'] ) ? 'business' : 'staff'; $result = Services::checkout()->cancel( $booking['id'], $by, $refund, ! isset( $body['online'] ) || ! empty( $body['online'] ), mb_substr( sanitize_textarea_field( (string) ( $body['reason'] ?? '' ) ), 0, 500 ) ); return $this->full( $result ) + array( 'refund_note' => $result['refund_note'] ); } /** * Record a payment, or a refund when the amount is negative. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When the amount is wrong. */ public function payments( WP_REST_Request $request ): array { $booking = $this->booking( $request ); $body = self::body( $request ); $amount = (int) ( $body['amount'] ?? 0 ); $method = (string) ( $body['method'] ?? PaymentService::OTHER ); if ( $amount < 0 && ! empty( $body['online'] ) ) { $result = Services::refunds()->refund_online( $booking, -$amount, sanitize_text_field( (string) ( $body['note'] ?? '' ) ) ); if ( '' !== $result['error'] ) { throw new BookingException( 'schedulereed_refund_failed', $result['error'], 502 ); } } else { Services::payment_service()->record( $booking['id'], $amount, $method, sanitize_text_field( (string) ( $body['note'] ?? '' ) ), sanitize_text_field( (string) ( $body['reference'] ?? '' ) ) ); } return $this->full( (array) Services::bookings()->find( $booking['id'] ) ); } /** * Mark as arrived. * * @param WP_REST_Request $request Request. * @return array */ public function check_in( WP_REST_Request $request ): array { return $this->full( Services::checkout()->check_in( $this->booking( $request )['id'] ) ); } /** * Send a booking email again. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When the email type is unknown or sending fails. */ public function resend( WP_REST_Request $request ): array { $booking = $this->booking( $request ); $type = (string) ( self::body( $request )['type'] ?? '' ); if ( '' === $type ) { $type = match ( $booking['status'] ) { Status::PENDING => 'booking_requested', Status::CANCELLED => 'booking_cancelled', default => 'booking_confirmed', }; } if ( ! isset( EmailTemplates::defaults()[ $type ] ) ) { throw new BookingException( 'schedulereed_unknown_email', __( 'Unknown email.', 'schedulereed' ) ); } if ( ! Services::notifier()->deliver( $type, $booking, array(), array(), true ) ) { throw new BookingException( 'schedulereed_email_failed', __( 'The email could not be sent. Check that the customer has an email address and that your site can send email.', 'schedulereed' ), 502 ); } return array( 'sent' => true ) + $this->full( $booking ); } /** * Bookings as CSV. * * @param WP_REST_Request $request Request. */ public function export( WP_REST_Request $request ): WP_REST_Response { $filters = $this->filters( $request ); $filters['per_page'] = 5000; $filters['page'] = 1; $rows = array( array( 'reference', 'status', 'start', 'end', 'service', 'staff', 'location', 'customer', 'email', 'phone', 'people', 'total', 'paid', 'currency', 'payment_method', 'source', 'created' ) ); foreach ( Services::bookings()->search( $filters )['items'] as $booking ) { $d = Services::notifier()->details( $booking ); $rows[] = array( $booking['uid'], $booking['status'], wp_date( 'Y-m-d H:i', $booking['start'] ), wp_date( 'Y-m-d H:i', $booking['end'] ), $d['service'], $d['staff'], $d['location'], $d['name'], $d['email'], $d['phone'], $d['people'], \ScheduleReed\Domain\Money::to_decimal( $booking['total'], $booking['currency'] ), \ScheduleReed\Domain\Money::to_decimal( $booking['paid'], $booking['currency'] ), $booking['currency'], $booking['payment_method'], $booking['source'], wp_date( 'Y-m-d H:i', $booking['created_at'] ), ); } $response = new WP_REST_Response( array( 'csv' => self::csv( $rows ) ) ); return $response; } /** * What the calendar shows between two times. * * @param WP_REST_Request $request Request. * @return array */ public function calendar( WP_REST_Request $request ): array { $from = max( 0, (int) $request['from'] ); $to = (int) $request['to']; $to = $to > $from ? min( $to, $from + 62 * DAY_IN_SECONDS ) : $from + WEEK_IN_SECONDS; $own = Capabilities::can_desk() ? 0 : Capabilities::own_staff_id(); $filters = array( 'from' => $from, 'to' => $to, 'status' => array( Status::AWAITING_PAYMENT, Status::PENDING, Status::CONFIRMED, Status::COMPLETED, Status::NO_SHOW ), 'per_page' => 2000, 'order' => 'asc', ); if ( $own > 0 ) { $filters['staff_id'] = $own; } elseif ( ! empty( $request['staff_id'] ) ) { $filters['staff_id'] = (int) $request['staff_id']; } if ( ! empty( $request['location_id'] ) ) { $filters['location_id'] = (int) $request['location_id']; } $events = array(); foreach ( Services::bookings()->search( $filters )['items'] as $booking ) { $details = Services::notifier()->details( $booking ); foreach ( $booking['items'] as $item ) { $bookable = Services::catalog()->bookable( $item['bookable_id'] ); $events[] = array( 'kind' => 'booking', 'id' => $booking['id'], 'item_id' => $item['id'], 'uid' => $booking['uid'], 'status' => $booking['status'], 'start' => $item['start'], 'end' => $item['end'], 'staff_id' => $item['staff_id'], 'location_id' => $item['location_id'], 'session_id' => $item['session_id'], 'bookable_id' => $item['bookable_id'], 'title' => $bookable ? $bookable->name : '', 'customer' => $details['name'], 'quantity' => $item['quantity'], 'paid' => $booking['paid'] >= $booking['total'], 'color' => self::color( $item ), ); } } $sessions = array(); foreach ( Services::bookables()->all() as $row ) { $bookable = Services::catalog()->bookable( (int) $row['id'] ); if ( null === $bookable || ! $bookable->uses_sessions() ) { continue; } foreach ( Services::sessions()->with_places( $bookable, Services::sessions_repo()->between( array( $bookable->id ), $from, $to ) ) as $session ) { if ( $own > 0 && $session['staff_id'] !== $own ) { continue; } $sessions[] = array( 'kind' => 'session', 'id' => $session['id'], 'bookable_id' => $bookable->id, 'title' => $bookable->name, 'start' => $session['start'], 'end' => $session['end'], 'staff_id' => $session['staff_id'], 'location_id' => $session['location_id'], 'booked' => $session['booked'], 'capacity' => $session['capacity'], 'color' => (string) ( $row['color'] ?? '' ), ); } } $busy = array_values( array_filter( Services::calendars()->events_between( $from, $to ), static fn( array $e ): bool => 0 === $own || ( 'staff' === $e['owner_type'] && $e['owner_id'] === $own ) ) ); return array( 'events' => $events, 'sessions' => $sessions, 'busy' => $busy, 'staff' => array_values( array_map( static fn( array $s ): array => array( 'id' => $s['id'], 'name' => $s['name'], 'color' => $s['color'], ), array_filter( Services::staff()->all( true ), static fn( array $s ): bool => 0 === $own || $s['id'] === $own ) ) ), ); } /** * Free times for staff booking, with why a chosen time is not free. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When the bookable is unknown. */ public function availability( WP_REST_Request $request ): array { $bookable = Services::catalog()->bookable( (int) $request['bookable_id'] ); if ( null === $bookable ) { throw new BookingException( 'schedulereed_unknown_bookable', __( 'That service is not available.', 'schedulereed' ), 404 ); } $opt = array( 'location_id' => (int) ( $request['location_id'] ?? 0 ), 'staff_id' => Capabilities::can_desk() ? (int) ( $request['staff_id'] ?? 0 ) : Capabilities::own_staff_id(), 'quantity' => max( 1, (int) ( $request['quantity'] ?? 1 ) ), 'units' => max( 1, (int) ( $request['units'] ?? 1 ) ), 'except_booking' => (int) ( $request['except_booking'] ?? 0 ), 'staff_rules' => true, ); $tz = Services::availability()->zone( $bookable, $opt ); $date = (string) ( $request['date'] ?? '' ); $date = DateOverride::is_date( $date ) ? $date : wp_date( 'Y-m-d', Clock::now(), $tz ); $from = ( new DateTimeImmutable( $date, $tz ) )->getTimestamp(); $out = array( 'timezone' => $tz->getName() ); if ( $bookable->uses_sessions() ) { $out['sessions'] = Services::sessions()->available( $bookable, $from, $from + DAY_IN_SECONDS - 1, $opt ); } else { $out['slots'] = Services::availability()->slots( $bookable, $from, $from + DAY_IN_SECONDS - 1, $opt )['slots']; if ( array() === $out['slots'] ) { // Point staff at the next day with room, so a closed day is not a dead end. $later = Services::availability()->slots( $bookable, $from + DAY_IN_SECONDS, $from + 60 * DAY_IN_SECONDS, $opt )['slots']; $out['next'] = array() === $later ? null : wp_date( 'Y-m-d', (int) $later[0]['start'], $tz ); } } if ( ! empty( $request['start'] ) ) { $out['reasons'] = Services::availability()->explain( $bookable, (int) $request['start'], $opt ); } return $out; } /** * The dashboard. * * @return array */ public function dashboard(): array { $now = Clock::now(); $tz = \ScheduleReed\Settings::timezone(); $today = ( new DateTimeImmutable( '@' . $now ) )->setTimezone( $tz )->setTime( 0, 0 )->getTimestamp(); $own = Capabilities::can_desk() ? 0 : Capabilities::own_staff_id(); $base = $own > 0 ? array( 'staff_id' => $own ) : array(); $upcoming = Services::bookings()->search( $base + array( 'from' => $today, 'to' => $today + DAY_IN_SECONDS, 'status' => array( Status::PENDING, Status::CONFIRMED, Status::COMPLETED, Status::NO_SHOW ), 'per_page' => 100, 'order' => 'asc', ) )['items']; $pending = Services::bookings()->search( $base + array( 'status' => array( Status::PENDING ), 'from' => $now, 'per_page' => 20, 'order' => 'asc', ) ); $out = array( 'today' => array_map( array( $this, 'row' ), $upcoming ), 'pending' => array( 'items' => array_map( array( $this, 'row' ), $pending['items'] ), 'total' => $pending['total'], ), 'setup' => Services::setup()->checklist(), ); if ( Capabilities::can_manage() ) { $week = Services::bookings()->totals( $today, $today + WEEK_IN_SECONDS ); $last = Services::bookings()->totals( $today - 30 * DAY_IN_SECONDS, $today ); $out['week'] = $week; $out['last_30'] = $last; $out['email_fails'] = Services::messages()->failures_since( $now - WEEK_IN_SECONDS ); $out['currency'] = \ScheduleReed\Settings::currency(); } return $out; } /** * A booking row for lists. * * @param array $booking Booking. * @return array */ public function row( array $booking ): array { $details = Services::notifier()->details( $booking ); return array( 'id' => $booking['id'], 'uid' => $booking['uid'], 'status' => $booking['status'], 'start' => $booking['start'], 'end' => $booking['end'], 'service' => $details['service'], 'staff' => $details['staff'], 'location' => $details['location'], 'customer' => $details['name'], 'customer_id' => $booking['customer_id'], 'email' => $details['email'], 'phone' => $details['phone'], 'people' => $details['people'], 'total' => $booking['total'], 'paid' => $booking['paid'], 'currency' => $booking['currency'], 'source' => $booking['source'], 'notes' => $booking['notes'], 'meeting_url' => $booking['meeting_url'], 'checked_in' => $booking['checked_in_at'] > 0, 'created_at' => $booking['created_at'], ); } /** * Everything about a booking for its panel. * * @param array $booking Booking. * @return array */ public function full( array $booking ): array { $booking = (array) Services::bookings()->find( $booking['id'] ); $customer = Services::customers()->find( $booking['customer_id'] ); $method = Services::methods()->find( $booking['payment_method'] ); unset( $booking['token'] ); return $this->row( $booking ) + array( 'booking' => $booking, 'customer_full' => $customer, 'customer_stats' => $customer ? Services::bookings()->customer_counts( $customer['id'] ) : array(), 'payment_label' => $method ? $method->label() : '', 'payments' => Services::payments()->for_booking( $booking['id'] ), 'online_refundable' => Services::refunds()->online_refundable( $booking ), 'refund_due' => Services::checkout()->refund_due( $booking, 'staff', Clock::now() ), 'policy' => Format::booking_policy( $booking ), 'activity' => Services::activity()->for_object( $booking['id'] ), 'messages' => Services::messages()->for_booking( $booking['id'] ), 'manage_url' => Format::manage_url( (array) Services::bookings()->find( $booking['id'] ) ), ); } /** * A booking the current user may touch. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When missing or not theirs. */ private function booking( WP_REST_Request $request ): array { $booking = Services::bookings()->find( (int) $request['id'] ); if ( null === $booking || ! Capabilities::can_touch( $booking ) ) { throw new BookingException( 'schedulereed_not_found', __( 'Booking not found.', 'schedulereed' ), 404 ); } return $booking; } /** * Search filters from a request, limited to the user's own for staff. * * @param WP_REST_Request $request Request. * @return array */ private function filters( WP_REST_Request $request ): array { $filters = array(); foreach ( array( 'from', 'to', 'staff_id', 'bookable_id', 'location_id', 'customer_id', 'page', 'per_page' ) as $key ) { if ( isset( $request[ $key ] ) && '' !== $request[ $key ] ) { $filters[ $key ] = (int) $request[ $key ]; } } foreach ( array( 'search', 'source', 'order', 'orderby' ) as $key ) { if ( isset( $request[ $key ] ) ) { $filters[ $key ] = sanitize_text_field( (string) $request[ $key ] ); } } if ( isset( $request['status'] ) ) { $filters['status'] = array_map( 'sanitize_key', is_array( $request['status'] ) ? $request['status'] : explode( ',', (string) $request['status'] ) ); } $filters['per_page'] = max( 1, min( 200, (int) ( $filters['per_page'] ?? 50 ) ) ); if ( ! Capabilities::can_desk() ) { $filters['staff_id'] = max( 1, Capabilities::own_staff_id() ); } return $filters; } /** * Calendar color: the staff member's, else the service's. * * @param array $item Item. */ private static function color( array $item ): string { if ( $item['staff_id'] > 0 ) { $staff = Services::staff()->find( $item['staff_id'] ); if ( $staff && '' !== $staff['color'] ) { return (string) $staff['color']; } } $row = Services::bookables()->find( $item['bookable_id'] ); return (string) ( $row['color'] ?? '' ); } /** * Rows as CSV text, with cells that could run as spreadsheet formulas made safe. * * @param array> $rows Rows. */ public static function csv( array $rows ): string { $out = ''; foreach ( $rows as $row ) { $cells = array(); foreach ( $row as $cell ) { $cell = (string) $cell; if ( '' !== $cell && in_array( $cell[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) && ! is_numeric( $cell ) ) { $cell = "'" . $cell; } $cells[] = '"' . str_replace( '"', '""', $cell ) . '"'; } $out .= implode( ',', $cells ) . "\r\n"; } return $out; } }