> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Round Robin Appointment Scheduling

## Article: Round Robin Appointment Scheduling

## Article Link: https://dev.wix.com/docs/coding-examples/business-solutions/wix-bookings/round-robin-appointment-scheduling.md

## Article Content:

# Round Robin Appointment Scheduling

Enable appointment bookings to be distributed among staff members in a weight-based round robin fashion. 

<div style="display: flex; flex-direction: row; align-items: center;"> 
<span style="display: flex; flex-direction: row; align-items: center; margin-right: 20px;"> 
<img src="https://wixmp-833713b177cebf373f611808.wixmp.com/images/b63c1547ac02ae3e117d666c004b4e11.png" style="width: 15px; height: 15px;"> 
<span style="margin-left:3px; color:rgb(51 56 83); font-size:1rem">Advanced</span> 
</span> 
<span style="color:rgb(51 56 83); font-size:1rem">Last updated: 06 May 2025</span> 
</div> 
<div style="display: flex; flex-direction: column; padding-top: 20px; padding-bottom: 20px;">
<div style="width: 100%; margin-bottom: 20px;"> 
<img src="https://static.wixstatic.com/media/d2a594_5a9dc47cb8454197ad5f97e8aaca22a7~mv2.webp" alt="Round Robin Appointment Scheduling" style="width: 100%;"> 
</div> 
<div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center; width: 100%;">
<div style="margin: 0px 20px 20px 0px;">
<a href="fallback::https://manage.wix.com/edit-template/from?originTemplateId=ae727529-4885-47d1-8f1a-a13ef0726be9&templateId=f904ca00-528f-4dd1-b5af-b4f93f8ff6c3&autoDevMode=true" target="_blank"> <button style="margin-right: 10px;background-color:#106DFF; color:white; padding:10px 20px; border:none; border-radius:21px; cursor:pointer; margin: 0px 20px 20px 0px;" target="_blank">Open Example</button></a> 
<a href="fallback::https://www.wix.com/velo-examples/round-robin-example" target="_blank"><button style="background-color:white; color:#106DFF; padding:10px 20px; border:1px solid #106DFF; border-radius:21px; cursor:pointer; width:125px;" target="_blank">Preview</button></a> 
</div> 
</div> 
</div> 
</div>

## About
---

In this example, we create an appointment scheduling system using a multi-state box. Using a weight-based round robin implementation, we first identify the staff member with the fewest existing appointments to receive the next booking. We then query this staff member’s availability and display dates and times for visitors to choose from. Upon a successful booking, we change the state of the multi-state box to display the visitor’s appointment details. 

## Before you begin
---
To use this example:
* You must install Wix Bookings on your site. 
* You must install Wix Stores on your site.  
* Your site must have at least one Bookings service. 
* Your site must have at least 2 staff members.  
* Your site must be connected to a premium account to see it work. 


## APIs 
---
<ul> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::multi-state-box/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/multi-state-box/introduction".md target="_blank">$w.MultiStateBox API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::date-picker/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/date-picker/introduction".md target="_blank">$w.DatePicker API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::dropdown/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/dropdown/introduction".md target="_blank">$w.Dropdown API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::button/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/button/introduction".md target="_blank">$w.Button API</a></li> 
<li><a href="fallback::https://dev.wix.com/docs/sdk/frontend-modules/bookings/introduction".md target="_blank">Bookings </a></li> 
<li><a href="fallback::https://dev.wix.com/docs/sdk/backend-modules/ecom/introduction".md target="_blank">Ecom </a></li> 
<li><a href="fallback::https://dev.wix.com/docs/sdk/frontend-modules/location/introduction".md target="_blank">Location </a></li> 
</ul> 

## How we built it 
---
We added the following to our site:

#### Page Elements

##### Home

* A multi-state box to display: 
  * Form with input fields for scheduling appointments.
  * Details of a scheduled appointment. 
* A date picker to select the date for an appointment.
* A dropdown to select the time for an appointment. 
* Buttons to book an appointment and to return to the home page.

#### Frontend Code 

##### Home

The code in this file initializes the page’s elements, validates input data for creating a booking,  and retrieves the created booking data from the backend.

In this file, we:
* Define the Wix Bookings App ID, which can be retrieved from your site’s dashboard. 
* Get the visitor’s time zone and define the time format for display. 
* Retrieve the staff member with the least number of bookings and their availability from the backend.
* Set the date picker to display the available appointment dates. 
* Populate the dropdown to display the available appointment times based on the currently selected date. 
* Validate the input data in the booking form. 
* Define objects for booking creation and confirmation. 
* Retrieve the newly created and confirmed booking from the backend to display to the visitor.
* Redirect to the home page when the Back to Home button is clicked. 


