feat: Instant Meeting (#12345)

Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-12-19 11:01:42 -08:00
1 parent 6d5983fabc
commit 200ce6932d
42 files changed
+1328 -79

No files matched your search

+81 -16
View File
@@ -1,5 +1,6 @@
import { LazyMotion, m, AnimatePresence } from "framer-motion";
import dynamic from "next/dynamic";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef } from "react";
import StickyBox from "react-sticky-box";
import { shallow } from "zustand/shallow";
@@ -9,8 +10,10 @@ import dayjs from "@calcom/dayjs";
import { useEmbedType, useEmbedUiConfig, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { BookerLayouts, defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils";
import { AvatarGroup, Button } from "@calcom/ui";
import { AvailableTimeSlots } from "./components/AvailableTimeSlots";
import { BookEventForm } from "./components/BookEventForm";
@@ -46,6 +49,7 @@ const BookerComponent = ({
durationConfig,
duration,
hashedLink,
isInstantMeeting = false,
}: BookerProps) => {
/**
* Prioritize dateSchedule load
@@ -149,6 +153,7 @@ const BookerComponent = ({
isTeamEvent,
org: entity.orgSlug,
durationConfig,
isInstantMeeting,
});
useEffect(() => {
@@ -220,6 +225,13 @@ const BookerComponent = ({
return (
<>
{event.data ? <BookingPageTagManager eventType={event.data} /> : null}
{bookerState !== "booking" && event.data?.isInstantEvent && (
<div
className="animate-fade-in-up fixed bottom-2 z-40 my-2 opacity-0"
style={{ animationDelay: "2s" }}>
<InstantBooking />
</div>
)}
<div
className={classNames(
// In a popup embed, if someone clicks outside the main(having main class or main tag), it closes the embed
@@ -240,22 +252,24 @@ const BookerComponent = ({
!isEmbed && layout === BookerLayouts.MONTH_VIEW && "border-subtle"
)}>
<AnimatePresence>
<BookerSection
area="header"
className={classNames(
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
"bg-default dark:bg-muted sticky top-0 z-10"
)}>
<Header
username={username}
eventSlug={eventSlug}
enabledLayouts={bookerLayouts.enabledLayouts}
extraDays={layout === BookerLayouts.COLUMN_VIEW ? columnViewExtraDays.current : extraDays}
isMobile={isMobile}
nextSlots={nextSlots}
/>
</BookerSection>
{!isInstantMeeting && (
<BookerSection
area="header"
className={classNames(
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
"bg-default dark:bg-muted sticky top-0 z-10"
)}>
<Header
username={username}
eventSlug={eventSlug}
enabledLayouts={bookerLayouts.enabledLayouts}
extraDays={layout === BookerLayouts.COLUMN_VIEW ? columnViewExtraDays.current : extraDays}
isMobile={isMobile}
nextSlots={nextSlots}
/>
</BookerSection>
)}
<StickyOnDesktop
key="meta"
className={classNames(
@@ -367,3 +381,54 @@ export const Booker = (props: BookerProps) => {
</LazyMotion>
);
};
export const InstantBooking = () => {
const { t } = useLocale();
const router = useRouter();
const pathname = usePathname();
return (
<div className=" bg-default border-subtle mx-2 block items-center gap-3 rounded-xl border p-[6px] text-sm shadow-sm delay-1000 sm:flex">
<div className="flex items-center gap-3 ps-1">
{/* TODO: max. show 4 people here */}
<div className="relative">
<AvatarGroup
size="sm"
className="relative"
items={[
{
image: "https://cal.com/stakeholder/peer.jpg",
alt: "Peer",
title: "Peer Richelsen",
},
{
image: "https://cal.com/stakeholder/bailey.jpg",
alt: "Bailey",
title: "Bailey Pumfleet",
},
{
image: "https://cal.com/stakeholder/alex-van-andel.jpg",
alt: "Alex",
title: "Alex Van Andel",
},
]}
/>
<div className="border-muted absolute -bottom-0.5 -right-1 h-2 w-2 rounded-full border bg-green-500" />
</div>
<div>{t("dont_want_to_wait")}</div>
</div>
<div className="mt-2 sm:mt-0">
<Button
color="primary"
onClick={() => {
const newPath = `${pathname}?isInstantMeeting=true`;
router.push(newPath);
}}
size="sm"
className="w-full justify-center rounded-lg sm:w-auto">
{t("connect_now")}
</Button>
</div>
</div>
);
};
@@ -3,7 +3,7 @@ import type { UseMutationResult } from "@tanstack/react-query";
import { useMutation } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import type { TFunction } from "next-i18next";
import { useRouter, useSearchParams } from "next/navigation";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import type { FieldError } from "react-hook-form";
import { useForm } from "react-hook-form";
@@ -12,6 +12,7 @@ import { z } from "zod";
import type { EventLocationType } from "@calcom/app-store/locations";
import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
import dayjs from "@calcom/dayjs";
import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
import {
createBooking,
@@ -19,16 +20,20 @@ import {
mapBookingToMutationInput,
mapRecurringBookingToMutationInput,
useTimePreferences,
createInstantBooking,
} from "@calcom/features/bookings/lib";
import getBookingResponsesSchema, {
getBookingResponsesPartialSchema,
} from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import { Spinner } from "@calcom/features/calendars/weeklyview/components/spinner/Spinner";
import { getFullName } from "@calcom/features/form-builder/utils";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { MINUTES_TO_BOOK } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc";
import { Dialog, DialogContent } from "@calcom/ui";
import { Alert, Button, EmptyScreen, Form, showToast } from "@calcom/ui";
import { Calendar } from "@calcom/ui/components/icon";
@@ -65,6 +70,7 @@ export const BookEventForm = ({ onCancel, hashedLink }: BookEventFormProps) => {
const bookingData = useBookerStore((state) => state.bookingData);
const duration = useBookerStore((state) => state.selectedDuration);
const timeslot = useBookerStore((state) => state.selectedTimeslot);
const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
const isRescheduling = !!rescheduleUid && !!bookingData;
const eventQuery = useEvent();
const eventType = eventQuery.data;
@@ -115,6 +121,7 @@ export const BookEventForm = ({ onCancel, hashedLink }: BookEventFormProps) => {
eventQuery={eventQuery}
rescheduleUid={rescheduleUid}
hashedLink={hashedLink}
isInstantMeeting={isInstantMeeting}
/>
);
};
@@ -126,12 +133,14 @@ export const BookEventFormChild = ({
eventQuery,
rescheduleUid,
hashedLink,
isInstantMeeting,
}: BookEventFormProps & {
initialValues: DefaultValues;
isRescheduling: boolean;
eventQuery: ReturnType<typeof useEvent>;
rescheduleUid: string | null;
hashedLink?: string | null;
isInstantMeeting?: boolean;
}) => {
const eventType = eventQuery.data;
const bookingFormSchema = z
@@ -164,6 +173,8 @@ export const BookEventFormChild = ({
const timeslot = useBookerStore((state) => state.selectedTimeslot);
const recurringEventCount = useBookerStore((state) => state.recurringEventCount);
const username = useBookerStore((state) => state.username);
const [expiryTime, setExpiryTime] = useState<Date | undefined>();
type BookingFormValues = {
locationType?: EventLocationType["type"];
responses: z.infer<typeof bookingFormSchema>["responses"] | null;
@@ -230,6 +241,18 @@ export const BookEventFormChild = ({
},
});
const createInstantBookingMutation = useMutation(createInstantBooking, {
onSuccess: (responseData) => {
updateQueryParam("bookingId", responseData.bookingId);
setExpiryTime(responseData.expires);
},
onError: (err, _, ctx) => {
console.error("Error creating instant booking", err);
errorRef && errorRef.current?.scrollIntoView({ behavior: "smooth" });
},
});
const createRecurringBookingMutation = useMutation(createRecurringBooking, {
onSuccess: async (responseData) => {
const booking = responseData[0] || {};
@@ -344,7 +367,9 @@ export const BookEventFormChild = ({
hashedLink,
};
if (eventQuery.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) {
if (isInstantMeeting) {
createInstantBookingMutation.mutate(mapBookingToMutationInput(bookingInput));
} else if (eventQuery.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) {
createRecurringBookingMutation.mutate(
mapRecurringBookingToMutationInput(bookingInput, recurringEventCount)
);
@@ -384,6 +409,7 @@ export const BookEventFormChild = ({
/>
{(createBookingMutation.isError ||
createRecurringBookingMutation.isError ||
createInstantBookingMutation.isError ||
bookingForm.formState.errors["globalError"]) && (
<div data-testid="booking-fail">
<Alert
@@ -395,6 +421,7 @@ export const BookEventFormChild = ({
bookingForm.formState.errors["globalError"],
createBookingMutation,
createRecurringBookingMutation,
createInstantBookingMutation,
t,
responseVercelIdHeader
)}
@@ -402,22 +429,32 @@ export const BookEventFormChild = ({
</div>
)}
<div className="modalsticky mt-auto flex justify-end space-x-2 rtl:space-x-reverse">
{!!onCancel && (
<Button color="minimal" type="button" onClick={onCancel} data-testid="back">
{t("back")}
{isInstantMeeting ? (
<Button type="submit" color="primary" loading={createInstantBookingMutation.isLoading}>
{t("confirm")}
</Button>
) : (
<>
{!!onCancel && (
<Button color="minimal" type="button" onClick={onCancel} data-testid="back">
{t("back")}
</Button>
)}
<Button
type="submit"
color="primary"
loading={createBookingMutation.isLoading || createRecurringBookingMutation.isLoading}
data-testid={
rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"
}>
{rescheduleUid && bookingData
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? t("confirm")
: t("verify_email_email_button")}
</Button>
</>
)}
<Button
type="submit"
color="primary"
loading={createBookingMutation.isLoading || createRecurringBookingMutation.isLoading}
data-testid={rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"}>
{rescheduleUid && bookingData
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? t("confirm")
: t("verify_email_email_button")}
</Button>
</div>
</Form>
<VerifyCodeDialog
@@ -431,10 +468,74 @@ export const BookEventFormChild = ({
}}
isUserSessionRequiredToVerify={false}
/>
<RedirectToInstantMeetingModal expiryTime={expiryTime} />
</div>
);
};
const RedirectToInstantMeetingModal = ({ expiryTime }: { expiryTime?: Date }) => {
const { t } = useLocale();
const router = useRouter();
const pathname = usePathname();
const bookingId = parseInt(getQueryParam("bookingId") || "0");
const hasInstantMeetingTokenExpired = expiryTime && new Date(expiryTime) < new Date();
const instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery(
{
bookingId: bookingId,
},
{
enabled: !!bookingId && !hasInstantMeetingTokenExpired,
refetchInterval: 2000,
onSuccess: (data) => {
try {
showToast(t("something_went_wrong_on_our_end"), "error");
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
data.booking?.metadata || {}
)?.videoCallUrl;
if (locationVideoCallUrl) {
router.push(locationVideoCallUrl);
} else {
showToast(t("something_went_wrong_on_our_end"), "error");
}
} catch (err) {
showToast(t("something_went_wrong_on_our_end"), "error");
}
},
}
);
return (
<Dialog open={!!bookingId}>
<DialogContent enableOverflow className="py-8">
<div>
{hasInstantMeetingTokenExpired ? (
<div>
<p className="font-medium">{t("please_book_a_time_sometime_later")}</p>
<Button
className="mt-4"
onClick={() => {
window.location.href = pathname;
}}
color="primary">
{t("go_back")}
</Button>
</div>
) : (
<div>
<p className="font-medium">{t("connecting_you_to_someone")}</p>
<p className="font-medium">{t("please_do_not_close_this_tab")}</p>
<Spinner className="relative mt-8" />
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
const getError = (
globalError: FieldError | undefined,
// It feels like an implementation detail to reimplement the types of useMutation here.
@@ -444,12 +545,13 @@ const getError = (
bookingMutation: UseMutationResult<any, any, any, any>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recurringBookingMutation: UseMutationResult<any, any, any, any>,
createInstantBookingMutation: UseMutationResult<any, any, any, any>,
t: TFunction,
responseVercelIdHeader: string | null
) => {
if (globalError) return globalError.message;
const error = bookingMutation.error || recurringBookingMutation.error;
const error = bookingMutation.error || recurringBookingMutation.error || createInstantBookingMutation.error;
return error.message ? (
<>
@@ -2,6 +2,7 @@ import { useFormContext } from "react-hook-form";
import type { LocationObject } from "@calcom/app-store/locations";
import { getOrganizerInputLocationTypes } from "@calcom/app-store/locations";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import getLocationOptionsForSelect from "@calcom/features/bookings/lib/getLocationOptionsForSelect";
import { FormBuilderField } from "@calcom/features/form-builder/FormBuilderField";
@@ -27,12 +28,16 @@ export const BookingFields = ({
const { watch, setValue } = useFormContext();
const locationResponse = watch("responses.location");
const currentView = rescheduleUid ? "reschedule" : "";
const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
return (
// TODO: It might make sense to extract this logic into BookingFields config, that would allow to quickly configure system fields and their editability in fresh booking and reschedule booking view
// The logic here intends to make modifications to booking fields based on the way we want to specifically show Booking Form
<div>
{fields.map((field, index) => {
// Don't Display Location field in case of instant meeting as only Cal Video is supported
if (isInstantMeeting && field.name === "location") return null;
// During reschedule by default all system fields are readOnly. Make them editable on case by case basis.
// Allowing a system field to be edited might require sending emails to attendees, so we need to be careful
let readOnly =
@@ -27,6 +27,7 @@ type StoreInitializeType = {
seatReferenceUid?: string;
durationConfig?: number[] | null;
org?: string | null;
isInstantMeeting?: boolean;
};
type SeatedEventData = {
@@ -131,6 +132,8 @@ export type BookerStore = {
org?: string | null;
seatedEventData: SeatedEventData;
setSeatedEventData: (seatedEventData: SeatedEventData) => void;
isInstantMeeting?: boolean;
};
/**
@@ -225,6 +228,7 @@ export const useBookerStore = create<BookerStore>((set, get) => ({
isTeamEvent,
durationConfig,
org,
isInstantMeeting,
}: StoreInitializeType) => {
const selectedDateInStore = get().selectedDate;
@@ -270,6 +274,21 @@ export const useBookerStore = create<BookerStore>((set, get) => ({
// force clear this.
if (rescheduleUid && bookingData) set({ selectedTimeslot: null });
if (month) set({ month });
if (isInstantMeeting) {
const month = dayjs().format("YYYY-MM");
const selectedDate = dayjs().format("YYYY-MM-DD");
const selectedTimeslot = new Date().toISOString();
set({
month,
selectedDate,
selectedTimeslot,
isInstantMeeting,
});
updateQueryParam("month", month);
updateQueryParam("date", selectedDate ?? "");
updateQueryParam("slot", selectedTimeslot ?? "");
}
//removeQueryParam("layout");
},
durationConfig: null,
@@ -308,6 +327,7 @@ export const useInitializeBookerStore = ({
isTeamEvent,
durationConfig,
org,
isInstantMeeting,
}: StoreInitializeType) => {
const initializeStore = useBookerStore((state) => state.initialize);
useEffect(() => {
@@ -323,6 +343,7 @@ export const useInitializeBookerStore = ({
org,
verifiedEmail,
durationConfig,
isInstantMeeting,
});
}, [
initializeStore,
@@ -337,5 +358,6 @@ export const useInitializeBookerStore = ({
isTeamEvent,
verifiedEmail,
durationConfig,
isInstantMeeting,
]);
};
@@ -72,6 +72,7 @@ export interface BookerProps {
* Refers to the private link from event types page.
*/
hashedLink?: string | null;
isInstantMeeting?: boolean;
}
export type BookerState = "loading" | "selecting_date" | "selecting_time" | "booking";
@@ -112,6 +112,7 @@ export const EventMetaBlock = ({
export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: EventDetailsProps) => {
const { t } = useLocale();
const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
const isInstantMeeting = useBookerStore((store) => store.isInstantMeeting);
return (
<>
@@ -129,7 +130,7 @@ export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: Even
);
case EventDetailBlocks.LOCATION:
if (!event?.locations?.length) return null;
if (!event?.locations?.length || isInstantMeeting) return null;
return (
<EventMetaBlock key={block}>
<AvailableEventLocations locations={event.locations} />
@@ -0,0 +1,8 @@
import { post } from "@calcom/lib/fetch-wrapper";
import type { BookingCreateBody, InstatBookingResponse } from "../types";
export const createInstantBooking = async (data: BookingCreateBody) => {
const response = await post<BookingCreateBody, InstatBookingResponse>("/api/book/instant-event", data);
return response;
};
@@ -549,7 +549,7 @@ async function getOriginalRescheduledBooking(uid: string, seatsEventType?: boole
});
}
async function getBookingData({
export async function getBookingData({
req,
isNotAnApiCall,
eventType,
@@ -791,7 +791,7 @@ async function createBooking({
return prisma.booking.create(createBookingObj);
}
function getCustomInputsResponses(
export function getCustomInputsResponses(
reqBody: {
responses?: Record<string, object>;
customInputs?: z.infer<typeof bookingCreateSchemaLegacyPropsForApi>["customInputs"];
+1
View File
@@ -5,3 +5,4 @@ export {
} from "./book-event-form/booking-to-mutation-input-mapper";
export { createBooking } from "./create-booking";
export { createRecurringBooking } from "./create-recurring-booking";
export { createInstantBooking } from "./create-instant-booking";
+4
View File
@@ -32,3 +32,7 @@ export type RecurringBookingCreateBody = BookingCreateBody & {
export type BookingResponse = Awaited<
ReturnType<typeof import("@calcom/features/bookings/lib/handleNewBooking").default>
>;
export type InstatBookingResponse = Awaited<
ReturnType<typeof import("@calcom/features/instant-meeting/handleInstantMeeting").default>
>;
@@ -23,6 +23,7 @@ const eventClasses = cva(
PENDING: "bg-default text-emphasis border-[1px] border-dashed border-gray-900",
REJECTED: "",
CANCELLED: "",
AWAITING_HOST: "",
},
disabled: {
true: "hover:cursor-default",
@@ -37,6 +38,7 @@ const eventClasses = cva(
PENDING: "border-gray-900",
REJECTED: "border-gray-900",
CANCELLED: "border-gray-900",
AWAITING_HOST: "",
custom: "",
},
},
@@ -1,5 +1,11 @@
export const Spinner = () => (
<div className="fixed left-[calc(50%+calc(var(--booker-meta-width,0px)/2))] top-1/2 z-[80] h-10 w-10 -translate-x-1/2 -translate-y-1/2">
import { classNames } from "@calcom/lib";
export const Spinner = ({ className }: { className?: string }) => (
<div
className={classNames(
"fixed left-[calc(50%+calc(var(--booker-meta-width,0px)/2))] top-1/2 z-[80] h-10 w-10 -translate-x-1/2 -translate-y-1/2",
className
)}>
<svg className="h-10 w-10" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
className="fill-default"
@@ -27,6 +27,7 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
description: true,
eventName: true,
slug: true,
isInstantEvent: true,
schedulingType: true,
length: true,
locations: true,
@@ -190,6 +191,7 @@ export const getPublicEvent = async (
orgSlug: org,
name: unPublishedOrgUser?.organization?.name ?? null,
},
isInstantEvent: false,
};
}
@@ -251,6 +253,7 @@ export const getPublicEvent = async (
name: (event.owner?.organization?.name || event.team?.parent?.name || event.team?.name) ?? null,
},
isDynamic: false,
isInstantEvent: event.isInstantEvent,
};
};
@@ -0,0 +1,211 @@
import { Prisma } from "@prisma/client";
import { randomBytes } from "crypto";
import type { NextApiRequest } from "next";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { createInstantMeetingWithCalVideo } from "@calcom/core/videoClient";
import dayjs from "@calcom/dayjs";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import {
getEventTypesFromDB,
getBookingData,
getCustomInputsResponses,
} from "@calcom/features/bookings/lib/handleNewBooking";
import { getFullName } from "@calcom/features/form-builder/utils";
import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { WEBAPP_URL } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
const handleInstantMeetingWebhookTrigger = async (args: {
subscriberOptions: GetSubscriberOptions;
webhookData: Record<string, unknown>;
}) => {
try {
const eventTrigger = WebhookTriggerEvents.INSTANT_MEETING;
const subscribers = await getWebhooks(args.subscriberOptions);
const { webhookData } = args;
const promises = subscribers.map((sub) => {
sendGenericWebhookPayload({
secretKey: sub.secret,
triggerEvent: eventTrigger,
createdAt: new Date().toISOString(),
webhook: sub,
data: webhookData,
}).catch((e) => {
console.error(
`Error executing webhook for event: ${eventTrigger}, URL: ${sub.subscriberUrl}`,
sub,
e
);
});
});
await Promise.all(promises);
} catch (error) {
console.error("Error executing webhook", error);
logger.error("Error while sending webhook", error);
}
};
async function handler(req: NextApiRequest) {
let eventType = await getEventTypesFromDB(req.body.eventTypeId);
eventType = {
...eventType,
bookingFields: getBookingFieldsWithSystemFields(eventType),
};
if (!eventType.team?.id) {
throw new Error("Only Team Event Types are supported for Instant Meeting");
}
const reqBody = await getBookingData({
req,
isNotAnApiCall: true,
eventType,
});
const { email: bookerEmail, name: bookerName } = reqBody;
const translator = short();
const seed = `${reqBody.email}:${dayjs(reqBody.start).utc().format()}:${new Date().getTime()}`;
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
const customInputs = getCustomInputsResponses(reqBody, eventType.customInputs);
const attendeeTimezone = reqBody.timeZone;
const attendeeLanguage = reqBody.language;
const tAttendees = await getTranslation(attendeeLanguage ?? "en", "common");
const fullName = getFullName(bookerName);
const invitee = [
{
email: bookerEmail,
name: fullName,
timeZone: attendeeTimezone,
locale: attendeeLanguage ?? "en",
},
];
const guests = (reqBody.guests || []).reduce((guestArray, guest) => {
guestArray.push({
email: guest,
name: "",
timeZone: attendeeTimezone,
locale: "en",
});
return guestArray;
}, [] as typeof invitee);
const attendeesList = [...invitee, ...guests];
const calVideoMeeting = await createInstantMeetingWithCalVideo(dayjs.utc(reqBody.end).toISOString());
if (!calVideoMeeting) {
throw new Error("Cal Video Meeting Creation Failed");
}
eventType.team.id;
const bookingReferenceToCreate = [
{
type: calVideoMeeting.type,
uid: calVideoMeeting.id,
meetingId: calVideoMeeting.id,
meetingPassword: calVideoMeeting.password,
meetingUrl: calVideoMeeting.url,
},
];
// Create Partial
const newBookingData: Prisma.BookingCreateInput = {
uid,
responses: reqBody.responses === null ? Prisma.JsonNull : reqBody.responses,
title: tAttendees("instant_meeting_with_title", { name: invitee[0].name }),
startTime: dayjs.utc(reqBody.start).toDate(),
endTime: dayjs.utc(reqBody.end).toDate(),
description: reqBody.notes,
customInputs: isPrismaObjOrUndefined(customInputs),
status: BookingStatus.AWAITING_HOST,
references: {
create: bookingReferenceToCreate,
},
location: "integrations:daily",
eventType: {
connect: {
id: reqBody.eventTypeId,
},
},
metadata: { ...reqBody.metadata, videoCallUrl: `${WEBAPP_URL}/video/${uid}` },
attendees: {
createMany: {
data: attendeesList,
},
},
};
const createBookingObj = {
include: {
attendees: true,
},
data: newBookingData,
};
const newBooking = await prisma.booking.create(createBookingObj);
// Create Instant Meeting Token
const token = randomBytes(32).toString("hex");
const instantMeetingToken = await prisma.instantMeetingToken.create({
data: {
token,
expires: new Date(new Date().getTime() + 1000 * 60 * 5),
team: {
connect: {
id: eventType.team.id,
},
},
booking: {
connect: {
id: newBooking.id,
},
},
updatedAt: new Date().toISOString(),
},
});
// Trigger Webhook
const subscriberOptions: GetSubscriberOptions = {
userId: null,
eventTypeId: eventType.id,
triggerEvent: WebhookTriggerEvents.INSTANT_MEETING,
teamId: eventType.team.id,
};
const webhookData = {
triggerEvent: WebhookTriggerEvents.INSTANT_MEETING,
uid: newBooking.uid,
responses: newBooking.responses,
connectAndJoinUrl: `${WEBAPP_URL}/connect-and-join?token=${token}`,
eventTypeId: eventType.id,
eventTypeTitle: eventType.title,
customInputs: newBooking.customInputs,
};
await handleInstantMeetingWebhookTrigger({
subscriberOptions,
webhookData,
});
return {
message: "Success",
meetingTokenId: instantMeetingToken.id,
bookingId: newBooking.id,
expires: instantMeetingToken.expires,
};
}
export default handler;
@@ -41,6 +41,7 @@ const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP_V2: Record<string, WebhookTriggerEve
{ value: WebhookTriggerEvents.MEETING_ENDED, label: "meeting_ended" },
{ value: WebhookTriggerEvents.MEETING_STARTED, label: "meeting_started" },
{ value: WebhookTriggerEvents.RECORDING_READY, label: "recording_ready" },
{ value: WebhookTriggerEvents.INSTANT_MEETING, label: "instant_meeting_created" },
],
"routing-forms": [{ value: WebhookTriggerEvents.FORM_SUBMITTED, label: "form_submitted" }],
} as const;
@@ -71,7 +72,9 @@ const WebhookForm = (props: {
subscriberUrl: props.webhook?.subscriberUrl || "",
active: props.webhook ? props.webhook.active : true,
eventTriggers: !props.webhook
? translatedTriggerOptions.map((option) => option.value)
? translatedTriggerOptions
.filter((option) => option.value !== WebhookTriggerEvents.INSTANT_MEETING)
.map((option) => option.value)
: props.webhook.eventTriggers,
secret: props?.webhook?.secret || "",
payloadTemplate: props?.webhook?.payloadTemplate || undefined,
@@ -14,6 +14,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
WebhookTriggerEvents.BOOKING_REQUESTED,
WebhookTriggerEvents.BOOKING_REJECTED,
WebhookTriggerEvents.RECORDING_READY,
WebhookTriggerEvents.INSTANT_MEETING,
] as const,
"routing-forms": [WebhookTriggerEvents.FORM_SUBMITTED] as const,
};