$opt Options. * @return array{slots: array>, truncated: bool} */ public function slots( Bookable $bookable, int $from, int $to, array $opt = array() ): array { $opt = $this->options( $opt ); if ( $bookable->uses_sessions() ) { return array( 'slots' => array(), 'truncated' => false, ); } $cacheable = 0 === $opt['except_booking'] && '' === $opt['except_hold'] && ! $opt['staff_rules']; $build = fn(): array => $this->compute( $bookable, $from, $to, $opt ); return $cacheable ? Cache::remember( 'slots', array( $bookable->id, $from, $to, $opt, Clock::now() - Clock::now() % 300 ), $build ) : $build(); } /** * Whether one booking fits, and with whom: the slot with its free staff * and resources, or null. * * @param Bookable $bookable Bookable. * @param int $start Start. * @param array $opt Options. * @return array|null */ public function check( Bookable $bookable, int $start, array $opt = array() ): ?array { $opt = $this->options( $opt ); $engine = new SlotEngine(); foreach ( $this->plans( $bookable, $opt ) as $plan ) { $end = $this->end( $bookable, $start, $plan, $opt ); $groups = $this->groups( $bookable, $plan, $start - DAY_IN_SECONDS, $end + DAY_IN_SECONDS, $opt ); $request = $this->request( $bookable, $plan, $start, $start, $end - $start, $opt ); $slot = $engine->check( $groups, $request, $start, $end ); if ( null !== $slot ) { return $this->shape( $slot, $plan, $request ) + array( 'groups' => $slot['options'] ); } } return null; } /** * Free places per date, for the calendar's density dots. * * @param Bookable $bookable Bookable. * @param string $from First date, Y-m-d, in the bookable's zone. * @param string $to Last date. * @param array $opt Options. * @return array Date => free slots (or places, for rentals by the day). */ public function days( Bookable $bookable, string $from, string $to, array $opt = array() ): array { $opt = $this->options( $opt ); $tz = $this->zone( $bookable, $opt ); $days = array(); $date = new DateTimeImmutable( $from, $tz ); $last = ( new DateTimeImmutable( $to, $tz ) )->format( 'Y-m-d' ); for ( $i = 0; $i < 400 && $date->format( 'Y-m-d' ) <= $last; $i++ ) { $days[ $date->format( 'Y-m-d' ) ] = 0; $date = $date->modify( '+1 day' ); } if ( $bookable->by_day() ) { foreach ( array_keys( $days ) as $day ) { $slot = $this->check( $bookable, $this->day_start( $bookable, $day, $tz ), $opt + array( 'units' => (int) $bookable->settings['min_units'] ) ); $days[ $day ] = null === $slot ? 0 : max( 1, (int) $slot['remaining'] ); } return $days; } $start = ( new DateTimeImmutable( $from, $tz ) )->getTimestamp(); $end = ( new DateTimeImmutable( $last, $tz ) )->modify( '+1 day' )->getTimestamp(); foreach ( $this->slots( $bookable, $start, $end - 1, $opt )['slots'] as $slot ) { $day = ( new DateTimeImmutable( '@' . $slot['start'] ) )->setTimezone( $tz )->format( 'Y-m-d' ); if ( isset( $days[ $day ] ) ) { ++$days[ $day ]; } } return $days; } /** * Why a start time cannot be booked: the rule debugger. * * @param Bookable $bookable Bookable. * @param int $start Start. * @param array $opt Options. * @return array> */ public function explain( Bookable $bookable, int $start, array $opt = array() ): array { $opt = $this->options( $opt ); $reasons = array(); foreach ( $this->plans( $bookable, $opt ) as $plan ) { $end = $this->end( $bookable, $start, $plan, $opt ); $groups = $this->groups( $bookable, $plan, $start - DAY_IN_SECONDS, $end + DAY_IN_SECONDS, $opt ); $request = $this->request( $bookable, $plan, $start, $start, $end - $start, $opt ); if ( array() === $groups ) { $reasons[] = array( 'code' => 'no_staff' ); continue; } $why = Explainer::explain( $groups, $request, $start, Clock::now() ); if ( array() === $why ) { return array(); } foreach ( $why as $reason ) { $reasons[] = $reason + array( 'location_id' => $plan['location_id'] ); } } return $reasons; } /** * Unix start of a rental day: check-in time for nights, midnight for days. * * @param Bookable $bookable Bookable. * @param string $date Y-m-d. * @param DateTimeZone $tz Zone. */ public function day_start( Bookable $bookable, string $date, DateTimeZone $tz ): int { $minutes = Bookable::NIGHTS === $bookable->duration_mode ? WeeklyHours::minutes( (string) $bookable->settings['check_in'], 'check_in' ) : 0; return Hours::at( $date, $minutes, $tz ); } /** * The zone the bookable's hours are shown in: the chosen location's, else the site's. * * @param Bookable $bookable Bookable. * @param array $opt Options. */ public function zone( Bookable $bookable, array $opt = array() ): DateTimeZone { $location_id = (int) ( $opt['location_id'] ?? 0 ); if ( $location_id <= 0 ) { $locations = Services::catalog()->locations_for( $bookable->id ); $location_id = 1 === count( $locations ) ? (int) array_key_first( $locations ) : 0; } $location = $location_id > 0 ? Services::locations()->find( $location_id ) : null; return Settings::zone( (string) ( $location['timezone'] ?? '' ) ); } /** * Earliest and latest start a customer may book. * * @param Bookable $bookable Bookable. * @param array $opt Options. * @param DateTimeZone $tz Zone for the same-day cut-off. * @return array{0: int, 1: int} */ public function limits( Bookable $bookable, array $opt, DateTimeZone $tz ): array { if ( ! empty( $opt['staff_rules'] ) ) { return array( PHP_INT_MIN, PHP_INT_MAX ); } $defaults = Settings::scheduling(); $now = Clock::now(); $lead = $bookable->lead_time > 0 ? $bookable->lead_time : (int) $defaults['lead_time']; $horizon = $bookable->horizon > 0 ? $bookable->horizon : (int) $defaults['horizon']; $earliest = $now + $lead * 60; $cutoff = (string) $bookable->settings['same_day_cutoff']; if ( '' !== $cutoff ) { $local = ( new DateTimeImmutable( '@' . $now ) )->setTimezone( $tz ); if ( (int) $local->format( 'H' ) * 60 + (int) $local->format( 'i' ) >= WeeklyHours::minutes( $cutoff, 'cutoff' ) ) { $earliest = max( $earliest, $local->setTime( 0, 0 )->modify( '+1 day' )->getTimestamp() ); } } return array( $earliest, $now + $horizon * DAY_IN_SECONDS ); } /** * Fill in option defaults. * * @param array $opt Options. * @return array */ private function options( array $opt ): array { return array( 'location_id' => max( 0, (int) ( $opt['location_id'] ?? 0 ) ), 'staff_id' => max( 0, (int) ( $opt['staff_id'] ?? 0 ) ), 'quantity' => max( 1, (int) ( $opt['quantity'] ?? 1 ) ), 'units' => max( 1, (int) ( $opt['units'] ?? 1 ) ), 'extra_minutes' => max( 0, (int) ( $opt['extra_minutes'] ?? 0 ) ), 'except_booking' => max( 0, (int) ( $opt['except_booking'] ?? 0 ) ), 'except_hold' => (string) ( $opt['except_hold'] ?? '' ), 'staff_rules' => ! empty( $opt['staff_rules'] ), 'ignore_bookings' => ! empty( $opt['ignore_bookings'] ), ); } /** * Run the engine for every plan and merge the slots by start time. * * @param Bookable $bookable Bookable. * @param int $from Earliest start. * @param int $to Latest start. * @param array $opt Options. * @return array{slots: array>, truncated: bool} */ private function compute( Bookable $bookable, int $from, int $to, array $opt ): array { $engine = new SlotEngine(); $by_start = array(); $truncated = false; foreach ( $this->plans( $bookable, $opt ) as $plan ) { $duration = $this->end( $bookable, $from, $plan, $opt ) - $from; $groups = $this->groups( $bookable, $plan, $from - DAY_IN_SECONDS, $to + $duration + DAY_IN_SECONDS, $opt ); if ( array() === $groups ) { continue; } $request = $this->request( $bookable, $plan, $from, $to, $duration, $opt ); foreach ( $engine->slots( $groups, $request ) as $slot ) { $shaped = $this->shape( $slot, $plan, $request ); $start = $shaped['start']; if ( ! isset( $by_start[ $start ] ) ) { $by_start[ $start ] = $shaped; continue; } $by_start[ $start ]['staff'] = array_values( array_unique( array_merge( $by_start[ $start ]['staff'], $shaped['staff'] ) ) ); $by_start[ $start ]['remaining'] = max( $by_start[ $start ]['remaining'], $shaped['remaining'] ); } $truncated = $truncated || $engine->truncated; } ksort( $by_start ); return array( 'slots' => array_values( $by_start ), 'truncated' => $truncated, ); } /** * Ways the bookable can run: one per location considered and staff * duration, since a staff member may take longer than the default. * * @param Bookable $bookable Bookable. * @param array $opt Options. * @return array> */ private function plans( Bookable $bookable, array $opt ): array { $catalog = Services::catalog(); $locations = $catalog->locations_for( $bookable->id ); if ( $opt['location_id'] > 0 ) { $locations = isset( $locations[ $opt['location_id'] ] ) ? array( $opt['location_id'] => $locations[ $opt['location_id'] ] ) : array(); if ( array() === $locations ) { return array(); } } $location_ids = array() === $locations ? array( 0 ) : array_keys( $locations ); $plans = array(); foreach ( $location_ids as $location_id ) { $staff = $catalog->staff_for( $bookable->id, $location_id ); if ( $opt['staff_id'] > 0 ) { $staff = isset( $staff[ $opt['staff_id'] ] ) ? array( $opt['staff_id'] => $staff[ $opt['staff_id'] ] ) : array(); if ( array() === $staff ) { continue; } } $location = $locations[ $location_id ] ?? null; if ( array() === $staff ) { $plans[] = array( 'location_id' => $location_id, 'location' => $location, 'staff' => array(), 'minutes' => $bookable->duration, ); continue; } $by_minutes = array(); foreach ( $staff as $id => $member ) { $minutes = null === $member['duration_override'] ? $bookable->duration : (int) $member['duration_override']; $by_minutes[ $minutes ][] = $member; } foreach ( $by_minutes as $minutes => $members ) { $plans[] = array( 'location_id' => $location_id, 'location' => $location, 'staff' => array_column( $members, null, 'id' ), 'minutes' => (int) $minutes, ); } } return $plans; } /** * When a booking starting at a time ends. * * @param Bookable $bookable Bookable. * @param int $start Start. * @param array $plan Plan. * @param array $opt Options. */ private function end( Bookable $bookable, int $start, array $plan, array $opt ): int { if ( $bookable->by_day() ) { $tz = $this->plan_zone( $plan ); $date = ( new DateTimeImmutable( '@' . $start ) )->setTimezone( $tz )->format( 'Y-m-d' ); $units = $bookable->clamp_units( $opt['units'] ); $last = ( new DateTimeImmutable( $date, $tz ) )->modify( "+{$units} days" )->format( 'Y-m-d' ); $minute = Bookable::NIGHTS === $bookable->duration_mode ? WeeklyHours::minutes( (string) $bookable->settings['check_out'], 'check_out' ) : 0; return Hours::at( $last, $minute, $tz ); } $units = Bookable::RANGE === $bookable->duration_mode ? $bookable->clamp_units( $opt['units'] ) : 1; return $start + ( $plan['minutes'] * $units + $opt['extra_minutes'] ) * 60; } /** * The engine request for a plan. * * @param Bookable $bookable Bookable. * @param array $plan Plan. * @param int $from Earliest start. * @param int $to Latest start. * @param int $duration Seconds. * @param array $opt Options. */ private function request( Bookable $bookable, array $plan, int $from, int $to, int $duration, array $opt ): SlotRequest { [ $earliest, $latest ] = $this->limits( $bookable, $opt, $this->plan_zone( $plan ) ); $group_slot = array() !== $plan['staff'] && $bookable->capacity > 1 && ! $bookable->by_day(); $step = $bookable->by_day() ? DAY_IN_SECONDS : ( $bookable->slot_interval > 0 ? $bookable->slot_interval * 60 : $plan['minutes'] * 60 ); return new SlotRequest( $from, $to, $duration, $step, $bookable->buffer_before * 60, $bookable->buffer_after * 60, $earliest, $latest, $opt['quantity'], $bookable->id, $group_slot ? $bookable->capacity : 1 ); } /** * Engine groups: staff, each resource pool, or the bookable itself. * * @param Bookable $bookable Bookable. * @param array $plan Plan. * @param int $from Window start. * @param int $to Window end. * @param array $opt Options. * @return array> */ private function groups( Bookable $bookable, array $plan, int $from, int $to, array $opt ): array { $schedules = Services::schedules(); $location = $plan['location']; $loc_id = (int) $plan['location_id']; $dates = array( gmdate( 'Y-m-d', $from - DAY_IN_SECONDS ), gmdate( 'Y-m-d', $to + DAY_IN_SECONDS ) ); $site = array( 'weekly' => $schedules->weekly( 'site', 0 ), 'overrides' => $schedules->overrides( 'site', array( 0 ), $dates[0], $dates[1] )[0] ?? array(), ); $loc_level = array( 'weekly' => $loc_id > 0 ? $schedules->weekly( 'location', $loc_id ) : null, 'overrides' => $loc_id > 0 ? ( $schedules->overrides( 'location', array( $loc_id ), $dates[0], $dates[1] )[ $loc_id ] ?? array() ) : array(), ); $own_hours = $schedules->weekly( 'bookable', $bookable->id ); $own_over = $schedules->overrides( 'bookable', array( $bookable->id ), $dates[0], $dates[1] )[ $bookable->id ] ?? array(); $loc_zone = (string) ( $location['timezone'] ?? '' ); $groups = array(); if ( array() !== $plan['staff'] ) { $ids = array_keys( $plan['staff'] ); $weekly = $schedules->weekly_many( 'staff', $ids ); $overrides = $schedules->overrides( 'staff', $ids, $dates[0], $dates[1] ); $busy = $this->merge_busy( $opt['ignore_bookings'] ? array() : Services::bookings()->busy_staff( $ids, $from, $to, $opt['except_booking'] ), $opt['ignore_bookings'] ? array() : Services::holds()->busy( 'staff', $ids, $from, $to, $opt['except_hold'] ), Services::sessions_repo()->busy_staff( $ids, $from, $to ), Services::calendars()->busy( 'staff', $ids, $from, $to ) ); /** * Change when staff are busy, e.g. Pro's travel time between locations. * * @param array $busy Staff ID => busy entries {start, end, kind, location_id, ...}. * @param int $location_id Location being booked (0 = none). * @param Bookable $bookable Bookable. */ $busy = (array) apply_filters( 'schedulereed_staff_busy', $busy, $loc_id, $bookable ); $candidates = array(); foreach ( $plan['staff'] as $id => $member ) { $levels = array( array( 'weekly' => $weekly[ $id ] ?? null, 'overrides' => $overrides[ $id ] ?? array(), ), $loc_level, $site, ); $tz = Settings::zone( '' !== (string) $member['timezone'] ? (string) $member['timezone'] : $loc_zone ); $candidates[ $id ] = array( 'open' => $this->open( $bookable, $levels, $tz, $from, $to, $own_hours, $own_over ), 'busy' => $busy[ $id ] ?? array(), 'capacity' => 1, ); } $groups[] = array( 'key' => 'staff', 'need' => 1, 'consumes' => 'booking', 'candidates' => $candidates, ); } $consumes = Bookable::RENTAL === $bookable->type ? 'quantity' : 'booking'; foreach ( (array) $bookable->settings['resources'] as $i => $pool ) { $resources = Services::catalog()->resources( $pool['ids'] ); if ( $loc_id > 0 && array() !== $resources ) { $where = Services::links()->map( 'resource', array_keys( $resources ), 'location' ); $resources = array_filter( $resources, static fn( array $r ): bool => array() === ( $where[ $r['id'] ] ?? array() ) || in_array( $loc_id, $where[ $r['id'] ], true ) ); } if ( count( $resources ) < (int) $pool['need'] ) { return array(); } $ids = array_keys( $resources ); $weekly = $schedules->weekly_many( 'resource', $ids ); $overrides = $schedules->overrides( 'resource', $ids, $dates[0], $dates[1] ); $busy = $this->merge_busy( $opt['ignore_bookings'] ? array() : Services::bookings()->busy_resources( $ids, $from, $to, $opt['except_booking'] ), $opt['ignore_bookings'] ? array() : Services::holds()->busy( 'resource', $ids, $from, $to, $opt['except_hold'] ), array(), Services::calendars()->busy( 'resource', $ids, $from, $to ) ); $candidates = array(); foreach ( $resources as $id => $resource ) { $levels = array( array( 'weekly' => $weekly[ $id ] ?? null, 'overrides' => $overrides[ $id ] ?? array(), ), $loc_level, $site, ); $candidates[ $id ] = array( 'open' => $this->open( $bookable, $levels, Settings::zone( $loc_zone ), $from, $to, $own_hours, $own_over ), 'busy' => $busy[ $id ] ?? array(), 'capacity' => max( 1, (int) $resource['quantity'] ), ); } $groups[] = array( 'key' => 'resource_' . $i, 'need' => (int) $pool['need'], 'consumes' => $consumes, 'candidates' => $candidates, ); } if ( array() === $groups ) { // Neither staff nor resources: the bookable's own capacity is what runs out. $busy = $this->merge_busy( $opt['ignore_bookings'] ? array() : Services::bookings()->busy_bookables( array( $bookable->id ), $from, $to, $opt['except_booking'] ), $opt['ignore_bookings'] ? array() : Services::holds()->busy( 'bookable', array( $bookable->id ), $from, $to, $opt['except_hold'] ), array(), Services::calendars()->busy( 'bookable', array( $bookable->id ), $from, $to ) ); $levels = array( array( 'weekly' => $own_hours, 'overrides' => $own_over, ), $loc_level, $site, ); $groups[] = array( 'key' => 'bookable', 'need' => 1, 'consumes' => 'quantity', 'candidates' => array( $bookable->id => array( 'open' => $this->open( $bookable, $levels, Settings::zone( $loc_zone ), $from, $to, null, array() ), 'busy' => $busy[ $bookable->id ] ?? array(), 'capacity' => $bookable->capacity, ), ), ); } return $groups; } /** * Open intervals for a candidate between two times. * * Rentals by the day or night are open around the clock except on closed * dates; everything else follows the hours. A bookable's own hours, when * set, narrow every candidate's. * * @param Bookable $bookable Bookable. * @param array $levels Most specific first. * @param DateTimeZone $tz Zone. * @param int $from Start. * @param int $to End. * @param WeeklyHours|null $own Bookable's own hours. * @param array $own_over Bookable's own overrides. * @return array */ private function open( Bookable $bookable, array $levels, DateTimeZone $tz, int $from, int $to, ?WeeklyHours $own, array $own_over ): array { $first = ( new DateTimeImmutable( '@' . $from ) )->setTimezone( $tz )->format( 'Y-m-d' ); $last = ( new DateTimeImmutable( '@' . $to ) )->setTimezone( $tz )->format( 'Y-m-d' ); $hours = new Hours( $levels ); if ( $bookable->by_day() ) { $open = array( array( $from, $to ) ); $closed = array(); $date = new DateTimeImmutable( $first, $tz ); for ( $i = 0; $i < 800 && $date->format( 'Y-m-d' ) <= $last; $i++ ) { $day = $date->format( 'Y-m-d' ); $local = $hours->local( $day ); if ( 'override' === $local['source'] && array() === $local['ranges'] ) { // A one-second gap late in the day blocks every day or night that covers it. $late = Hours::at( $day, 1410, $tz ); $closed[] = array( $late, $late + 1 ); } $date = $date->modify( '+1 day' ); } return Intervals::subtract( $open, $closed ); } $open = Intervals::normalize( $hours->between( $first, $last, $tz ) ); if ( null !== $own || array() !== $own_over ) { $narrow = new Hours( array( array( 'weekly' => $own ?? WeeklyHours::from_array( array_fill_keys( range( 1, 7 ), array( array( '00:00', '24:00' ) ) ) ), 'overrides' => $own_over, ), ) ); $open = Intervals::intersect( $open, $narrow->between( $first, $last, $tz ) ); } return $open; } /** * Join busy lists keyed by owner. * * @param array>> ...$lists Lists. * @return array>> */ private function merge_busy( array ...$lists ): array { $out = array(); foreach ( $lists as $list ) { foreach ( $list as $id => $entries ) { $out[ $id ] = array_merge( $out[ $id ] ?? array(), $entries ); } } return $out; } /** * A plan's zone. * * @param array $plan Plan. */ private function plan_zone( array $plan ): DateTimeZone { return Settings::zone( (string) ( $plan['location']['timezone'] ?? '' ) ); } /** * An engine slot as the API shows it. * * @param array $slot Engine slot. * @param array $plan Plan. * @param SlotRequest $request Request. * @return array */ private function shape( array $slot, array $plan, SlotRequest $request ): array { $resources = array(); foreach ( $slot['options'] as $key => $ids ) { if ( str_starts_with( (string) $key, 'resource_' ) ) { $resources[ (string) $key ] = $ids; } } $remaining = (int) $slot['remaining']; if ( 1 === $request->capacity && isset( $slot['options']['staff'] ) && ! isset( $slot['options']['bookable'] ) && array() === $resources ) { $remaining = count( $slot['options']['staff'] ); } return array( 'start' => (int) $slot['start'], 'end' => (int) $slot['end'], 'staff' => $slot['options']['staff'] ?? array(), 'resources' => $resources, 'location_id' => (int) $plan['location_id'], 'remaining' => $remaining, ); } }