feat: Future Limit - Toggle to exclude unavailable days (#14915)

* wip

* wip

* wip

* Add tests

* Update getSchedule.test.ts

* Update types.ts

* Self review fixes

* Update text

* PR feedback from Carina

* Use utcoffset for range as well

* Remove logging from the function that runs on every timeslot

* Add one more test

* Show x days instead of x+1 days for both ROLLING and ROLLING_WINDOW

* refactor tests

* Move bookingScenario imports to the top as they import prismock mock that has to be imported very early

* More reordering of imports

* Fix accidental min update at wrong place

* Handle legacy value of zero for periodDays

* Range fix

* Fix isDateOutOfBound not being checked properly during booking. Also added a test for the case

* Fix duplicate element, how the hell it reached there

* Use today plus x days for ROLLING periodType

* Add disabled for Checkbox as well

* Revert logger.ts

* Formatting

Signed-off-by: zomars <[email protected]>

* Fix ordering of imports that is causing tests failure

---------

Signed-off-by: zomars <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-05-20 13:41:07 +01:00
1 parent b67d37fac7
commit 56022a1ba8
34 files changed
+1618 -428

No files matched your search

+219 -111
View File
@@ -3,7 +3,7 @@ import * as RadioGroup from "@radix-ui/react-radio-group";
import type { EventTypeSetupProps } from "pages/event-types/[type]";
import type { Key } from "react";
import React, { useEffect, useState } from "react";
import type { UseFormRegisterReturn } from "react-hook-form";
import type { UseFormRegisterReturn, UseFormReturn } from "react-hook-form";
import { Controller, useFormContext } from "react-hook-form";
import type { SingleValue } from "react-select";
@@ -11,15 +11,193 @@ import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hook
import { getDefinedBufferTimes } from "@calcom/features/eventtypes/lib/getDefinedBufferTimes";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import { classNames } from "@calcom/lib";
import { ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK } from "@calcom/lib/constants";
import type { DurationType } from "@calcom/lib/convertToNewDurationType";
import convertToNewDurationType from "@calcom/lib/convertToNewDurationType";
import findDurationType from "@calcom/lib/findDurationType";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { ascendingLimitKeys, intervalLimitKeyToUnit } from "@calcom/lib/intervalLimit";
import type { PeriodType } from "@calcom/prisma/enums";
import { PeriodType } from "@calcom/prisma/enums";
import type { IntervalLimit } from "@calcom/types/Calendar";
import { Button, DateRangePicker, InputField, Label, Select, SettingsToggle, TextField } from "@calcom/ui";
import CheckboxField from "@components/ui/form/CheckboxField";
type IPeriodType = (typeof PeriodType)[keyof typeof PeriodType];
/**
* We technically have a ROLLING_WINDOW future limit option that isn't shown as a Radio Option. Because UX is better by providing it as a toggle with ROLLING Limit radio option.
* Also, ROLLING_WINDOW reuses the same `periodDays` field and `periodCountCalendarDays` fields
*
* So we consider `periodType=ROLLING && rollingExcludeUnavailableDays=true` to be the ROLLING_WINDOW option
* We can't set `periodType=ROLLING_WINDOW` directly because it is not a valid Radio Option in UI
* So, here we can convert from periodType to uiValue any time.
*/
const getUiValueFromPeriodType = (periodType: PeriodType) => {
if (periodType === PeriodType.ROLLING_WINDOW) {
return {
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: true,
};
}
if (periodType === PeriodType.ROLLING) {
return {
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: false,
};
}
return {
value: periodType,
rollingExcludeUnavailableDays: null,
};
};
/**
* It compliments `getUiValueFromPeriodType`
*/
const getPeriodTypeFromUiValue = (uiValue: { value: PeriodType; rollingExcludeUnavailableDays: boolean }) => {
if (uiValue.value === PeriodType.ROLLING && uiValue.rollingExcludeUnavailableDays === true) {
return PeriodType.ROLLING_WINDOW;
}
return uiValue.value;
};
function RangeLimitRadioItem({
isDisabled,
formMethods,
radioValue,
}: {
radioValue: string;
isDisabled: boolean;
formMethods: UseFormReturn<FormValues>;
}) {
const { t } = useLocale();
return (
<div className={classNames("text-default mb-2 flex flex-wrap items-center text-sm")}>
{!isDisabled && (
<RadioGroup.Item
id={radioValue}
value={radioValue}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
<div>
<span>{t("within_date_range")}&nbsp;</span>
<div className="me-2 ms-2 inline-flex space-x-2 rtl:space-x-reverse">
<Controller
name="periodDates"
render={({ field: { onChange } }) => (
<DateRangePicker
dates={{
startDate: formMethods.getValues("periodDates").startDate,
endDate: formMethods.getValues("periodDates").endDate,
}}
disabled={isDisabled}
onDatesChange={({ startDate, endDate }) => {
onChange({
startDate,
endDate,
});
}}
/>
)}
/>
</div>
</div>
</div>
);
}
function RollingLimitRadioItem({
radioValue,
isDisabled,
formMethods,
onChange,
rollingExcludeUnavailableDays,
}: {
radioValue: IPeriodType;
isDisabled: boolean;
formMethods: UseFormReturn<FormValues>;
onChange: (opt: { value: number } | null) => void;
rollingExcludeUnavailableDays: boolean;
}) {
const { t } = useLocale();
const options = [
{ value: 0, label: t("business_days") },
{ value: 1, label: t("calendar_days") },
];
const getSelectedOption = () =>
options.find((opt) => opt.value === (formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0));
const periodDaysWatch = formMethods.watch("periodDays");
return (
<div className={classNames("text-default mb-2 flex flex-wrap items-baseline text-sm")}>
{!isDisabled && (
<RadioGroup.Item
id={radioValue}
value={radioValue}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
<div>
<div className="flex items-center">
<TextField
labelSrOnly
type="number"
className="border-default my-0 block w-16 text-sm [appearance:textfield] ltr:mr-2 rtl:ml-2"
placeholder="30"
disabled={isDisabled}
min={0}
max={rollingExcludeUnavailableDays ? ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK : undefined}
{...formMethods.register("periodDays", { valueAsNumber: true })}
/>
<Select
options={options}
isSearchable={false}
isDisabled={isDisabled}
onChange={onChange}
name="periodCoundCalendarDays"
value={getSelectedOption()}
defaultValue={getSelectedOption()}
/>
<span className="me-2 ms-2">&nbsp;{t("into_the_future")}</span>
</div>
<div className="py-2">
<CheckboxField
checked={!!rollingExcludeUnavailableDays}
disabled={isDisabled}
description={t("always_show_x_days", {
x: periodDaysWatch,
})}
onChange={(e) => {
const isChecked = e.target.checked;
formMethods.setValue(
"periodDays",
Math.min(periodDaysWatch, ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK)
);
formMethods.setValue(
"periodType",
getPeriodTypeFromUiValue({
value: PeriodType.ROLLING,
rollingExcludeUnavailableDays: isChecked,
}),
{ shouldDirty: true }
);
}}
/>
</div>
</div>
</div>
);
}
const MinimumBookingNoticeInput = React.forwardRef<
HTMLInputElement,
Omit<UseFormRegisterReturn<"minimumBookingNotice">, "ref">
@@ -114,23 +292,6 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
const { t, i18n } = useLocale();
const formMethods = useFormContext<FormValues>();
const PERIOD_TYPES = [
{
type: "ROLLING" as const,
suffix: t("into_the_future"),
},
{
type: "RANGE" as const,
prefix: t("within_date_range"),
},
{
type: "UNLIMITED" as const,
prefix: t("indefinitely_into_future"),
},
];
const watchPeriodType = formMethods.watch("periodType");
const { shouldLockIndicator, shouldLockDisableProps } = useLockedFieldsManager({
eventType,
translate: t,
@@ -143,11 +304,6 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
const periodTypeLocked = shouldLockDisableProps("periodType");
const offsetStartLockedProps = shouldLockDisableProps("offsetStart");
const optionsPeriod = [
{ value: 0, label: t("business_days") },
{ value: 1, label: t("calendar_days") },
];
const [offsetToggle, setOffsetToggle] = useState(formMethods.getValues("offsetStart") > 0);
// Preview how the offset will affect start times
@@ -389,6 +545,10 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
render={({ field: { onChange, value } }) => {
const isChecked = value && value !== "UNLIMITED";
const { value: watchPeriodTypeUiValue, rollingExcludeUnavailableDays } = getUiValueFromPeriodType(
formMethods.watch("periodType")
);
return (
<SettingsToggle
labelClassName="text-sm"
@@ -402,99 +562,47 @@ export const EventLimitsTab = ({ eventType }: Pick<EventTypeSetupProps, "eventTy
description={t("limit_future_bookings_description")}
{...periodTypeLocked}
checked={isChecked}
onCheckedChange={(bool) => {
if (bool && !formMethods.getValues("periodDays")) {
onCheckedChange={(isEnabled) => {
if (isEnabled && !formMethods.getValues("periodDays")) {
formMethods.setValue("periodDays", 30, { shouldDirty: true });
}
return onChange(bool ? "ROLLING" : "UNLIMITED");
return onChange(isEnabled ? PeriodType.ROLLING : PeriodType.UNLIMITED);
}}>
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
<RadioGroup.Root
value={watchPeriodType}
onValueChange={(val) =>
formMethods.setValue("periodType", val as PeriodType, { shouldDirty: true })
}>
{PERIOD_TYPES.filter((opt) =>
periodTypeLocked.disabled ? watchPeriodType === opt.type : true
).map((period) => {
if (period.type === "UNLIMITED") return null;
return (
<div
className={classNames(
"text-default mb-2 flex flex-wrap items-center text-sm",
watchPeriodType === "UNLIMITED" && "pointer-events-none opacity-30"
)}
key={period.type}>
{!periodTypeLocked.disabled && (
<RadioGroup.Item
id={period.type}
value={period.type}
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
</RadioGroup.Item>
)}
{period.prefix ? <span>{period.prefix}&nbsp;</span> : null}
{period.type === "ROLLING" && (
<div className="flex items-center">
<TextField
labelSrOnly
type="number"
className="border-default my-0 block w-16 text-sm [appearance:textfield] ltr:mr-2 rtl:ml-2"
placeholder="30"
disabled={periodTypeLocked.disabled}
{...formMethods.register("periodDays", { valueAsNumber: true })}
/>
<Select
options={optionsPeriod}
isSearchable={false}
isDisabled={periodTypeLocked.disabled}
onChange={(opt) => {
formMethods.setValue(
"periodCountCalendarDays",
opt?.value === 1 ? true : false,
{ shouldDirty: true }
);
}}
name="periodCoundCalendarDays"
value={optionsPeriod.find((opt) => {
opt.value ===
(formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0);
})}
defaultValue={optionsPeriod.find(
(opt) =>
opt.value ===
(formMethods.getValues("periodCountCalendarDays") === true ? 1 : 0)
)}
/>
</div>
)}
{period.type === "RANGE" && (
<div className="me-2 ms-2 inline-flex space-x-2 rtl:space-x-reverse">
<Controller
name="periodDates"
render={({ field: { onChange } }) => (
<DateRangePicker
dates={{
startDate: formMethods.getValues("periodDates").startDate,
endDate: formMethods.getValues("periodDates").endDate,
}}
disabled={periodTypeLocked.disabled}
onDatesChange={({ startDate, endDate }) => {
onChange({
startDate,
endDate,
});
}}
/>
)}
/>
</div>
)}
{period.suffix ? <span className="me-2 ms-2">&nbsp;{period.suffix}</span> : null}
</div>
value={watchPeriodTypeUiValue}
onValueChange={(val) => {
formMethods.setValue(
"periodType",
getPeriodTypeFromUiValue({
value: val as IPeriodType,
rollingExcludeUnavailableDays: formMethods.getValues("rollingExcludeUnavailableDays"),
}),
{
shouldDirty: true,
}
);
})}
}}>
{(periodTypeLocked.disabled ? watchPeriodTypeUiValue === PeriodType.ROLLING : true) && (
<RollingLimitRadioItem
rollingExcludeUnavailableDays={!!rollingExcludeUnavailableDays}
radioValue={PeriodType.ROLLING}
isDisabled={periodTypeLocked.disabled}
formMethods={formMethods}
onChange={(opt) => {
formMethods.setValue("periodCountCalendarDays", opt?.value === 1, {
shouldDirty: true,
});
}}
/>
)}
{(periodTypeLocked.disabled ? watchPeriodTypeUiValue === PeriodType.RANGE : true) && (
<RangeLimitRadioItem
radioValue={PeriodType.RANGE}
isDisabled={periodTypeLocked.disabled}
formMethods={formMethods}
/>
)}
</RadioGroup.Root>
</div>
</SettingsToggle>
@@ -2441,6 +2441,7 @@
"csat_score": "CSAT Score",
"lockedSMS": "Locked SMS",
"signing_up_terms": "By proceeding, you agree to our <1>Terms</1> and <2>Privacy Policy</2>.",
"always_show_x_days": "Always {{x}} days available",
"unable_to_subscribe_to_the_platform": "An error occurred while trying to subscribe to the platform plan, please try again later",
"updating_oauth_client_error": "An error occurred while updating the OAuth client, please try again later",
"creating_oauth_client_error": "An error occurred while creating the OAuth client, please try again later",
@@ -1,12 +1,5 @@
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
import { describe } from "vitest";
import { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import type { TRequestRescheduleInputSchema } from "@calcom/trpc/server/routers/viewer/bookings/requestReschedule.schema";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { test } from "@calcom/web/test/fixtures/fixtures";
import { getSampleUserInSession } from "../utils/bookingScenario/getSampleUserInSession";
import { setupAndTeardown } from "../utils/bookingScenario/setupAndTeardown";
import {
createBookingScenario,
getGoogleCalendarCredential,
@@ -19,8 +12,15 @@ import {
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { expectBookingRequestRescheduledEmails } from "@calcom/web/test/utils/bookingScenario/expects";
import { getSampleUserInSession } from "../utils/bookingScenario/getSampleUserInSession";
import { setupAndTeardown } from "../utils/bookingScenario/setupAndTeardown";
import type { Request, Response } from "express";
import type { NextApiRequest, NextApiResponse } from "next";
import { describe } from "vitest";
import { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import type { TRequestRescheduleInputSchema } from "@calcom/trpc/server/routers/viewer/bookings/requestReschedule.schema";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { test } from "@calcom/web/test/fixtures/fixtures";
export type CustomNextApiRequest = NextApiRequest & Request;
+34 -175
View File
@@ -1,13 +1,4 @@
import CalendarManagerMock from "../../../../tests/libs/__mocks__/CalendarManager";
import prismock from "../../../../tests/libs/__mocks__/prisma";
import { diff } from "jest-diff";
import { describe, expect, vi, beforeEach, afterEach, test } from "vitest";
import dayjs from "@calcom/dayjs";
import type { BookingStatus } from "@calcom/prisma/enums";
import type { Slot } from "@calcom/trpc/server/routers/viewer/slots/types";
import { getAvailableSlots as getSchedule } from "@calcom/trpc/server/routers/viewer/slots/util";
import {
getDate,
@@ -16,157 +7,28 @@ import {
createOrganization,
getOrganizer,
getScenarioData,
Timezones,
TestData,
} from "../utils/bookingScenario/bookingScenario";
import { describe, vi, test } from "vitest";
import dayjs from "@calcom/dayjs";
import type { BookingStatus } from "@calcom/prisma/enums";
import { getAvailableSlots as getSchedule } from "@calcom/trpc/server/routers/viewer/slots/util";
import { expect } from "./getSchedule/expects";
import { setupAndTeardown } from "./getSchedule/setupAndTeardown";
import { timeTravelToTheBeginningOfToday } from "./getSchedule/utils";
vi.mock("@calcom/lib/constants", () => ({
IS_PRODUCTION: true,
WEBAPP_URL: "http://localhost:3000",
RESERVED_SUBDOMAINS: ["auth", "docs"],
}));
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Matchers<R> {
toHaveTimeSlots(expectedSlots: string[], date: { dateString: string }): R;
}
}
}
expect.extend({
toHaveTimeSlots(
schedule: { slots: Record<string, Slot[]> },
expectedSlots: string[],
{ dateString }: { dateString: string }
) {
if (!schedule.slots[`${dateString}`]) {
return {
pass: false,
message: () => `has no timeslots for ${dateString}`,
};
}
if (
!schedule.slots[`${dateString}`]
.map((slot) => slot.time)
.every((actualSlotTime, index) => {
return `${dateString}T${expectedSlots[index]}` === actualSlotTime;
})
) {
return {
pass: false,
message: () =>
`has incorrect timeslots for ${dateString}.\n\r ${diff(
expectedSlots.map((expectedSlot) => `${dateString}T${expectedSlot}`),
schedule.slots[`${dateString}`].map((slot) => slot.time)
)}`,
};
}
return {
pass: true,
message: () => "has correct timeslots ",
};
},
});
const Timezones = {
"+5:30": "Asia/Kolkata",
"+6:00": "Asia/Dhaka",
};
const TestData = {
selectedCalendars: {
google: {
integration: "google_calendar",
externalId: "[email protected]",
},
},
credentials: {
google: getGoogleCalendarCredential(),
},
schedules: {
IstWorkHours: {
id: 1,
name: "9:30AM to 6PM in India - 4:00AM to 12:30PM in GMT",
availability: [
{
userId: null,
eventTypeId: null,
days: [0, 1, 2, 3, 4, 5, 6],
startTime: new Date("1970-01-01T09:30:00.000Z"),
endTime: new Date("1970-01-01T18:00:00.000Z"),
date: null,
},
],
timeZone: Timezones["+5:30"],
},
IstWorkHoursWithDateOverride: (dateString: string) => ({
id: 1,
name: "9:30AM to 6PM in India - 4:00AM to 12:30PM in GMT but with a Date Override for 2PM to 6PM IST(in GST time it is 8:30AM to 12:30PM)",
availability: [
{
userId: null,
eventTypeId: null,
days: [0, 1, 2, 3, 4, 5, 6],
startTime: new Date("1970-01-01T09:30:00.000Z"),
endTime: new Date("1970-01-01T18:00:00.000Z"),
date: null,
},
{
userId: null,
eventTypeId: null,
days: [0, 1, 2, 3, 4, 5, 6],
startTime: new Date("1970-01-01T14:00:00.000Z"),
endTime: new Date("1970-01-01T18:00:00.000Z"),
date: dateString,
},
],
timeZone: Timezones["+5:30"],
}),
},
users: {
example: {
name: "Example",
username: "example",
defaultScheduleId: 1,
email: "[email protected]",
timeZone: Timezones["+5:30"],
},
},
apps: {
googleCalendar: {
slug: "google-calendar",
dirName: "whatever",
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
keys: {
expiry_date: Infinity,
client_id: "client_id",
client_secret: "client_secret",
redirect_uris: ["http://localhost:3000/auth/callback"],
},
},
},
};
const cleanup = async () => {
await prismock.eventType.deleteMany();
await prismock.user.deleteMany();
await prismock.schedule.deleteMany();
await prismock.selectedCalendar.deleteMany();
await prismock.credential.deleteMany();
await prismock.booking.deleteMany();
await prismock.app.deleteMany();
};
beforeEach(async () => {
await cleanup();
});
afterEach(async () => {
await cleanup();
});
describe("getSchedule", () => {
setupAndTeardown();
describe("Calendar event", () => {
test("correctly identifies unavailable slots from calendar", async () => {
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
@@ -201,7 +63,7 @@ describe("getSchedule", () => {
selectedCalendars: [TestData.selectedCalendars.google],
},
],
apps: [TestData.apps.googleCalendar],
apps: [TestData.apps["google-calendar"]],
};
// An event with one accepted booking
await createBookingScenario(scenarioData);
@@ -445,22 +307,12 @@ describe("getSchedule", () => {
);
});
// FIXME: Fix minimumBookingNotice is respected test
// eslint-disable-next-line playwright/no-skipped-test
test.skip("minimumBookingNotice is respected", async () => {
vi.useFakeTimers().setSystemTime(
(() => {
const today = new Date();
// Beginning of the day in current timezone of the system
return new Date(today.getFullYear(), today.getMonth(), today.getDate());
})()
);
test("minimumBookingNotice is respected", async () => {
await createBookingScenario({
eventTypes: [
{
id: 1,
length: 120,
length: 2 * 60,
minimumBookingNotice: 13 * 60, // Would take the minimum bookable time to be 18:30UTC+13 = 7:30AM UTC
users: [
{
@@ -470,7 +322,7 @@ describe("getSchedule", () => {
},
{
id: 2,
length: 120,
length: 2 * 60,
minimumBookingNotice: 10 * 60, // Would take the minimum bookable time to be 18:30UTC+10 = 4:30AM UTC
users: [
{
@@ -487,8 +339,13 @@ describe("getSchedule", () => {
},
],
});
const { dateString: todayDateString } = getDate();
const { dateString: minus1DateString } = getDate({ dateIncrement: -1 });
// Time Travel to the beginning of today after getting all the dates correctly.
timeTravelToTheBeginningOfToday({ utcOffsetInHours: 5.5 });
const scheduleForEventWithBookingNotice13Hrs = await getSchedule({
input: {
eventTypeId: 1,
@@ -499,9 +356,11 @@ describe("getSchedule", () => {
isTeamEvent: false,
},
});
expect(scheduleForEventWithBookingNotice13Hrs).toHaveTimeSlots(
[
/*`04:00:00.000Z`, `06:00:00.000Z`, - Minimum time slot is 07:30 UTC*/ `08:00:00.000Z`,
/*`04:00:00.000Z`, `06:00:00.000Z`, - Minimum time slot is 07:30 UTC which is 13hrs from 18:30*/
`08:00:00.000Z`,
`10:00:00.000Z`,
`12:00:00.000Z`,
],
@@ -522,17 +381,15 @@ describe("getSchedule", () => {
});
expect(scheduleForEventWithBookingNotice10Hrs).toHaveTimeSlots(
[
/*`04:00:00.000Z`, - Minimum bookable time slot is 04:30 UTC but next available is 06:00*/
`06:00:00.000Z`,
`08:00:00.000Z`,
`10:00:00.000Z`,
`12:00:00.000Z`,
/*`04:00:00.000Z`, - Minimum bookable time slot is 04:30 UTC which is 10hrs from 18:30 */
`05:00:00.000Z`,
`07:00:00.000Z`,
`09:00:00.000Z`,
],
{
dateString: todayDateString,
}
);
vi.useRealTimers();
});
test("afterBuffer and beforeBuffer tests - Non Cal Busy Time", async () => {
@@ -569,7 +426,7 @@ describe("getSchedule", () => {
selectedCalendars: [TestData.selectedCalendars.google],
},
],
apps: [TestData.apps.googleCalendar],
apps: [TestData.apps["google-calendar"]],
};
await createBookingScenario(scenarioData);
@@ -643,7 +500,7 @@ describe("getSchedule", () => {
status: "ACCEPTED" as BookingStatus,
},
],
apps: [TestData.apps.googleCalendar],
apps: [TestData.apps["google-calendar"]],
};
await createBookingScenario(scenarioData);
@@ -701,7 +558,7 @@ describe("getSchedule", () => {
selectedCalendars: [TestData.selectedCalendars.google],
},
],
apps: [TestData.apps.googleCalendar],
apps: [TestData.apps["google-calendar"]],
};
await createBookingScenario(scenarioData);
@@ -879,6 +736,7 @@ describe("getSchedule", () => {
}
);
});
test("test that booking limit is working correctly if user is all day available", async () => {
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
@@ -938,6 +796,7 @@ describe("getSchedule", () => {
],
},
],
// One bookings for each(E1 and E2) on plus2Date
bookings: [
{
userId: 101,
+105
View File
@@ -0,0 +1,105 @@
import { diff } from "jest-diff";
import { expect } from "vitest";
import type { Slot } from "@calcom/trpc/server/routers/viewer/slots/types";
export const expectedSlotsForSchedule = {
IstWorkHours: {
interval: {
"1hr": {
allPossibleSlotsStartingAt430: [
"04:30:00.000Z",
"05:30:00.000Z",
"06:30:00.000Z",
"07:30:00.000Z",
"08:30:00.000Z",
"09:30:00.000Z",
"10:30:00.000Z",
"11:30:00.000Z",
],
allPossibleSlotsStartingAt4: [
"04:00:00.000Z",
"05:00:00.000Z",
"06:00:00.000Z",
"07:00:00.000Z",
"08:00:00.000Z",
"09:00:00.000Z",
"10:00:00.000Z",
"11:00:00.000Z",
],
},
},
},
};
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
interface Matchers<R> {
toHaveTimeSlots(expectedSlots: string[], date: { dateString: string; doExactMatch?: boolean }): R;
toHaveNoTimeSlots(date: { dateString: string }): R;
}
}
}
expect.extend({
toHaveTimeSlots(
schedule: { slots: Record<string, Slot[]> },
expectedSlots: string[],
{ dateString, doExactMatch }: { dateString: string; doExactMatch: boolean }
) {
if (!schedule.slots[`${dateString}`]) {
return {
pass: false,
message: () => `has no timeslots for ${dateString}`,
};
}
if (
!schedule.slots[`${dateString}`]
.map((slot) => slot.time)
.every((actualSlotTime, index) => {
return `${dateString}T${expectedSlots[index]}` === actualSlotTime;
})
) {
return {
pass: false,
message: () =>
`has incorrect timeslots for ${dateString}.\n\r ${diff(
expectedSlots.map((expectedSlot) => `${dateString}T${expectedSlot}`),
schedule.slots[`${dateString}`].map((slot) => slot.time)
)}`,
};
}
if (doExactMatch) {
return {
pass: expectedSlots.length === schedule.slots[`${dateString}`].length,
message: () =>
`number of slots don't match for ${dateString}. Expected ${expectedSlots.length} but got ${
schedule.slots[`${dateString}`].length
}`,
};
}
return {
pass: true,
message: () => "has correct timeslots ",
};
},
toHaveNoTimeSlots(schedule: { slots: Record<string, Slot[]> }, { dateString }: { dateString: string }) {
if (!schedule.slots[`${dateString}`] || schedule.slots[`${dateString}`].length === 0) {
return {
pass: true,
message: () => `has no timeslots for ${dateString}`,
};
}
return {
pass: false,
message: () => `has timeslots for ${dateString}`,
};
},
});
export { expect } from "vitest";
@@ -0,0 +1,353 @@
import type { ScenarioData } from "../../utils/bookingScenario/bookingScenario";
import {
TestData,
Timezones,
getDate,
createBookingScenario,
} from "../../utils/bookingScenario/bookingScenario";
import { describe, expect, vi, test } from "vitest";
import { PeriodType } from "@calcom/prisma/enums";
import { getAvailableSlots as getSchedule } from "@calcom/trpc/server/routers/viewer/slots/util";
import { expectedSlotsForSchedule } from "./expects";
import { setupAndTeardown } from "./setupAndTeardown";
import { timeTravelToTheBeginningOfToday } from "./utils";
function getPeriodTypeData({
type,
periodDays,
periodCountCalendarDays,
periodStartDate,
periodEndDate,
}: {
type: PeriodType;
periodDays?: number;
periodCountCalendarDays?: boolean;
periodStartDate?: Date;
periodEndDate?: Date;
}) {
if (type === PeriodType.ROLLING) {
if (!periodCountCalendarDays || !periodDays) {
throw new Error("periodCountCalendarDays and periodDays are required for ROLLING period type");
}
return {
periodType: PeriodType.ROLLING,
periodDays,
periodCountCalendarDays,
};
}
if (type === PeriodType.ROLLING_WINDOW) {
if (!periodCountCalendarDays || !periodDays) {
throw new Error("periodCountCalendarDays and periodDays are required for ROLLING period type");
}
return {
periodType: PeriodType.ROLLING_WINDOW,
periodDays,
periodCountCalendarDays,
};
}
if (type === PeriodType.RANGE) {
if (!periodStartDate || !periodEndDate) {
throw new Error("periodStartDate and periodEndDate are required for RANGE period type");
}
return {
periodType: PeriodType.RANGE,
periodStartDate,
periodEndDate,
};
}
}
vi.mock("@calcom/lib/constants", () => ({
IS_PRODUCTION: true,
WEBAPP_URL: "http://localhost:3000",
RESERVED_SUBDOMAINS: ["auth", "docs"],
ROLLING_WINDOW_PERIOD_MAX_DAYS_TO_CHECK: 61,
}));
describe("getSchedule", () => {
setupAndTeardown();
describe("Future Limits", () => {
describe("PeriodType=ROLLING", () => {
test("Basic test", async () => {
const { dateString: yesterdayDateString } = getDate({ dateIncrement: -1 });
const { dateString: todayDateString } = getDate();
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
const { dateString: plus3DateString } = getDate({ dateIncrement: 3 });
const { dateString: plus4DateString } = getDate({ dateIncrement: 4 });
const { dateString: plus5DateString } = getDate({ dateIncrement: 5 });
timeTravelToTheBeginningOfToday({ utcOffsetInHours: 5.5 });
const scenarioData = {
eventTypes: [
{
id: 1,
length: 60,
...getPeriodTypeData({
type: "ROLLING",
periodDays: 2,
periodCountCalendarDays: true,
}),
users: [
{
id: 101,
},
],
},
],
users: [
{
...TestData.users.example,
id: 101,
schedules: [TestData.schedules.IstWorkHours],
},
],
} satisfies ScenarioData;
await createBookingScenario(scenarioData);
const scheduleForEvent = await getSchedule({
input: {
eventTypeId: 1,
eventTypeSlug: "",
usernameList: [],
// Because this time is in GMT, it will be 00:00 in IST with todayDateString
startTime: `${yesterdayDateString}T18:30:00.000Z`,
endTime: `${plus5DateString}T18:29:59.999Z`,
timeZone: Timezones["+5:30"],
isTeamEvent: false,
},
});
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: todayDateString,
doExactMatch: true,
}
);
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus1DateString,
doExactMatch: true,
}
);
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus2DateString,
doExactMatch: true,
}
);
// No Timeslots beyond plus2Date as that is beyond the rolling period
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus3DateString,
});
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus4DateString,
});
});
});
describe("PeriodType=ROLLING_WINDOW", () => {
test("Basic test", async () => {
const { dateString: yesterdayDateString } = getDate({ dateIncrement: -1 });
const { dateString: todayDateString } = getDate();
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
const { dateString: plus3DateString } = getDate({ dateIncrement: 3 });
const { dateString: plus4DateString } = getDate({ dateIncrement: 4 });
const { dateString: plus5DateString } = getDate({ dateIncrement: 5 });
timeTravelToTheBeginningOfToday({ utcOffsetInHours: 5.5 });
const scenarioData = {
eventTypes: [
{
id: 1,
length: 60,
...getPeriodTypeData({
type: "ROLLING_WINDOW",
periodDays: 3,
periodCountCalendarDays: true,
}),
users: [
{
id: 101,
},
],
},
],
users: [
{
...TestData.users.example,
id: 101,
schedules: [TestData.schedules.IstWorkHours],
},
],
bookings: [
{
userId: 101,
eventTypeId: 1,
status: "ACCEPTED",
// Fully book plus2 Date
startTime: `${plus1DateString}T18:30:00.000Z`,
endTime: `${plus2DateString}T18:30:00.000Z`,
},
],
} satisfies ScenarioData;
await createBookingScenario(scenarioData);
const scheduleForEvent = await getSchedule({
input: {
eventTypeId: 1,
eventTypeSlug: "",
usernameList: [],
// Because this time is in GMT, it will be 00:00 in IST with todayDateString
startTime: `${yesterdayDateString}T18:30:00.000Z`,
endTime: `${plus5DateString}T18:29:59.999Z`,
timeZone: Timezones["+5:30"],
isTeamEvent: false,
},
});
console.log({ scheduleForEvent });
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: todayDateString,
doExactMatch: true,
}
);
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus1DateString,
doExactMatch: true,
}
);
// plus2Date is fully booked. So, instead we will have timeslots one day later
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus2DateString,
});
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus3DateString,
doExactMatch: true,
}
);
// No Timeslots on plus4Date as beyond the rolling period
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus4DateString,
});
});
});
describe("PeriodType=RANGE", () => {
test("Basic test", async () => {
const { dateString: yesterdayDateString } = getDate({ dateIncrement: -1 });
const { dateString: todayDateString } = getDate();
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
const { dateString: plus3DateString } = getDate({ dateIncrement: 3 });
const { dateString: plus4DateString } = getDate({ dateIncrement: 4 });
const { dateString: plus5DateString } = getDate({ dateIncrement: 5 });
timeTravelToTheBeginningOfToday({ utcOffsetInHours: 5.5 });
const scenarioData = {
eventTypes: [
{
id: 1,
length: 60,
// Makes today and tomorrow only available
...getPeriodTypeData({
type: "RANGE",
// dayPlus1InIst
periodStartDate: new Date(`${todayDateString}T18:30:00.000Z`),
// datePlus2InIst
periodEndDate: new Date(`${plus1DateString}T18:30:00.000Z`),
periodCountCalendarDays: true,
}),
users: [
{
id: 101,
},
],
},
],
users: [
{
...TestData.users.example,
id: 101,
schedules: [TestData.schedules.IstWorkHours],
},
],
} satisfies ScenarioData;
await createBookingScenario(scenarioData);
const scheduleForEvent = await getSchedule({
input: {
eventTypeId: 1,
eventTypeSlug: "",
usernameList: [],
// Because this time is in GMT, it will be 00:00 in IST with todayDateString
startTime: `${yesterdayDateString}T18:30:00.000Z`,
endTime: `${plus5DateString}T18:29:59.999Z`,
timeZone: Timezones["+5:30"],
isTeamEvent: false,
},
});
console.log({ scheduleForEvent });
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: todayDateString,
});
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus1DateString,
doExactMatch: true,
}
);
expect(scheduleForEvent).toHaveTimeSlots(
expectedSlotsForSchedule["IstWorkHours"].interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus2DateString,
doExactMatch: true,
}
);
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus3DateString,
});
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus4DateString,
});
expect(scheduleForEvent).toHaveNoTimeSlots({
dateString: plus4DateString,
});
});
});
});
});
@@ -0,0 +1,24 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { vi, beforeEach, afterEach } from "vitest";
const cleanup = async () => {
await prismock.eventType.deleteMany();
await prismock.user.deleteMany();
await prismock.schedule.deleteMany();
await prismock.selectedCalendar.deleteMany();
await prismock.credential.deleteMany();
await prismock.booking.deleteMany();
await prismock.app.deleteMany();
vi.useRealTimers();
};
export function setupAndTeardown() {
beforeEach(async () => {
await cleanup();
});
afterEach(async () => {
await cleanup();
});
}
+16
View File
@@ -0,0 +1,16 @@
import { getDate } from "../../utils/bookingScenario/bookingScenario";
import { vi } from "vitest";
export function timeTravelToTheBeginningOfToday({ utcOffsetInHours = 0 }: { utcOffsetInHours: number }) {
const timeInTheUtcOffsetInHours = 24 - utcOffsetInHours;
const timeInTheUtcOffsetInMinutes = timeInTheUtcOffsetInHours * 60;
const hours = Math.floor(timeInTheUtcOffsetInMinutes / 60);
const hoursString = hours < 10 ? `0${hours}` : `${hours}`;
const minutes = timeInTheUtcOffsetInMinutes % 60;
const minutesString = minutes < 10 ? `0${minutes}` : `${minutes}`;
const { dateString: yesterdayDateString } = getDate({ dateIncrement: -1 });
console.log({ yesterdayDateString, hours, minutes });
vi.setSystemTime(`${yesterdayDateString}T${hoursString}:${minutesString}:00.000Z`);
}
@@ -6,7 +6,6 @@ import type { BookingReference, Attendee, Booking, Membership } from "@prisma/cl
import type { Prisma } from "@prisma/client";
import type { WebhookTriggerEvents } from "@prisma/client";
import type Stripe from "stripe";
import type { getMockRequestDataForBooking } from "test/utils/bookingScenario/getMockRequestDataForBooking";
import { v4 as uuidv4 } from "uuid";
import "vitest-fetch-mock";
import type { z } from "zod";
@@ -28,6 +27,7 @@ import type { NewCalendarEventType } from "@calcom/types/Calendar";
import type { EventBusyDate, IntervalLimit } from "@calcom/types/Calendar";
import { getMockPaymentService } from "./MockPaymentService";
import type { getMockRequestDataForBooking } from "./getMockRequestDataForBooking";
logger.settings.minLevel = 0;
const log = logger.getSubLogger({ prefix: ["[bookingScenario]"] });
@@ -812,6 +812,7 @@ export const TestData = {
},
schedules: {
IstWorkHours: {
id: 1,
name: "9:30AM to 6PM in India - 4:00AM to 12:30PM in GMT",
availability: [
{
@@ -1,5 +1,7 @@
import prismaMock from "../../../../../tests/libs/__mocks__/prisma";
import type { InputEventType, getOrganizer } from "./bookingScenario";
import type { WebhookTriggerEvents, Booking, BookingReference, DestinationCalendar } from "@prisma/client";
import { parse } from "node-html-parser";
import type { VEvent } from "node-ical";
@@ -16,7 +18,6 @@ import type { AppsStatus } from "@calcom/types/Calendar";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { Fixtures } from "@calcom/web/test/fixtures/fixtures";
import type { InputEventType, getOrganizer } from "./bookingScenario";
import { DEFAULT_TIMEZONE_BOOKER } from "./getMockRequestDataForBooking";
// This is too complex at the moment, I really need to simplify this.
@@ -1,6 +1,7 @@
import type { SchedulingType } from "@calcom/prisma/client";
import { getDate } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import type { SchedulingType } from "@calcom/prisma/client";
export const DEFAULT_TIMEZONE_BOOKER = "Asia/Kolkata";
export function getBasicMockRequestDataForBooking() {
return {
@@ -1,10 +1,10 @@
import { beforeEach, afterEach } from "vitest";
import {
enableEmailFeature,
mockNoTranslations,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { beforeEach, afterEach } from "vitest";
export function setupAndTeardown() {
beforeEach(() => {
// Required to able to generate token in email in some cases
+2 -1
View File
@@ -1,9 +1,10 @@
import { createOrganization } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import type { TestFunction } from "vitest";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { test } from "@calcom/web/test/fixtures/fixtures";
import type { Fixtures } from "@calcom/web/test/fixtures/fixtures";
import { createOrganization } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
const WEBSITE_PROTOCOL = new URL(WEBSITE_URL).protocol;
const _testWithAndWithoutOrg = (