route( '/admin/(?P' . $types . ')', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create' ), 'permission' => $manage, ), ) ); $this->route( '/admin/(?P' . $types . ')/(?P\d+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'show' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update' ), 'permission' => array( $this, 'can_edit' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'archive' ), 'permission' => $manage, ), ) ); $this->route( '/admin/bookables/(?P\d+)/duplicate', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'duplicate' ), 'permission' => $manage, ), ) ); $owners = implode( '|', ScheduleRepository::OWNERS ); $this->route( '/admin/hours/(?P' . $owners . ')/(?P\d+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'hours' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'save_hours' ), 'permission' => array( $this, 'can_edit_hours' ), ), ) ); $this->route( '/admin/hours/(?P' . $owners . ')/(?P\d+)/overrides', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'overrides' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'add_override' ), 'permission' => array( $this, 'can_edit_hours' ), ), ) ); $this->route( '/admin/hours/(?P' . $owners . ')/(?P\d+)/overrides/(?P\d+)', array( array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_override' ), 'permission' => array( $this, 'can_edit_hours' ), ), ) ); $this->route( '/admin/holidays', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'holidays' ), 'permission' => $manage, ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'import_holidays' ), 'permission' => $manage, ), ) ); $this->route( '/admin/bookables/(?P\d+)/sessions', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'sessions' ), 'permission' => $enter, ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'add_session' ), 'permission' => $manage, ), ) ); $this->route( '/admin/sessions/(?P\d+)', array( array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_session' ), 'permission' => $manage, ), ) ); $this->route( '/admin/sessions/(?P\d+)/cancel', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'cancel_session' ), 'permission' => $manage, ), ) ); } /** * Managers edit anything; staff edit their own profile. * * @param WP_REST_Request $request Request. */ public function can_edit( WP_REST_Request $request ): bool { return Capabilities::can_manage() || ( 'staff' === $request['type'] && (int) $request['id'] > 0 && Capabilities::own_staff_id() === (int) $request['id'] ); } /** * Managers edit any hours; staff their own. * * @param WP_REST_Request $request Request. */ public function can_edit_hours( WP_REST_Request $request ): bool { return Capabilities::can_manage() || ( 'staff' === $request['owner'] && (int) $request['id'] > 0 && Capabilities::own_staff_id() === (int) $request['id'] ); } /** * Every item of a type. * * @param WP_REST_Request $request Request. * @return array> */ public function list( WP_REST_Request $request ): array { $type = (string) $request['type']; return array_values( array_map( fn( array $row ): array => $this->present( $type, $row ), $this->repo( $type )->all( ! empty( $request['active'] ) ) ) ); } /** * One item. * * @param WP_REST_Request $request Request. * @return array */ public function show( WP_REST_Request $request ): array { $type = (string) $request['type']; return $this->present( $type, $this->find( $type, (int) $request['id'] ) ); } /** * Add an item. * * @param WP_REST_Request $request Request. * @return array */ public function create( WP_REST_Request $request ): array { $type = (string) $request['type']; $body = self::body( $request ); $row = $this->validate( $type, $body, array() ); $id = $this->repo( $type )->create( $row ); $this->save_links( $type, $id, $body ); if ( 'staff' === $type ) { self::staff_saved( $id, $body ); } $this->saved( $type, $id ); return $this->present( $type, $this->find( $type, $id ) ); } /** * Change an item. * * @param WP_REST_Request $request Request. * @return array */ public function update( WP_REST_Request $request ): array { $type = (string) $request['type']; $current = $this->find( $type, (int) $request['id'] ); $body = self::body( $request ); if ( ! Capabilities::can_manage() ) { // Staff may change their own name, bio, photo and contact details only. $body = array_intersect_key( $body, array_flip( array( 'name', 'bio', 'photo_id', 'phone', 'timezone', 'color' ) ) ); } $this->repo( $type )->update( $current['id'], $this->validate( $type, $body, $current ) ); if ( Capabilities::can_manage() ) { $this->save_links( $type, $current['id'], $body ); if ( 'staff' === $type ) { self::staff_saved( $current['id'], $body ); } } $this->saved( $type, $current['id'] ); return $this->present( $type, $this->find( $type, $current['id'] ) ); } /** * Archive an item; past bookings keep its name. * * @param WP_REST_Request $request Request. * @return array */ public function archive( WP_REST_Request $request ): array { $type = (string) $request['type']; $item = $this->find( $type, (int) $request['id'] ); $this->repo( $type )->archive( $item['id'] ); $this->saved( $type, $item['id'] ); return array( 'archived' => true ); } /** * Copy a bookable with its staff and locations. * * @param WP_REST_Request $request Request. * @return array */ public function duplicate( WP_REST_Request $request ): array { $row = $this->find( 'bookables', (int) $request['id'] ); $new = Bookable::validate( array( /* translators: %s: service name. */ 'name' => sprintf( __( '%s (copy)', 'schedulereed' ), $row['name'] ), 'status' => 'draft', ), $row ); $id = Services::bookables()->create( $new ); foreach ( array( 'staff', 'location' ) as $target ) { Services::links()->set( 'bookable', $id, $target, array_values( Services::links()->targets( 'bookable', $row['id'], $target ) ) ); } $hours = Services::schedules()->weekly( 'bookable', $row['id'] ); if ( null !== $hours ) { Services::schedules()->set_weekly( 'bookable', $id, $hours ); } $this->saved( 'bookables', $id ); return $this->present( 'bookables', $this->find( 'bookables', $id ) ); } /** * Weekly hours of an owner; null means it follows the level above. * * @param WP_REST_Request $request Request. * @return array */ public function hours( WP_REST_Request $request ): array { $hours = Services::schedules()->weekly( (string) $request['owner'], (int) $request['id'] ); return array( 'hours' => $hours?->to_array() ); } /** * Save weekly hours; null removes them so the owner follows the level above. * * @param WP_REST_Request $request Request. * @return array */ public function save_hours( WP_REST_Request $request ): array { $raw = self::body( $request )['hours'] ?? null; $hours = null === $raw ? null : WeeklyHours::from_array( $raw ); Services::schedules()->set_weekly( (string) $request['owner'], (int) $request['id'], $hours ); Cache::bump(); return array( 'hours' => $hours?->to_array() ); } /** * Dates with special hours (closures, holidays, extra hours). * * @param WP_REST_Request $request Request. * @return array> */ public function overrides( WP_REST_Request $request ): array { return Services::schedules()->list_overrides( (string) $request['owner'], (int) $request['id'], wp_date( 'Y-m-d', time() - 30 * DAY_IN_SECONDS ) ); } /** * Add special hours for a date range. * * @param WP_REST_Request $request Request. * @return array */ public function add_override( WP_REST_Request $request ): array { $id = Services::schedules()->add_override( (string) $request['owner'], (int) $request['id'], DateOverride::from_array( self::body( $request ) ) ); Cache::bump(); return array( 'id' => $id ); } /** * Remove special hours. * * @param WP_REST_Request $request Request. * @return array */ public function delete_override( WP_REST_Request $request ): array { $ok = Services::schedules()->delete_override( (string) $request['owner'], (int) $request['id'], (int) $request['override'] ); Cache::bump(); return array( 'deleted' => $ok ); } /** * Countries with holiday lists, and a preview for one. * * @param WP_REST_Request $request Request. * @return array */ public function holidays( WP_REST_Request $request ): array { $country = strtoupper( (string) ( $request['country'] ?? Settings::country() ) ); $year = (int) ( $request['year'] ?? wp_date( 'Y' ) ); return array( 'countries' => Holidays::countries(), 'country' => $country, 'dates' => in_array( $country, Holidays::countries(), true ) ? Holidays::for_year( $country, $year ) : array(), ); } /** * Close the business on a country's public holidays for this year and next, * replacing earlier imported ones. * * @param WP_REST_Request $request Request. * @return array * @throws InvalidArgumentException When the country is unknown. */ public function import_holidays( WP_REST_Request $request ): array { $body = self::body( $request ); $country = strtoupper( (string) ( $body['country'] ?? '' ) ); if ( ! in_array( $country, Holidays::countries(), true ) ) { throw new InvalidArgumentException( 'country is not one we have holidays for.' ); } $skip = array_flip( array_map( 'strval', (array) ( $body['skip'] ?? array() ) ) ); Services::schedules()->clear_holidays(); $year = (int) wp_date( 'Y' ); $today = wp_date( 'Y-m-d' ); $count = 0; foreach ( array( $year, $year + 1 ) as $y ) { foreach ( Holidays::for_year( $country, $y ) as $date => $name ) { if ( $date < $today || isset( $skip[ $date ] ) ) { continue; } Services::schedules()->add_override( 'site', 0, DateOverride::closed_on( $date, $name ), ScheduleRepository::HOLIDAY ); ++$count; } } update_option( Settings::COUNTRY, $country ); Cache::bump(); return array( 'added' => $count ); } /** * Sessions of a class or event. * * @param WP_REST_Request $request Request. * @return array> */ public function sessions( WP_REST_Request $request ): array { $bookable = $this->bookable( (int) $request['id'] ); $from = (int) ( $request['from'] ?? time() - DAY_IN_SECONDS ); $to = (int) ( $request['to'] ?? $from + 120 * DAY_IN_SECONDS ); return Services::sessions()->with_places( $bookable, Services::sessions_repo()->between( array( $bookable->id ), $from, $to, true ) ); } /** * Add a session (an event date, or a one-off class). * * @param WP_REST_Request $request Request. * @return array */ public function add_session( WP_REST_Request $request ): array { $bookable = $this->bookable( (int) $request['id'] ); $data = $this->session_fields( self::body( $request ), $bookable ); $repeat = max( 1, min( 52, (int) ( self::body( $request )['repeat_weeks'] ?? 1 ) ) ); $ids = array(); for ( $i = 0; $i < $repeat; $i++ ) { $ids[] = Services::sessions_repo()->create( array_merge( $data, array( 'start' => $data['start'] + $i * WEEK_IN_SECONDS, 'end' => $data['end'] + $i * WEEK_IN_SECONDS, 'status' => 'scheduled', 'series' => $repeat > 1 ? 'weekly-' . $data['start'] : '', ) ) ); } Cache::bump(); return array( 'ids' => $ids ); } /** * Change a session. * * @param WP_REST_Request $request Request. * @return array * @throws BookingException When the session is missing. */ public function update_session( WP_REST_Request $request ): array { $session = Services::sessions_repo()->find( (int) $request['id'] ); if ( null === $session ) { throw new BookingException( 'schedulereed_not_found', __( 'Session not found.', 'schedulereed' ), 404 ); } $bookable = $this->bookable( $session['bookable_id'] ); Services::sessions_repo()->update( $session['id'], $this->session_fields( self::body( $request ) + $session, $bookable ) ); Cache::bump(); return (array) Services::sessions_repo()->find( $session['id'] ); } /** * Cancel a session and its bookings. * * @param WP_REST_Request $request Request. * @return array */ public function cancel_session( WP_REST_Request $request ): array { $reason = mb_substr( sanitize_textarea_field( (string) ( self::body( $request )['reason'] ?? '' ) ), 0, 500 ); return array( 'cancelled_bookings' => Services::sessions()->cancel( (int) $request['id'], $reason ) ); } /** * Validate session fields. * * @param array $raw Fields. * @param Bookable $bookable Bookable. * @return array * @throws InvalidArgumentException When malformed. */ private function session_fields( array $raw, Bookable $bookable ): array { $start = (int) ( $raw['start'] ?? 0 ); if ( $start <= 0 ) { throw new InvalidArgumentException( 'start is required.' ); } $end = (int) ( $raw['end'] ?? 0 ); $end = $end > $start ? $end : $start + $bookable->duration * 60; return array( 'bookable_id' => $bookable->id, 'start' => $start, 'end' => $end, 'capacity' => max( 0, min( 100000, (int) ( $raw['capacity'] ?? 0 ) ) ), 'staff_id' => max( 0, (int) ( $raw['staff_id'] ?? 0 ) ), 'location_id' => max( 0, (int) ( $raw['location_id'] ?? 0 ) ), 'tickets' => array() === (array) ( $raw['tickets'] ?? array() ) ? array() : Bookable::settings( array( 'tickets' => $raw['tickets'] ), $bookable->type, $bookable->duration_mode )['tickets'], 'note' => mb_substr( sanitize_text_field( (string) ( $raw['note'] ?? '' ) ), 0, 191 ), ); } /** * Validate an item into a row. * * @param string $type Type. * @param array $raw Submitted. * @param array $current Current row. * @return array * @throws InvalidArgumentException When malformed. */ private function validate( string $type, array $raw, array $current ): array { if ( 'bookables' === $type ) { $row = Bookable::validate( $raw, $current ); $row['description'] = wp_kses_post( (string) $row['description'] ); /** * Whether a service may need several units of a resource at * once (room plus two projectors). Pro turns this on. * * @param bool $on Whether it may. */ if ( ! apply_filters( 'schedulereed_resource_units', false ) ) { foreach ( $row['settings']['resources'] as $i => $pool ) { $row['settings']['resources'][ $i ]['need'] = 1; } } return $row; } $get = static fn( string $key, mixed $fallback ) => array_key_exists( $key, $raw ) ? $raw[ $key ] : ( $current[ $key ] ?? $fallback ); $name = trim( sanitize_text_field( (string) $get( 'name', '' ) ) ); if ( '' === $name || mb_strlen( $name ) > 191 ) { throw new InvalidArgumentException( 'name must be 1 to 191 characters.' ); } $status = (string) $get( 'status', 'active' ); if ( ! in_array( $status, array( 'active', 'inactive' ), true ) ) { throw new InvalidArgumentException( 'status must be active or inactive.' ); } $row = array( 'name' => $name, 'status' => $status, 'sort' => (int) $get( 'sort', 0 ), 'settings' => array_merge( (array) ( $current['settings'] ?? array() ), array_intersect_key( (array) ( $raw['settings'] ?? array() ), array_flip( array( 'notify', 'description', 'zoom', 'meet', 'meeting_url' ) ) ) ), ); $tz = (string) $get( 'timezone', '' ); if ( '' !== $tz && ! in_array( $tz, timezone_identifiers_list(), true ) ) { throw new InvalidArgumentException( 'timezone must be a time zone such as Europe/London.' ); } switch ( $type ) { case 'staff': $email = sanitize_email( (string) $get( 'email', '' ) ); $color = (string) $get( 'color', '' ); if ( '' !== $color && 1 !== preg_match( '/^#[0-9a-fA-F]{6}$/', $color ) ) { throw new InvalidArgumentException( 'color must be a #rrggbb colour.' ); } $user = (int) $get( 'user_id', 0 ); if ( $user > 0 && false === get_userdata( $user ) ) { throw new InvalidArgumentException( 'user_id is not a user on this site.' ); } return $row + array( 'user_id' => $user, 'email' => $email, 'phone' => mb_substr( preg_replace( '/[^0-9+()\-. ]/', '', (string) $get( 'phone', '' ) ), 0, 40 ), 'bio' => wp_kses_post( (string) $get( 'bio', '' ) ), 'photo_id' => max( 0, (int) $get( 'photo_id', 0 ) ), 'color' => $color, 'timezone' => $tz, ); case 'resources': return $row + array( 'quantity' => max( 1, min( 10000, (int) $get( 'quantity', 1 ) ) ), 'price_minor' => max( 0, (int) $get( 'price_minor', 0 ) ), ); default: return $row + array( 'address' => mb_substr( sanitize_textarea_field( (string) $get( 'address', '' ) ), 0, 500 ), 'phone' => mb_substr( preg_replace( '/[^0-9+()\-. ]/', '', (string) $get( 'phone', '' ) ), 0, 40 ), 'timezone' => $tz, 'online' => (int) (bool) $get( 'online', 0 ), ); } } /** * Save who offers what, where. * * @param string $type Type. * @param int $id ID. * @param array $body Body with staff, locations or bookables lists. */ private function save_links( string $type, int $id, array $body ): void { $links = Services::links(); if ( 'bookables' === $type ) { if ( isset( $body['staff'] ) ) { $links->set( 'bookable', $id, 'staff', (array) $body['staff'] ); } if ( isset( $body['locations'] ) ) { $links->set( 'bookable', $id, 'location', array_map( 'intval', (array) $body['locations'] ) ); } } if ( 'staff' === $type ) { if ( isset( $body['bookables'] ) ) { // Set from the staff side: rewrite this member in each bookable's list. $wanted = array_flip( array_map( 'intval', (array) $body['bookables'] ) ); foreach ( Services::bookables()->all() as $row ) { $current = Services::links()->targets( 'bookable', (int) $row['id'], 'staff' ); $has = isset( $current[ $id ] ); if ( isset( $wanted[ $row['id'] ] ) !== $has ) { if ( $has ) { unset( $current[ $id ] ); } else { $current[ $id ] = array( 'id' => $id ); } $links->set( 'bookable', (int) $row['id'], 'staff', array_values( $current ) ); } } } if ( isset( $body['locations'] ) ) { $links->set( 'staff', $id, 'location', array_map( 'intval', (array) $body['locations'] ) ); } } if ( 'resources' === $type && isset( $body['locations'] ) ) { $links->set( 'resource', $id, 'location', array_map( 'intval', (array) $body['locations'] ) ); } } /** * An item with what the admin screens show next to it. * * @param string $type Type. * @param array $row Row. * @return array */ private function present( string $type, array $row ): array { $owner = rtrim( 'bookables' === $type ? 'bookable' : ( 'staff' === $type ? 'staff' : substr( $type, 0, -1 ) ), 's' ); $out = $row; if ( 'bookables' === $type ) { $out['price'] = (int) $row['price_minor']; $out['settings'] = Bookable::from_row( $row )->settings; $out['staff'] = array_values( Services::links()->targets( 'bookable', $row['id'], 'staff' ) ); $out['locations'] = array_keys( Services::links()->targets( 'bookable', $row['id'], 'location' ) ); $out['ical_url'] = CalendarSync::export_url( 'bookable', $row['id'] ); } if ( 'staff' === $type ) { $out['bookables'] = Services::links()->owners( 'bookable', 'staff', $row['id'] ); $out['locations'] = array_keys( Services::links()->targets( 'staff', $row['id'], 'location' ) ); $out['ical_url'] = CalendarSync::export_url( 'staff', $row['id'] ); $out['photo'] = $row['photo_id'] ? (string) wp_get_attachment_image_url( (int) $row['photo_id'], 'thumbnail' ) : ''; $user = $row['user_id'] ? get_userdata( (int) $row['user_id'] ) : false; $out['user'] = $user ? array( 'id' => $user->ID, 'name' => $user->display_name, 'email' => $user->user_email, 'access' => Capabilities::access( $user ), ) : null; } if ( 'resources' === $type ) { $out['locations'] = array_keys( Services::links()->targets( 'resource', $row['id'], 'location' ) ); } $out['has_hours'] = null !== Services::schedules()->weekly( $owner, $row['id'] ); return $out; } /** * A manager added or changed a staff member. * * @param int $id Staff ID. * @param array $body Request body. */ private static function staff_saved( int $id, array $body ): void { /** * A manager added or changed a staff member, e.g. for Pro to give * them a login (create_login, access). Throw InvalidArgumentException * to answer with a 400. * * @param int $id Staff ID. * @param array $body Request body. */ do_action( 'schedulereed_staff_saved', $id, $body ); } /** * After a change: forget cached slots and loaded bookables. * * @param string $type Type. * @param int $id ID. */ private function saved( string $type, int $id ): void { Cache::bump(); Services::catalog()->flush(); if ( 'bookables' === $type ) { $bookable = Services::catalog()->bookable( $id ); if ( null !== $bookable && Bookable::CLASS_TYPE === $bookable->type ) { Services::sessions()->generate( $bookable ); } } /** * Fires after a bookable, staff member, resource or location is saved. * * @param string $type bookables, staff, resources or locations. * @param int $id ID. */ do_action( 'schedulereed_catalog_saved', $type, $id ); } private function repo( string $type ): EntityRepository { return match ( $type ) { 'bookables' => Services::bookables(), 'staff' => Services::staff(), 'resources' => Services::resources(), default => Services::locations(), }; } /** * An item or a 404. * * @param string $type Type. * @param int $id ID. * @return array * @throws BookingException When missing. */ private function find( string $type, int $id ): array { $row = $this->repo( $type )->find( $id ); if ( null === $row ) { throw new BookingException( 'schedulereed_not_found', __( 'Not found.', 'schedulereed' ), 404 ); } return $row; } /** * A bookable or a 404. * * @param int $id ID. * @throws BookingException When missing. */ private function bookable( int $id ): Bookable { $bookable = Services::catalog()->bookable( $id ); if ( null === $bookable ) { throw new BookingException( 'schedulereed_not_found', __( 'Not found.', 'schedulereed' ), 404 ); } return $bookable; } }