#### Backend Code

##### WixBookings.web.js

We defined the following methods:
* `getResourcesWithMinimumWeight()`: Calls `getFirstService()` to retrieve the staff member IDs of the booking service, defines a query filter to call `queryExtendedBookings()`, then uses the query results to find and return the staff member with the least number of booked appointments.  
* `getFirstService()`: Queries all services and returns the first service (under the assumption that your appointment scheduling system is that service). 
* `queryExtendedBookings()`: Retrieves the extended bookings that match the query filter criteria for the staff members. 
* `queryAvailability()`: Calls `getFirstService()` and extracts the service ID, calls `queryAvailability()` on the availability calendar with a query filter, and then returns a list of the staff member’s availability entries. 
* `createBooking()`: Creates an appointment booking with the provided booking object.


##### WixBookings.web.js
The code in this file uses the Wix Ecom Checkout API to create a checkout and order to successfully confirm the created appointment booking.

We defined the following methods:
* `createCheckout()`: Creates a checkout that holds information about the booking that was created. 
* `createOrder()`: Creates an order from the checkout, which confirms the booking creation. 



## Code Snippets
---
<details open> 
<summary> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" width="22" height="22">
    <path d="M16.003 15.18c0 .57-.11 1.01-.31 1.32.2.31.31.75.31 1.32 0 .94.33 1.22.53 1.24.27.02.481.25.471.52-.01.27-.22.48-.49.48-.521 0-1.512-.47-1.512-2.24 0-.51-.1-.74-.16-.81h-.06c-.06 0-.11 0-.16-.01a.505.505 0 0 1-.561-.29.522.522 0 0 1-.04-.21c0-.08 0-.17.04-.25.1-.22.35-.32.58-.27h.2c.06-.06.17-.29.17-.81 0-1.77.992-2.24 1.513-2.24.28 0 .5.22.5.5s-.22.5-.5.5c-.18.02-.511.3-.511 1.24l-.01.01Zm5.967 1.1c-.09-.22-.33-.33-.57-.28h-.211c-.06-.06-.17-.29-.17-.81 0-1.77-.991-2.24-1.512-2.24-.27 0-.48.21-.49.48-.01.27.2.5.47.52.2.02.53.3.53 1.24 0 .57.11 1.01.311 1.32-.2.31-.31.75-.31 1.32 0 .94-.33 1.22-.511 1.24-.28 0-.5.22-.5.5s.22.5.5.5c.52 0 1.512-.47 1.512-2.24 0-.51.1-.74.16-.81h.06c.06 0 .11 0 .15-.01.23.06.47-.05.57-.27.041-.08.041-.17.041-.25 0-.07 0-.14-.04-.21h.01ZM17.014 4H6.001C5.451 4 5 4.45 5 5v14c0 .55.45 1 1.001 1h7.008v-1H6.001V5h11.013v6h1.001V5c0-.55-.45-1-1-1Zm-9.01 7h7.008v-1H8.004v1Zm7.008-4H8.004v1h7.008V7Z"></path>
  </svg> WixBookings.web.js </summary> 

