spatie / opening-hours

Query and format a set of opening hours

Home Page:https://freek.dev/595-managing-opening-hours-with-php

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Free time slots during the day ?

VConsulting opened this issue · comments

Hello,

I have a list of existing appointments in an example table:

[
  [
    'open' => '2022-07-21 10:00:00',
    'end' => '2022-07-21 11:00:00',
  ] ,
  [
    'open' => '2022-07-21 14:00:00',
    'end' => '2022-07-21 15:00:00',
  ] ,
]

is it possible to bring out the free time slots of the day?
Thanks

commented

Hello,

Here is an example of how you can deal with appointments and opening hours in the same time.

To be able to know in which state precisely you are at any time, the easier approach is to have 1 OpeningHours for the global schedule (when can the appointments can be taken in the week), this instance can also have holidays etc. in its exceptions.

And 1 other OpeningHours will represent appointments, then you would browse whatever time period you need and check both instance to know if it's closed/occupied/available:

In the example below I jump from a state change to the next one, which allows to make as less loop turns as possible and have whatever minute-precise ranges: opening hours can be 08:36-12:13 and appointment 09:07-09-22, it will work fine.

$meetings = [
  [
    'open' => '2022-07-21 10:00:00',
    'end' => '2022-07-21 11:00:00',
  ] ,
  [
    'open' => '2022-07-21 14:00:00',
    'end' => '2022-07-21 15:00:00',
  ] ,
];

// $openingHours instance will represent the tipical business opening hours
$openingHours = \Spatie\OpeningHours\OpeningHours::create([
    'monday'     => ['09:00-12:00', '13:00-18:00'],
    'tuesday'    => ['09:00-12:00', '13:00-18:00'],
    'wednesday'  => ['09:00-12:00'],
    'thursday'   => ['09:00-12:00', '13:00-18:00'],
    'friday'     => ['09:00-12:00', '13:00-20:00'],
    'saturday'   => [],
    'sunday'     => [],
]);

// We transforms the open/end pair into ranges that can be used as exception
$exceptions = [];

foreach ($meetings as $meeting) {
    [$openDate, $openHour] = explode(' ', preg_replace('/(\d{1,2}:\d{1,2}):\d{1,2}$/', '$1', $meeting['open'])); // preg_replace removes seconds
    [$endDate, $endHour] = explode(' ', preg_replace('/(\d{1,2}:\d{1,2}):\d{1,2}$/', '$1', $meeting['end']));

    foreach (CarbonPeriod::create($openDate, $endDate) as $date) {
        $key = $date->format('Y-m-d');
        $exceptions[$key] = $exceptions[$key] ?? [];
        $exceptions[$key][] = ($date->isSameDay($openDate) ? $openHour : '00:00')
            . '-' . ($date->isSameDay($endDate) ? $endHour : '24:00');
    }
}

// $meetingHours instance will represent the time occupied with a appointment
$appointmentHours = \Spatie\OpeningHours\OpeningHours::create([
    'exceptions' => $exceptions,
]);

// Choose when you start to show the slot and until when
$start = CarbonImmutable::parse('2022-07-21 06:35');
$end = $start->addDays(2);

$date = $start;

while ($date < $end) {
    if (!$openingHours->isOpenAt($date)) {
        echo 'On ' . $date->format('Y-m-d') . ' at ' . $date->format('H:i') . ", it's closed.\n";
        // Advance until it's open
        $date = $openingHours->nextOpen($date);

        continue;
    }

    echo 'On ' . $date->format('Y-m-d') . ' at ' . $date->format('H:i') . ", it's open.\n";

    $nextChange = null;

    // When it's open check if there is a appointment, in this case "isOpenAt" mean ongoing appointment because it's on $meetingHours
    // that contain the hours of the appointment

    if ($appointmentHours->isOpenAt($date)) {
        echo "    and there is a appointment already.\n";

        try {
            // Find when it ends
            $nextChange = $appointmentHours->nextClose($date);
        } catch (\Spatie\OpeningHours\Exceptions\MaximumLimitExceeded) {
        }
    } else {
        echo "    and there is a no appointment until...\n";

        try {
            // Find when start the next meeting
            $nextChange = $appointmentHours->nextOpen($date);
        } catch (\Spatie\OpeningHours\Exceptions\MaximumLimitExceeded) {
        }
    }

    // Check when business closes
    $date = $openingHours->nextClose($date);

    // Go to next change, business close or appointement start/end, whatever happen the soonest
    if ($nextChange !== null && $nextChange < $date) {
      $date = $nextChange;
    }
}

To display slots in some table, you might prefer to simply add a fixed amount of time, in this case you just need to change the while-loop and it goes much simpler but in this case all your times need to be an exact multiple:

$appointmentDuration = 15; // minutes
$date = $start->floorMinutes($appointmentDuration);

while ($date < $end) {
    if (!$openingHours->isOpenAt($date)) {
        echo 'On ' . $date->format('Y-m-d') . ' at ' . $date->format('H:i') . ", it's closed.\n";
    } else {
        echo 'On ' . $date->format('Y-m-d') . ' at ' . $date->format('H:i') . ", it's open.\n";

        $nextChange = null;

        // When it's open check if there is a appointment, in this case "isOpenAt" mean ongoing appointment because it's on $meetingHours
        // that contain the hours of the appointment

        if ($appointmentHours->isOpenAt($date)) {
            echo "    and there is a appointment already.\n";
        } else {
            echo "    and there is a no appointment until...\n";
        }
    }

    $date = $date->addMinutes($appointmentDuration);
}