1) with a staff * member or resource, at a time from the open hours. * - class: dated sessions from a weekly timetable, with capacity and an * optional instructor. * - event: dated sessions with ticket types and capacity per ticket type. * - rental: hours, days or nights of a resource with a quantity. * * Columns hold what the availability engine filters on; everything else is * in `settings` (see the defaults in DEFAULTS). */ final class Bookable { public const APPOINTMENT = 'appointment'; public const CLASS_TYPE = 'class'; public const EVENT = 'event'; public const RENTAL = 'rental'; public const TYPES = array( self::APPOINTMENT, self::CLASS_TYPE, self::EVENT, self::RENTAL ); /** Duration modes. */ public const FIXED = 'fixed'; public const RANGE = 'range'; public const DAYS = 'days'; public const NIGHTS = 'nights'; /** How staff are chosen. */ public const STAFF_CUSTOMER = 'customer'; public const STAFF_ANY = 'any'; public const STAFF_ROUND_ROBIN = 'round_robin'; public const STAFF_LEAST_BUSY = 'least_busy'; /** * Settings and their defaults. */ public const DEFAULTS = array( // Customer-chosen duration (range mode): minutes, or days/nights for rentals. 'min_units' => 1, 'max_units' => 1, 'unit_step' => 1, 'extras' => array(), 'staff_mode' => self::STAFF_CUSTOMER, // Resource pools: each needs `need` of `ids`; quantity-consuming for rentals. 'resources' => array(), // null = the site setting. 'approval' => null, 'deposit' => null, 'cancellation' => null, 'payment_methods' => null, 'check_in' => '15:00', 'check_out' => '11:00', 'max_people' => 1, 'person_types' => array(), 'tickets' => array(), 'min_attendees' => 0, 'min_hours' => 24, 'timetable' => array(), 'meeting' => '', 'form' => '', 'same_day_cutoff' => '', 'members_only' => false, 'location_mode' => 'customer', 'waitlist' => true, 'recurring' => false, ); /** * Constructor. * * @param int $id ID. * @param string $type Type. * @param string $name Name. * @param string $status active or draft. * @param int $duration Minutes (appointments, classes, events, hourly rentals). * @param string $duration_mode FIXED, RANGE, DAYS or NIGHTS. * @param int $slot_interval Minutes between starts; 0 = the duration. * @param int $buffer_before Minutes. * @param int $buffer_after Minutes. * @param int $capacity Places per slot or session. * @param int $lead_time Minimum notice, minutes; 0 = site default. * @param int $horizon Days ahead bookable; 0 = site default. * @param int $price Minor units. * @param string $price_basis booking, person, hour, day or night. * @param array $settings Settings merged with DEFAULTS. */ public function __construct( public readonly int $id, public readonly string $type, public readonly string $name, public readonly string $status, public readonly int $duration, public readonly string $duration_mode, public readonly int $slot_interval, public readonly int $buffer_before, public readonly int $buffer_after, public readonly int $capacity, public readonly int $lead_time, public readonly int $horizon, public readonly int $price, public readonly string $price_basis, public readonly array $settings ) { } /** * From a database row (as BookableRepository returns it). * * @param array $row Row. */ public static function from_row( array $row ): self { $settings = is_array( $row['settings'] ?? null ) ? $row['settings'] : (array) json_decode( (string) ( $row['settings'] ?? '' ), true ); return new self( (int) $row['id'], in_array( $row['type'], self::TYPES, true ) ? (string) $row['type'] : self::APPOINTMENT, (string) $row['name'], (string) $row['status'], max( 5, (int) $row['duration'] ), (string) $row['duration_mode'], (int) $row['slot_interval'], (int) $row['buffer_before'], (int) $row['buffer_after'], max( 1, (int) $row['capacity'] ), (int) $row['lead_time'], (int) $row['horizon'], (int) $row['price_minor'], (string) $row['price_basis'], array_merge( self::DEFAULTS, $settings ) ); } /** * Validate submitted fields into a row for the repository. * * @param array $raw Submitted values. * @param array $current Current row when editing, for fields not sent. * @return array * @throws InvalidArgumentException When something is malformed. */ public static function validate( array $raw, array $current = array() ): array { $get = static fn( string $key, mixed $fallback ) => array_key_exists( $key, $raw ) ? $raw[ $key ] : ( $current[ $key ] ?? $fallback ); $type = (string) $get( 'type', self::APPOINTMENT ); if ( ! in_array( $type, self::TYPES, true ) ) { throw new InvalidArgumentException( 'type must be appointment, class, event or rental.' ); } $name = trim( strip_tags( (string) $get( 'name', '' ) ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Domain code is plain PHP and cannot call WordPress. if ( '' === $name || mb_strlen( $name ) > 191 ) { throw new InvalidArgumentException( 'name must be 1 to 191 characters.' ); } $mode = (string) $get( 'duration_mode', self::RENTAL === $type ? self::NIGHTS : self::FIXED ); if ( ! in_array( $mode, array( self::FIXED, self::RANGE, self::DAYS, self::NIGHTS ), true ) ) { throw new InvalidArgumentException( 'duration_mode must be fixed, range, days or nights.' ); } if ( in_array( $mode, array( self::DAYS, self::NIGHTS ), true ) && self::RENTAL !== $type ) { throw new InvalidArgumentException( 'Only rentals can be booked by the day or night.' ); } $numbers = array(); foreach ( array( 'duration' => array( 60, 5, 1440 ), 'slot_interval' => array( 0, 0, 1440 ), 'buffer_before' => array( 0, 0, 720 ), 'buffer_after' => array( 0, 0, 720 ), 'capacity' => array( 1, 1, 10000 ), 'lead_time' => array( 0, 0, 525600 ), 'horizon' => array( 0, 0, 1095 ), ) as $field => [ $default, $min, $max ] ) { $value = $get( $field, $default ); if ( ! is_numeric( $value ) || (int) $value < $min || (int) $value > $max ) { throw new InvalidArgumentException( "{$field} must be a whole number from {$min} to {$max}." ); } $numbers[ $field ] = (int) $value; } $price = $get( 'price', $current['price_minor'] ?? 0 ); if ( ! is_numeric( $price ) || (int) $price < 0 ) { throw new InvalidArgumentException( 'price must be a whole number of minor units, at least 0.' ); } $basis = (string) $get( 'price_basis', self::NIGHTS === $mode ? PriceCalculator::PER_NIGHT : PriceCalculator::PER_BOOKING ); if ( ! in_array( $basis, PriceCalculator::BASES, true ) ) { throw new InvalidArgumentException( 'price_basis must be booking, person, hour, day or night.' ); } $status = (string) $get( 'status', 'active' ); if ( ! in_array( $status, array( 'active', 'draft' ), true ) ) { throw new InvalidArgumentException( 'status must be active or draft.' ); } $color = (string) $get( 'color', '' ); if ( '' !== $color && 1 !== preg_match( '/^#[0-9a-fA-F]{6}$/', $color ) ) { throw new InvalidArgumentException( 'color must be a #rrggbb colour.' ); } $settings = self::settings( array_merge( (array) ( $current['settings'] ?? array() ), (array) ( $raw['settings'] ?? array() ) ), $type, $mode ); return array( 'type' => $type, 'name' => $name, 'description' => (string) $get( 'description', '' ), 'status' => $status, 'duration' => $numbers['duration'], 'duration_mode' => $mode, 'slot_interval' => $numbers['slot_interval'], 'buffer_before' => $numbers['buffer_before'], 'buffer_after' => $numbers['buffer_after'], 'capacity' => $numbers['capacity'], 'lead_time' => $numbers['lead_time'], 'horizon' => $numbers['horizon'], 'price_minor' => (int) $price, 'price_basis' => $basis, 'color' => $color, 'image_id' => max( 0, (int) $get( 'image_id', 0 ) ), 'settings' => $settings, ); } /** * Validate the settings object, keeping only known keys. * * @param array $raw Settings. * @param string $type Type. * @param string $mode Duration mode. * @return array * @throws InvalidArgumentException When malformed. */ public static function settings( array $raw, string $type, string $mode ): array { $s = array_merge( self::DEFAULTS, array_intersect_key( $raw, self::DEFAULTS ) ); foreach ( array( 'min_units', 'max_units', 'unit_step', 'max_people' ) as $field ) { $s[ $field ] = (int) $s[ $field ]; if ( $s[ $field ] < 1 || $s[ $field ] > 1000 ) { throw new InvalidArgumentException( "settings.{$field} must be 1 to 1000." ); } } if ( $s['max_units'] < $s['min_units'] ) { throw new InvalidArgumentException( 'settings.max_units must not be less than settings.min_units.' ); } $s['extras'] = array_values( array_map( static fn( Extra $e ): array => $e->to_array(), Extra::list_from( $s['extras'] ) ) ); if ( ! in_array( $s['staff_mode'], array( self::STAFF_CUSTOMER, self::STAFF_ANY, self::STAFF_ROUND_ROBIN, self::STAFF_LEAST_BUSY ), true ) ) { throw new InvalidArgumentException( 'settings.staff_mode must be customer, any, round_robin or least_busy.' ); } if ( null !== $s['approval'] && ! in_array( $s['approval'], array( 'auto', 'manual' ), true ) ) { throw new InvalidArgumentException( 'settings.approval must be null, auto or manual.' ); } if ( null !== $s['deposit'] ) { $s['deposit'] = DepositPolicy::from_array( (array) $s['deposit'] )->to_array(); } if ( null !== $s['cancellation'] ) { $s['cancellation'] = CancellationPolicy::from_array( $s['cancellation'] )?->to_array(); } if ( null !== $s['payment_methods'] ) { $s['payment_methods'] = array_values( array_filter( array_map( 'strval', (array) $s['payment_methods'] ), static fn( string $id ): bool => 1 === preg_match( '/^[a-z0-9_]{1,40}$/', $id ) ) ); } foreach ( array( 'check_in', 'check_out' ) as $field ) { WeeklyHours::minutes( (string) $s[ $field ], "settings.{$field}" ); } if ( '' !== $s['same_day_cutoff'] ) { WeeklyHours::minutes( (string) $s['same_day_cutoff'], 'settings.same_day_cutoff' ); } $pools = array(); foreach ( array_values( (array) $s['resources'] ) as $i => $pool ) { $ids = array_values( array_unique( array_filter( array_map( 'intval', (array) ( $pool['ids'] ?? array() ) ) ) ) ); if ( array() === $ids ) { throw new InvalidArgumentException( "settings.resources.{$i}.ids must list at least one resource." ); } $need = max( 1, (int) ( $pool['need'] ?? 1 ) ); if ( $need > count( $ids ) ) { throw new InvalidArgumentException( "settings.resources.{$i}.need cannot be more than the resources listed." ); } $pools[] = array( 'ids' => $ids, 'need' => $need, ); } if ( count( $pools ) > 5 ) { throw new InvalidArgumentException( 'settings.resources can have at most 5 pools.' ); } $s['resources'] = $pools; $s['person_types'] = self::priced_list( $s['person_types'], 'settings.person_types', array( 'counts' ) ); $s['tickets'] = self::priced_list( $s['tickets'], 'settings.tickets', array( 'capacity' ) ); $s['min_attendees'] = max( 0, (int) $s['min_attendees'] ); $s['min_hours'] = max( 0, min( 720, (int) $s['min_hours'] ) ); $timetable = array(); foreach ( array_values( (array) $s['timetable'] ) as $i => $entry ) { $weekday = (int) ( $entry['weekday'] ?? 0 ); if ( $weekday < 1 || $weekday > 7 ) { throw new InvalidArgumentException( "settings.timetable.{$i}.weekday must be 1 to 7." ); } WeeklyHours::minutes( (string) ( $entry['time'] ?? '' ), "settings.timetable.{$i}.time" ); $timetable[] = array( 'weekday' => $weekday, 'time' => (string) $entry['time'], 'staff_id' => max( 0, (int) ( $entry['staff_id'] ?? 0 ) ), 'location_id' => max( 0, (int) ( $entry['location_id'] ?? 0 ) ), ); } if ( count( $timetable ) > 50 ) { throw new InvalidArgumentException( 'settings.timetable can have at most 50 entries.' ); } $s['timetable'] = $timetable; if ( ! in_array( $s['meeting'], array( '', 'zoom', 'meet', 'custom' ), true ) ) { throw new InvalidArgumentException( 'settings.meeting must be empty, zoom, meet or custom.' ); } if ( ! in_array( $s['location_mode'], array( 'customer', 'any' ), true ) ) { throw new InvalidArgumentException( 'settings.location_mode must be customer or any.' ); } $s['form'] = preg_replace( '/[^a-z0-9_-]/', '', strtolower( (string) $s['form'] ) ); $s['members_only'] = (bool) $s['members_only']; $s['waitlist'] = (bool) $s['waitlist']; $s['recurring'] = (bool) $s['recurring']; unset( $type, $mode ); return $s; } /** * Validate a list of {id, label, price} items with an extra number field. * * @param mixed $raw Raw list. * @param string $field Field path. * @param string[] $extras Extra integer fields kept on each item. * @return array> * @throws InvalidArgumentException When malformed. */ private static function priced_list( mixed $raw, string $field, array $extras ): array { $out = array(); $ids = array(); foreach ( array_values( (array) $raw ) as $i => $item ) { $id = (string) ( $item['id'] ?? '' ); $label = trim( strip_tags( (string) ( $item['label'] ?? '' ) ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- Domain code is plain PHP and cannot call WordPress. if ( 1 !== preg_match( '/^[a-z0-9_-]{1,40}$/', $id ) || isset( $ids[ $id ] ) ) { throw new InvalidArgumentException( "{$field}.{$i}.id must be unique lowercase letters, digits, - or _." ); } if ( '' === $label ) { throw new InvalidArgumentException( "{$field}.{$i}.label is required." ); } $ids[ $id ] = true; $entry = array( 'id' => $id, 'label' => mb_substr( $label, 0, 60 ), 'price' => max( 0, (int) ( $item['price'] ?? 0 ) ), ); foreach ( $extras as $extra ) { $entry[ $extra ] = 'counts' === $extra ? (bool) ( $item[ $extra ] ?? true ) : max( 0, (int) ( $item[ $extra ] ?? 0 ) ); } $out[] = $entry; } if ( count( $out ) > 10 ) { throw new InvalidArgumentException( "{$field} can have at most 10 entries." ); } return $out; } public function is_active(): bool { return 'active' === $this->status; } /** * Whether bookings use dated sessions (classes and events). */ public function uses_sessions(): bool { return self::CLASS_TYPE === $this->type || self::EVENT === $this->type; } /** * Whether bookings are whole days or nights. */ public function by_day(): bool { return self::DAYS === $this->duration_mode || self::NIGHTS === $this->duration_mode; } /** * Seconds between possible starts. */ public function step(): int { return 60 * ( $this->slot_interval > 0 ? $this->slot_interval : $this->duration ); } /** * Extras, keyed by ID. * * @return Extra[] */ public function extras(): array { return Extra::list_from( $this->settings['extras'] ); } /** * Booking length in seconds for a number of units (range mode) and * extra minutes from add-ons. * * @param int $units Units chosen (range mode: multiples of the duration). * @param int $extra_minutes Minutes added by extras. */ public function seconds( int $units = 1, int $extra_minutes = 0 ): int { $units = self::RANGE === $this->duration_mode ? $this->clamp_units( $units ) : 1; return ( $this->duration * $units + max( 0, $extra_minutes ) ) * 60; } /** * Units within the allowed range and step. * * @param int $units Requested. */ public function clamp_units( int $units ): int { $min = (int) $this->settings['min_units']; $max = (int) $this->settings['max_units']; $step = max( 1, (int) $this->settings['unit_step'] ); $units = max( $min, min( $max, $units ) ); return $min + intdiv( $units - $min, $step ) * $step; } /** * The units a price is multiplied by: hours booked, days or nights. * * @param int $seconds Booked length without extras. * @param int $days Days or nights for rentals by day. */ public function price_units( int $seconds, int $days ): int { return match ( $this->price_basis ) { PriceCalculator::PER_HOUR => max( 1, (int) ceil( $seconds / 3600 ) ), PriceCalculator::PER_DAY, PriceCalculator::PER_NIGHT => max( 1, $days ), default => 1, }; } }