```javascript
import { Permissions, webMethod } from "wix-web-module";
import { extendedBookings, availabilityCalendar, bookings, services } from '@wix/bookings';

export const queryAvailability = webMethod(Permissions.Anyone, async (resourceId, timezone) => {
    const service = await getFirstService()
    const query = {
        "filter": {
            "serviceId": service._id,
            "startDate": new Date(),
            "endDate": new Date(new Date().setDate(new Date().getDate() + 7)),
            "resourceId": resourceId,
            "bookable": true
        }
    }
    console.log('query:', query);
    const options = {
        timezone: timezone
    }
    console.log('options:', options);
    try {
        return (await availabilityCalendar.queryAvailability(query, options)).availabilityEntries;
    } catch (error) {
        console.error(error);
    }
})

export const createBooking = webMethod(Permissions.Anyone, async (booking, options) => {
    try {
        const result = await bookings.createBooking(booking, options);
        return result;
    } catch (error) {
        console.error(error);
        throw new Error('createBooking failed')
    }
})

export const getFirstService = webMethod(Permissions.Anyone, async () => {
    const result = await services.queryServices().find();
    return result.items[0];
})

export const queryExtendedBookings = webMethod(Permissions.Anyone, async (query) => {
    try {
        const result = await extendedBookings.queryExtendedBookings(query, null);
        return result;
    } catch (error) {
        console.error(error);
        throw new Error('queryExtendedBookings failed')
    }
})

export const getResourcesWithMinimumWeight = webMethod(Permissions.Anyone, async () => {
    const service = await getFirstService();
    const { staffMemberIds } = service;
    console.log('staffMemberIds:', staffMemberIds);
    const weekBefore = new Date(new Date().setDate(new Date().getDate() - 7))
    const weekAfter = new Date(new Date().setDate(new Date().getDate() + 7))
    const query = {
        "filter": {
            "bookedEntity.item.slot.resource.id": { "$hasSome": staffMemberIds },
            "startDate": {
                "$gte": weekBefore
            },
            "endDate": {
                "$lte": weekAfter
            },
            "status": ["CONFIRMED"]
        },
        "paging": {
            "limit": 100
        }
    }
    const extendedBookings = (await queryExtendedBookings(query)).extendedBookings;
    if (extendedBookings.length === 0) {
        return staffMemberIds[0];
    } else {
        const staffNumBookings = new Map()
        staffMemberIds.forEach(staffMembersId => staffNumBookings.set(staffMembersId, 0));
        extendedBookings.forEach(extendedBooking => {
            let resourceId = extendedBooking.booking.bookedEntity.slot.resource._id;
            staffNumBookings.set(resourceId, staffNumBookings.get(resourceId) + 1);
        })
        const min = Math.min(...staffNumBookings.values());
        for (let [key, value] of staffNumBookings.entries()) {
            if (value === min)
                return key;
        }
    }
})

```
</details>

<details open> 
<summary> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" width="22" height="22">
    <path d="M16.003 15.18c0 .57-.11 1.01-.31 1.32.2.31.31.75.31 1.32 0 .94.33 1.22.53 1.24.27.02.481.25.471.52-.01.27-.22.48-.49.48-.521 0-1.512-.47-1.512-2.24 0-.51-.1-.74-.16-.81h-.06c-.06 0-.11 0-.16-.01a.505.505 0 0 1-.561-.29.522.522 0 0 1-.04-.21c0-.08 0-.17.04-.25.1-.22.35-.32.58-.27h.2c.06-.06.17-.29.17-.81 0-1.77.992-2.24 1.513-2.24.28 0 .5.22.5.5s-.22.5-.5.5c-.18.02-.511.3-.511 1.24l-.01.01Zm5.967 1.1c-.09-.22-.33-.33-.57-.28h-.211c-.06-.06-.17-.29-.17-.81 0-1.77-.991-2.24-1.512-2.24-.27 0-.48.21-.49.48-.01.27.2.5.47.52.2.02.53.3.53 1.24 0 .57.11 1.01.311 1.32-.2.31-.31.75-.31 1.32 0 .94-.33 1.22-.511 1.24-.28 0-.5.22-.5.5s.22.5.5.5c.52 0 1.512-.47 1.512-2.24 0-.51.1-.74.16-.81h.06c.06 0 .11 0 .15-.01.23.06.47-.05.57-.27.041-.08.041-.17.041-.25 0-.07 0-.14-.04-.21h.01ZM17.014 4H6.001C5.451 4 5 4.45 5 5v14c0 .55.45 1 1.001 1h7.008v-1H6.001V5h11.013v6h1.001V5c0-.55-.45-1-1-1Zm-9.01 7h7.008v-1H8.004v1Zm7.008-4H8.004v1h7.008V7Z"></path>
  </svg> WixEcom.web.js </summary> 

```javascript
import { Permissions, webMethod } from "wix-web-module";
import { checkout } from '@wix/ecom';

export const createCheckout = webMethod(Permissions.Anyone, async (options) => {
    try {
        const newCheckout = await checkout.createCheckout(options);
        console.log('Success! Checkout created, checkout:', newCheckout);
        return newCheckout;
    } catch (error) {
        console.error(error);
    }
})

export const createOrder = webMethod(Permissions.Anyone, async (checkoutId) => {
    try {
        const newOrder = await checkout.createOrder(checkoutId);
        console.log('Success! Order created:', newOrder);
        return newOrder;
    } catch (error) {
        console.error(error);
    }
});

```
</details>

