Scheduling infrastructure for absolutely everyone.
feat: availability in instant meeting (#16424)
Udit Takkar6cd427bc7824
diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.jsonindex 51accb3d745..eee194cf973 100644--- a/apps/web/public/static/locales/en/common.json+++ b/apps/web/public/static/locales/en/common.json@@ -2201,6 +2201,7 @@"member_removed": "Member removed","my_availability": "My Availability","team_availability": "Team Availability",+ "instant_meeting_availability": "Instant meeting availability","backup_code": "Backup Code","backup_codes": "Backup Codes","backup_code_instructions": "Each backup code can be used exactly once to grant access without your authenticator.",diff --git a/apps/web/test/lib/handleChildrenEventTypes.test.ts b/apps/web/test/lib/handleChildrenEventTypes.test.tsindex afc0abe74fb..18b8c96001d 100644--- a/apps/web/test/lib/handleChildrenEventTypes.test.ts+++ b/apps/web/test/lib/handleChildrenEventTypes.test.ts@@ -143,6 +143,7 @@ describe("handleChildrenEventTypes", () => {users: { connect: [{ id: 4 }] },lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,+ instantMeetingScheduleId: undefined,bookingLimits: undefined,durationLimits: undefined,recurringEvent: undefined,@@ -199,6 +200,7 @@ describe("handleChildrenEventTypes", () => {scheduleId: null,lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,+ instantMeetingScheduleId: undefined,hashedLink: { create: { link: expect.any(String) } },},where: {@@ -304,6 +306,7 @@ describe("handleChildrenEventTypes", () => {recurringEvent: undefined,eventTypeColor: undefined,hashedLink: undefined,+ instantMeetingScheduleId: undefined,lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,userId: 4,@@ -357,6 +360,7 @@ describe("handleChildrenEventTypes", () => {locations: [],lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,+ instantMeetingScheduleId: undefined,},where: {userId_parentId: {@@ -421,6 +425,7 @@ describe("handleChildrenEventTypes", () => {recurringEvent: undefined,eventTypeColor: undefined,hashedLink: undefined,+ instantMeetingScheduleId: undefined,locations: [],lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,@@ -447,6 +452,7 @@ describe("handleChildrenEventTypes", () => {lockTimeZoneToggleOnBookingPage: false,requiresBookerEmailVerification: false,hashedLink: undefined,+ instantMeetingScheduleId: undefined,},where: {userId_parentId: {diff --git a/packages/features/bookings/Booker/Booker.tsx b/packages/features/bookings/Booker/Booker.tsxindex f06ef2852e7..bbc798d44d5 100644--- a/packages/features/bookings/Booker/Booker.tsx+++ b/packages/features/bookings/Booker/Booker.tsx@@ -439,7 +439,7 @@ const BookerComponent = ({}}/>- {bookerState !== "booking" && event.data?.isInstantEvent && (+ {bookerState !== "booking" && event.data?.showInstantEventConnectNowModal && (<divclassName={classNames("animate-fade-in-up z-40 my-2 opacity-0",diff --git a/packages/features/bookings/types.ts b/packages/features/bookings/types.tsindex 92163d29374..41eb8d24517 100644--- a/packages/features/bookings/types.ts+++ b/packages/features/bookings/types.ts@@ -51,7 +51,7 @@ export type BookerEvent = Pick<| "bookingFields"| "seatsShowAvailabilityCount"| "isInstantEvent"-> & { users: BookerEventUser[] } & { profile: BookerEventProfile };+> & { users: BookerEventUser[]; showInstantEventConnectNowModal: boolean } & { profile: BookerEventProfile };export type ValidationErrors<T extends object> = { key: FieldPath<T>; error: ErrorOption }[];diff --git a/packages/features/eventtypes/components/EventType.tsx b/packages/features/eventtypes/components/EventType.tsxindex 9b2ffe46473..9b5180f9853 100644--- a/packages/features/eventtypes/components/EventType.tsx+++ b/packages/features/eventtypes/components/EventType.tsx@@ -210,6 +210,7 @@ export const EventType = (props: EventTypeSetupProps & { allActiveWorkflows?: WoinstantMeetingExpiryTimeOffsetInSeconds: eventType.instantMeetingExpiryTimeOffsetInSeconds,description: eventType.description ?? undefined,schedule: eventType.schedule || undefined,+ instantMeetingSchedule: eventType.instantMeetingSchedule || undefined,bookingLimits: eventType.bookingLimits || undefined,onlyShowFirstAvailableSlot: eventType.onlyShowFirstAvailableSlot || undefined,durationLimits: eventType.durationLimits || undefined,diff --git a/packages/features/eventtypes/components/tabs/instant/InstantEventController.tsx b/packages/features/eventtypes/components/tabs/instant/InstantEventController.tsxindex d498e7f1181..aea168004a3 100644--- a/packages/features/eventtypes/components/tabs/instant/InstantEventController.tsx+++ b/packages/features/eventtypes/components/tabs/instant/InstantEventController.tsx@@ -2,10 +2,12 @@ import type { Webhook } from "@prisma/client";import { useSession } from "next-auth/react";import { useState } from "react";import { useFormContext, Controller } from "react-hook-form";+import { components } from "react-select";+import type { OptionProps, SingleValueProps } from "react-select";import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";-import type { EventTypeSetup, FormValues } from "@calcom/features/eventtypes/lib/types";+import type { EventTypeSetup, FormValues, AvailabilityOption } from "@calcom/features/eventtypes/lib/types";import { WebhookForm } from "@calcom/features/webhooks/components";import type { WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";@@ -24,6 +26,8 @@ import {showToast,TextField,Label,+ Select,+ Badge,} from "@calcom/ui";type InstantEventControllerProps = {@@ -32,6 +36,36 @@ type InstantEventControllerProps = {isTeamEvent: boolean;};+const Option = ({ ...props }: OptionProps<AvailabilityOption>) => {+ const { label, isDefault } = props.data;+ const { t } = useLocale();+ return (+ <components.Option {...props}>+ <span>{label}</span>+ {isDefault && (+ <Badge variant="blue" className="ml-2">+ {t("default")}+ </Badge>+ )}+ </components.Option>+ );+};++const SingleValue = ({ ...props }: SingleValueProps<AvailabilityOption>) => {+ const { label, isDefault } = props.data;+ const { t } = useLocale();+ return (+ <components.SingleValue {...props}>+ <span>{label}</span>+ {isDefault && (+ <Badge variant="blue" className="ml-2">+ {t("default")}+ </Badge>+ )}+ </components.SingleValue>+ );+};+export default function InstantEventController({eventType,paymentEnabled,@@ -42,13 +76,28 @@ export default function InstantEventController({const [instantEventState, setInstantEventState] = useState<boolean>(eventType?.isInstantEvent ?? false);const formMethods = useFormContext<FormValues>();- const { shouldLockDisableProps } = useLockedFieldsManager({ eventType, translate: t, formMethods });+ const { shouldLockDisableProps } = useLockedFieldsManager({+ eventType,+ translate: t,+ formMethods,+ });const instantLocked = shouldLockDisableProps("isInstantEvent");const isOrg = !!session.data?.user?.org?.id;- if (session.status === "loading") return <></>;+ const { data, isPending } = trpc.viewer.availability.list.useQuery(undefined);++ if (session.status === "loading" || isPending || !data) return <></>;++ const schedules = data.schedules;++ const options = schedules.map((schedule) => ({+ value: schedule.id,+ label: schedule.name,+ isDefault: schedule.isDefault,+ isManaged: false,+ }));return (<LicenseRequired>@@ -96,6 +145,32 @@ export default function InstantEventController({<div className="border-subtle rounded-b-lg border border-t-0 p-6">{instantEventState && (<div className="flex flex-col gap-2">+ <Controller+ name="instantMeetingSchedule"+ render={({ field: { onChange, value } }) => {+ const optionValue: AvailabilityOption | undefined = options.find(+ (option) => option.value === value+ );+ return (+ <>+ <Label>{t("instant_meeting_availability")}</Label>+ <Select+ placeholder={t("select")}+ options={options}+ isDisabled={shouldLockDisableProps("instantMeetingSchedule").disabled}+ isSearchable={false}+ onChange={(selected) => {+ if (selected) onChange(selected.value);+ }}+ className="mb-4 block w-full min-w-0 flex-1 rounded-sm text-sm"+ value={optionValue}+ components={{ Option, SingleValue }}+ isMulti={false}+ />+ </>+ );+ }}+ /><Controllername="instantMeetingExpiryTimeOffsetInSeconds"render={({ field: { value, onChange } }) => (diff --git a/packages/features/eventtypes/lib/getPublicEvent.ts b/packages/features/eventtypes/lib/getPublicEvent.tsindex 68ae1973dc5..78b491de4d7 100644--- a/packages/features/eventtypes/lib/getPublicEvent.ts+++ b/packages/features/eventtypes/lib/getPublicEvent.ts@@ -4,6 +4,7 @@ import { Prisma } from "@prisma/client";import type { LocationObject } from "@calcom/app-store/locations";import { privacyFilteredLocations } from "@calcom/app-store/locations";import { getAppFromSlug } from "@calcom/app-store/utils";+import dayjs from "@calcom/dayjs";import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";import { isRecurringEvent, parseRecurringEvent } from "@calcom/lib";@@ -120,11 +121,84 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({timeZone: true,},},+ instantMeetingSchedule: {+ select: {+ id: true,+ timeZone: true,+ },+ },+hidden: true,assignAllTeamMembers: true,rescheduleWithSameRoundRobinHost: true,});+export async function isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId,+ availabilityTimezone,+ length,+}: {+ prisma: PrismaClient;+ instantMeetingScheduleId: number;+ availabilityTimezone: string;+ length: number;+}): Promise<boolean> {+ const now = dayjs().tz(availabilityTimezone);+ const currentDay = now.day();+ const meetingEndTime = now.add(length, "minute");++ const res = await prisma.schedule.findUniqueOrThrow({+ where: {+ id: instantMeetingScheduleId,+ },+ select: {+ availability: true,+ },+ });++ const dateOverride = res.availability.find((a) => a.date && dayjs(a.date).isSame(now, "day"));++ if (dateOverride) {+ return !isAvailableInTimeSlot(dateOverride, now, meetingEndTime);+ }++ for (const availability of res.availability) {+ if (!availability.date && availability.days.includes(currentDay)) {+ const isAvailable = isAvailableInTimeSlot(availability, now, meetingEndTime);+ if (isAvailable) {+ return true;+ }+ }+ }++ return false;+}++function isAvailableInTimeSlot(+ availability: { startTime: Date; endTime: Date; days: number[] },+ now: dayjs.Dayjs,+ meetingEndTime: dayjs.Dayjs+): boolean {+ const startTime = dayjs(availability.startTime).utc().format("HH:mm");+ const endTime = dayjs(availability.endTime).utc().format("HH:mm");++ const periodStart = now+ .startOf("day")+ .hour(parseInt(startTime.split(":")[0]))+ .minute(parseInt(startTime.split(":")[1]));+ const periodEnd = now+ .startOf("day")+ .hour(parseInt(endTime.split(":")[0]))+ .minute(parseInt(endTime.split(":")[1]));++ const isWithinPeriod =+ now.isBetween(periodStart, periodEnd, null, "[)") &&+ meetingEndTime.isBetween(periodStart, periodEnd, null, "(]");++ return isWithinPeriod;+}+// TODO: Convert it to accept a single parameter with structured dataexport const getPublicEvent = async (username: string,@@ -216,6 +290,7 @@ export const getPublicEvent = async (logoUrl: null,},isInstantEvent: false,+ showInstantEventConnectNowModal: false,};}@@ -334,6 +409,20 @@ export const getPublicEvent = async (},});}++ let showInstantEventConnectNowModal = eventWithUserProfiles.isInstantEvent;++ if (eventWithUserProfiles.isInstantEvent && eventWithUserProfiles.instantMeetingSchedule?.id) {+ const { id, timeZone } = eventWithUserProfiles.instantMeetingSchedule;++ showInstantEventConnectNowModal = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: id,+ availabilityTimezone: timeZone ?? "Europe/London",+ length: eventWithUserProfiles.length,+ });+ }+return {...eventWithUserProfiles,bookerLayouts: bookerLayoutsSchema.parse(eventMetaData?.bookerLayouts || null),@@ -372,6 +461,7 @@ export const getPublicEvent = async (isDynamic: false,isInstantEvent: eventWithUserProfiles.isInstantEvent,+ showInstantEventConnectNowModal,aiPhoneCallConfig: eventWithUserProfiles.aiPhoneCallConfig,assignAllTeamMembers: event.assignAllTeamMembers,};diff --git a/packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts b/packages/features/eventtypes/lib/isCurrentlyAvailable.test.tsnew file mode 100644index 00000000000..77c6cec7283--- /dev/null+++ b/packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts@@ -0,0 +1,134 @@+import { PrismaClient } from "@prisma/client";+import { describe, it, expect, vi, beforeAll } from "vitest";++import { isCurrentlyAvailable } from "./getPublicEvent";++const prisma = new PrismaClient();++beforeAll(() => {+ vi.setSystemTime(new Date("2024-09-01T10:00:00Z"));+});++describe("isCurrentlyAvailable", () => {+ it("should return true if the current time is within the availability period", async () => {+ const mockAvailability = [+ {+ startTime: new Date("1970-01-01T09:00:00Z"),+ endTime: new Date("1970-01-01T17:00:00Z"),+ days: [0, 1, 2, 3, 4, 5, 6],+ },+ ];++ vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({+ availability: mockAvailability,+ });++ const result = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: 1,+ availabilityTimezone: "Europe/London",+ length: 30,+ });++ expect(result).toBe(true);+ });++ it("should return false if the current time is outside the availability period", async () => {+ const mockAvailability = [+ {+ startTime: new Date("1970-01-01T09:00:00Z"),+ endTime: new Date("1970-01-01T17:00:00Z"),+ days: [1, 2, 3, 4, 5],+ },+ ];++ vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({+ availability: mockAvailability,+ });++ const result = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: 1,+ availabilityTimezone: "Europe/London",+ length: 30,+ });++ expect(result).toBe(false);+ });++ it("should return false if there is no availability for the current day", async () => {+ const mockAvailability = [+ {+ startTime: new Date("1970-01-01T12:00:00Z"),+ endTime: new Date("1970-01-01T17:00:00Z"),+ days: [0],+ },+ ];++ vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({+ availability: mockAvailability,+ });++ const result = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: 1,+ availabilityTimezone: "Europe/London",+ length: 30,+ });++ expect(result).toBe(false);+ });++ it("should return false if the meeting end time is outside the availability period", async () => {+ const mockAvailability = [+ {+ startTime: new Date("1970-01-01T09:00:00Z"),+ endTime: new Date("1970-01-01T17:00:00Z"),+ days: [1, 2, 3, 4, 5],+ },+ ];++ vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({+ availability: mockAvailability,+ });++ const result = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: 1,+ availabilityTimezone: "Europe/London",+ length: 60,+ });++ expect(result).toBe(false);+ });++ it("should return false when there's an override blocking availability", async () => {+ const mockAvailability = [+ {+ startTime: new Date("1970-01-01T00:00:00Z"),+ endTime: new Date("1970-01-01T23:59:59Z"),+ days: [0, 1, 2, 3, 4, 5, 6],+ },+ // Date-specific override+ {+ date: new Date("2024-09-01"),+ startTime: new Date("2024-09-01T09:00:00Z"),+ endTime: new Date("2024-09-01T17:00:00Z"),+ days: [],+ },+ ];++ vi.spyOn(prisma.schedule, "findUniqueOrThrow").mockResolvedValue({+ availability: mockAvailability,+ });++ const result = await isCurrentlyAvailable({+ prisma,+ instantMeetingScheduleId: 1,+ availabilityTimezone: "Europe/London",+ length: 30,+ });++ expect(result).toBe(false);+ });+});diff --git a/packages/lib/event-types/getEventTypeById.ts b/packages/lib/event-types/getEventTypeById.tsindex af60ac6eb17..935284697b8 100644--- a/packages/lib/event-types/getEventTypeById.ts+++ b/packages/lib/event-types/getEventTypeById.ts@@ -104,6 +104,7 @@ export const getEventTypeById = async ({const eventType = {...restEventType,schedule: rawEventType.schedule?.id || rawEventType.users[0]?.defaultScheduleId || null,+ instantMeetingSchedule: rawEventType.instantMeetingSchedule?.id || null,scheduleName: rawEventType.schedule?.name || null,recurringEvent: parseRecurringEvent(restEventType.recurringEvent),bookingLimits: parseBookingLimit(restEventType.bookingLimits),diff --git a/packages/lib/server/eventTypeSelect.ts b/packages/lib/server/eventTypeSelect.tsindex 4b91e0e833a..52032041c99 100644--- a/packages/lib/server/eventTypeSelect.ts+++ b/packages/lib/server/eventTypeSelect.ts@@ -36,6 +36,7 @@ export const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({seatsShowAttendees: true,seatsShowAvailabilityCount: true,scheduleId: true,+ instantMeetingScheduleId: true,price: true,currency: true,slotInterval: true,diff --git a/packages/lib/server/repository/eventType.ts b/packages/lib/server/repository/eventType.tsindex 645088ce116..24ceec5a7d8 100644--- a/packages/lib/server/repository/eventType.ts+++ b/packages/lib/server/repository/eventType.ts@@ -521,6 +521,12 @@ export class EventTypeRepository {name: true,},},+ instantMeetingSchedule: {+ select: {+ id: true,+ name: true,+ },+ },hosts: {select: {isFixed: true,diff --git a/packages/lib/test/builder.ts b/packages/lib/test/builder.tsindex f028e793bf8..8112b4b82c7 100644--- a/packages/lib/test/builder.ts+++ b/packages/lib/test/builder.ts@@ -86,6 +86,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {position: 1,isInstantEvent: false,instantMeetingExpiryTimeOffsetInSeconds: 90,+ instantMeetingScheduleId: null,locations: null,length: 15,offsetStart: 0,diff --git a/packages/prisma/migrations/20240830084943_add_instant_meeting_schedule/migration.sql b/packages/prisma/migrations/20240830084943_add_instant_meeting_schedule/migration.sqlnew file mode 100644index 00000000000..ce3657696ac--- /dev/null+++ b/packages/prisma/migrations/20240830084943_add_instant_meeting_schedule/migration.sql@@ -0,0 +1,5 @@+-- AlterTable+ALTER TABLE "EventType" ADD COLUMN "instantMeetingScheduleId" INTEGER;++-- AddForeignKey+ALTER TABLE "EventType" ADD CONSTRAINT "EventType_instantMeetingScheduleId_fkey" FOREIGN KEY ("instantMeetingScheduleId") REFERENCES "Schedule"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex d2abafed005..bf78dd7d7ec 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -138,6 +138,8 @@ model EventType {durationLimits Json?isInstantEvent Boolean @default(false)instantMeetingExpiryTimeOffsetInSeconds Int @default(90)+ instantMeetingScheduleId Int?+ instantMeetingSchedule Schedule? @relation("InstantMeetingSchedule", fields: [instantMeetingScheduleId], references: [id])assignAllTeamMembers Boolean @default(false)useEventTypeDestinationCalendarEmail Boolean @default(false)aiPhoneCallConfig AIPhoneCallConfiguration?@@ -622,13 +624,14 @@ model Booking {}model Schedule {- id Int @id @default(autoincrement())- user User @relation(fields: [userId], references: [id], onDelete: Cascade)- userId Int- eventType EventType[]- name String- timeZone String?- availability Availability[]+ id Int @id @default(autoincrement())+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ userId Int+ eventType EventType[]+ instantMeetingEvents EventType[] @relation("InstantMeetingSchedule")+ name String+ timeZone String?+ availability Availability[]@@index([userId])}diff --git a/packages/trpc/server/routers/viewer/eventTypes/duplicate.handler.ts b/packages/trpc/server/routers/viewer/eventTypes/duplicate.handler.tsindex 13037254d58..b26b7abe08c 100644--- a/packages/trpc/server/routers/viewer/eventTypes/duplicate.handler.ts+++ b/packages/trpc/server/routers/viewer/eventTypes/duplicate.handler.ts@@ -90,6 +90,7 @@ export const duplicateHandler = async ({ ctx, input }: DuplicateOptions) => {// @ts-ignore - descriptionAsSafeHTML is added on the fly using a prisma middleware it shouldn't be used to create event type. Such a property doesn't exist on schemadescriptionAsSafeHTML: _descriptionAsSafeHTML,secondaryEmailId,+ instantMeetingScheduleId: _instantMeetingScheduleId,...rest} = eventType;diff --git a/packages/trpc/server/routers/viewer/eventTypes/types.ts b/packages/trpc/server/routers/viewer/eventTypes/types.tsindex a44a209fb02..fbea40b40cd 100644--- a/packages/trpc/server/routers/viewer/eventTypes/types.ts+++ b/packages/trpc/server/routers/viewer/eventTypes/types.ts@@ -61,6 +61,7 @@ export const EventTypeUpdateInput = _EventTypeModel).optional(),schedule: z.number().nullable().optional(),+ instantMeetingSchedule: z.number().nullable().optional(),hashedLink: z.string(),assignAllTeamMembers: z.boolean().optional(),isRRWeightsEnabled: z.boolean().optional(),diff --git a/packages/trpc/server/routers/viewer/eventTypes/update.handler.ts b/packages/trpc/server/routers/viewer/eventTypes/update.handler.tsindex 3ff14339aa8..f1ceb7ec474 100644--- a/packages/trpc/server/routers/viewer/eventTypes/update.handler.ts+++ b/packages/trpc/server/routers/viewer/eventTypes/update.handler.ts@@ -51,6 +51,7 @@ export type UpdateEventTypeReturn = Awaited<ReturnType<typeof updateHandler>>;export const updateHandler = async ({ ctx, input }: UpdateOptions) => {const {schedule,+ instantMeetingSchedule,periodType,locations,bookingLimits,@@ -231,6 +232,18 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {};}+ if (instantMeetingSchedule) {+ data.instantMeetingSchedule = {+ connect: {+ id: instantMeetingSchedule,+ },+ };+ } else if (schedule === null) {+ data.instantMeetingSchedule = {+ disconnect: true,+ };+ }+if (users?.length) {data.users = {set: [],