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

@@ -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 = (