<details open> 
<summary> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" width="22" height="22">
    <path d="M16.003 15.18c0 .57-.11 1.01-.31 1.32.2.31.31.75.31 1.32 0 .94.33 1.22.53 1.24.27.02.481.25.471.52-.01.27-.22.48-.49.48-.521 0-1.512-.47-1.512-2.24 0-.51-.1-.74-.16-.81h-.06c-.06 0-.11 0-.16-.01a.505.505 0 0 1-.561-.29.522.522 0 0 1-.04-.21c0-.08 0-.17.04-.25.1-.22.35-.32.58-.27h.2c.06-.06.17-.29.17-.81 0-1.77.992-2.24 1.513-2.24.28 0 .5.22.5.5s-.22.5-.5.5c-.18.02-.511.3-.511 1.24l-.01.01Zm5.967 1.1c-.09-.22-.33-.33-.57-.28h-.211c-.06-.06-.17-.29-.17-.81 0-1.77-.991-2.24-1.512-2.24-.27 0-.48.21-.49.48-.01.27.2.5.47.52.2.02.53.3.53 1.24 0 .57.11 1.01.311 1.32-.2.31-.31.75-.31 1.32 0 .94-.33 1.22-.511 1.24-.28 0-.5.22-.5.5s.22.5.5.5c.52 0 1.512-.47 1.512-2.24 0-.51.1-.74.16-.81h.06c.06 0 .11 0 .15-.01.23.06.47-.05.57-.27.041-.08.041-.17.041-.25 0-.07 0-.14-.04-.21h.01ZM17.014 4H6.001C5.451 4 5 4.45 5 5v14c0 .55.45 1 1.001 1h7.008v-1H6.001V5h11.013v6h1.001V5c0-.55-.45-1-1-1Zm-9.01 7h7.008v-1H8.004v1Zm7.008-4H8.004v1h7.008V7Z"></path>
  </svg> Home </summary> 

