find_slots( [ 'service_id' => (int) $service_id, 'date_from' => (string) $date_from, 'date_to' => (string) $date_to, 'duration_option_id' => (string) $duration_option_id, 'team_member_id' => (int) $team_member_id, 'extras' => (string) $extras, 'attendees' => (int) $attendees, 'location_id' => (int) $location_id, 'time_from' => (string) $time_from, ] ); } catch ( \Throwable $e ) { Log::error( 'Booktics slot search failed: ' . $e->getMessage() ); return [ 'ok' => false, 'error' => 'Free times could not be loaded. Tell the visitor to open the booking page.', ]; } if ( empty( $found['ok'] ) ) { return $found; } $days = []; $cards = []; $total = 0; $truncated = false; foreach ( $found['days'] as $date => $slots ) { $labelled = array_map( fn( array $slot ): array => $slot + [ 'label' => $this->time_label( $slot['start'] ) ], $slots ); // Each start time once, with every staff member free then: for the // model, so a big team cannot push afternoon times out of what it // sees, and for the card, so 5 free staff are one button, not 5. $unique = []; $buttons = []; foreach ( $labelled as $slot ) { $unique[ $slot['start'] ] ??= [ 'start' => $slot['start'], 'label' => $slot['label'], 'staff_ids' => [], ]; $unique[ $slot['start'] ]['staff_ids'][] = $slot['staff_id']; $buttons[ $slot['start'] ] ??= [ 'start' => $slot['start'], 'label' => $slot['label'], 'staff' => [], ]; $buttons[ $slot['start'] ]['staff'][] = [ 'id' => $slot['staff_id'], 'name' => $slot['staff_name'], ]; } $unique = array_values( $unique ); $total += count( $unique ); $day = [ 'date' => $date, 'date_label' => $this->date_label( $date ), 'count' => count( $unique ), 'times' => array_slice( $unique, 0, self::MAX_TIMES ), ]; if ( count( $unique ) > self::MAX_TIMES ) { $day['more_after'] = $unique[ self::MAX_TIMES - 1 ]['start']; $truncated = true; } $days[] = $day; if ( $labelled ) { $cards[] = [ 'date' => $date, 'date_label' => $this->date_label( $date ), // Same cut as the model's list, so the card stays a size a phone can show. 'slots' => array_slice( array_values( $buttons ), 0, self::MAX_TIMES ), ]; } } $result = [ 'ok' => true, 'timezone' => $this->timezone_label(), 'staff' => $found['staff'], 'days' => $days, ]; $notes = []; if ( $found['staff_total'] > count( $found['staff'] ) ) { $notes[] = 'Only ' . count( $found['staff'] ) . ' of ' . $found['staff_total'] . ' staff were searched. A time not listed may be free with someone else: ask whether the visitor has a staff member in mind and search for that person.'; } if ( $truncated ) { $notes[] = 'Some days list only their first ' . self::MAX_TIMES . ' times (see more_after). A time not listed is not proof it is taken: call booktics-available-slots again with time_from set to the visitor\'s time.'; } if ( 0 === $total ) { $notes[] = 'No free times in this range. Try the next 7 days once.'; } if ( $notes ) { $result['note'] = implode( ' ', $notes ); } if ( 0 === $total ) { return $result; } // Rebuilt from what was parsed: a tap sends this back to the model as text. $picked = self::parse_extras( (string) $extras ); $this->set_card( 'slot_picker', [ 'service_id' => $found['service']['id'], 'service_name' => $found['service']['title'], 'timezone_label' => $this->timezone_label(), 'days' => $cards, // The times were found for these. A tap sends them back, so an // older card still books what it showed after the chat moved on. 'choices' => array_filter( [ 'duration' => (string) $duration_option_id, 'extras' => implode( ',', array_map( static fn( int $id, int $qty ): string => $id . ':' . $qty, array_keys( $picked ), $picked ) ), 'attendees' => (int) $attendees, 'location' => (int) $location_id, ] ), ] ); return $result; } /** * Check a visitor's choice and collect free slots, merged across staff. * * @param array $choice service_id, date_from, date_to, duration_option_id, team_member_id, extras, attendees, location_id, time_from. * @param bool $fresh Skip the one-minute cache, for checking a time right before a booking link. * @return array [ 'ok' => true, 'service' => array, 'staff' => [ [ id, name ] ], 'staff_total' => int, 'days' => [ 'Y-m-d' => [ [ start, staff_id, staff_name ] ] ] ] * or [ 'ok' => false, 'error' => string ]. */ public function find_slots( array $choice, bool $fresh = false ): array { $inactive = $this->inactive(); if ( null !== $inactive ) { return $inactive; } $service = $this->gateway->service( (int) ( $choice['service_id'] ?? 0 ) ); if ( null === $service ) { return $this->error( 'That service is not available. Call booktics-service-search again.' ); } if ( ! $service['staff'] ) { return $this->error( 'This service has no staff assigned. Suggest another service.' ); } $tz = $this->gateway->now()->getTimezone(); $today = $this->gateway->now()->format( 'Y-m-d' ); $from = $this->parse_date( (string) ( $choice['date_from'] ?? '' ), $tz ); $to = '' !== (string) ( $choice['date_to'] ?? '' ) ? $this->parse_date( (string) $choice['date_to'], $tz ) : $from; if ( null === $from || null === $to ) { return $this->error( 'Dates must be YYYY-MM-DD.' ); } if ( $from->format( 'Y-m-d' ) < $today ) { return $this->error( 'That date has passed. Ask for a date from today on.' ); } if ( $to < $from || $to > $from->modify( '+' . ( self::MAX_DAYS - 1 ) . ' days' ) ) { return $this->error( 'Search at most 7 days at a time.' ); } $duration = (string) ( $choice['duration_option_id'] ?? '' ); if ( '' !== $duration && ! in_array( $duration, array_column( $service['durations'], 'id' ), true ) ) { $labels = array_map( static fn( array $d ): string => '' !== $d['name'] ? $d['name'] : $d['minutes'] . ' min', $service['durations'] ); return $this->error( 'That duration is not offered for this service. Options: ' . implode( ', ', $labels ) . '.' ); } $extras = self::parse_extras( (string) ( $choice['extras'] ?? '' ) ); $offered = $this->gateway->extras( $service['id'] ); if ( array_diff( array_keys( $extras ), array_column( $offered, 'id' ) ) ) { return $this->error( 'That extra is not offered for this service.' ); } foreach ( $offered as $extra ) { if ( ( $extras[ $extra['id'] ] ?? 0 ) > $extra['max_qty'] ) { return $this->error( $extra['name'] . ' allows at most ' . $extra['max_qty'] . ' per booking.' ); } } $time_from = (string) ( $choice['time_from'] ?? '' ); if ( '' !== $time_from && 1 !== preg_match( '/^([01]\d|2[0-3]):[0-5]\d$/', $time_from ) ) { return $this->error( 'time_from must be HH:MM, 24 hour.' ); } $min = (int) ( $service['group_min'] ?? 1 ); $attendees = (int) ( $choice['attendees'] ?? 0 ); if ( $attendees < 1 && $min > 1 ) { // Searching for one person would offer times the form then refuses. return $this->error( 'This service needs at least ' . $min . ' people per booking. Ask how many people are coming, then pass attendees.' ); } $attendees = max( 1, $attendees ); if ( $attendees < $min ) { return $this->error( 'This service needs at least ' . $min . ' people per booking.' ); } if ( $attendees > $service['group_max'] ) { return $this->error( 'This service allows at most ' . $service['group_max'] . ' people per booking.' ); } $all_staff = $this->staff_for( $service['staff'], (int) ( $choice['team_member_id'] ?? 0 ), (int) ( $choice['location_id'] ?? 0 ) ); if ( ! $all_staff ) { return $this->error( 'That staff member does not offer this service here.' ); } $room = self::MAX_LOOKUPS - $this->lookups; $staff = array_slice( $all_staff, 0, min( self::MAX_STAFF, $room ) ); if ( ! $staff ) { return $this->error( 'Enough times were searched for this message. Show the visitor what was found, or ask for one day or one staff member and search again on the next message.' ); } $args = array_filter( [ 'additional_duration_id' => $duration, 'extra_services' => $extras, 'total_attendees' => $attendees > 1 ? $attendees : 0, ] ); // Ask Booktics for one extra day on each side: older Booktics ignores // holidays on the first and last day of a range. The extra days are dropped. $padded_from = $from->modify( '-1 day' )->format( 'Y-m-d' ); $padded_to = $to->modify( '+1 day' )->format( 'Y-m-d' ); $now_hm = $this->gateway->now()->format( 'H:i' ); $days = []; for ( $day = $from; $day <= $to; $day = $day->modify( '+1 day' ) ) { $days[ $day->format( 'Y-m-d' ) ] = []; } $cache_key = 'aisentic_bt_slots_' . md5( (string) wp_json_encode( [ $service['id'], array_column( $staff, 'id' ), $padded_from, $padded_to, $args ] ) ); $by_staff = $fresh ? false : get_transient( $cache_key ); if ( ! is_array( $by_staff ) ) { $by_staff = []; foreach ( $staff as $member ) { $by_staff[ $member['id'] ] = $this->gateway->slots( $service['id'], $member['id'], $padded_from, $padded_to, $args ); } $this->lookups += count( $staff ); set_transient( $cache_key, $by_staff, self::CACHE_TTL ); } foreach ( $staff as $member ) { $by_date = $by_staff[ $member['id'] ] ?? []; foreach ( $by_date as $date => $slots ) { if ( ! array_key_exists( $date, $days ) ) { continue; } foreach ( $slots as $slot ) { if ( ! $slot['is_available'] || ( $date === $today && $slot['start'] <= $now_hm ) || $slot['start'] < $time_from ) { continue; } $days[ $date ][] = [ 'start' => $slot['start'], 'staff_id' => $member['id'], 'staff_name' => $member['name'], ]; } } } foreach ( $days as $date => $slots ) { usort( $slots, static fn( array $a, array $b ): int => [ $a['start'], $a['staff_name'] ] <=> [ $b['start'], $b['staff_name'] ] ); $days[ $date ] = $slots; } return [ 'ok' => true, 'service' => $service, 'staff' => array_map( static fn( array $m ): array => [ 'id' => $m['id'], 'name' => $m['name'], ], $staff ), 'staff_total' => count( $all_staff ), 'days' => $days, ]; } /** * "7:1,9:2" as [ 7 => 1, 9 => 2 ]. Bad pairs are skipped. * * @param string $value Raw pairs. * @return array */ public static function parse_extras( string $value ): array { $out = []; foreach ( array_filter( array_map( 'trim', explode( ',', $value ) ) ) as $pair ) { [ $id, $qty ] = array_pad( explode( ':', $pair, 2 ), 2, '1' ); if ( (int) $id > 0 ) { $out[ (int) $id ] = max( 1, (int) $qty ); } } return $out; } /** * Staff to query: the chosen one, else everyone on the service, filtered by branch. * * @param array $staff Service staff [ [ id, name ] ]. * @param int $member_id Chosen staff id, 0 for anyone. * @param int $location_id Branch id, 0 for any. * @return array */ private function staff_for( array $staff, int $member_id, int $location_id ): array { if ( $location_id > 0 ) { $team_ids = []; foreach ( $this->gateway->locations() as $location ) { if ( $location['id'] === $location_id ) { $team_ids = $location['team_ids']; } } $staff = array_filter( $staff, static fn( array $m ): bool => in_array( $m['id'], $team_ids, true ) ); } if ( $member_id > 0 ) { $staff = array_filter( $staff, static fn( array $m ): bool => $m['id'] === $member_id ); } return array_values( $staff ); } /** * Parse a strict YYYY-MM-DD date in the site timezone. * * @param string $value Date. * @param \DateTimeZone $tz Site timezone. * @return \DateTimeImmutable|null */ private function parse_date( string $value, \DateTimeZone $tz ): ?\DateTimeImmutable { $date = \DateTimeImmutable::createFromFormat( '!Y-m-d', $value, $tz ); return $date && $date->format( 'Y-m-d' ) === $value ? $date : null; } /** * Failure result. * * @param string $message Message for the model. * @return array */ private function error( string $message ): array { return [ 'ok' => false, 'error' => $message, ]; } }