feat: link email to participant (requireEmailForGuests) (#24661)

* feat: link email to participatn

* fix: bugs

* refactor: improve code

* refactor: prevent repload

* chore: remove unued

* fix: type

* refactor

* fix: type

* feat: restrict host

* feat: type

* feat: tests

* fix: don't allow guest

* fix: merk guest

* fix: bugs

* fix: test

* fix: test

* refactor: feedback

* fix: tests

---------

Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
Udit TakkarandVolnei Munhoz authored and GitHub committed 2025-11-05 11:15:41 +00:00
1 parent bf0fbe4888
commit c196ff1095
28 files changed
+618 -155

No files matched your search

@@ -202,10 +202,9 @@ export const generateGuestMeetingTokenFromOwnerMeetingToken = async ({
userId,
}: {
meetingToken: string | null;
userId?: number;
userId?: number | string;
}) => {
if (!meetingToken) return null;
const token = await fetcher(`/meeting-tokens/${meetingToken}`).then(ZGetMeetingTokenResponseSchema.parse);
const guestMeetingToken = await postToDailyAPI("/meeting-tokens", {
properties: {
@@ -0,0 +1,52 @@
export type Host = {
id: number;
email: string;
};
export type Guest = {
email: string;
name: string;
};
type BookingInput = {
attendees?: { email: string; name: string }[] | null;
user?: { id: number; email: string } | null;
eventType?: {
hosts?: { userId: number; user: { email: string } }[];
users?: { id: number; email: string }[];
} | null;
};
export function getHostsAndGuests(booking: BookingInput): { hosts: Host[]; guests: Guest[] } {
const hostMap = new Map<number, Host>();
const addHost = (id: number, email: string) => {
if (!hostMap.has(id)) {
hostMap.set(id, { id, email });
}
};
booking?.eventType?.hosts?.forEach((host) => addHost(host.userId, host.user.email));
booking?.eventType?.users?.forEach((user) => addHost(user.id, user.email));
if (booking?.user?.id && booking?.user?.email) {
addHost(booking.user.id, booking.user.email);
}
const attendeeEmails = new Set(booking.attendees?.map((attendee) => attendee.email) ?? []);
const filteredHosts = Array.from(hostMap.values()).filter(
(host) => attendeeEmails.has(host.email) || host.id === booking.user?.id
);
const hostEmails = new Set(filteredHosts.map((host) => host.email));
const guests =
booking.attendees?.filter((attendee) => !hostEmails.has(attendee.email)).map((attendee) => ({
email: attendee.email,
name: attendee.name,
})) ?? [];
return {
hosts: filteredHosts,
guests,
};
}
@@ -559,7 +559,7 @@ export class BookingRepository {
});
}
async findBookingForMeetingPage({ bookingUid }: { bookingUid: string }) {
async findBookingIncludeCalVideoSettingsAndReferences({ bookingUid }: { bookingUid: string }) {
return await this.prismaClient.booking.findUnique({
where: {
uid: bookingUid,
@@ -573,6 +573,22 @@ export class BookingRepository {
select: {
id: true,
hideOrganizerEmail: true,
hosts: {
select: {
userId: true,
user: {
select: {
email: true,
},
},
},
},
users: {
select: {
id: true,
email: true,
},
},
calVideoSettings: {
select: {
disableRecordingForGuests: true,
@@ -582,6 +598,7 @@ export class BookingRepository {
disableTranscriptionForGuests: true,
disableTranscriptionForOrganizer: true,
redirectUrlOnExit: true,
requireEmailForGuests: true,
},
},
},
@@ -143,6 +143,23 @@ const CalVideoSettings = ({ calVideoSettings }: { calVideoSettings?: CalVideoSet
/>
)}
<Controller
name="calVideoSettings.requireEmailForGuests"
defaultValue={!!calVideoSettings?.requireEmailForGuests}
render={({ field: { onChange, value } }) => {
return (
<SettingsToggle
title={t("require_email_for_guests")}
description={t("require_email_for_guests_description")}
labelClassName="text-sm leading-6 whitespace-normal break-words"
checked={value}
onCheckedChange={onChange}
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
/>
);
}}
/>
<TextField
label={t("enter_redirect_url_on_exit_description")}
defaultValue={calVideoSettings?.redirectUrlOnExit || ""}
@@ -30,7 +30,6 @@ export type TLocationOptions = Pick<EventTypeSetupProps, "locationOptions">["loc
export type TDestinationCalendar = { integration: string } | null;
export type TPrefillLocation = { credentialId?: number; type: string };
type LocationsProps = {
team: { id: number } | null;
destinationCalendar: TDestinationCalendar;
@@ -254,6 +254,7 @@ const calVideoSettingsSchema = z
disableTranscriptionForGuests: z.boolean().nullish(),
disableTranscriptionForOrganizer: z.boolean().nullish(),
redirectUrlOnExit: z.string().url().nullish(),
requireEmailForGuests: z.boolean().nullish(),
})
.optional()
.nullable();
@@ -301,4 +302,5 @@ export interface CalVideoSettings {
disableTranscriptionForGuests?: boolean;
disableTranscriptionForOrganizer?: boolean;
redirectUrlOnExit?: string;
requireEmailForGuests?: boolean;
}
@@ -770,6 +770,7 @@ export class EventTypeRepository {
disableTranscriptionForGuests: true,
disableTranscriptionForOrganizer: true,
redirectUrlOnExit: true,
requireEmailForGuests: true,
},
},
} satisfies Prisma.EventTypeSelect;
@@ -1067,6 +1068,7 @@ export class EventTypeRepository {
disableTranscriptionForGuests: true,
disableTranscriptionForOrganizer: true,
redirectUrlOnExit: true,
requireEmailForGuests: true,
},
},
} satisfies Prisma.EventTypeSelect;
@@ -1,4 +1,6 @@
import dayjs from "@calcom/dayjs";
import { getHostsAndGuests } from "@calcom/features/bookings/lib/getHostsAndGuests";
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -18,40 +20,10 @@ type OriginalRescheduledBooking =
| null
| undefined;
export type Host = {
id: number;
email: string;
};
export type Booking = Awaited<ReturnType<typeof getBooking>>;
type Webhook = TWebhook;
export type Participants = TTriggerNoShowPayloadSchema["data"][number]["participants"];
export function getHosts(booking: Booking): Host[] {
const hostMap = new Map<number, Host>();
const addHost = (id: number, email: string) => {
if (!hostMap.has(id)) {
hostMap.set(id, { id, email });
}
};
booking?.eventType?.hosts?.forEach((host) => addHost(host.userId, host.user.email));
booking?.eventType?.users?.forEach((user) => addHost(user.id, user.email));
// Add booking.user if not already included
if (booking?.user?.id && booking?.user?.email) {
addHost(booking.user.id, booking.user.email);
}
// Filter hosts to only include those who are also attendees
const attendeeEmails = new Set(booking.attendees?.map((attendee) => attendee.email));
const filteredHosts = Array.from(hostMap.values()).filter(
(host) => attendeeEmails.has(host.email) || host.id === booking.user?.id
);
return filteredHosts;
}
type ParticipantsWithEmail = (Participants[number] & { email?: string; isLoggedIn?: boolean })[];
export function sendWebhookPayload(
webhook: Webhook,
@@ -77,7 +49,7 @@ export function sendWebhookPayload(
attendees: booking.attendees,
endTime: booking.endTime,
participants,
...(!!hostEmail ? { hostEmail } : {}),
...(hostEmail ? { hostEmail } : {}),
...(originalRescheduledBooking ? { rescheduledBy: originalRescheduledBooking.rescheduledBy } : {}),
eventType: {
...booking.eventType,
@@ -109,19 +81,36 @@ export function calculateMaxStartTime(startTime: Date, time: number, timeUnit: T
.unix();
}
export function checkIfUserJoinedTheCall(userId: number, allParticipants: Participants): boolean {
function checkIfHostJoinedTheCall(email: string, allParticipants: ParticipantsWithEmail): boolean {
return allParticipants.some(
(participant) => participant.user_id && parseInt(participant.user_id) === userId
(participant) => participant.email && participant.isLoggedIn && participant.email === email
);
}
const getUserById = async (userId: number) => {
return prisma.user.findUnique({
where: { id: userId },
});
};
function checkIfGuestJoinedTheCall(email: string, allParticipants: ParticipantsWithEmail): boolean {
return allParticipants.some((participant) => participant.email && participant.email === email);
}
type ParticipantsWithEmail = (Participants[number] & { email?: string })[];
const getUserOrGuestById = async (id: string) => {
// Try User table (numeric IDs)
if (!isNaN(Number(id))) {
const user = await prisma.user.findUnique({
where: { id: parseInt(id) },
select: { email: true },
});
if (user) return { email: user.email, isLoggedIn: true };
}
// Try VideoCallGuest table (UUID)
const guestSession = await prisma.videoCallGuest
.findUnique({
where: { id },
select: { email: true },
})
.catch(() => null);
return { email: guestSession?.email, isLoggedIn: false };
};
export async function getParticipantsWithEmail(
allParticipants: Participants
@@ -130,8 +119,8 @@ export async function getParticipantsWithEmail(
allParticipants.map(async (participant) => {
if (!participant.user_id) return participant;
const user = await getUserById(parseInt(participant.user_id));
return { ...participant, email: user?.email };
const { email, isLoggedIn } = await getUserOrGuestById(participant.user_id);
return { ...participant, email, isLoggedIn };
})
);
@@ -149,6 +138,8 @@ export const prepareNoShowTrigger = async (
hostsThatJoinedTheCall: Host[];
numberOfHostsThatJoined: number;
didGuestJoinTheCall: boolean;
guestsThatJoinedTheCall: { email: string; name: string }[];
guestsThatDidntJoinTheCall: { email: string; name: string }[];
originalRescheduledBooking?: OriginalRescheduledBooking;
participants: ParticipantsWithEmail;
} | void> => {
@@ -198,14 +189,15 @@ export const prepareNoShowTrigger = async (
}
const meetingDetails = await getMeetingSessionsFromRoomName(dailyVideoReference.uid);
const hosts = getHosts(booking);
const { hosts, guests } = getHostsAndGuests(booking);
const allParticipants = meetingDetails.data.flatMap((meeting) => meeting.participants);
const participantsWithEmail = await getParticipantsWithEmail(allParticipants);
const hostsThatJoinedTheCall: Host[] = [];
const hostsThatDidntJoinTheCall: Host[] = [];
for (const host of hosts) {
if (checkIfUserJoinedTheCall(host.id, allParticipants)) {
if (checkIfHostJoinedTheCall(host.email, participantsWithEmail)) {
hostsThatJoinedTheCall.push(host);
} else {
hostsThatDidntJoinTheCall.push(host);
@@ -214,11 +206,26 @@ export const prepareNoShowTrigger = async (
const numberOfHostsThatJoined = hosts.length - hostsThatDidntJoinTheCall.length;
const didGuestJoinTheCall = meetingDetails.data.some(
(meeting) => meeting.max_participants > numberOfHostsThatJoined
);
const requireEmailForGuests = booking.eventType?.calVideoSettings?.requireEmailForGuests ?? false;
const participantsWithEmail = await getParticipantsWithEmail(allParticipants);
let didGuestJoinTheCall: boolean;
const guestsThatJoinedTheCall: { email: string; name: string }[] = [];
const guestsThatDidntJoinTheCall: { email: string; name: string }[] = [];
if (requireEmailForGuests) {
for (const guest of guests) {
if (checkIfGuestJoinedTheCall(guest.email, participantsWithEmail)) {
guestsThatJoinedTheCall.push(guest);
} else {
guestsThatDidntJoinTheCall.push(guest);
}
}
didGuestJoinTheCall = guestsThatJoinedTheCall.length > 0;
} else {
didGuestJoinTheCall = meetingDetails.data.some(
(meeting) => meeting.max_participants > numberOfHostsThatJoined
);
}
return {
hostsThatDidntJoinTheCall,
@@ -227,6 +234,8 @@ export const prepareNoShowTrigger = async (
numberOfHostsThatJoined,
webhook,
didGuestJoinTheCall,
guestsThatJoinedTheCall,
guestsThatDidntJoinTheCall,
originalRescheduledBooking,
participants: participantsWithEmail,
};
@@ -24,6 +24,11 @@ export const getBooking = async (bookingId: number) => {
id: true,
teamId: true,
parentId: true,
calVideoSettings: {
select: {
requireEmailForGuests: true,
},
},
hosts: {
select: {
userId: true,
@@ -159,6 +159,7 @@ describe("Trigger Guest No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -265,6 +266,7 @@ describe("Trigger Guest No Show:", () => {
user_name: "MOCK_USER_NAME",
join_time: 0,
duration: 15,
isLoggedIn: true,
},
];
@@ -323,6 +325,7 @@ describe("Trigger Guest No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -468,6 +471,7 @@ describe("Trigger Guest No Show:", () => {
join_time: 0,
duration: 15,
email: "[email protected]",
isLoggedIn: true,
},
];
@@ -526,6 +530,7 @@ describe("Trigger Guest No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -1,26 +1,38 @@
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger, log } from "./common";
import type { Host } from "./common";
const markAllGuestNoshowInBooking = async ({
const markGuestAsNoshowInBooking = async ({
bookingId,
hostsThatJoinedTheCall,
guestsThatDidntJoinTheCall,
}: {
bookingId: number;
hostsThatJoinedTheCall: Host[];
guestsThatDidntJoinTheCall?: { email: string; name: string }[];
}) => {
try {
const hostsThatJoinedTheCallEmails = hostsThatJoinedTheCall.map((h) => h.email);
await prisma.attendee.updateMany({
where: {
bookingId,
email: { notIn: hostsThatJoinedTheCallEmails },
},
data: { noShow: true },
});
if (guestsThatDidntJoinTheCall && guestsThatDidntJoinTheCall.length > 0) {
const guestEmailsThatDidntJoin = guestsThatDidntJoinTheCall.map((g) => g.email);
await prisma.attendee.updateMany({
where: {
bookingId,
email: { in: guestEmailsThatDidntJoin },
},
data: { noShow: true },
});
} else {
const hostsThatJoinedTheCallEmails = hostsThatJoinedTheCall.map((h) => h.email);
await prisma.attendee.updateMany({
where: {
bookingId,
email: { notIn: hostsThatJoinedTheCallEmails },
},
data: { noShow: true },
});
}
} catch (err) {
log.error("Error marking guests as no show in booking", err);
}
@@ -35,22 +47,46 @@ export async function triggerGuestNoShow(payload: string): Promise<void> {
booking,
hostsThatJoinedTheCall,
didGuestJoinTheCall,
guestsThatDidntJoinTheCall,
originalRescheduledBooking,
participants,
} = result;
const maxStartTime = calculateMaxStartTime(booking.startTime, webhook.time, webhook.timeUnit);
if (!didGuestJoinTheCall) {
await sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
booking,
maxStartTime,
participants,
originalRescheduledBooking
);
const requireEmailForGuests = booking.eventType?.calVideoSettings?.requireEmailForGuests ?? false;
await markAllGuestNoshowInBooking({ bookingId: booking.id, hostsThatJoinedTheCall });
if (requireEmailForGuests) {
if (guestsThatDidntJoinTheCall.length > 0) {
await Promise.all([
sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
booking,
maxStartTime,
participants,
originalRescheduledBooking
),
markGuestAsNoshowInBooking({
bookingId: booking.id,
hostsThatJoinedTheCall,
guestsThatDidntJoinTheCall,
}),
]);
}
} else {
if (!didGuestJoinTheCall) {
await Promise.all([
sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
booking,
maxStartTime,
participants,
originalRescheduledBooking
),
markGuestAsNoshowInBooking({ bookingId: booking.id, hostsThatJoinedTheCall }),
]);
}
}
}
@@ -160,6 +160,7 @@ describe("Trigger Host No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -324,6 +325,7 @@ describe("Trigger Host No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -528,6 +530,7 @@ describe("Trigger Host No Show:", () => {
id: 1,
teamId: null,
parentId: null,
calVideoSettings: null,
},
webhook: {
...TEST_WEBHOOK,
@@ -1,7 +1,8 @@
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { Booking, Host } from "./common";
import type { Booking } from "./common";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger, log } from "./common";
const markHostsAsNoShowInBooking = async (booking: Booking, hostsThatDidntJoinTheCall: Host[]) => {
@@ -0,0 +1,30 @@
import type { PrismaClient } from "@calcom/prisma";
export class VideoCallGuestRepository {
constructor(private prismaClient: PrismaClient) {}
async upsertVideoCallGuest({
bookingUid,
email,
name,
}: {
bookingUid: string;
email: string;
name: string;
}) {
return await this.prismaClient.videoCallGuest.upsert({
where: {
bookingUid_email: {
bookingUid,
email,
},
},
update: { name },
create: {
bookingUid,
email,
name,
},
});
}
}
@@ -20,6 +20,7 @@ export class CalVideoSettingsRepository {
disableTranscriptionForGuests?: boolean | null;
disableTranscriptionForOrganizer?: boolean | null;
redirectUrlOnExit?: string | null;
requireEmailForGuests?: boolean | null;
};
}) {
return await prisma.calVideoSettings.create({
@@ -31,6 +32,7 @@ export class CalVideoSettingsRepository {
disableTranscriptionForGuests: calVideoSettings.disableTranscriptionForGuests ?? false,
disableTranscriptionForOrganizer: calVideoSettings.disableTranscriptionForOrganizer ?? false,
redirectUrlOnExit: calVideoSettings.redirectUrlOnExit ?? null,
requireEmailForGuests: calVideoSettings.requireEmailForGuests ?? false,
eventTypeId,
},
});
@@ -49,6 +51,7 @@ export class CalVideoSettingsRepository {
enableAutomaticTranscription?: boolean | null;
enableAutomaticRecordingForOrganizer?: boolean | null;
redirectUrlOnExit?: string | null;
requireEmailForGuests?: boolean | null;
};
}) {
return await prisma.calVideoSettings.upsert({
@@ -61,6 +64,7 @@ export class CalVideoSettingsRepository {
disableTranscriptionForGuests: calVideoSettings.disableTranscriptionForGuests ?? false,
disableTranscriptionForOrganizer: calVideoSettings.disableTranscriptionForOrganizer ?? false,
redirectUrlOnExit: calVideoSettings.redirectUrlOnExit ?? null,
requireEmailForGuests: calVideoSettings.requireEmailForGuests ?? false,
updatedAt: new Date(),
},
create: {
@@ -71,6 +75,7 @@ export class CalVideoSettingsRepository {
disableTranscriptionForGuests: calVideoSettings.disableTranscriptionForGuests ?? false,
disableTranscriptionForOrganizer: calVideoSettings.disableTranscriptionForOrganizer ?? false,
redirectUrlOnExit: calVideoSettings.redirectUrlOnExit ?? null,
requireEmailForGuests: calVideoSettings.requireEmailForGuests ?? false,
eventTypeId,
},
});
@@ -184,6 +184,7 @@ export const useEventTypeForm = ({
enableAutomaticRecordingForOrganizer: z.boolean().nullable(),
disableTranscriptionForGuests: z.boolean().nullable(),
disableTranscriptionForOrganizer: z.boolean().nullable(),
requireEmailForGuests: z.boolean().nullable(),
})
.optional()
.nullable(),
@@ -0,0 +1,24 @@
-- AlterTable
ALTER TABLE "public"."CalVideoSettings" ADD COLUMN "requireEmailForGuests" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "public"."VideoCallGuest" (
"id" TEXT NOT NULL,
"bookingUid" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"joinedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "VideoCallGuest_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "VideoCallGuest_bookingUid_idx" ON "public"."VideoCallGuest"("bookingUid");
-- CreateIndex
CREATE INDEX "VideoCallGuest_email_idx" ON "public"."VideoCallGuest"("email");
-- CreateIndex
CREATE UNIQUE INDEX "VideoCallGuest_bookingUid_email_key" ON "public"."VideoCallGuest"("bookingUid", "email");
+15
View File
@@ -107,10 +107,25 @@ model CalVideoSettings {
redirectUrlOnExit String?
disableTranscriptionForGuests Boolean @default(false)
disableTranscriptionForOrganizer Boolean @default(false)
requireEmailForGuests Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model VideoCallGuest {
id String @id @default(uuid())
bookingUid String
email String
name String
joinedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([bookingUid, email])
@@index([bookingUid])
@@index([email])
}
model EventType {
id Int @id @default(autoincrement())
/// @zod.string.min(1)
@@ -92,6 +92,7 @@ export const createHandler = async ({ ctx, input }: CreateOptions) => {
disableTranscriptionForGuests: calVideoSettings.disableTranscriptionForGuests ?? false,
disableTranscriptionForOrganizer: calVideoSettings.disableTranscriptionForOrganizer ?? false,
redirectUrlOnExit: calVideoSettings.redirectUrlOnExit ?? null,
requireEmailForGuests: calVideoSettings.requireEmailForGuests ?? false,
},
};
}
@@ -50,6 +50,7 @@ export const duplicateHandler = async ({ ctx, input }: DuplicateOptions) => {
disableRecordingForGuests: true,
enableAutomaticTranscription: true,
enableAutomaticRecordingForOrganizer: true,
requireEmailForGuests: true,
redirectUrlOnExit: true,
disableTranscriptionForGuests: true,
disableTranscriptionForOrganizer: true,
@@ -139,6 +139,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
disableRecordingForGuests: true,
enableAutomaticTranscription: true,
enableAutomaticRecordingForOrganizer: true,
requireEmailForGuests: true,
disableTranscriptionForGuests: true,
disableTranscriptionForOrganizer: true,
redirectUrlOnExit: true,
@@ -44,6 +44,7 @@ const calVideoSettingsSchema = z
disableTranscriptionForGuests: z.boolean().nullish(),
disableTranscriptionForOrganizer: z.boolean().nullish(),
redirectUrlOnExit: z.string().url().nullish(),
requireEmailForGuests: z.boolean().nullish(),
})
.optional()
.nullable();