```javascript
import { queryAvailability, createBooking, getResourcesWithMinimumWeight } from 'backend/WixBookings.web.js';
import { createCheckout, createOrder } from 'backend/WixEcom.web.js';
import { location } from '@wix/site-location';



//Wix Bookings app ID, required for checkout object.
//Read more here: https://www.wix.com/velo/reference/wix-ecom-backend/checkout/createcheckout
const WIX_BOOKINGS_APP_DEF_ID = "13d21c63-b5ec-5912-8397-c3a5ddb27a97";


const inputFields = [{
        input: '#firstNameInput',
        errorMessage: 'First Name'
    },
    {
        input: '#lastNameInput',
        errorMessage: 'Last Name'
    },
    {
        input: '#emailInput',
        errorMessage: 'Email Address'
    },
    {
        input: '#phoneInput',
        errorMessage: 'Phone Number'
    },
];

const TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone
const TIME_OPTIONS = { timeZone: TIMEZONE, hour12: false, hour: "2-digit", minute: "2-digit", second: undefined }
let slotForBookings


$w.onReady(function () {
    initData()
});


async function initData() {
    const resourceIdForAvailability = await getResourcesWithMinimumWeight()
    const availability = await queryAvailability(resourceIdForAvailability, TIMEZONE)
    setEvents(availability)
    await setDatePicker(availability)
    await populateTimeDropdown(availability)
}


$w('#bookNowButton').onClick(async () => {

    const isFormValid = await validateMandatoryFields()
    console.log('isFormValid', isFormValid)
    if (isFormValid) {
        $w('#bookingError').hide();
        $w('#bookNowButton, #datePicker, #timeDropdown').disable();

        let booking = await createBookingsAndCheckout()
        $w('#startTime').text = new Date(booking.booking.bookedEntity.slot.startDate).toLocaleString();
        $w('#endTime').text = new Date(booking.booking.bookedEntity.slot.endDate).toLocaleString();
        $w('#callWith').text = booking.booking.bookedEntity.slot.resource.name;
        $w('#statebox').changeState('success');
    } else {
        $w('#bookingError').show();
    }
})


function validateMandatoryFields() {
    let validationArr = []
    for (const i in inputFields) {
        const isFieldValid = $w(inputFields[i].input).valid
        validationArr.push(isFieldValid)
    }

    if (validationArr.includes(false)) {
        return false;
    } else {
        return true;
    }
}


function setEvents(availability) {
    $w("#datePicker").onChange(() => {
        populateTimeDropdown(availability)
        $w("#timeDropdown").value =  $w("#timeDropdown").options[0].value;
    })


    $w("#timeDropdown").onChange(() => {
        let roundRobinSlots = [];
        slotForBookings = [];
        let datePickerLocaleDate = $w("#datePicker").value.toLocaleDateString();
        let timeDropdownLocaleTime = $w("#timeDropdown").value
        availability.forEach(availableSlot => {
            if (new Date(availableSlot.slot.startDate).toLocaleDateString().includes(datePickerLocaleDate) &&
                new Date(availableSlot.slot.startDate).toLocaleTimeString('en-US', TIME_OPTIONS).includes(timeDropdownLocaleTime)) {
                roundRobinSlots.push(availableSlot);
            }
            
        })

        slotForBookings = roundRobinSlots[Math.floor(Math.random() * roundRobinSlots.length)];
    })

    $w('#backToHomeButton').onClick(async () => {
        const baseUrl = await location.baseUrl()
        location.to(baseUrl)
    })
}

 function setDatePicker(availability) {
    const availableDates = [];
    availability.forEach(availableTime => {
        availableDates.push({
            startDate: new Date(new Date(availableTime.slot.startDate).toLocaleDateString()),
            endDate: new Date(new Date(availableTime.slot.startDate).toLocaleDateString())
        })
    })
    $w("#datePicker").enabledDateRanges = availableDates;
    $w("#datePicker").value = availableDates[0].startDate
}

function populateTimeDropdown(availability) {
    const availableSlots = [];
    const availableTimes = [];
    const temp = [];
    availability.forEach(availableTime => {
        const slotMatchesSelectedDate = new Date(availableTime.slot.startDate).toLocaleDateString().includes($w("#datePicker").value.toLocaleDateString())
        if (slotMatchesSelectedDate) {
            availableSlots.push(availableTime);
        }

    })
    availableSlots.forEach(availableSlot => {
        // Why is there an error here? if its something bugged in the product maybe we need to add a comment here?
        let dropdownText = new Date(availableSlot.slot.startDate).toLocaleTimeString('en-US', TIME_OPTIONS)
        if (!temp.includes(dropdownText)) {
            temp.push(dropdownText);
            availableTimes.push({ label: dropdownText, value: dropdownText });
        }
    })

    $w("#timeDropdown").options = availableTimes;
    $w("#timeDropdown").value = availableTimes[0].value
}

async function createBookingsAndCheckout() {

    const bookingObject = {
        totalParticipants: 1,
        contactDetails: {
            firstName: $w('#firstNameInput').value,
            lastName: $w('#lastNameInput').value,
            email: $w('#emailInput').value
        },

        bookedEntity: {
            slot: {
                startDate: slotForBookings.slot.startDate,
                endDate: slotForBookings.slot.endDate,
                timezone: slotForBookings.slot.timezone,
                location: {
                    locationType: slotForBookings.slot.location.locationType
                },
                resource: {
                    id: slotForBookings.slot.resource._id,
                    name: slotForBookings.slot.resource.name,
                    scheduleId: slotForBookings.slot.resource.scheduleId
                },
                scheduleId: slotForBookings.slot.scheduleId,
                serviceId: slotForBookings.slot.serviceId
            }
        }
    }
    let createdBooking = await createBooking(bookingObject, {});

    const options = {
        lineItems: [{
            quantity: 1,
            catalogReference: {
                // Wix Bookings app Id
                appId: WIX_BOOKINGS_APP_DEF_ID,
                // Wix Bookings bookings Id
                catalogItemId: createdBooking.booking._id
            }
        }],
        checkoutInfo: {
            billingInfo: {
                contactDetails: {
                    firstName: $w('#firstNameInput').value,
                    lastName: $w('#lastNameInput').value,
                    phone: $w('#phoneInput').value
                }
            },
            buyerInfo: {
                email: $w('#emailInput').value,
            }
        },
        channelType: "WEB"
    }
    let createCheckoutEcom = await createCheckout(options)
    let order = await createOrder(createCheckoutEcom._id)

    return createdBooking
}

```
</details>

<!-- Static content -->
## Get Help
--- 
### Join the community 

Join the [Wix Studio][discord-community] community on Discord, where experienced developers and fellow creators come together to share tips, troubleshoot issues, and collaborate.

### Hire a developer 

Building a coded solution on your own can be challenging. Let an experienced Wix developer build it for you, so you can keep working on your site or business.
Visit the [Wix Marketplace][wix-marketplace] to find a trusted developer. 

<!-- Predefined links -->
[discord-community]: https://discord.com/invite/GhdmDN926z 
[wix-marketplace]: https://www.wix.com/marketplace/brief-auto-match/web-developer?entry=velo&origin=examples-page "Wix Marketplace"