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

@@ -0,0 +1,18 @@
import type { EventTypeSetupProps } from "pages/event-types/[type]";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import InstantEventController from "./InstantEventController";
export const EventInstantTab = ({
eventType,
isTeamEvent,
}: Pick<EventTypeSetupProps, "eventType"> & { isTeamEvent: boolean }) => {
const paymentAppData = getPaymentAppData(eventType);
const requirePayment = paymentAppData.price > 0;
return (
<InstantEventController paymentEnabled={requirePayment} eventType={eventType} isTeamEvent={isTeamEvent} />
);
};
@@ -214,6 +214,14 @@ function EventTypeSingleLayout({
}
const showWebhooks = !(isManagedEventType || isChildrenManagedEventType);
if (showWebhooks) {
if (team) {
navigation.push({
name: "instant_tab_title",
href: `/event-types/${eventType.id}?tabName=instant`,
icon: Zap,
info: `instant_event_tab_description`,
});
}
navigation.push({
name: "webhooks",
href: `/event-types/${eventType.id}?tabName=webhooks`,
@@ -0,0 +1,99 @@
import { useSession } from "next-auth/react";
import type { EventTypeSetup, FormValues } from "pages/event-types/[type]";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert, Button, EmptyScreen, SettingsToggle } from "@calcom/ui";
import { Zap } from "@calcom/ui/components/icon";
type InstantEventControllerProps = {
eventType: EventTypeSetup;
paymentEnabled: boolean;
isTeamEvent: boolean;
};
export default function InstantEventController({
eventType,
paymentEnabled,
isTeamEvent,
}: InstantEventControllerProps) {
const { t } = useLocale();
const session = useSession();
const [instantEventState, setInstantEventState] = useState<boolean>(eventType?.isInstantEvent ?? false);
const formMethods = useFormContext<FormValues>();
const { shouldLockDisableProps } = useLockedFieldsManager(
eventType,
t("locked_fields_admin_description"),
t("locked_fields_member_description")
);
const instantLocked = shouldLockDisableProps("isInstantEvent");
const isOrg = !!session.data?.user?.org?.id;
if (session.status === "loading") return <></>;
return (
<LicenseRequired>
<div className="block items-start sm:flex">
{!isOrg || !isTeamEvent ? (
<EmptyScreen
headline={t("instant_tab_title")}
Icon={Zap}
description={t("uprade_to_create_instant_bookings")}
buttonRaw={<Button href="/enterprise">{t("upgrade")}</Button>}
/>
) : (
<div className={!paymentEnabled ? "w-full" : ""}>
{paymentEnabled ? (
<Alert severity="warning" title={t("warning_payment_instant_meeting_event")} />
) : (
<>
<Alert
className="mb-4"
severity="warning"
title={t("warning_instant_meeting_experimental")}
/>
<SettingsToggle
labelClassName="text-sm"
toggleSwitchAtTheEnd={true}
switchContainerClassName={classNames(
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
instantEventState && "rounded-b-none"
)}
childrenClassName="lg:ml-0"
title={t("instant_tab_title")}
{...instantLocked}
description={t("instant_event_tab_description")}
checked={instantEventState}
data-testid="instant-event-check"
onCheckedChange={(e) => {
if (!e) {
formMethods.setValue("isInstantEvent", false);
setInstantEventState(false);
} else {
formMethods.setValue("isInstantEvent", true);
setInstantEventState(true);
}
}}>
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
{instantEventState && (
<div data-testid="instant-event-collapsible" className="flex flex-col gap-2 text-sm">
<p>{t("warning_payment_instant_meeting_event")}</p>
</div>
)}
</div>
</SettingsToggle>
</>
)}
</div>
)}
</div>
</LicenseRequired>
);
}
+22
View File
@@ -0,0 +1,22 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import handleInstantMeeting from "@calcom/features/instant-meeting/handleInstantMeeting";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { defaultResponder } from "@calcom/lib/server";
async function handler(req: NextApiRequest & { userId?: number }, res: NextApiResponse) {
const userIp = getIP(req);
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `instant.event-${userIp}`,
});
const session = await getServerSession({ req, res });
req.userId = session?.user?.id || -1;
const booking = await handleInstantMeeting(req);
return booking;
}
export default defaultResponder(handler);
+92
View File
@@ -0,0 +1,92 @@
import { useSession } from "next-auth/react";
import { Trans } from "next-i18next";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { TRPCClientError } from "@calcom/trpc/react";
import { Button, EmptyScreen, Alert } from "@calcom/ui";
import { Zap } from "@calcom/ui/components/icon";
import PageWrapper from "@components/PageWrapper";
function ConnectAndJoin() {
const { t } = useLocale();
const router = useRouter();
const token = getQueryParam("token");
const [meetingUrl, setMeetingUrl] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | undefined>();
const session = useSession();
const isUserPartOfOrg = session.status === "authenticated" && !!session.data.user?.org;
const mutation = trpc.viewer.connectAndJoin.useMutation({
onSuccess: (res) => {
if (res.meetingUrl && !res.isBookingAlreadyAcceptedBySomeoneElse) {
router.push(res.meetingUrl);
} else if (res.isBookingAlreadyAcceptedBySomeoneElse && res.meetingUrl) {
setMeetingUrl(res.meetingUrl);
}
},
onError: (err) => {
console.log("err", err, err instanceof TRPCClientError);
if (err instanceof TRPCClientError) {
setErrorMessage(t(err.message));
} else {
setErrorMessage(t("something_went_wrong"));
}
},
});
if (session.status === "loading") return <p>{t("loading")}</p>;
if (!token) return <p>{t("token_not_found")}</p>;
return (
<div className="mx-8 mt-12 block items-start sm:flex">
{session ? (
<EmptyScreen
headline={t("instant_tab_title")}
Icon={Zap}
description={t("uprade_to_create_instant_bookings")}
buttonRaw={
<div className="flex flex-col items-center justify-center gap-4">
{meetingUrl ? (
<div className="text-default flex flex-col items-center gap-2 text-center text-sm font-normal">
<Trans i18nKey="some_other_host_already_accepted_the_meeting">
Some other host already accepted the meeting. Do you still want to join?
<Link className="inline-block cursor-pointer underline" href={meetingUrl}>
Continue to Meeting Url
</Link>
</Trans>
</div>
) : (
<Button
loading={mutation.isLoading}
tooltip={isUserPartOfOrg ? t("join_meeting") : t("not_part_of_org")}
disabled={!isUserPartOfOrg}
onClick={() => {
mutation.mutate({ token });
}}>
{t("join_meeting")}
</Button>
)}
{errorMessage && <Alert severity="error" message={errorMessage} />}
</div>
}
/>
) : (
<div>{t("you_must_be_logged_in_to", { url: WEBAPP_URL })}</div>
)}
</div>
);
}
ConnectAndJoin.requiresLicense = true;
ConnectAndJoin.PageWrapper = PageWrapper;
export default ConnectAndJoin;
@@ -63,6 +63,10 @@ const EventAdvancedTab = dynamic(() =>
import("@components/eventtype/EventAdvancedTab").then((mod) => mod.EventAdvancedTab)
);
const EventInstantTab = dynamic(() =>
import("@components/eventtype/EventInstantTab").then((mod) => mod.EventInstantTab)
);
const EventRecurringTab = dynamic(() =>
import("@components/eventtype/EventRecurringTab").then((mod) => mod.EventRecurringTab)
);
@@ -84,6 +88,7 @@ export type FormValues = {
eventTitle: string;
eventName: string;
slug: string;
isInstantEvent: boolean;
length: number;
offsetStart: number;
description: string;
@@ -149,6 +154,7 @@ const querySchema = z.object({
"availability",
"apps",
"limits",
"instant",
"recurring",
"team",
"advanced",
@@ -248,6 +254,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
title: eventType.title,
locations: eventType.locations || [],
recurringEvent: eventType.recurringEvent || null,
isInstantEvent: eventType.isInstantEvent,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
@@ -410,6 +417,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
team: <EventTeamTab teamMembers={teamMembers} team={team} eventType={eventType} />,
limits: <EventLimitsTab eventType={eventType} />,
advanced: <EventAdvancedTab eventType={eventType} team={team} />,
instant: <EventInstantTab eventType={eventType} isTeamEvent={!!team} />,
recurring: <EventRecurringTab eventType={eventType} />,
apps: <EventAppsTab eventType={{ ...eventType, URL: permalink }} />,
workflows: (
@@ -0,0 +1,121 @@
import type { GetServerSidePropsContext } from "next";
import { z } from "zod";
import { Booker } from "@calcom/atoms";
import { getBookerWrapperClasses } from "@calcom/features/bookings/Booker/utils/getBookerWrapperClasses";
import { BookerSeo } from "@calcom/features/bookings/components/BookerSeo";
import { getMultipleDurationValue } from "@calcom/features/bookings/lib/get-booking";
import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import type { EmbedProps } from "@lib/withEmbedSsr";
import PageWrapper from "@components/PageWrapper";
export type PageProps = inferSSRProps<typeof getServerSideProps> & EmbedProps;
export default function Type({
slug,
user,
booking,
away,
isEmbed,
isBrandingHidden,
entity,
duration,
}: PageProps) {
return (
<main className={getBookerWrapperClasses({ isEmbed: !!isEmbed })}>
<BookerSeo
username={user}
eventSlug={slug}
rescheduleUid={undefined}
hideBranding={isBrandingHidden}
isTeamEvent
entity={entity}
bookingData={booking}
/>
<Booker
username={user}
eventSlug={slug}
bookingData={booking}
isAway={away}
hideBranding={isBrandingHidden}
isTeamEvent
isInstantMeeting
entity={entity}
duration={duration}
/>
</main>
);
}
const paramsSchema = z.object({
type: z.string().transform((s) => slugify(s)),
slug: z.string().transform((s) => slugify(s)),
});
Type.PageWrapper = PageWrapper;
Type.isBookingPage = true;
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const { slug: teamSlug, type: meetingSlug } = paramsSchema.parse(context.params);
const { duration: queryDuration } = context.query;
const { ssrInit } = await import("@server/lib/ssr");
const ssr = await ssrInit(context);
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req, context.params?.orgSlug);
const team = await prisma.team.findFirst({
where: {
...getSlugOrRequestedSlug(teamSlug),
parent: isValidOrgDomain && currentOrgDomain ? getSlugOrRequestedSlug(currentOrgDomain) : null,
},
select: {
id: true,
hideBranding: true,
},
});
if (!team) {
return {
notFound: true,
} as const;
}
const org = isValidOrgDomain ? currentOrgDomain : null;
const eventData = await ssr.viewer.public.event.fetch({
username: teamSlug,
eventSlug: meetingSlug,
isTeamEvent: true,
org,
});
if (!eventData || !org) {
return {
notFound: true,
} as const;
}
return {
props: {
entity: eventData.entity,
duration: getMultipleDurationValue(
eventData.metadata?.multipleDuration,
queryDuration,
eventData.length
),
booking: null,
away: false,
user: teamSlug,
teamId: team.id,
slug: meetingSlug,
trpcState: ssr.dehydrate(),
isBrandingHidden: team?.hideBranding,
themeBasis: null,
},
};
};
+4 -1
View File
@@ -31,6 +31,7 @@ export default function Type({
isBrandingHidden,
entity,
duration,
isInstantMeeting,
}: PageProps) {
return (
<main className={getBookerWrapperClasses({ isEmbed: !!isEmbed })}>
@@ -48,6 +49,7 @@ export default function Type({
eventSlug={slug}
bookingData={booking}
isAway={away}
isInstantMeeting={isInstantMeeting}
hideBranding={isBrandingHidden}
isTeamEvent
entity={entity}
@@ -71,7 +73,7 @@ const paramsSchema = z.object({
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const session = await getServerSession(context);
const { slug: teamSlug, type: meetingSlug } = paramsSchema.parse(context.params);
const { rescheduleUid, duration: queryDuration } = context.query;
const { rescheduleUid, duration: queryDuration, isInstantMeeting: queryIsInstantMeeting } = context.query;
const { ssrInit } = await import("@server/lib/ssr");
const ssr = await ssrInit(context);
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req, context.params?.orgSlug);
@@ -143,6 +145,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
slug: meetingSlug,
trpcState: ssr.dehydrate(),
isBrandingHidden: team?.hideBranding,
isInstantMeeting: eventData.isInstantEvent && queryIsInstantMeeting ? true : false,
themeBasis: null,
},
};
@@ -113,6 +113,7 @@
"requested_to_reschedule_subject_attendee": "Action Required Reschedule: Please book a new time for {{eventType}} with {{name}}",
"hi_user_name": "Hi {{name}}",
"ics_event_title": "{{eventType}} with {{name}}",
"please_book_a_time_sometime_later":"No one was available at the moment. Please book for sometime later",
"new_event_subject": "New event: {{attendeeName}} - {{date}} - {{eventType}}",
"join_by_entrypoint": "Join by {{entryPoint}}",
"notes": "Notes",
@@ -129,12 +130,16 @@
"meeting_id": "Meeting ID",
"meeting_password": "Meeting Password",
"meeting_url": "Meeting URL",
"meeting_url_not_found":"Meeting URL not found",
"token_not_found":"Token not found",
"some_other_host_already_accepted_the_meeting":"Some other host already accepted the meeting. Do you still want to join? <1>Continue to Meeting Url</1>",
"meeting_request_rejected": "Your meeting request has been rejected",
"rejected_event_type_with_organizer": "Rejected: {{eventType}} with {{organizer}} on {{date}}",
"hi": "Hi",
"join_team": "Join team",
"manage_this_team": "Manage this team",
"team_info": "Team Info",
"join_meeting":"Join Meeting",
"request_another_invitation_email": "If you prefer not to use {{toEmail}} as your {{appName}} email or already have a {{appName}} account, please request another invitation to that email.",
"you_have_been_invited": "You have been invited to join the team {{teamName}}",
"user_invited_you": "{{user}} invited you to join the {{entity}} {{team}} on {{appName}}",
@@ -435,6 +440,7 @@
"browse_api_documentation": "Browse our API documentation",
"leverage_our_api": "Leverage our API for full control and customizability.",
"create_webhook": "Create Webhook",
"instant_meeting_created":"Instant Meeting Created",
"booking_cancelled": "Booking Canceled",
"booking_rescheduled": "Booking Rescheduled",
"recording_ready": "Recording Download Link Ready",
@@ -686,6 +692,7 @@
"add_members": "Add members...",
"no_assigned_members": "No assigned members",
"assigned_to": "Assigned to",
"you_must_be_logged_in_to":"You must be logged in to {{url}}",
"start_assigning_members_above": "Start assigning members above",
"locked_fields_admin_description": "Members will not be able to edit this",
"locked_fields_member_description": "This option was locked by the team admin",
@@ -798,6 +805,9 @@
"requires_confirmation_description": "The booking needs to be manually confirmed before it is pushed to the integrations and a confirmation mail is sent.",
"recurring_event": "Recurring Event",
"recurring_event_description": "People can subscribe for recurring events",
"cannot_be_used_with_paid_event_types":"It cannot be used with paid event types",
"warning_payment_instant_meeting_event":"Instant Meetings are not supported with recurring events and payment apps yet",
"warning_instant_meeting_experimental":"Experimental: Instant Meeting Events are currently experimental.",
"starting": "Starting",
"disable_guests": "Disable Guests",
"disable_guests_description": "Disable adding additional guests while booking.",
@@ -1321,6 +1331,7 @@
"customize_your_brand_colors": "Customize your own brand colour into your booking page.",
"pro": "Pro",
"removes_cal_branding": "Removes any {{appName}} related brandings, i.e. 'Powered by {{appName}}.'",
"instant_meeting_with_title":"Instant Meeting with {{name}}",
"profile_picture": "Profile Picture",
"upload": "Upload",
"add_profile_photo": "Add profile photo",
@@ -2026,6 +2037,8 @@
"add_times_to_your_email": "Select a few available times and embed them in your Email",
"select_time": "Select Time",
"select_date": "Select Date",
"connecting_you_to_someone":"We are connecting you to someone.",
"please_do_not_close_this_tab":"Please do not close this tab",
"see_all_available_times": "See all available times",
"org_team_names_example_1": "e.g. Marketing Team",
"org_team_names_example_2": "e.g. Sales Team",
@@ -2048,6 +2061,7 @@
"cal_video_logo_upload_instruction":"To ensure your logo is visible against Cal video's dark background, please upload a light-colored image in PNG or SVG format to maintain transparency.",
"org_admin_other_teams": "Other teams",
"org_admin_other_teams_description": "Here you can see teams inside your organization that you are not part of. You can add yourself to them if needed.",
"not_part_of_org":"You are not part of any organization",
"no_other_teams_found": "No other teams found",
"no_other_teams_found_description": "There are no other teams in this organization.",
"attendee_first_name_variable": "Attendee first name",
@@ -2168,6 +2182,10 @@
"need_help": "Need help?",
"troubleshooter": "Troubleshooter",
"please_install_a_calendar": "Please install a calendar",
"instant_tab_title": "Instant Booking",
"instant_event_tab_description": "Let people book immediately",
"uprade_to_create_instant_bookings": "Upgrade to Enterprise and let guests join an instant call that attendees can jump straight into. This is only for team event types",
"dont_want_to_wait": "Don't want to wait?",
"meeting_started": "Meeting Started",
"ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"
}