File size: 159,848 Bytes
5ce3423
 
73cd842
 
 
1
2
3
4
5
6
{"task_id": "https://github.com/calcom/cal.com/pull/8087", "pr_url": "https://github.com/calcom/cal.com/pull/8087", "source_repo": "cal.dot.com", "pr_title": "Async import of the appStore packages", "diff": "diff --git a/packages/app-store/_utils/getCalendar.ts b/packages/app-store/_utils/getCalendar.ts\nindex 8a329485f16..10c60ed1c34 100644\n--- a/packages/app-store/_utils/getCalendar.ts\n+++ b/packages/app-store/_utils/getCalendar.ts\n@@ -6,13 +6,13 @@ import appStore from \"..\";\n \n const log = logger.getChildLogger({ prefix: [\"CalendarManager\"] });\n \n-export const getCalendar = (credential: CredentialPayload | null): Calendar | null => {\n+export const getCalendar = async (credential: CredentialPayload | null): Promise<Calendar | null> => {\n   if (!credential || !credential.key) return null;\n   let { type: calendarType } = credential;\n   if (calendarType?.endsWith(\"_other_calendar\")) {\n     calendarType = calendarType.split(\"_other_calendar\")[0];\n   }\n-  const calendarApp = appStore[calendarType.split(\"_\").join(\"\") as keyof typeof appStore];\n+  const calendarApp = await appStore[calendarType.split(\"_\").join(\"\") as keyof typeof appStore];\n   if (!(calendarApp && \"lib\" in calendarApp && \"CalendarService\" in calendarApp.lib)) {\n     log.warn(`calendar of type ${calendarType} is not implemented`);\n     return null;\ndiff --git a/packages/app-store/index.ts b/packages/app-store/index.ts\nindex 2aacc6731bb..e232b9fa4fa 100644\n--- a/packages/app-store/index.ts\n+++ b/packages/app-store/index.ts\n@@ -1,63 +1,33 @@\n-// import * as example from \"./_example\";\n-import * as applecalendar from \"./applecalendar\";\n-import * as caldavcalendar from \"./caldavcalendar\";\n-import * as closecom from \"./closecom\";\n-import * as dailyvideo from \"./dailyvideo\";\n-import * as exchange2013calendar from \"./exchange2013calendar\";\n-import * as exchange2016calendar from \"./exchange2016calendar\";\n-import * as exchangecalendar from \"./exchangecalendar\";\n-import * as facetime from \"./facetime\";\n-import * as giphy from \"./giphy\";\n-import * as googlecalendar from \"./googlecalendar\";\n-import * as googlevideo from \"./googlevideo\";\n-import * as hubspot from \"./hubspot\";\n-import * as huddle01video from \"./huddle01video\";\n-import * as jitsivideo from \"./jitsivideo\";\n-import * as larkcalendar from \"./larkcalendar\";\n-import * as office365calendar from \"./office365calendar\";\n-import * as office365video from \"./office365video\";\n-import * as plausible from \"./plausible\";\n-import * as salesforce from \"./salesforce\";\n-import * as sendgrid from \"./sendgrid\";\n-import * as stripepayment from \"./stripepayment\";\n-import * as sylapsvideo from \"./sylapsvideo\";\n-import * as tandemvideo from \"./tandemvideo\";\n-import * as vital from \"./vital\";\n-import * as wipemycalother from \"./wipemycalother\";\n-import * as zapier from \"./zapier\";\n-import * as zohocrm from \"./zohocrm\";\n-import * as zoomvideo from \"./zoomvideo\";\n-\n const appStore = {\n-  //   example,\n-  applecalendar,\n-  caldavcalendar,\n-  closecom,\n-  dailyvideo,\n-  googlecalendar,\n-  googlevideo,\n-  hubspot,\n-  huddle01video,\n-  jitsivideo,\n-  sylapsvideo,\n-  larkcalendar,\n-  office365calendar,\n-  office365video,\n-  plausible,\n-  salesforce,\n-  zohocrm,\n-  sendgrid,\n-  stripepayment,\n-  tandemvideo,\n-  vital,\n-  zoomvideo,\n-  wipemycalother,\n-  giphy,\n-  zapier,\n-  exchange2013calendar,\n-  exchange2016calendar,\n-  exchangecalendar,\n-  facetime,\n+  // example: import(\"./example\"),\n+  applecalendar: import(\"./applecalendar\"),\n+  caldavcalendar: import(\"./caldavcalendar\"),\n+  closecom: import(\"./closecom\"),\n+  dailyvideo: import(\"./dailyvideo\"),\n+  googlecalendar: import(\"./googlecalendar\"),\n+  googlevideo: import(\"./googlevideo\"),\n+  hubspot: import(\"./hubspot\"),\n+  huddle01video: import(\"./huddle01video\"),\n+  jitsivideo: import(\"./jitsivideo\"),\n+  larkcalendar: import(\"./larkcalendar\"),\n+  office365calendar: import(\"./office365calendar\"),\n+  office365video: import(\"./office365video\"),\n+  plausible: import(\"./plausible\"),\n+  salesforce: import(\"./salesforce\"),\n+  zohocrm: import(\"./zohocrm\"),\n+  sendgrid: import(\"./sendgrid\"),\n+  stripepayment: import(\"./stripepayment\"),\n+  tandemvideo: import(\"./tandemvideo\"),\n+  vital: import(\"./vital\"),\n+  zoomvideo: import(\"./zoomvideo\"),\n+  wipemycalother: import(\"./wipemycalother\"),\n+  giphy: import(\"./giphy\"),\n+  zapier: import(\"./zapier\"),\n+  exchange2013calendar: import(\"./exchange2013calendar\"),\n+  exchange2016calendar: import(\"./exchange2016calendar\"),\n+  exchangecalendar: import(\"./exchangecalendar\"),\n+  facetime: import(\"./facetime\"),\n+  sylapsvideo: import(\"./sylapsvideo\"),\n };\n \n export default appStore;\ndiff --git a/packages/app-store/vital/lib/reschedule.ts b/packages/app-store/vital/lib/reschedule.ts\nindex d216a987cfd..07733c58efe 100644\n--- a/packages/app-store/vital/lib/reschedule.ts\n+++ b/packages/app-store/vital/lib/reschedule.ts\n@@ -122,10 +122,10 @@ const Reschedule = async (bookingUid: string, cancellationReason: string) => {\n       (ref) => !!credentialsMap.get(ref.type)\n     );\n     try {\n-      bookingRefsFiltered.forEach((bookingRef) => {\n+      bookingRefsFiltered.forEach(async (bookingRef) => {\n         if (bookingRef.uid) {\n           if (bookingRef.type.endsWith(\"_calendar\")) {\n-            const calendar = getCalendar(credentialsMap.get(bookingRef.type));\n+            const calendar = await getCalendar(credentialsMap.get(bookingRef.type));\n             return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent);\n           } else if (bookingRef.type.endsWith(\"_video\")) {\n             return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);\ndiff --git a/packages/app-store/wipemycalother/lib/reschedule.ts b/packages/app-store/wipemycalother/lib/reschedule.ts\nindex 5e735097f2d..bf62fdc5afd 100644\n--- a/packages/app-store/wipemycalother/lib/reschedule.ts\n+++ b/packages/app-store/wipemycalother/lib/reschedule.ts\n@@ -122,10 +122,10 @@ const Reschedule = async (bookingUid: string, cancellationReason: string) => {\n       (ref) => !!credentialsMap.get(ref.type)\n     );\n     try {\n-      bookingRefsFiltered.forEach((bookingRef) => {\n+      bookingRefsFiltered.forEach(async (bookingRef) => {\n         if (bookingRef.uid) {\n           if (bookingRef.type.endsWith(\"_calendar\")) {\n-            const calendar = getCalendar(credentialsMap.get(bookingRef.type));\n+            const calendar = await getCalendar(credentialsMap.get(bookingRef.type));\n             return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent);\n           } else if (bookingRef.type.endsWith(\"_video\")) {\n             return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);\ndiff --git a/packages/core/CalendarManager.ts b/packages/core/CalendarManager.ts\nindex 4d5bf3103ef..9a5c3129499 100644\n--- a/packages/core/CalendarManager.ts\n+++ b/packages/core/CalendarManager.ts\n@@ -28,6 +28,7 @@ export const getCalendarCredentials = (credentials: Array<CredentialPayload>) =>\n         const calendar = getCalendar(credential);\n         return app.variant === \"calendar\" ? [{ integration: app, credential, calendar }] : [];\n       });\n+\n       return credentials.length ? credentials : [];\n     });\n \n@@ -43,8 +44,8 @@ export const getConnectedCalendars = async (\n   const connectedCalendars = await Promise.all(\n     calendarCredentials.map(async (item) => {\n       try {\n-        const { calendar, integration, credential } = item;\n-\n+        const { integration, credential } = item;\n+        const calendar = await item.calendar;\n         // Don't leak credentials to the client\n         const credentialId = credential.id;\n         if (!calendar) {\n@@ -138,7 +139,7 @@ export const getCachedResults = async (\n   selectedCalendars: SelectedCalendar[]\n ): Promise<EventBusyDate[][]> => {\n   const calendarCredentials = withCredentials.filter((credential) => credential.type.endsWith(\"_calendar\"));\n-  const calendars = calendarCredentials.map((credential) => getCalendar(credential));\n+  const calendars = await Promise.all(calendarCredentials.map((credential) => getCalendar(credential)));\n   performance.mark(\"getBusyCalendarTimesStart\");\n   const results = calendars.map(async (c, i) => {\n     /** Filter out nulls */\n@@ -229,7 +230,7 @@ export const createEvent = async (\n   calEvent: CalendarEvent\n ): Promise<EventResult<NewCalendarEventType>> => {\n   const uid: string = getUid(calEvent);\n-  const calendar = getCalendar(credential);\n+  const calendar = await getCalendar(credential);\n   let success = true;\n   let calError: string | undefined = undefined;\n \n@@ -280,7 +281,7 @@ export const updateEvent = async (\n   externalCalendarId: string | null\n ): Promise<EventResult<NewCalendarEventType>> => {\n   const uid = getUid(calEvent);\n-  const calendar = getCalendar(credential);\n+  const calendar = await getCalendar(credential);\n   let success = false;\n   let calError: string | undefined = undefined;\n   let calWarnings: string[] | undefined = [];\n@@ -326,12 +327,12 @@ export const updateEvent = async (\n   };\n };\n \n-export const deleteEvent = (\n+export const deleteEvent = async (\n   credential: CredentialPayload,\n   uid: string,\n   event: CalendarEvent\n ): Promise<unknown> => {\n-  const calendar = getCalendar(credential);\n+  const calendar = await getCalendar(credential);\n   if (calendar) {\n     return calendar.deleteEvent(uid, event);\n   }\ndiff --git a/packages/core/EventManager.ts b/packages/core/EventManager.ts\nindex d8bc62d5445..4b3b3564b13 100644\n--- a/packages/core/EventManager.ts\n+++ b/packages/core/EventManager.ts\n@@ -485,8 +485,7 @@ export default class EventManager {\n               id: oldCalendarEvent.credentialId,\n             },\n           });\n-          const calendar = getCalendar(calendarCredential);\n-\n+          const calendar = await getCalendar(calendarCredential);\n           await calendar?.deleteEvent(oldCalendarEvent.uid, event, oldCalendarEvent.externalCalendarId);\n         }\n       }\ndiff --git a/packages/core/videoClient.ts b/packages/core/videoClient.ts\nindex ff5308b9562..06887ce96da 100644\n--- a/packages/core/videoClient.ts\n+++ b/packages/core/videoClient.ts\n@@ -18,21 +18,25 @@ const log = logger.getChildLogger({ prefix: [\"[lib] videoClient\"] });\n const translator = short();\n \n // factory\n-const getVideoAdapters = (withCredentials: CredentialPayload[]): VideoApiAdapter[] =>\n-  withCredentials.reduce<VideoApiAdapter[]>((acc, cred) => {\n+const getVideoAdapters = async (withCredentials: CredentialPayload[]): Promise<VideoApiAdapter[]> => {\n+  const videoAdapters: VideoApiAdapter[] = [];\n+\n+  for (const cred of withCredentials) {\n     const appName = cred.type.split(\"_\").join(\"\"); // Transform `zoom_video` to `zoomvideo`;\n-    const app = appStore[appName as keyof typeof appStore];\n+    const app = await appStore[appName as keyof typeof appStore];\n+\n     if (app && \"lib\" in app && \"VideoApiAdapter\" in app.lib) {\n       const makeVideoApiAdapter = app.lib.VideoApiAdapter as VideoApiAdapterFactory;\n       const videoAdapter = makeVideoApiAdapter(cred);\n-      acc.push(videoAdapter);\n-      return acc;\n+      videoAdapters.push(videoAdapter);\n     }\n-    return acc;\n-  }, []);\n+  }\n+\n+  return videoAdapters;\n+};\n \n-const getBusyVideoTimes = (withCredentials: CredentialPayload[]) =>\n-  Promise.all(getVideoAdapters(withCredentials).map((c) => c?.getAvailability())).then((results) =>\n+const getBusyVideoTimes = async (withCredentials: CredentialPayload[]) =>\n+  Promise.all((await getVideoAdapters(withCredentials)).map((c) => c?.getAvailability())).then((results) =>\n     results.reduce((acc, availability) => acc.concat(availability), [] as (EventBusyDate | undefined)[])\n   );\n \n@@ -45,7 +49,7 @@ const createMeeting = async (credential: CredentialWithAppName, calEvent: Calend\n     );\n   }\n \n-  const videoAdapters = getVideoAdapters([credential]);\n+  const videoAdapters = await getVideoAdapters([credential]);\n   const [firstVideoAdapter] = videoAdapters;\n   let createdMeeting;\n   let returnObject: {\n@@ -104,7 +108,7 @@ const updateMeeting = async (\n \n   let success = true;\n \n-  const [firstVideoAdapter] = getVideoAdapters([credential]);\n+  const [firstVideoAdapter] = await getVideoAdapters([credential]);\n   const updatedMeeting =\n     credential && bookingRef\n       ? await firstVideoAdapter?.updateMeeting(bookingRef, calEvent).catch(async (e) => {\n@@ -135,9 +139,9 @@ const updateMeeting = async (\n   };\n };\n \n-const deleteMeeting = (credential: CredentialPayload, uid: string): Promise<unknown> => {\n+const deleteMeeting = async (credential: CredentialPayload, uid: string): Promise<unknown> => {\n   if (credential) {\n-    const videoAdapter = getVideoAdapters([credential])[0];\n+    const videoAdapter = (await getVideoAdapters([credential]))[0];\n     // There are certain video apps with no video adapter defined. e.g. riverby,whereby\n     if (videoAdapter) {\n       return videoAdapter.deleteMeeting(uid);\n@@ -155,7 +159,7 @@ const createMeetingWithCalVideo = async (calEvent: CalendarEvent) => {\n   } catch (e) {\n     return;\n   }\n-  const [videoAdapter] = getVideoAdapters([\n+  const [videoAdapter] = await getVideoAdapters([\n     {\n       id: 0,\n       appId: \"daily-video\",\n@@ -178,7 +182,7 @@ const getRecordingsOfCalVideoByRoomName = async (\n     console.error(\"Error: Cal video provider is not installed.\");\n     return;\n   }\n-  const [videoAdapter] = getVideoAdapters([\n+  const [videoAdapter] = await getVideoAdapters([\n     {\n       id: 0,\n       appId: \"daily-video\",\n@@ -199,7 +203,7 @@ const getDownloadLinkOfCalVideoByRecordingId = async (recordingId: string) => {\n     console.error(\"Error: Cal video provider is not installed.\");\n     return;\n   }\n-  const [videoAdapter] = getVideoAdapters([\n+  const [videoAdapter] = await getVideoAdapters([\n     {\n       id: 0,\n       appId: \"daily-video\",\ndiff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts\nindex 679d8bd4522..dd87a161a01 100644\n--- a/packages/features/bookings/lib/handleCancelBooking.ts\n+++ b/packages/features/bookings/lib/handleCancelBooking.ts\n@@ -240,7 +240,7 @@ async function handler(req: CustomRequest) {\n               integrationsToDelete.push(deleteMeeting(credential, reference.uid));\n             }\n             if (reference.type.includes(\"_calendar\")) {\n-              const calendar = getCalendar(credential);\n+              const calendar = await getCalendar(credential);\n               if (calendar) {\n                 integrationsToDelete.push(\n                   calendar?.deleteEvent(reference.uid, evt, reference.externalCalendarId)\n@@ -262,7 +262,7 @@ async function handler(req: CustomRequest) {\n               );\n             }\n             if (reference.type.includes(\"_calendar\")) {\n-              const calendar = getCalendar(credential);\n+              const calendar = await getCalendar(credential);\n               if (calendar) {\n                 integrationsToDelete.push(\n                   calendar?.updateEvent(reference.uid, updatedEvt, reference.externalCalendarId)\n@@ -449,7 +449,7 @@ async function handler(req: CustomRequest) {\n         (credential) => credential.id === credentialId\n       );\n       if (calendarCredential) {\n-        const calendar = getCalendar(calendarCredential);\n+        const calendar = await getCalendar(calendarCredential);\n         if (\n           bookingToDelete.eventType?.recurringEvent &&\n           bookingToDelete.recurringEventId &&\n@@ -458,7 +458,7 @@ async function handler(req: CustomRequest) {\n           bookingToDelete.user.credentials\n             .filter((credential) => credential.type.endsWith(\"_calendar\"))\n             .forEach(async (credential) => {\n-              const calendar = getCalendar(credential);\n+              const calendar = await getCalendar(credential);\n               for (const updBooking of updatedBookings) {\n                 const bookingRef = updBooking.references.find((ref) => ref.type.includes(\"_calendar\"));\n                 if (bookingRef) {\n@@ -474,12 +474,13 @@ async function handler(req: CustomRequest) {\n       }\n     } else {\n       // For bookings made before the refactor we go through the old behaviour of running through each calendar credential\n-      bookingToDelete.user.credentials\n-        .filter((credential) => credential.type.endsWith(\"_calendar\"))\n-        .forEach((credential) => {\n-          const calendar = getCalendar(credential);\n-          apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);\n-        });\n+      const calendarCredentials = bookingToDelete.user.credentials.filter((credential) =>\n+        credential.type.endsWith(\"_calendar\")\n+      );\n+      for (const credential of calendarCredentials) {\n+        const calendar = await getCalendar(credential);\n+        apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);\n+      }\n     }\n   }\n \n@@ -585,7 +586,7 @@ async function handler(req: CustomRequest) {\n     }\n \n     // Posible to refactor TODO:\n-    const paymentApp = appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];\n+    const paymentApp = await appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];\n     if (!(paymentApp && \"lib\" in paymentApp && \"PaymentService\" in paymentApp.lib)) {\n       console.warn(`payment App service of type ${paymentApp} is not implemented`);\n       return null;\ndiff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.ts\nindex 9776737003a..9fe941e75a8 100644\n--- a/packages/features/bookings/lib/handleNewBooking.ts\n+++ b/packages/features/bookings/lib/handleNewBooking.ts\n@@ -885,7 +885,7 @@ async function handler(\n               integrationsToDelete.push(deleteMeeting(credential, reference.uid));\n             }\n             if (reference.type.includes(\"_calendar\") && originalBookingEvt) {\n-              const calendar = getCalendar(credential);\n+              const calendar = await getCalendar(credential);\n               if (calendar) {\n                 integrationsToDelete.push(\n                   calendar?.deleteEvent(reference.uid, originalBookingEvt, reference.externalCalendarId)\ndiff --git a/packages/lib/payment/deletePayment.ts b/packages/lib/payment/deletePayment.ts\nindex b4e1fb4ce7c..9afa9b3e548 100644\n--- a/packages/lib/payment/deletePayment.ts\n+++ b/packages/lib/payment/deletePayment.ts\n@@ -13,7 +13,7 @@ const deletePayment = async (\n     } | null;\n   }\n ): Promise<boolean> => {\n-  const paymentApp = appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore];\n+  const paymentApp = await appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore];\n   if (!(paymentApp && \"lib\" in paymentApp && \"PaymentService\" in paymentApp.lib)) {\n     console.warn(`payment App service of type ${paymentApp} is not implemented`);\n     return false;\ndiff --git a/packages/lib/payment/handlePayment.ts b/packages/lib/payment/handlePayment.ts\nindex dcded8e6e8e..ff65249a076 100644\n--- a/packages/lib/payment/handlePayment.ts\n+++ b/packages/lib/payment/handlePayment.ts\n@@ -23,7 +23,7 @@ const handlePayment = async (\n     uid: string;\n   }\n ) => {\n-  const paymentApp = appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore];\n+  const paymentApp = await appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore];\n   if (!(paymentApp && \"lib\" in paymentApp && \"PaymentService\" in paymentApp.lib)) {\n     console.warn(`payment App service of type ${paymentApp} is not implemented`);\n     return null;\ndiff --git a/packages/trpc/server/routers/viewer/bookings.tsx b/packages/trpc/server/routers/viewer/bookings.tsx\nindex 8292e1bc137..e4c34cd97f6 100644\n--- a/packages/trpc/server/routers/viewer/bookings.tsx\n+++ b/packages/trpc/server/routers/viewer/bookings.tsx\n@@ -550,10 +550,10 @@ export const bookingsRouter = router({\n         const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter(\n           (ref) => !!credentialsMap.get(ref.type)\n         );\n-        bookingRefsFiltered.forEach((bookingRef) => {\n+        bookingRefsFiltered.forEach(async (bookingRef) => {\n           if (bookingRef.uid) {\n             if (bookingRef.type.endsWith(\"_calendar\")) {\n-              const calendar = getCalendar(credentialsMap.get(bookingRef.type));\n+              const calendar = await getCalendar(credentialsMap.get(bookingRef.type));\n \n               return calendar?.deleteEvent(\n                 bookingRef.uid,\n@@ -964,7 +964,7 @@ export const bookingsRouter = router({\n             }\n \n             // Posible to refactor TODO:\n-            const paymentApp = appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];\n+            const paymentApp = await appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];\n             if (!(paymentApp && \"lib\" in paymentApp && \"PaymentService\" in paymentApp.lib)) {\n               console.warn(`payment App service of type ${paymentApp} is not implemented`);\n               return null;\n", "gold_issues": [{"pr_url": "https://github.com/calcom/cal.com/pull/8087", "source_repo": "cal.dot.com", "pr_title": "Async import of the appStore packages", "issue_index": 0, "comment": "Consider adding try-catch around the await to handle import failures gracefully", "severity": "Low"}, {"pr_url": "https://github.com/calcom/cal.com/pull/8087", "source_repo": "cal.dot.com", "pr_title": "Async import of the appStore packages", "issue_index": 1, "comment": "The code uses forEach with async callbacks, which causes asynchronous operations (e.g., calendar/video event deletions, payment refunds) to run concurrently without being awaited. This 'fire-and-forget' behavior leads to unhandled promise rejections, race conditions, and incomplete cleanup, as surrounding try-catch blocks cannot properly handle errors from these unawaited promises. Replace forEach with for...of loops or Promise.all() with map() to ensure proper sequential execution and error handling.", "severity": "Critical"}]}
{"task_id": "https://github.com/calcom/cal.com/pull/10600", "pr_url": "https://github.com/calcom/cal.com/pull/10600", "source_repo": "cal.dot.com", "pr_title": "feat: 2fa backup codes", "diff": "diff --git a/apps/web/components/auth/BackupCode.tsx b/apps/web/components/auth/BackupCode.tsx\nnew file mode 100644\nindex 00000000000..a9121d815eb\n--- /dev/null\n+++ b/apps/web/components/auth/BackupCode.tsx\n@@ -0,0 +1,29 @@\n+import React from \"react\";\n+import { useFormContext } from \"react-hook-form\";\n+\n+import { useLocale } from \"@calcom/lib/hooks/useLocale\";\n+import { Label, TextField } from \"@calcom/ui\";\n+\n+export default function TwoFactor({ center = true }) {\n+  const { t } = useLocale();\n+  const methods = useFormContext();\n+\n+  return (\n+    <div className={center ? \"mx-auto !mt-0 max-w-sm\" : \"!mt-0 max-w-sm\"}>\n+      <Label className=\"mt-4\">{t(\"backup_code\")}</Label>\n+\n+      <p className=\"text-subtle mb-4 text-sm\">{t(\"backup_code_instructions\")}</p>\n+\n+      <TextField\n+        id=\"backup-code\"\n+        label=\"\"\n+        defaultValue=\"\"\n+        placeholder=\"XXXXX-XXXXX\"\n+        minLength={10} // without dash\n+        maxLength={11} // with dash\n+        required\n+        {...methods.register(\"backupCode\")}\n+      />\n+    </div>\n+  );\n+}\ndiff --git a/apps/web/components/auth/TwoFactor.tsx b/apps/web/components/auth/TwoFactor.tsx\nindex e074639fe2e..f46aa3b7e34 100644\n--- a/apps/web/components/auth/TwoFactor.tsx\n+++ b/apps/web/components/auth/TwoFactor.tsx\n@@ -5,7 +5,7 @@ import { useFormContext } from \"react-hook-form\";\n import { useLocale } from \"@calcom/lib/hooks/useLocale\";\n import { Label, Input } from \"@calcom/ui\";\n \n-export default function TwoFactor({ center = true }) {\n+export default function TwoFactor({ center = true, autoFocus = true }) {\n   const [value, onChange] = useState(\"\");\n   const { t } = useLocale();\n   const methods = useFormContext();\n@@ -40,7 +40,7 @@ export default function TwoFactor({ center = true }) {\n             name={`2fa${index + 1}`}\n             inputMode=\"decimal\"\n             {...digit}\n-            autoFocus={index === 0}\n+            autoFocus={autoFocus && index === 0}\n             autoComplete=\"one-time-code\"\n           />\n         ))}\ndiff --git a/apps/web/components/settings/DisableTwoFactorModal.tsx b/apps/web/components/settings/DisableTwoFactorModal.tsx\nindex 385e775f320..46d49ce62aa 100644\n--- a/apps/web/components/settings/DisableTwoFactorModal.tsx\n+++ b/apps/web/components/settings/DisableTwoFactorModal.tsx\n@@ -5,6 +5,7 @@ import { ErrorCode } from \"@calcom/features/auth/lib/ErrorCode\";\n import { useLocale } from \"@calcom/lib/hooks/useLocale\";\n import { Button, Dialog, DialogContent, DialogFooter, Form, PasswordField } from \"@calcom/ui\";\n \n+import BackupCode from \"@components/auth/BackupCode\";\n import TwoFactor from \"@components/auth/TwoFactor\";\n \n import TwoFactorAuthAPI from \"./TwoFactorAuthAPI\";\n@@ -20,6 +21,7 @@ interface DisableTwoFactorAuthModalProps {\n }\n \n interface DisableTwoFactorValues {\n+  backupCode: string;\n   totpCode: string;\n   password: string;\n }\n@@ -33,11 +35,19 @@ const DisableTwoFactorAuthModal = ({\n }: DisableTwoFactorAuthModalProps) => {\n   const [isDisabling, setIsDisabling] = useState(false);\n   const [errorMessage, setErrorMessage] = useState<string | null>(null);\n+  const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);\n   const { t } = useLocale();\n \n   const form = useForm<DisableTwoFactorValues>();\n \n-  async function handleDisable({ totpCode, password }: DisableTwoFactorValues) {\n+  const resetForm = (clearPassword = true) => {\n+    if (clearPassword) form.setValue(\"password\", \"\");\n+    form.setValue(\"backupCode\", \"\");\n+    form.setValue(\"totpCode\", \"\");\n+    setErrorMessage(null);\n+  };\n+\n+  async function handleDisable({ password, totpCode, backupCode }: DisableTwoFactorValues) {\n     if (isDisabling) {\n       return;\n     }\n@@ -45,8 +55,10 @@ const DisableTwoFactorAuthModal = ({\n     setErrorMessage(null);\n \n     try {\n-      const response = await TwoFactorAuthAPI.disable(password, totpCode);\n+      const response = await TwoFactorAuthAPI.disable(password, totpCode, backupCode);\n       if (response.status === 200) {\n+        setTwoFactorLostAccess(false);\n+        resetForm();\n         onDisable();\n         return;\n       }\n@@ -54,12 +66,14 @@ const DisableTwoFactorAuthModal = ({\n       const body = await response.json();\n       if (body.error === ErrorCode.IncorrectPassword) {\n         setErrorMessage(t(\"incorrect_password\"));\n-      }\n-      if (body.error === ErrorCode.SecondFactorRequired) {\n+      } else if (body.error === ErrorCode.SecondFactorRequired) {\n         setErrorMessage(t(\"2fa_required\"));\n-      }\n-      if (body.error === ErrorCode.IncorrectTwoFactorCode) {\n+      } else if (body.error === ErrorCode.IncorrectTwoFactorCode) {\n         setErrorMessage(t(\"incorrect_2fa\"));\n+      } else if (body.error === ErrorCode.IncorrectBackupCode) {\n+        setErrorMessage(t(\"incorrect_backup_code\"));\n+      } else if (body.error === ErrorCode.MissingBackupCodes) {\n+        setErrorMessage(t(\"missing_backup_codes\"));\n       } else {\n         setErrorMessage(t(\"something_went_wrong\"));\n       }\n@@ -78,6 +92,7 @@ const DisableTwoFactorAuthModal = ({\n           <div className=\"mb-8\">\n             {!disablePassword && (\n               <PasswordField\n+                required\n                 labelProps={{\n                   className: \"block text-sm font-medium text-default\",\n                 }}\n@@ -85,12 +100,25 @@ const DisableTwoFactorAuthModal = ({\n                 className=\"border-default mt-1 block w-full rounded-md border px-3 py-2 text-sm focus:border-black focus:outline-none focus:ring-black\"\n               />\n             )}\n-            <TwoFactor center={false} />\n+            {twoFactorLostAccess ? (\n+              <BackupCode center={false} />\n+            ) : (\n+              <TwoFactor center={false} autoFocus={false} />\n+            )}\n \n             {errorMessage && <p className=\"mt-1 text-sm text-red-700\">{errorMessage}</p>}\n           </div>\n \n           <DialogFooter showDivider className=\"relative mt-5\">\n+            <Button\n+              color=\"minimal\"\n+              className=\"mr-auto\"\n+              onClick={() => {\n+                setTwoFactorLostAccess(!twoFactorLostAccess);\n+                resetForm(false);\n+              }}>\n+              {twoFactorLostAccess ? t(\"go_back\") : t(\"lost_access\")}\n+            </Button>\n             <Button color=\"secondary\" onClick={onCancel}>\n               {t(\"cancel\")}\n             </Button>\ndiff --git a/apps/web/components/settings/EnableTwoFactorModal.tsx b/apps/web/components/settings/EnableTwoFactorModal.tsx\nindex 099558a8af0..0ed406787fa 100644\n--- a/apps/web/components/settings/EnableTwoFactorModal.tsx\n+++ b/apps/web/components/settings/EnableTwoFactorModal.tsx\n@@ -5,7 +5,7 @@ import { useForm } from \"react-hook-form\";\n import { ErrorCode } from \"@calcom/features/auth/lib/ErrorCode\";\n import { useCallbackRef } from \"@calcom/lib/hooks/useCallbackRef\";\n import { useLocale } from \"@calcom/lib/hooks/useLocale\";\n-import { Button, Dialog, DialogContent, DialogFooter, Form, TextField } from \"@calcom/ui\";\n+import { Button, Dialog, DialogContent, DialogFooter, Form, PasswordField, showToast } from \"@calcom/ui\";\n \n import TwoFactor from \"@components/auth/TwoFactor\";\n \n@@ -28,6 +28,7 @@ interface EnableTwoFactorModalProps {\n \n enum SetupStep {\n   ConfirmPassword,\n+  DisplayBackupCodes,\n   DisplayQrCode,\n   EnterTotpCode,\n }\n@@ -54,16 +55,25 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n \n   const setupDescriptions = {\n     [SetupStep.ConfirmPassword]: t(\"2fa_confirm_current_password\"),\n+    [SetupStep.DisplayBackupCodes]: t(\"backup_code_instructions\"),\n     [SetupStep.DisplayQrCode]: t(\"2fa_scan_image_or_use_code\"),\n     [SetupStep.EnterTotpCode]: t(\"2fa_enter_six_digit_code\"),\n   };\n   const [step, setStep] = useState(SetupStep.ConfirmPassword);\n   const [password, setPassword] = useState(\"\");\n+  const [backupCodes, setBackupCodes] = useState([]);\n+  const [backupCodesUrl, setBackupCodesUrl] = useState(\"\");\n   const [dataUri, setDataUri] = useState(\"\");\n   const [secret, setSecret] = useState(\"\");\n   const [isSubmitting, setIsSubmitting] = useState(false);\n   const [errorMessage, setErrorMessage] = useState<string | null>(null);\n \n+  const resetState = () => {\n+    setPassword(\"\");\n+    setErrorMessage(null);\n+    setStep(SetupStep.ConfirmPassword);\n+  };\n+\n   async function handleSetup(e: React.FormEvent) {\n     e.preventDefault();\n \n@@ -79,6 +89,15 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n       const body = await response.json();\n \n       if (response.status === 200) {\n+        setBackupCodes(body.backupCodes);\n+\n+        // create backup codes download url\n+        const textBlob = new Blob([body.backupCodes.map(formatBackupCode).join(\"\\n\")], {\n+          type: \"text/plain\",\n+        });\n+        if (backupCodesUrl) URL.revokeObjectURL(backupCodesUrl);\n+        setBackupCodesUrl(URL.createObjectURL(textBlob));\n+\n         setDataUri(body.dataUri);\n         setSecret(body.secret);\n         setStep(SetupStep.DisplayQrCode);\n@@ -113,7 +132,7 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n       const body = await response.json();\n \n       if (response.status === 200) {\n-        onEnable();\n+        setStep(SetupStep.DisplayBackupCodes);\n         return;\n       }\n \n@@ -141,13 +160,18 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n     }\n   }, [form, handleEnableRef, totpCode]);\n \n+  const formatBackupCode = (code: string) => `${code.slice(0, 5)}-${code.slice(5, 10)}`;\n+\n   return (\n     <Dialog open={open} onOpenChange={onOpenChange}>\n-      <DialogContent title={t(\"enable_2fa\")} description={setupDescriptions[step]} type=\"creation\">\n+      <DialogContent\n+        title={step === SetupStep.DisplayBackupCodes ? t(\"backup_codes\") : t(\"enable_2fa\")}\n+        description={setupDescriptions[step]}\n+        type=\"creation\">\n         <WithStep step={SetupStep.ConfirmPassword} current={step}>\n           <form onSubmit={handleSetup}>\n             <div className=\"mb-4\">\n-              <TextField\n+              <PasswordField\n                 label={t(\"password\")}\n                 type=\"password\"\n                 name=\"password\"\n@@ -173,6 +197,15 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n             </p>\n           </>\n         </WithStep>\n+        <WithStep step={SetupStep.DisplayBackupCodes} current={step}>\n+          <>\n+            <div className=\"mt-5 grid grid-cols-2 gap-1 text-center font-mono md:pl-10 md:pr-10\">\n+              {backupCodes.map((code) => (\n+                <div key={code}>{formatBackupCode(code)}</div>\n+              ))}\n+            </div>\n+          </>\n+        </WithStep>\n         <Form handleSubmit={handleEnable} form={form}>\n           <WithStep step={SetupStep.EnterTotpCode} current={step}>\n             <div className=\"-mt-4 pb-2\">\n@@ -186,9 +219,16 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n             </div>\n           </WithStep>\n           <DialogFooter className=\"mt-8\" showDivider>\n-            <Button color=\"secondary\" onClick={onCancel}>\n-              {t(\"cancel\")}\n-            </Button>\n+            {step !== SetupStep.DisplayBackupCodes ? (\n+              <Button\n+                color=\"secondary\"\n+                onClick={() => {\n+                  onCancel();\n+                  resetState();\n+                }}>\n+                {t(\"cancel\")}\n+              </Button>\n+            ) : null}\n             <WithStep step={SetupStep.ConfirmPassword} current={step}>\n               <Button\n                 type=\"submit\"\n@@ -218,6 +258,35 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable\n                 {t(\"enable\")}\n               </Button>\n             </WithStep>\n+            <WithStep step={SetupStep.DisplayBackupCodes} current={step}>\n+              <>\n+                <Button\n+                  color=\"secondary\"\n+                  data-testid=\"backup-codes-close\"\n+                  onClick={(e) => {\n+                    e.preventDefault();\n+                    resetState();\n+                    onEnable();\n+                  }}>\n+                  {t(\"close\")}\n+                </Button>\n+                <Button\n+                  color=\"secondary\"\n+                  data-testid=\"backup-codes-copy\"\n+                  onClick={(e) => {\n+                    e.preventDefault();\n+                    navigator.clipboard.writeText(backupCodes.map(formatBackupCode).join(\"\\n\"));\n+                    showToast(t(\"backup_codes_copied\"), \"success\");\n+                  }}>\n+                  {t(\"copy\")}\n+                </Button>\n+                <a download=\"cal-backup-codes.txt\" href={backupCodesUrl}>\n+                  <Button color=\"primary\" data-testid=\"backup-codes-download\">\n+                    {t(\"download\")}\n+                  </Button>\n+                </a>\n+              </>\n+            </WithStep>\n           </DialogFooter>\n         </Form>\n       </DialogContent>\ndiff --git a/apps/web/components/settings/TwoFactorAuthAPI.ts b/apps/web/components/settings/TwoFactorAuthAPI.ts\nindex 35ef6305759..1ea7792e875 100644\n--- a/apps/web/components/settings/TwoFactorAuthAPI.ts\n+++ b/apps/web/components/settings/TwoFactorAuthAPI.ts\n@@ -19,10 +19,10 @@ const TwoFactorAuthAPI = {\n     });\n   },\n \n-  async disable(password: string, code: string) {\n+  async disable(password: string, code: string, backupCode: string) {\n     return fetch(\"/api/auth/two-factor/totp/disable\", {\n       method: \"POST\",\n-      body: JSON.stringify({ password, code }),\n+      body: JSON.stringify({ password, code, backupCode }),\n       headers: {\n         \"Content-Type\": \"application/json\",\n       },\ndiff --git a/apps/web/pages/api/auth/two-factor/totp/disable.ts b/apps/web/pages/api/auth/two-factor/totp/disable.ts\nindex abc0835c4a9..fecb75d92f2 100644\n--- a/apps/web/pages/api/auth/two-factor/totp/disable.ts\n+++ b/apps/web/pages/api/auth/two-factor/totp/disable.ts\n@@ -43,8 +43,30 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n       return res.status(400).json({ error: ErrorCode.IncorrectPassword });\n     }\n   }\n-  // if user has 2fa\n-  if (user.twoFactorEnabled) {\n+\n+  // if user has 2fa and using backup code\n+  if (user.twoFactorEnabled && req.body.backupCode) {\n+    if (!process.env.CALENDSO_ENCRYPTION_KEY) {\n+      console.error(\"Missing encryption key; cannot proceed with backup code login.\");\n+      throw new Error(ErrorCode.InternalServerError);\n+    }\n+\n+    if (!user.backupCodes) {\n+      return res.status(400).json({ error: ErrorCode.MissingBackupCodes });\n+    }\n+\n+    const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY));\n+\n+    // check if user-supplied code matches one\n+    const index = backupCodes.indexOf(req.body.backupCode.replaceAll(\"-\", \"\"));\n+    if (index === -1) {\n+      return res.status(400).json({ error: ErrorCode.IncorrectBackupCode });\n+    }\n+\n+    // we delete all stored backup codes at the end, no need to do this here\n+\n+    // if user has 2fa and NOT using backup code, try totp\n+  } else if (user.twoFactorEnabled) {\n     if (!req.body.code) {\n       return res.status(400).json({ error: ErrorCode.SecondFactorRequired });\n       // throw new Error(ErrorCode.SecondFactorRequired);\n@@ -82,6 +104,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n       id: session.user.id,\n     },\n     data: {\n+      backupCodes: null,\n       twoFactorEnabled: false,\n       twoFactorSecret: null,\n     },\ndiff --git a/apps/web/pages/api/auth/two-factor/totp/setup.ts b/apps/web/pages/api/auth/two-factor/totp/setup.ts\nindex de63fcada67..a6fbed03912 100644\n--- a/apps/web/pages/api/auth/two-factor/totp/setup.ts\n+++ b/apps/web/pages/api/auth/two-factor/totp/setup.ts\n@@ -1,3 +1,4 @@\n+import crypto from \"crypto\";\n import type { NextApiRequest, NextApiResponse } from \"next\";\n import { authenticator } from \"otplib\";\n import qrcode from \"qrcode\";\n@@ -56,11 +57,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n   // bytes without updating the sanity checks in the enable and login endpoints.\n   const secret = authenticator.generateSecret(20);\n \n+  // generate backup codes with 10 character length\n+  const backupCodes = Array.from(Array(10), () => crypto.randomBytes(5).toString(\"hex\"));\n+\n   await prisma.user.update({\n     where: {\n       id: session.user.id,\n     },\n     data: {\n+      backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), process.env.CALENDSO_ENCRYPTION_KEY),\n       twoFactorEnabled: false,\n       twoFactorSecret: symmetricEncrypt(secret, process.env.CALENDSO_ENCRYPTION_KEY),\n     },\n@@ -70,5 +75,5 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n   const keyUri = authenticator.keyuri(name, \"Cal\", secret);\n   const dataUri = await qrcode.toDataURL(keyUri);\n \n-  return res.json({ secret, keyUri, dataUri });\n+  return res.json({ secret, keyUri, dataUri, backupCodes });\n }\ndiff --git a/apps/web/pages/auth/login.tsx b/apps/web/pages/auth/login.tsx\nindex 4847ceb9fbf..ca4e752e72d 100644\n--- a/apps/web/pages/auth/login.tsx\n+++ b/apps/web/pages/auth/login.tsx\n@@ -21,7 +21,7 @@ import { useLocale } from \"@calcom/lib/hooks/useLocale\";\n import { collectPageParameters, telemetryEventTypes, useTelemetry } from \"@calcom/lib/telemetry\";\n import prisma from \"@calcom/prisma\";\n import { Alert, Button, EmailField, PasswordField } from \"@calcom/ui\";\n-import { ArrowLeft } from \"@calcom/ui/components/icon\";\n+import { ArrowLeft, Lock } from \"@calcom/ui/components/icon\";\n \n import type { inferSSRProps } from \"@lib/types/inferSSRProps\";\n import type { WithNonceProps } from \"@lib/withNonce\";\n@@ -29,6 +29,7 @@ import withNonce from \"@lib/withNonce\";\n \n import AddToHomescreen from \"@components/AddToHomescreen\";\n import PageWrapper from \"@components/PageWrapper\";\n+import BackupCode from \"@components/auth/BackupCode\";\n import TwoFactor from \"@components/auth/TwoFactor\";\n import AuthContainer from \"@components/ui/AuthContainer\";\n \n@@ -39,6 +40,7 @@ interface LoginValues {\n   email: string;\n   password: string;\n   totpCode: string;\n+  backupCode: string;\n   csrfToken: string;\n }\n export default function Login({\n@@ -65,6 +67,7 @@ export default function Login({\n   const methods = useForm<LoginValues>({ resolver: zodResolver(formSchema) });\n   const { register, formState } = methods;\n   const [twoFactorRequired, setTwoFactorRequired] = useState(!!totpEmail || false);\n+  const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);\n   const [errorMessage, setErrorMessage] = useState<string | null>(null);\n \n   const errorMessages: { [key: string]: string } = {\n@@ -98,15 +101,35 @@ export default function Login({\n   );\n \n   const TwoFactorFooter = (\n-    <Button\n-      onClick={() => {\n-        setTwoFactorRequired(false);\n-        methods.setValue(\"totpCode\", \"\");\n-      }}\n-      StartIcon={ArrowLeft}\n-      color=\"minimal\">\n-      {t(\"go_back\")}\n-    </Button>\n+    <>\n+      <Button\n+        onClick={() => {\n+          if (twoFactorLostAccess) {\n+            setTwoFactorLostAccess(false);\n+            methods.setValue(\"backupCode\", \"\");\n+          } else {\n+            setTwoFactorRequired(false);\n+            methods.setValue(\"totpCode\", \"\");\n+          }\n+          setErrorMessage(null);\n+        }}\n+        StartIcon={ArrowLeft}\n+        color=\"minimal\">\n+        {t(\"go_back\")}\n+      </Button>\n+      {!twoFactorLostAccess ? (\n+        <Button\n+          onClick={() => {\n+            setTwoFactorLostAccess(true);\n+            setErrorMessage(null);\n+            methods.setValue(\"totpCode\", \"\");\n+          }}\n+          StartIcon={Lock}\n+          color=\"minimal\">\n+          {t(\"lost_access\")}\n+        </Button>\n+      ) : null}\n+    </>\n   );\n \n   const ExternalTotpFooter = (\n@@ -130,8 +153,9 @@ export default function Login({\n     if (!res) setErrorMessage(errorMessages[ErrorCode.InternalServerError]);\n     // we're logged in! let's do a hard refresh to the desired url\n     else if (!res.error) router.push(callbackUrl);\n-    // reveal two factor input if required\n     else if (res.error === ErrorCode.SecondFactorRequired) setTwoFactorRequired(true);\n+    else if (res.error === ErrorCode.IncorrectBackupCode) setErrorMessage(t(\"incorrect_backup_code\"));\n+    else if (res.error === ErrorCode.MissingBackupCodes) setErrorMessage(t(\"missing_backup_codes\"));\n     // fallback if error not found\n     else setErrorMessage(errorMessages[res.error] || t(\"something_went_wrong\"));\n   };\n@@ -194,7 +218,7 @@ export default function Login({\n                 </div>\n               </div>\n \n-              {twoFactorRequired && <TwoFactor center />}\n+              {twoFactorRequired ? !twoFactorLostAccess ? <TwoFactor center /> : <BackupCode center /> : null}\n \n               {errorMessage && <Alert severity=\"error\" title={errorMessage} />}\n               <Button\ndiff --git a/apps/web/playwright/login.2fa.e2e.ts b/apps/web/playwright/login.2fa.e2e.ts\nindex 5aff1299499..6b1e588c4cc 100644\n--- a/apps/web/playwright/login.2fa.e2e.ts\n+++ b/apps/web/playwright/login.2fa.e2e.ts\n@@ -9,6 +9,8 @@ import { test } from \"./lib/fixtures\";\n \n test.describe.configure({ mode: \"parallel\" });\n \n+// TODO: add more backup code tests, e.g. login + disabling 2fa with backup\n+\n // a test to logout requires both a succesfull login as logout, to prevent\n // a doubling of tests failing on logout & logout, we can group them.\n test.describe(\"2FA Tests\", async () => {\n@@ -45,6 +47,8 @@ test.describe(\"2FA Tests\", async () => {\n         secret: secret!,\n       });\n \n+      // FIXME: this passes even when switch is not checked, compare to test\n+      // below which checks for data-state=\"checked\" and works as expected\n       await page.waitForSelector(`[data-testid=two-factor-switch]`);\n       await expect(page.locator(`[data-testid=two-factor-switch]`).isChecked()).toBeTruthy();\n \n@@ -103,6 +107,23 @@ test.describe(\"2FA Tests\", async () => {\n       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n       await fillOtp({ page, secret: secret! });\n \n+      // backup codes are now showing, so run a few tests\n+\n+      // click download button\n+      const promise = page.waitForEvent(\"download\");\n+      await page.getByTestId(\"backup-codes-download\").click();\n+      const download = await promise;\n+      expect(download.suggestedFilename()).toBe(\"cal-backup-codes.txt\");\n+      // TODO: check file content\n+\n+      // click copy button\n+      await page.getByTestId(\"backup-codes-copy\").click();\n+      await page.getByTestId(\"toast-success\").waitFor();\n+      // TODO: check clipboard content\n+\n+      // close backup code dialog\n+      await page.getByTestId(\"backup-codes-close\").click();\n+\n       await expect(page.locator(`[data-testid=two-factor-switch][data-state=\"checked\"]`)).toBeVisible();\n \n       return user;\ndiff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json\nindex 082de5a93c8..a246e379687 100644\n--- a/apps/web/public/static/locales/en/common.json\n+++ b/apps/web/public/static/locales/en/common.json\n@@ -2010,6 +2010,13 @@\n   \"member_removed\": \"Member removed\",\n   \"my_availability\": \"My Availability\",\n   \"team_availability\": \"Team Availability\",\n+  \"backup_code\": \"Backup Code\",\n+  \"backup_codes\": \"Backup Codes\",\n+  \"backup_code_instructions\": \"Each backup code can be used exactly once to grant access without your authenticator.\",\n+  \"backup_codes_copied\": \"Backup codes copied!\",\n+  \"incorrect_backup_code\": \"Backup code is incorrect.\",\n+  \"lost_access\": \"Lost access\",\n+  \"missing_backup_codes\": \"No backup codes found. Please generate them in your settings.\",\n   \"admin_org_notification_email_subject\": \"New organization created: pending action\",\n   \"hi_admin\": \"Hi Administrator\",\n   \"admin_org_notification_email_title\": \"An organization requires DNS setup\",\ndiff --git a/packages/features/auth/lib/ErrorCode.ts b/packages/features/auth/lib/ErrorCode.ts\nindex ae054721e42..c4f86af26b5 100644\n--- a/packages/features/auth/lib/ErrorCode.ts\n+++ b/packages/features/auth/lib/ErrorCode.ts\n@@ -8,6 +8,8 @@ export enum ErrorCode {\n   TwoFactorSetupRequired = \"two-factor-setup-required\",\n   SecondFactorRequired = \"second-factor-required\",\n   IncorrectTwoFactorCode = \"incorrect-two-factor-code\",\n+  IncorrectBackupCode = \"incorrect-backup-code\",\n+  MissingBackupCodes = \"missing-backup-codes\",\n   IncorrectEmailVerificationCode = \"incorrect_email_verification_code\",\n   InternalServerError = \"internal-server-error\",\n   NewPasswordMatchesOld = \"new-password-matches-old\",\ndiff --git a/packages/features/auth/lib/next-auth-options.ts b/packages/features/auth/lib/next-auth-options.ts\nindex 01d3aa66a81..7fd3ffbcafb 100644\n--- a/packages/features/auth/lib/next-auth-options.ts\n+++ b/packages/features/auth/lib/next-auth-options.ts\n@@ -11,7 +11,7 @@ import ImpersonationProvider from \"@calcom/features/ee/impersonation/lib/Imperso\n import { clientSecretVerifier, hostedCal, isSAMLLoginEnabled } from \"@calcom/features/ee/sso/lib/saml\";\n import { checkRateLimitAndThrowError } from \"@calcom/lib/checkRateLimitAndThrowError\";\n import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from \"@calcom/lib/constants\";\n-import { symmetricDecrypt } from \"@calcom/lib/crypto\";\n+import { symmetricDecrypt, symmetricEncrypt } from \"@calcom/lib/crypto\";\n import { defaultCookies } from \"@calcom/lib/default-cookies\";\n import { isENVDev } from \"@calcom/lib/env\";\n import { randomString } from \"@calcom/lib/random\";\n@@ -62,6 +62,7 @@ const providers: Provider[] = [\n       email: { label: \"Email Address\", type: \"email\", placeholder: \"john.doe@example.com\" },\n       password: { label: \"Password\", type: \"password\", placeholder: \"Your super secure password\" },\n       totpCode: { label: \"Two-factor Code\", type: \"input\", placeholder: \"Code from authenticator app\" },\n+      backupCode: { label: \"Backup Code\", type: \"input\", placeholder: \"Two-factor backup code\" },\n     },\n     async authorize(credentials) {\n       if (!credentials) {\n@@ -85,6 +86,7 @@ const providers: Provider[] = [\n           organizationId: true,\n           twoFactorEnabled: true,\n           twoFactorSecret: true,\n+          backupCodes: true,\n           locale: true,\n           organization: {\n             select: {\n@@ -126,7 +128,33 @@ const providers: Provider[] = [\n         }\n       }\n \n-      if (user.twoFactorEnabled) {\n+      if (user.twoFactorEnabled && credentials.backupCode) {\n+        if (!process.env.CALENDSO_ENCRYPTION_KEY) {\n+          console.error(\"Missing encryption key; cannot proceed with backup code login.\");\n+          throw new Error(ErrorCode.InternalServerError);\n+        }\n+\n+        if (!user.backupCodes) throw new Error(ErrorCode.MissingBackupCodes);\n+\n+        const backupCodes = JSON.parse(\n+          symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY)\n+        );\n+\n+        // check if user-supplied code matches one\n+        const index = backupCodes.indexOf(credentials.backupCode.replaceAll(\"-\", \"\"));\n+        if (index === -1) throw new Error(ErrorCode.IncorrectBackupCode);\n+\n+        // delete verified backup code and re-encrypt remaining\n+        backupCodes[index] = null;\n+        await prisma.user.update({\n+          where: {\n+            id: user.id,\n+          },\n+          data: {\n+            backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), process.env.CALENDSO_ENCRYPTION_KEY),\n+          },\n+        });\n+      } else if (user.twoFactorEnabled) {\n         if (!credentials.totpCode) {\n           throw new Error(ErrorCode.SecondFactorRequired);\n         }\ndiff --git a/packages/lib/test/builder.ts b/packages/lib/test/builder.ts\nindex 20962a69ffc..43c25e40776 100644\n--- a/packages/lib/test/builder.ts\n+++ b/packages/lib/test/builder.ts\n@@ -189,6 +189,7 @@ export const buildUser = <T extends Partial<UserPayload>>(user?: T): UserPayload\n     availability: [],\n     avatar: \"\",\n     away: false,\n+    backupCodes: null,\n     bio: null,\n     brandColor: \"#292929\",\n     bufferTime: 0,\ndiff --git a/packages/prisma/migrations/20230804153419_add_backup_codes/migration.sql b/packages/prisma/migrations/20230804153419_add_backup_codes/migration.sql\nnew file mode 100644\nindex 00000000000..469f554e496\n--- /dev/null\n+++ b/packages/prisma/migrations/20230804153419_add_backup_codes/migration.sql\n@@ -0,0 +1,2 @@\n+-- AlterTable\n+ALTER TABLE \"users\" ADD COLUMN     \"backupCodes\" TEXT;\ndiff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma\nindex 7a4caa669ff..ec45c33d0c9 100644\n--- a/packages/prisma/schema.prisma\n+++ b/packages/prisma/schema.prisma\n@@ -202,6 +202,7 @@ model User {\n   timeFormat          Int?                 @default(12)\n   twoFactorSecret     String?\n   twoFactorEnabled    Boolean              @default(false)\n+  backupCodes         String?\n   identityProvider    IdentityProvider     @default(CAL)\n   identityProviderId  String?\n   availability        Availability[]\ndiff --git a/packages/ui/components/form/inputs/Input.tsx b/packages/ui/components/form/inputs/Input.tsx\nindex 5944b40ec63..4f50cd9eb1a 100644\n--- a/packages/ui/components/form/inputs/Input.tsx\n+++ b/packages/ui/components/form/inputs/Input.tsx\n@@ -44,7 +44,11 @@ export const PasswordField = forwardRef<HTMLInputElement, InputFieldProps>(funct\n         addOnFilled={false}\n         addOnSuffix={\n           <Tooltip content={textLabel}>\n-            <button className=\"text-emphasis h-9\" type=\"button\" onClick={() => toggleIsPasswordVisible()}>\n+            <button\n+              className=\"text-emphasis h-9\"\n+              tabIndex={-1}\n+              type=\"button\"\n+              onClick={() => toggleIsPasswordVisible()}>\n               {isPasswordVisible ? (\n                 <EyeOff className=\"h-4 stroke-[2.5px]\" />\n               ) : (\n", "gold_issues": [{"pr_url": "https://github.com/calcom/cal.com/pull/10600", "source_repo": "cal.dot.com", "pr_title": "feat: 2fa backup codes", "issue_index": 0, "comment": "The exported function TwoFactor handles backup codes and is in BackupCode.tsx. Inconsistent naming.", "severity": "Low"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10600", "source_repo": "cal.dot.com", "pr_title": "feat: 2fa backup codes", "issue_index": 1, "comment": "Error message mentions 'backup code login' but this is a disable endpoint, not login", "severity": "Low"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10600", "source_repo": "cal.dot.com", "pr_title": "feat: 2fa backup codes", "issue_index": 2, "comment": "Backup code validation is case-sensitive due to the use of indexOf(). This causes validation to fail if a user enters uppercase hex characters, as backup codes should be case-insensitive for a better user experience.", "severity": "Medium"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10600", "source_repo": "cal.dot.com", "pr_title": "feat: 2fa backup codes", "issue_index": 3, "comment": "Because backupCodes are decrypted and mutated in memory before being written back, two concurrent login requests using the same backupCode could both pass this check and update, so a single backup code may effectively be accepted more than once if used concurrently, weakening the intended one-time-use semantics.", "severity": "High"}]}
{"task_id": "https://github.com/calcom/cal.com/pull/10967", "pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "diff": "diff --git a/apps/web/pages/api/cron/bookingReminder.ts b/apps/web/pages/api/cron/bookingReminder.ts\nindex ab511b5a427..571b4850dd2 100644\n--- a/apps/web/pages/api/cron/bookingReminder.ts\n+++ b/apps/web/pages/api/cron/bookingReminder.ts\n@@ -104,7 +104,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n       });\n \n       const attendeesList = await Promise.all(attendeesListPromises);\n-\n+      const selectedDestinationCalendar = booking.destinationCalendar || user.destinationCalendar;\n       const evt: CalendarEvent = {\n         type: booking.title,\n         title: booking.title,\n@@ -127,7 +127,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)\n         attendees: attendeesList,\n         uid: booking.uid,\n         recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),\n-        destinationCalendar: booking.destinationCalendar || user.destinationCalendar,\n+        destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],\n       };\n \n       await sendOrganizerRequestReminderEmail(evt);\ndiff --git a/apps/web/playwright/webhook.e2e.ts b/apps/web/playwright/webhook.e2e.ts\nindex a157578d5ea..a56f5a425bc 100644\n--- a/apps/web/playwright/webhook.e2e.ts\n+++ b/apps/web/playwright/webhook.e2e.ts\n@@ -246,7 +246,7 @@ test.describe(\"BOOKING_REJECTED\", async () => {\n           },\n         ],\n         location: \"[redacted/dynamic]\",\n-        destinationCalendar: null,\n+        destinationCalendar: [],\n         // hideCalendarNotes: false,\n         requiresConfirmation: \"[redacted/dynamic]\",\n         eventTypeId: \"[redacted/dynamic]\",\ndiff --git a/packages/app-store/googlecalendar/lib/CalendarService.ts b/packages/app-store/googlecalendar/lib/CalendarService.ts\nindex b746233a437..755c7bcc401 100644\n--- a/packages/app-store/googlecalendar/lib/CalendarService.ts\n+++ b/packages/app-store/googlecalendar/lib/CalendarService.ts\n@@ -84,7 +84,7 @@ export default class GoogleCalendarService implements Calendar {\n     };\n   };\n \n-  async createEvent(calEventRaw: CalendarEvent): Promise<NewCalendarEventType> {\n+  async createEvent(calEventRaw: CalendarEvent, credentialId: number): Promise<NewCalendarEventType> {\n     const eventAttendees = calEventRaw.attendees.map(({ id: _id, ...rest }) => ({\n       ...rest,\n       responseStatus: \"accepted\",\n@@ -97,6 +97,10 @@ export default class GoogleCalendarService implements Calendar {\n         responseStatus: \"accepted\",\n       })) || [];\n     return new Promise(async (resolve, reject) => {\n+      const [mainHostDestinationCalendar] =\n+        calEventRaw?.destinationCalendar && calEventRaw?.destinationCalendar.length > 0\n+          ? calEventRaw.destinationCalendar\n+          : [];\n       const myGoogleAuth = await this.auth.getToken();\n       const payload: calendar_v3.Schema$Event = {\n         summary: calEventRaw.title,\n@@ -115,8 +119,8 @@ export default class GoogleCalendarService implements Calendar {\n             id: String(calEventRaw.organizer.id),\n             responseStatus: \"accepted\",\n             organizer: true,\n-            email: calEventRaw.destinationCalendar?.externalId\n-              ? calEventRaw.destinationCalendar.externalId\n+            email: mainHostDestinationCalendar?.externalId\n+              ? mainHostDestinationCalendar.externalId\n               : calEventRaw.organizer.email,\n           },\n           ...eventAttendees,\n@@ -138,13 +142,16 @@ export default class GoogleCalendarService implements Calendar {\n       const calendar = google.calendar({\n         version: \"v3\",\n       });\n-      const selectedCalendar = calEventRaw.destinationCalendar?.externalId\n-        ? calEventRaw.destinationCalendar.externalId\n-        : \"primary\";\n+      // Find in calEventRaw.destinationCalendar the one with the same credentialId\n+\n+      const selectedCalendar = calEventRaw.destinationCalendar?.find(\n+        (cal) => cal.credentialId === credentialId\n+      )?.externalId;\n+\n       calendar.events.insert(\n         {\n           auth: myGoogleAuth,\n-          calendarId: selectedCalendar,\n+          calendarId: selectedCalendar || \"primary\",\n           requestBody: payload,\n           conferenceDataVersion: 1,\n           sendUpdates: \"none\",\n@@ -188,6 +195,8 @@ export default class GoogleCalendarService implements Calendar {\n \n   async updateEvent(uid: string, event: CalendarEvent, externalCalendarId: string): Promise<any> {\n     return new Promise(async (resolve, reject) => {\n+      const [mainHostDestinationCalendar] =\n+        event?.destinationCalendar && event?.destinationCalendar.length > 0 ? event.destinationCalendar : [];\n       const myGoogleAuth = await this.auth.getToken();\n       const eventAttendees = event.attendees.map(({ ...rest }) => ({\n         ...rest,\n@@ -216,8 +225,8 @@ export default class GoogleCalendarService implements Calendar {\n             id: String(event.organizer.id),\n             organizer: true,\n             responseStatus: \"accepted\",\n-            email: event.destinationCalendar?.externalId\n-              ? event.destinationCalendar.externalId\n+            email: mainHostDestinationCalendar?.externalId\n+              ? mainHostDestinationCalendar.externalId\n               : event.organizer.email,\n           },\n           ...(eventAttendees as any),\n@@ -244,7 +253,7 @@ export default class GoogleCalendarService implements Calendar {\n \n       const selectedCalendar = externalCalendarId\n         ? externalCalendarId\n-        : event.destinationCalendar?.externalId;\n+        : event.destinationCalendar?.find((cal) => cal.externalId === externalCalendarId)?.externalId;\n \n       calendar.events.update(\n         {\n@@ -303,7 +312,9 @@ export default class GoogleCalendarService implements Calendar {\n       });\n \n       const defaultCalendarId = \"primary\";\n-      const calendarId = externalCalendarId ? externalCalendarId : event.destinationCalendar?.externalId;\n+      const calendarId = externalCalendarId\n+        ? externalCalendarId\n+        : event.destinationCalendar?.find((cal) => cal.externalId === externalCalendarId)?.externalId;\n \n       calendar.events.delete(\n         {\ndiff --git a/packages/app-store/larkcalendar/lib/CalendarService.ts b/packages/app-store/larkcalendar/lib/CalendarService.ts\nindex 61774563e17..f2979b59526 100644\n--- a/packages/app-store/larkcalendar/lib/CalendarService.ts\n+++ b/packages/app-store/larkcalendar/lib/CalendarService.ts\n@@ -125,7 +125,8 @@ export default class LarkCalendarService implements Calendar {\n   async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {\n     let eventId = \"\";\n     let eventRespData;\n-    const calendarId = event.destinationCalendar?.externalId;\n+    const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n+    const calendarId = mainHostDestinationCalendar?.externalId;\n     if (!calendarId) {\n       throw new Error(\"no calendar id\");\n     }\n@@ -160,7 +161,8 @@ export default class LarkCalendarService implements Calendar {\n   }\n \n   private createAttendees = async (event: CalendarEvent, eventId: string) => {\n-    const calendarId = event.destinationCalendar?.externalId;\n+    const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n+    const calendarId = mainHostDestinationCalendar?.externalId;\n     if (!calendarId) {\n       this.log.error(\"no calendar id provided in createAttendees\");\n       throw new Error(\"no calendar id provided in createAttendees\");\n@@ -187,7 +189,8 @@ export default class LarkCalendarService implements Calendar {\n   async updateEvent(uid: string, event: CalendarEvent, externalCalendarId?: string) {\n     const eventId = uid;\n     let eventRespData;\n-    const calendarId = externalCalendarId || event.destinationCalendar?.externalId;\n+    const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n+    const calendarId = externalCalendarId || mainHostDestinationCalendar?.externalId;\n     if (!calendarId) {\n       this.log.error(\"no calendar id provided in updateEvent\");\n       throw new Error(\"no calendar id provided in updateEvent\");\n@@ -231,7 +234,8 @@ export default class LarkCalendarService implements Calendar {\n    * @returns\n    */\n   async deleteEvent(uid: string, event: CalendarEvent, externalCalendarId?: string) {\n-    const calendarId = externalCalendarId || event.destinationCalendar?.externalId;\n+    const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n+    const calendarId = externalCalendarId || mainHostDestinationCalendar?.externalId;\n     if (!calendarId) {\n       this.log.error(\"no calendar id provided in deleteEvent\");\n       throw new Error(\"no calendar id provided in deleteEvent\");\ndiff --git a/packages/app-store/office365calendar/lib/CalendarService.ts b/packages/app-store/office365calendar/lib/CalendarService.ts\nindex c4faa5f8ec5..5283eed7191 100644\n--- a/packages/app-store/office365calendar/lib/CalendarService.ts\n+++ b/packages/app-store/office365calendar/lib/CalendarService.ts\n@@ -70,9 +70,10 @@ export default class Office365CalendarService implements Calendar {\n   }\n \n   async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {\n+    const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n     try {\n-      const eventsUrl = event.destinationCalendar?.externalId\n-        ? `/me/calendars/${event.destinationCalendar?.externalId}/events`\n+      const eventsUrl = mainHostDestinationCalendar?.externalId\n+        ? `/me/calendars/${mainHostDestinationCalendar?.externalId}/events`\n         : \"/me/calendar/events\";\n \n       const response = await this.fetcher(eventsUrl, {\ndiff --git a/packages/core/CalendarManager.ts b/packages/core/CalendarManager.ts\nindex b256eb1cfc2..e3a995dbe6f 100644\n--- a/packages/core/CalendarManager.ts\n+++ b/packages/core/CalendarManager.ts\n@@ -217,7 +217,8 @@ export const getBusyCalendarTimes = async (\n \n export const createEvent = async (\n   credential: CredentialWithAppName,\n-  calEvent: CalendarEvent\n+  calEvent: CalendarEvent,\n+  externalId?: string\n ): Promise<EventResult<NewCalendarEventType>> => {\n   const uid: string = getUid(calEvent);\n   const calendar = await getCalendar(credential);\n@@ -226,29 +227,31 @@ export const createEvent = async (\n \n   // Check if the disabledNotes flag is set to true\n   if (calEvent.hideCalendarNotes) {\n-    calEvent.additionalNotes = \"Notes have been hidden by the organiser\"; // TODO: i18n this string?\n+    calEvent.additionalNotes = \"Notes have been hidden by the organizer\"; // TODO: i18n this string?\n   }\n \n   // TODO: Surface success/error messages coming from apps to improve end user visibility\n   const creationResult = calendar\n-    ? await calendar.createEvent(calEvent).catch(async (error: { code: number; calError: string }) => {\n-        success = false;\n-        /**\n-         * There is a time when selectedCalendar externalId doesn't match witch certain credential\n-         * so google returns 404.\n-         * */\n-        if (error?.code === 404) {\n+    ? await calendar\n+        .createEvent(calEvent, credential.id)\n+        .catch(async (error: { code: number; calError: string }) => {\n+          success = false;\n+          /**\n+           * There is a time when selectedCalendar externalId doesn't match witch certain credential\n+           * so google returns 404.\n+           * */\n+          if (error?.code === 404) {\n+            return undefined;\n+          }\n+          if (error?.calError) {\n+            calError = error.calError;\n+          }\n+          log.error(\"createEvent failed\", JSON.stringify(error), calEvent);\n+          // @TODO: This code will be off till we can investigate an error with it\n+          //https://github.com/calcom/cal.com/issues/3949\n+          // await sendBrokenIntegrationEmail(calEvent, \"calendar\");\n           return undefined;\n-        }\n-        if (error?.calError) {\n-          calError = error.calError;\n-        }\n-        log.error(\"createEvent failed\", JSON.stringify(error), calEvent);\n-        // @TODO: This code will be off till we can investigate an error with it\n-        //https://github.com/calcom/cal.com/issues/3949\n-        // await sendBrokenIntegrationEmail(calEvent, \"calendar\");\n-        return undefined;\n-      })\n+        })\n     : undefined;\n \n   return {\n@@ -261,6 +264,8 @@ export const createEvent = async (\n     originalEvent: calEvent,\n     calError,\n     calWarnings: creationResult?.additionalInfo?.calWarnings || [],\n+    externalId,\n+    credentialId: credential.id,\n   };\n };\n \ndiff --git a/packages/core/EventManager.ts b/packages/core/EventManager.ts\nindex 72aa75eb68a..cc8d5c55b96 100644\n--- a/packages/core/EventManager.ts\n+++ b/packages/core/EventManager.ts\n@@ -114,7 +114,9 @@ export default class EventManager {\n     }\n \n     // Fallback to Cal Video if Google Meet is selected w/o a Google Cal\n-    if (evt.location === MeetLocationType && evt.destinationCalendar?.integration !== \"google_calendar\") {\n+    // @NOTE: destinationCalendar it's an array now so as a fallback we will only check the first one\n+    const [mainHostDestinationCalendar] = evt.destinationCalendar ?? [];\n+    if (evt.location === MeetLocationType && mainHostDestinationCalendar.integration !== \"google_calendar\") {\n       evt[\"location\"] = \"integrations:daily\";\n     }\n     const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;\n@@ -164,8 +166,8 @@ export default class EventManager {\n         meetingId: createdEventObj ? createdEventObj.id : result.createdEvent?.id?.toString(),\n         meetingPassword: createdEventObj ? createdEventObj.password : result.createdEvent?.password,\n         meetingUrl: createdEventObj ? createdEventObj.onlineMeetingUrl : result.createdEvent?.url,\n-        externalCalendarId: isCalendarType ? evt.destinationCalendar?.externalId : undefined,\n-        credentialId: isCalendarType ? evt.destinationCalendar?.credentialId : result.credentialId,\n+        externalCalendarId: isCalendarType ? result.externalId : undefined,\n+        credentialId: isCalendarType ? result.credentialId : undefined,\n       };\n     });\n \n@@ -203,8 +205,8 @@ export default class EventManager {\n         meetingId: result.createdEvent?.id?.toString(),\n         meetingPassword: result.createdEvent?.password,\n         meetingUrl: result.createdEvent?.url,\n-        externalCalendarId: evt.destinationCalendar?.externalId,\n-        credentialId: result.credentialId ?? evt.destinationCalendar?.credentialId,\n+        externalCalendarId: result.externalId,\n+        credentialId: result.credentialId ?? undefined,\n       };\n     });\n \n@@ -332,29 +334,52 @@ export default class EventManager {\n    * @private\n    */\n   private async createAllCalendarEvents(event: CalendarEvent) {\n-    /** Can I use destinationCalendar here? */\n-    /* How can I link a DC to a cred? */\n-\n     let createdEvents: EventResult<NewCalendarEventType>[] = [];\n-    if (event.destinationCalendar) {\n-      if (event.destinationCalendar.credentialId) {\n-        const credential = this.calendarCredentials.find(\n-          (c) => c.id === event.destinationCalendar?.credentialId\n-        );\n-\n-        if (credential) {\n-          const createdEvent = await createEvent(credential, event);\n-          if (createdEvent) {\n-            createdEvents.push(createdEvent);\n+    if (event.destinationCalendar && event.destinationCalendar.length > 0) {\n+      for (const destination of event.destinationCalendar) {\n+        if (destination.credentialId) {\n+          let credential = this.calendarCredentials.find((c) => c.id === destination.credentialId);\n+          if (!credential) {\n+            // Fetch credential from DB\n+            const credentialFromDB = await prisma.credential.findUnique({\n+              include: {\n+                app: {\n+                  select: {\n+                    slug: true,\n+                  },\n+                },\n+              },\n+              where: {\n+                id: destination.credentialId,\n+              },\n+            });\n+            if (credentialFromDB && credentialFromDB.app?.slug) {\n+              credential = {\n+                appName: credentialFromDB?.app.slug ?? \"\",\n+                id: credentialFromDB.id,\n+                type: credentialFromDB.type,\n+                key: credentialFromDB.key,\n+                userId: credentialFromDB.userId,\n+                teamId: credentialFromDB.teamId,\n+                invalid: credentialFromDB.invalid,\n+                appId: credentialFromDB.appId,\n+              };\n+            }\n+          }\n+          if (credential) {\n+            const createdEvent = await createEvent(credential, event, destination.externalId);\n+            if (createdEvent) {\n+              createdEvents.push(createdEvent);\n+            }\n           }\n+        } else {\n+          const destinationCalendarCredentials = this.calendarCredentials.filter(\n+            (c) => c.type === destination.integration\n+          );\n+          createdEvents = createdEvents.concat(\n+            await Promise.all(destinationCalendarCredentials.map(async (c) => await createEvent(c, event)))\n+          );\n         }\n-      } else {\n-        const destinationCalendarCredentials = this.calendarCredentials.filter(\n-          (c) => c.type === event.destinationCalendar?.integration\n-        );\n-        createdEvents = createdEvents.concat(\n-          await Promise.all(destinationCalendarCredentials.map(async (c) => await createEvent(c, event)))\n-        );\n       }\n     } else {\n       /**\n@@ -451,7 +476,7 @@ export default class EventManager {\n     booking: PartialBooking,\n     newBookingId?: number\n   ): Promise<Array<EventResult<NewCalendarEventType>>> {\n-    let calendarReference: PartialReference | undefined = undefined,\n+    let calendarReference: PartialReference[] | undefined = undefined,\n       credential;\n     try {\n       // If a newBookingId is given, update that calendar event\n@@ -468,33 +493,62 @@ export default class EventManager {\n       }\n \n       calendarReference = newBooking?.references.length\n-        ? newBooking.references.find((reference) => reference.type.includes(\"_calendar\"))\n-        : booking.references.find((reference) => reference.type.includes(\"_calendar\"));\n+        ? newBooking.references.filter((reference) => reference.type.includes(\"_calendar\"))\n+        : booking.references.filter((reference) => reference.type.includes(\"_calendar\"));\n \n-      if (!calendarReference) {\n+      if (calendarReference.length === 0) {\n         return [];\n       }\n-      const { uid: bookingRefUid, externalCalendarId: bookingExternalCalendarId } = calendarReference;\n-      let calenderExternalId: string | null = null;\n-      if (bookingExternalCalendarId) {\n-        calenderExternalId = bookingExternalCalendarId;\n-      }\n-\n+      // process all calendar references\n       let result = [];\n-      if (calendarReference.credentialId) {\n-        credential = this.calendarCredentials.filter(\n-          (credential) => credential.id === calendarReference?.credentialId\n-        )[0];\n-        result.push(updateEvent(credential, event, bookingRefUid, calenderExternalId));\n-      } else {\n-        const credentials = this.calendarCredentials.filter(\n-          (credential) => credential.type === calendarReference?.type\n-        );\n-        for (const credential of credentials) {\n+      for (const reference of calendarReference) {\n+        const { uid: bookingRefUid, externalCalendarId: bookingExternalCalendarId } = reference;\n+        let calenderExternalId: string | null = null;\n+        if (bookingExternalCalendarId) {\n+          calenderExternalId = bookingExternalCalendarId;\n+        }\n+\n+        if (reference.credentialId) {\n+          credential = this.calendarCredentials.filter(\n+            (credential) => credential.id === reference?.credentialId\n+          )[0];\n+          if (!credential) {\n+            // Fetch credential from DB\n+            const credentialFromDB = await prisma.credential.findUnique({\n+              include: {\n+                app: {\n+                  select: {\n+                    slug: true,\n+                  },\n+                },\n+              },\n+              where: {\n+                id: reference.credentialId,\n+              },\n+            });\n+            if (credentialFromDB && credentialFromDB.app?.slug) {\n+              credential = {\n+                appName: credentialFromDB?.app.slug ?? \"\",\n+                id: credentialFromDB.id,\n+                type: credentialFromDB.type,\n+                key: credentialFromDB.key,\n+                userId: credentialFromDB.userId,\n+                teamId: credentialFromDB.teamId,\n+                invalid: credentialFromDB.invalid,\n+                appId: credentialFromDB.appId,\n+              };\n+            }\n+          }\n           result.push(updateEvent(credential, event, bookingRefUid, calenderExternalId));\n+        } else {\n+          const credentials = this.calendarCredentials.filter(\n+            (credential) => credential.type === reference?.type\n+          );\n+          for (const credential of credentials) {\n+            result.push(updateEvent(credential, event, bookingRefUid, calenderExternalId));\n+          }\n         }\n       }\n-\n       // If we are merging two calendar events we should delete the old calendar event\n       if (newBookingId) {\n         const oldCalendarEvent = booking.references.find((reference) => reference.type.includes(\"_calendar\"));\n@@ -516,17 +570,17 @@ export default class EventManager {\n           .filter((cred) => cred.type.includes(\"other_calendar\"))\n           .map(async (cred) => {\n             const calendarReference = booking.references.find((ref) => ref.type === cred.type);\n-            if (!calendarReference)\n-              if (!calendarReference) {\n-                return {\n-                  appName: cred.appName,\n-                  type: cred.type,\n-                  success: false,\n-                  uid: \"\",\n-                  originalEvent: event,\n-                  credentialId: cred.id,\n-                };\n-              }\n+\n+            if (!calendarReference) {\n+              return {\n+                appName: cred.appName,\n+                type: cred.type,\n+                success: false,\n+                uid: \"\",\n+                originalEvent: event,\n+                credentialId: cred.id,\n+              };\n+            }\n             const { externalCalendarId: bookingExternalCalendarId, meetingId: bookingRefUid } =\n               calendarReference;\n             return await updateEvent(cred, event, bookingRefUid ?? null, bookingExternalCalendarId ?? null);\n@@ -539,17 +593,19 @@ export default class EventManager {\n       if (error instanceof Error) {\n         message = message.replace(\"{thing}\", error.message);\n       }\n-      console.error(message);\n-      return Promise.resolve([\n-        {\n-          appName: \"none\",\n-          type: calendarReference?.type || \"calendar\",\n-          success: false,\n-          uid: \"\",\n-          originalEvent: event,\n-          credentialId: 0,\n-        },\n-      ]);\n+\n+      return Promise.resolve(\n+        calendarReference?.map((reference) => {\n+          return {\n+            appName: \"none\",\n+            type: reference?.type || \"calendar\",\n+            success: false,\n+            uid: \"\",\n+            originalEvent: event,\n+            credentialId: 0,\n+          };\n+        }) ?? ([] as Array<EventResult<NewCalendarEventType>>)\n+      );\n     }\n   }\n \ndiff --git a/packages/core/builders/CalendarEvent/builder.ts b/packages/core/builders/CalendarEvent/builder.ts\nindex 8aa4b3cb7c8..80a75ba2b14 100644\n--- a/packages/core/builders/CalendarEvent/builder.ts\n+++ b/packages/core/builders/CalendarEvent/builder.ts\n@@ -1,4 +1,5 @@\n-import { Prisma, Booking } from \"@prisma/client\";\n+import type { Booking } from \"@prisma/client\";\n+import { Prisma } from \"@prisma/client\";\n import short from \"short-uuid\";\n import { v5 as uuidv5 } from \"uuid\";\n \ndiff --git a/packages/core/builders/CalendarEvent/class.ts b/packages/core/builders/CalendarEvent/class.ts\nindex 880fde52872..2f069c3425a 100644\n--- a/packages/core/builders/CalendarEvent/class.ts\n+++ b/packages/core/builders/CalendarEvent/class.ts\n@@ -23,7 +23,7 @@ class CalendarEventClass implements CalendarEvent {\n   uid?: string | null;\n   videoCallData?: VideoCallData;\n   paymentInfo?: any;\n-  destinationCalendar?: DestinationCalendar | null;\n+  destinationCalendar?: DestinationCalendar[] | null;\n   cancellationReason?: string | null;\n   rejectionReason?: string | null;\n   hideCalendarNotes?: boolean;\ndiff --git a/packages/emails/src/templates/BrokenIntegrationEmail.tsx b/packages/emails/src/templates/BrokenIntegrationEmail.tsx\nindex 99f7fe72ce2..afb7edd31d6 100644\n--- a/packages/emails/src/templates/BrokenIntegrationEmail.tsx\n+++ b/packages/emails/src/templates/BrokenIntegrationEmail.tsx\n@@ -85,8 +85,9 @@ export const BrokenIntegrationEmail = (\n \n   if (type === \"calendar\") {\n     // The calendar name is stored as name_calendar\n-    let calendar = calEvent.destinationCalendar\n-      ? calEvent.destinationCalendar?.integration.split(\"_\")\n+    const [mainHostDestinationCalendar] = calEvent.destinationCalendar ?? [];\n+    let calendar = mainHostDestinationCalendar\n+      ? mainHostDestinationCalendar?.integration.split(\"_\")\n       : \"calendar\";\n \n     if (Array.isArray(calendar)) {\ndiff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts\nindex 277aaae159c..dcfee8a4a76 100644\n--- a/packages/features/bookings/lib/handleCancelBooking.ts\n+++ b/packages/features/bookings/lib/handleCancelBooking.ts\n@@ -248,7 +248,11 @@ async function handler(req: CustomRequest) {\n       ? parseRecurringEvent(bookingToDelete.eventType?.recurringEvent)\n       : undefined,\n     location: bookingToDelete?.location,\n-    destinationCalendar: bookingToDelete?.destinationCalendar || bookingToDelete?.user.destinationCalendar,\n+    destinationCalendar: bookingToDelete?.destinationCalendar\n+      ? [bookingToDelete?.destinationCalendar]\n+      : bookingToDelete?.user.destinationCalendar\n+      ? [bookingToDelete?.user.destinationCalendar]\n+      : [],\n     cancellationReason: cancellationReason,\n     ...(teamMembers && { team: { name: \"\", members: teamMembers } }),\n     seatsPerTimeSlot: bookingToDelete.eventType?.seatsPerTimeSlot,\n@@ -411,58 +415,71 @@ async function handler(req: CustomRequest) {\n \n   const apiDeletes = [];\n \n-  const bookingCalendarReference = bookingToDelete.references.find((reference) =>\n+  const bookingCalendarReference = bookingToDelete.references.filter((reference) =>\n     reference.type.includes(\"_calendar\")\n   );\n \n-  if (bookingCalendarReference) {\n-    const { credentialId, uid, externalCalendarId } = bookingCalendarReference;\n-    // If the booking calendar reference contains a credentialId\n-    if (credentialId) {\n-      // Find the correct calendar credential under user credentials\n-      const calendarCredential = bookingToDelete.user.credentials.find(\n-        (credential) => credential.id === credentialId\n-      );\n-      if (calendarCredential) {\n-        const calendar = await getCalendar(calendarCredential);\n-        if (\n-          bookingToDelete.eventType?.recurringEvent &&\n-          bookingToDelete.recurringEventId &&\n-          allRemainingBookings\n-        ) {\n-          const promises = bookingToDelete.user.credentials\n-            .filter((credential) => credential.type.endsWith(\"_calendar\"))\n-            .map(async (credential) => {\n-              const calendar = await getCalendar(credential);\n-              for (const updBooking of updatedBookings) {\n-                const bookingRef = updBooking.references.find((ref) => ref.type.includes(\"_calendar\"));\n-                if (bookingRef) {\n-                  const { uid, externalCalendarId } = bookingRef;\n-                  const deletedEvent = await calendar?.deleteEvent(uid, evt, externalCalendarId);\n-                  apiDeletes.push(deletedEvent);\n+  if (bookingCalendarReference.length > 0) {\n+    for (const reference of bookingCalendarReference) {\n+      const { credentialId, uid, externalCalendarId } = reference;\n+      // If the booking calendar reference contains a credentialId\n+      if (credentialId) {\n+        // Find the correct calendar credential under user credentials\n+        let calendarCredential = bookingToDelete.user.credentials.find(\n+          (credential) => credential.id === credentialId\n+        );\n+        if (!calendarCredential) {\n+          // get credential from DB\n+          const foundCalendarCredential = await prisma.credential.findUnique({\n+            where: {\n+              id: credentialId,\n+            },\n+          });\n+          if (foundCalendarCredential) {\n+            calendarCredential = foundCalendarCredential;\n+          }\n+        }\n+        if (calendarCredential) {\n+          const calendar = await getCalendar(calendarCredential);\n+          if (\n+            bookingToDelete.eventType?.recurringEvent &&\n+            bookingToDelete.recurringEventId &&\n+            allRemainingBookings\n+          ) {\n+            const promises = bookingToDelete.user.credentials\n+              .filter((credential) => credential.type.endsWith(\"_calendar\"))\n+              .map(async (credential) => {\n+                const calendar = await getCalendar(credential);\n+                for (const updBooking of updatedBookings) {\n+                  const bookingRef = updBooking.references.find((ref) => ref.type.includes(\"_calendar\"));\n+                  if (bookingRef) {\n+                    const { uid, externalCalendarId } = bookingRef;\n+                    const deletedEvent = await calendar?.deleteEvent(uid, evt, externalCalendarId);\n+                    apiDeletes.push(deletedEvent);\n+                  }\n                 }\n+              });\n+            try {\n+              await Promise.all(promises);\n+            } catch (error) {\n+              if (error instanceof Error) {\n+                logger.error(error.message);\n               }\n-            });\n-          try {\n-            await Promise.all(promises);\n-          } catch (error) {\n-            if (error instanceof Error) {\n-              logger.error(error.message);\n             }\n+          } else {\n+            apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);\n           }\n-        } else {\n+        }\n+      } else {\n+        // For bookings made before the refactor we go through the old behavior of running through each calendar credential\n+        const calendarCredentials = bookingToDelete.user.credentials.filter((credential) =>\n+          credential.type.endsWith(\"_calendar\")\n+        );\n+        for (const credential of calendarCredentials) {\n+          const calendar = await getCalendar(credential);\n           apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);\n         }\n       }\n-    } else {\n-      // For bookings made before the refactor we go through the old behaviour of running through each calendar credential\n-      const calendarCredentials = bookingToDelete.user.credentials.filter((credential) =>\n-        credential.type.endsWith(\"_calendar\")\n-      );\n-      for (const credential of calendarCredentials) {\n-        const calendar = await getCalendar(credential);\n-        apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);\n-      }\n     }\n   }\n \n@@ -508,7 +525,11 @@ async function handler(req: CustomRequest) {\n       attendees: attendeesList,\n       location: bookingToDelete.location ?? \"\",\n       uid: bookingToDelete.uid ?? \"\",\n-      destinationCalendar: bookingToDelete?.destinationCalendar || bookingToDelete?.user.destinationCalendar,\n+      destinationCalendar: bookingToDelete?.destinationCalendar\n+        ? [bookingToDelete?.destinationCalendar]\n+        : bookingToDelete?.user.destinationCalendar\n+        ? [bookingToDelete?.user.destinationCalendar]\n+        : [],\n     };\n \n     const successPayment = bookingToDelete.payment.find((payment) => payment.success);\ndiff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.ts\nindex 03702f100dc..a7b1fdd3c24 100644\n--- a/packages/features/bookings/lib/handleNewBooking.ts\n+++ b/packages/features/bookings/lib/handleNewBooking.ts\n@@ -1,4 +1,4 @@\n-import type { App, Attendee, Credential, EventTypeCustomInput } from \"@prisma/client\";\n+import type { App, Attendee, Credential, EventTypeCustomInput, DestinationCalendar } from \"@prisma/client\";\n import { Prisma } from \"@prisma/client\";\n import async from \"async\";\n import { isValidPhoneNumber } from \"libphonenumber-js\";\n@@ -367,7 +367,7 @@ async function ensureAvailableUsers(\n ) {\n   const availableUsers: IsFixedAwareUser[] = [];\n \n-  const orginalBookingDuration = input.originalRescheduledBooking\n+  const originalBookingDuration = input.originalRescheduledBooking\n     ? dayjs(input.originalRescheduledBooking.endTime).diff(\n         dayjs(input.originalRescheduledBooking.startTime),\n         \"minutes\"\n@@ -380,7 +380,7 @@ async function ensureAvailableUsers(\n       {\n         userId: user.id,\n         eventTypeId: eventType.id,\n-        duration: orginalBookingDuration,\n+        duration: originalBookingDuration,\n         ...input,\n       },\n       {\n@@ -686,8 +686,7 @@ async function handler(\n   if (!eventType) throw new HttpError({ statusCode: 404, message: \"eventType.notFound\" });\n \n   const isTeamEventType =\n-    eventType.schedulingType === SchedulingType.COLLECTIVE ||\n-    eventType.schedulingType === SchedulingType.ROUND_ROBIN;\n+    !!eventType.schedulingType && [\"COLLECTIVE\", \"ROUND_ROBIN\"].includes(eventType.schedulingType);\n \n   const paymentAppData = getPaymentAppData(eventType);\n \n@@ -722,31 +721,46 @@ async function handler(\n     throw new HttpError({ statusCode: 400, message: error.message });\n   }\n \n-  const loadUsers = async () =>\n-    !eventTypeId\n-      ? await prisma.user.findMany({\n+  const loadUsers = async () => {\n+    try {\n+      if (!eventTypeId) {\n+        if (!Array.isArray(dynamicUserList) || dynamicUserList.length === 0) {\n+          throw new Error(\"dynamicUserList is not properly defined or empty.\");\n+        }\n+\n+        const users = await prisma.user.findMany({\n           where: {\n-            username: {\n-              in: dynamicUserList,\n-            },\n+            username: { in: dynamicUserList },\n           },\n           select: {\n             ...userSelect.select,\n-            credentials: true, // Don't leak to client\n+            credentials: true,\n             metadata: true,\n-            organization: {\n-              select: {\n-                slug: true,\n-              },\n-            },\n           },\n-        })\n-      : eventType.hosts?.length\n-      ? eventType.hosts.map(({ user, isFixed }) => ({\n+        });\n+\n+        return users;\n+      } else {\n+        const hosts = eventType.hosts || [];\n+\n+        if (!Array.isArray(hosts)) {\n+          throw new Error(\"eventType.hosts is not properly defined.\");\n+        }\n+\n+        const users = hosts.map(({ user, isFixed }) => ({\n           ...user,\n           isFixed,\n-        }))\n-      : eventType.users || [];\n+        }));\n+\n+        return users.length ? users : eventType.users;\n+      }\n+    } catch (error) {\n+      if (error instanceof HttpError || error instanceof Prisma.PrismaClientKnownRequestError) {\n+        throw new HttpError({ statusCode: 400, message: error.message });\n+      }\n+      throw new HttpError({ statusCode: 500, message: \"Unable to load users\" });\n+    }\n+  };\n   // loadUsers allows type inferring\n   let users: (Awaited<ReturnType<typeof loadUsers>>[number] & {\n     isFixed?: boolean;\n@@ -970,20 +984,26 @@ async function handler(\n     : getLocationValueForDB(locationBodyString, eventType.locations);\n \n   const customInputs = getCustomInputsResponses(reqBody, eventType.customInputs);\n-  const teamMemberPromises =\n-    users.length > 1\n-      ? users.slice(1).map(async function (user) {\n-          return {\n-            email: user.email || \"\",\n-            name: user.name || \"\",\n-            timeZone: user.timeZone,\n-            language: {\n-              translate: await getTranslation(user.locale ?? \"en\", \"common\"),\n-              locale: user.locale ?? \"en\",\n-            },\n-          };\n-        })\n-      : [];\n+  const teamDestinationCalendars: DestinationCalendar[] = [];\n+\n+  // Organizer or user owner of this event type it's not listed as a team member.\n+  const teamMemberPromises = users.slice(1).map(async (user) => {\n+    // push to teamDestinationCalendars if it's a team event but collective only\n+    if (isTeamEventType && eventType.schedulingType === \"COLLECTIVE\" && user.destinationCalendar) {\n+      teamDestinationCalendars.push(user.destinationCalendar);\n+    }\n+    return {\n+      email: user.email ?? \"\",\n+      name: user.name ?? \"\",\n+      firstName: \"\",\n+      lastName: \"\",\n+      timeZone: user.timeZone,\n+      language: {\n+        translate: await getTranslation(user.locale ?? \"en\", \"common\"),\n+        locale: user.locale ?? \"en\",\n+      },\n+    };\n+  });\n \n   const teamMembers = await Promise.all(teamMemberPromises);\n \n@@ -1040,16 +1060,24 @@ async function handler(\n     attendees: attendeesList,\n     location: bookingLocation, // Will be processed by the EventManager later.\n     conferenceCredentialId,\n-    /** For team events & dynamic collective events, we will need to handle each member destinationCalendar eventually */\n-    destinationCalendar: eventType.destinationCalendar || organizerUser.destinationCalendar,\n+    destinationCalendar: eventType.destinationCalendar\n+      ? [eventType.destinationCalendar]\n+      : organizerUser.destinationCalendar\n+      ? [organizerUser.destinationCalendar]\n+      : null,\n     hideCalendarNotes: eventType.hideCalendarNotes,\n     requiresConfirmation: requiresConfirmation ?? false,\n     eventTypeId: eventType.id,\n     // if seats are not enabled we should default true\n     seatsShowAttendees: eventType.seatsPerTimeSlot ? eventType.seatsShowAttendees : true,\n     seatsPerTimeSlot: eventType.seatsPerTimeSlot,\n+    schedulingType: eventType.schedulingType,\n   };\n \n+  if (isTeamEventType && eventType.schedulingType === \"COLLECTIVE\") {\n+    evt.destinationCalendar?.push(...teamDestinationCalendars);\n+  }\n+\n   /* Used for seats bookings to update evt object with video data */\n   const addVideoCallDataToEvt = (bookingReferences: BookingReference[]) => {\n     const videoCallReference = bookingReferences.find((reference) => reference.type.includes(\"_video\"));\n@@ -1843,11 +1871,12 @@ async function handler(\n           id: organizerUser.id,\n         },\n       },\n-      destinationCalendar: evt.destinationCalendar\n-        ? {\n-            connect: { id: evt.destinationCalendar.id },\n-          }\n-        : undefined,\n+      destinationCalendar:\n+        evt.destinationCalendar && evt.destinationCalendar.length > 0\n+          ? {\n+              connect: { id: evt.destinationCalendar[0].id },\n+            }\n+          : undefined,\n     };\n \n     if (reqBody.recurringEventId) {\ndiff --git a/packages/features/ee/payments/api/paypal-webhook.ts b/packages/features/ee/payments/api/paypal-webhook.ts\nindex 493626200b6..06708fe0fdf 100644\n--- a/packages/features/ee/payments/api/paypal-webhook.ts\n+++ b/packages/features/ee/payments/api/paypal-webhook.ts\n@@ -149,7 +149,11 @@ export async function handlePaymentSuccess(\n     },\n     attendees: attendeesList,\n     uid: booking.uid,\n-    destinationCalendar: booking.destinationCalendar || user.destinationCalendar,\n+    destinationCalendar: booking.destinationCalendar\n+      ? [booking.destinationCalendar]\n+      : user.destinationCalendar\n+      ? [user.destinationCalendar]\n+      : [],\n     recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),\n   };\n \ndiff --git a/packages/features/ee/payments/api/webhook.ts b/packages/features/ee/payments/api/webhook.ts\nindex deb8f6e9931..c6b563a0711 100644\n--- a/packages/features/ee/payments/api/webhook.ts\n+++ b/packages/features/ee/payments/api/webhook.ts\n@@ -98,7 +98,7 @@ async function getBooking(bookingId: number) {\n   });\n \n   const attendeesList = await Promise.all(attendeesListPromises);\n-\n+  const selectedDestinationCalendar = booking.destinationCalendar || user.destinationCalendar;\n   const evt: CalendarEvent = {\n     type: booking.title,\n     title: booking.title,\n@@ -116,7 +116,7 @@ async function getBooking(bookingId: number) {\n     },\n     attendees: attendeesList,\n     uid: booking.uid,\n-    destinationCalendar: booking.destinationCalendar || user.destinationCalendar,\n+    destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],\n     recurringEvent: parseRecurringEvent(eventType?.recurringEvent),\n   };\n \n@@ -204,7 +204,7 @@ async function handlePaymentSuccess(event: Stripe.Event) {\n   });\n \n   const attendeesList = await Promise.all(attendeesListPromises);\n-\n+  const selectedDestinationCalendar = booking.destinationCalendar || user.destinationCalendar;\n   const evt: CalendarEvent = {\n     type: booking.title,\n     title: booking.title,\n@@ -226,7 +226,7 @@ async function handlePaymentSuccess(event: Stripe.Event) {\n     attendees: attendeesList,\n     location: booking.location,\n     uid: booking.uid,\n-    destinationCalendar: booking.destinationCalendar || user.destinationCalendar,\n+    destinationCalendar: selectedDestinationCalendar ? [selectedDestinationCalendar] : [],\n     recurringEvent: parseRecurringEvent(eventTypeRaw?.recurringEvent),\n   };\n \ndiff --git a/packages/lib/CalendarService.ts b/packages/lib/CalendarService.ts\nindex c18dec7332a..da4a32f7fd8 100644\n--- a/packages/lib/CalendarService.ts\n+++ b/packages/lib/CalendarService.ts\n@@ -153,12 +153,14 @@ export default abstract class BaseCalendarService implements Calendar {\n       if (error || !iCalString)\n         throw new Error(`Error creating iCalString:=> ${error?.message} : ${error?.name} `);\n \n+      const [mainHostDestinationCalendar] = event.destinationCalendar ?? [];\n+\n       // We create the event directly on iCal\n       const responses = await Promise.all(\n         calendars\n           .filter((c) =>\n-            event.destinationCalendar?.externalId\n-              ? c.externalId === event.destinationCalendar.externalId\n+            mainHostDestinationCalendar?.externalId\n+              ? c.externalId === mainHostDestinationCalendar.externalId\n               : true\n           )\n           .map((calendar) =>\n@@ -504,13 +506,13 @@ export default abstract class BaseCalendarService implements Calendar {\n \n       return calendars.reduce<IntegrationCalendar[]>((newCalendars, calendar) => {\n         if (!calendar.components?.includes(\"VEVENT\")) return newCalendars;\n-\n+        const [mainHostDestinationCalendar] = event?.destinationCalendar ?? [];\n         newCalendars.push({\n           externalId: calendar.url,\n           /** @url https://github.com/calcom/cal.com/issues/7186 */\n           name: typeof calendar.displayName === \"string\" ? calendar.displayName : \"\",\n-          primary: event?.destinationCalendar?.externalId\n-            ? event.destinationCalendar.externalId === calendar.url\n+          primary: mainHostDestinationCalendar?.externalId\n+            ? mainHostDestinationCalendar.externalId === calendar.url\n             : false,\n           integration: this.integrationName,\n           email: this.credentials.username ?? \"\",\ndiff --git a/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts b/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts\nindex 4d676f9bfb5..fe7032b1412 100644\n--- a/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts\n+++ b/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts\n@@ -287,7 +287,11 @@ export const deleteCredentialHandler = async ({ ctx, input }: DeleteCredentialOp\n                 uid: booking.uid,\n                 recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),\n                 location: booking.location,\n-                destinationCalendar: booking.destinationCalendar || booking.user?.destinationCalendar,\n+                destinationCalendar: booking.destinationCalendar\n+                  ? [booking.destinationCalendar]\n+                  : booking.user?.destinationCalendar\n+                  ? [booking.user?.destinationCalendar]\n+                  : [],\n                 cancellationReason: \"Payment method removed by organizer\",\n                 seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot,\n                 seatsShowAttendees: booking.eventType?.seatsShowAttendees,\ndiff --git a/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts b/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts\nindex 8d32d64c15c..d3182bdfc02 100644\n--- a/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts\n+++ b/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts\n@@ -172,7 +172,11 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => {\n     attendees: attendeesList,\n     location: booking.location ?? \"\",\n     uid: booking.uid,\n-    destinationCalendar: booking?.destinationCalendar || user.destinationCalendar,\n+    destinationCalendar: booking?.destinationCalendar\n+      ? [booking.destinationCalendar]\n+      : user.destinationCalendar\n+      ? [user.destinationCalendar]\n+      : [],\n     requiresConfirmation: booking?.eventType?.requiresConfirmation ?? false,\n     eventTypeId: booking.eventType?.id,\n   };\ndiff --git a/packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts b/packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts\nindex 19695fd4452..e4110f2405b 100644\n--- a/packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts\n+++ b/packages/trpc/server/routers/viewer/bookings/editLocation.handler.ts\n@@ -82,7 +82,11 @@ export const editLocationHandler = async ({ ctx, input }: EditLocationOptions) =\n       recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),\n       location,\n       conferenceCredentialId: details?.credentialId,\n-      destinationCalendar: booking?.destinationCalendar || booking?.user?.destinationCalendar,\n+      destinationCalendar: booking?.destinationCalendar\n+        ? [booking?.destinationCalendar]\n+        : booking?.user?.destinationCalendar\n+        ? [booking?.user?.destinationCalendar]\n+        : [],\n       seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot,\n       seatsShowAttendees: booking.eventType?.seatsShowAttendees,\n     };\ndiff --git a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts\nindex 324ed230575..8d1adb8e16d 100644\n--- a/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts\n+++ b/packages/trpc/server/routers/viewer/bookings/requestReschedule.handler.ts\n@@ -237,7 +237,9 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule\n     ),\n     uid: bookingToReschedule?.uid,\n     location: bookingToReschedule?.location,\n-    destinationCalendar: bookingToReschedule?.destinationCalendar || bookingToReschedule?.destinationCalendar,\n+    destinationCalendar: bookingToReschedule?.destinationCalendar\n+      ? [bookingToReschedule?.destinationCalendar]\n+      : [],\n     cancellationReason: `Please reschedule. ${cancellationReason}`, // TODO::Add i18-next for this\n   };\n \ndiff --git a/packages/trpc/server/routers/viewer/organizations/create.handler.ts b/packages/trpc/server/routers/viewer/organizations/create.handler.ts\nindex 2cfabcf5fe6..c80deb47741 100644\n--- a/packages/trpc/server/routers/viewer/organizations/create.handler.ts\n+++ b/packages/trpc/server/routers/viewer/organizations/create.handler.ts\n@@ -148,9 +148,9 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {\n         organization: {\n           create: {\n             name,\n-            ...(!IS_TEAM_BILLING_ENABLED && { slug }),\n+            ...(IS_TEAM_BILLING_ENABLED ? { slug } : {}),\n             metadata: {\n-              ...(IS_TEAM_BILLING_ENABLED && { requestedSlug: slug }),\n+              ...(IS_TEAM_BILLING_ENABLED ? { requestedSlug: slug } : {}),\n               isOrganization: true,\n               isOrganizationVerified: false,\n               isOrganizationConfigured,\ndiff --git a/packages/types/Calendar.d.ts b/packages/types/Calendar.d.ts\nindex a7e3ba70a9d..c5714c2c0df 100644\n--- a/packages/types/Calendar.d.ts\n+++ b/packages/types/Calendar.d.ts\n@@ -8,6 +8,7 @@ import type z from \"zod\";\n import type { bookingResponse } from \"@calcom/features/bookings/lib/getBookingResponsesSchema\";\n import type { Calendar } from \"@calcom/features/calendars/weeklyview\";\n import type { TimeFormat } from \"@calcom/lib/timeFormat\";\n+import type { SchedulingType } from \"@calcom/prisma/enums\";\n import type { Frequency } from \"@calcom/prisma/zod-utils\";\n import type { CredentialPayload } from \"@calcom/types/Credential\";\n \n@@ -167,7 +168,7 @@ export interface CalendarEvent {\n   videoCallData?: VideoCallData;\n   paymentInfo?: PaymentInfo | null;\n   requiresConfirmation?: boolean | null;\n-  destinationCalendar?: DestinationCalendar | null;\n+  destinationCalendar?: DestinationCalendar[] | null;\n   cancellationReason?: string | null;\n   rejectionReason?: string | null;\n   hideCalendarNotes?: boolean;\n@@ -178,6 +179,7 @@ export interface CalendarEvent {\n   seatsShowAttendees?: boolean | null;\n   attendeeSeatId?: string;\n   seatsPerTimeSlot?: number | null;\n+  schedulingType?: SchedulingType | null;\n   iCalUID?: string | null;\n \n   // It has responses to all the fields(system + user)\n@@ -216,7 +218,7 @@ export interface IntegrationCalendar extends Ensure<Partial<SelectedCalendar>, \"\n }\n \n export interface Calendar {\n-  createEvent(event: CalendarEvent): Promise<NewCalendarEventType>;\n+  createEvent(event: CalendarEvent, credentialId: number): Promise<NewCalendarEventType>;\n \n   updateEvent(\n     uid: string,\ndiff --git a/packages/types/EventManager.d.ts b/packages/types/EventManager.d.ts\nindex d93069f63e8..14209e0b412 100644\n--- a/packages/types/EventManager.d.ts\n+++ b/packages/types/EventManager.d.ts\n@@ -23,6 +23,7 @@ export interface EventResult<T> {\n   calError?: string;\n   calWarnings?: string[];\n   credentialId?: number;\n+  externalId?: string | null;\n }\n \n export interface CreateUpdateResult {\n", "gold_issues": [{"pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "issue_index": 0, "comment": "Potential null reference if mainHostDestinationCalendar is undefined if evt.destinationCalendar is null or an empty array ", "severity": "High"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "issue_index": 1, "comment": "The optional chaining on mainHostDestinationCalendar?.integration is redundant since you already check mainHostDestinationCalendar in the ternary condition.", "severity": "Low"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "issue_index": 2, "comment": "Logic error: when externalCalendarId is provided, you're searching for a calendar where externalId === externalCalendarId, but this will always fail since you're looking for a calendar that matches itself. Should likely find by credentialId or use different logic.", "severity": "High"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "issue_index": 3, "comment": "Logic inversion in organization creation: The slug property is now conditionally set when IS_TEAM_BILLING_ENABLED is true, instead of when it's false as originally intended. This change, combined with requestedSlug still being set when IS_TEAM_BILLING_ENABLED is true, results in both properties being set when billing is enabled, and neither when disabled", "severity": "Medium"}, {"pr_url": "https://github.com/calcom/cal.com/pull/10967", "source_repo": "cal.dot.com", "pr_title": "fix: handle collective multiple host on destinationCalendar", "issue_index": 4, "comment": "The Calendar interface now requires createEvent(event, credentialId), but some implementations (e.g., Lark/Office365) still declare createEvent(event) only—this breaks the interface contract (also applies to other locations in the PR).", "severity": "Low"}]}
{"task_id": "https://github.com/calcom/cal.com/pull/22345", "pr_url": "https://github.com/calcom/cal.com/pull/22345", "source_repo": "cal.dot.com", "pr_title": "feat: convert InsightsBookingService to use Prisma.sql raw queries", "diff": "diff --git a/packages/lib/server/service/__tests__/insightsBooking.integration-test.ts b/packages/lib/server/service/__tests__/insightsBooking.integration-test.ts\nindex fdfd58336fa..fabd45af99b 100644\n--- a/packages/lib/server/service/__tests__/insightsBooking.integration-test.ts\n+++ b/packages/lib/server/service/__tests__/insightsBooking.integration-test.ts\n@@ -1,4 +1,5 @@\n import type { Team, User, Membership } from \"@prisma/client\";\n+import { Prisma } from \"@prisma/client\";\n import { describe, expect, it } from \"vitest\";\n \n import prisma from \"@calcom/prisma\";\n@@ -6,6 +7,8 @@ import { BookingStatus, MembershipRole } from \"@calcom/prisma/enums\";\n \n import { InsightsBookingService } from \"../../service/insightsBooking\";\n \n+const NOTHING_CONDITION = Prisma.sql`1=0`;\n+\n // Helper function to create unique test data\n async function createTestData({\n   teamRole = MembershipRole.MEMBER,\n@@ -204,7 +207,7 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getAuthorizationConditions();\n-      expect(conditions).toEqual({ id: -1 });\n+      expect(conditions).toEqual(NOTHING_CONDITION);\n     });\n \n     it(\"should return NOTHING for non-owner/admin user\", async () => {\n@@ -239,7 +242,7 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getAuthorizationConditions();\n-      expect(conditions).toEqual({ id: -1 });\n+      expect(conditions).toEqual(NOTHING_CONDITION);\n \n       // Clean up\n       await prisma.membership.delete({\n@@ -267,14 +270,7 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getAuthorizationConditions();\n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            userId: testData.user.id,\n-            teamId: null,\n-          },\n-        ],\n-      });\n+      expect(conditions).toEqual(Prisma.sql`(\"userId\" = ${testData.user.id}) AND (\"teamId\" IS NULL)`);\n \n       await testData.cleanup();\n     });\n@@ -296,24 +292,11 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getAuthorizationConditions();\n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            OR: [\n-              {\n-                teamId: testData.team.id,\n-                isTeamBooking: true,\n-              },\n-              {\n-                userId: {\n-                  in: [testData.user.id],\n-                },\n-                isTeamBooking: false,\n-              },\n-            ],\n-          },\n-        ],\n-      });\n+      expect(conditions).toEqual(\n+        Prisma.sql`((\"teamId\" = ${testData.team.id}) AND (\"isTeamBooking\" = true)) OR ((\"userId\" = ANY(${[\n+          testData.user.id,\n+        ]})) AND (\"isTeamBooking\" = false))`\n+      );\n \n       // Clean up\n       await testData.cleanup();\n@@ -346,26 +329,18 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n \n       const conditions = await service.getAuthorizationConditions();\n \n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            OR: [\n-              {\n-                teamId: {\n-                  in: [testData.org.id, testData.team.id, team2.id, team3.id],\n-                },\n-                isTeamBooking: true,\n-              },\n-              {\n-                userId: {\n-                  in: [testData.user.id, user2.id, user3.id],\n-                },\n-                isTeamBooking: false,\n-              },\n-            ],\n-          },\n-        ],\n-      });\n+      expect(conditions).toEqual(\n+        Prisma.sql`((\"teamId\" = ANY(${[\n+          testData.org.id,\n+          testData.team.id,\n+          team2.id,\n+          team3.id,\n+        ]})) AND (\"isTeamBooking\" = true)) OR ((\"userId\" = ANY(${[\n+          testData.user.id,\n+          user2.id,\n+          user3.id,\n+        ]})) AND (\"isTeamBooking\" = false))`\n+      );\n \n       await testData.cleanup();\n     });\n@@ -406,13 +381,9 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getFilterConditions();\n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            OR: [{ eventTypeId: testData.eventType.id }, { eventParentId: testData.eventType.id }],\n-          },\n-        ],\n-      });\n+      expect(conditions).toEqual(\n+        Prisma.sql`(\"eventTypeId\" = ${testData.eventType.id}) OR (\"eventParentId\" = ${testData.eventType.id})`\n+      );\n \n       await testData.cleanup();\n     });\n@@ -433,13 +404,7 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getFilterConditions();\n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            userId: testData.user.id,\n-          },\n-        ],\n-      });\n+      expect(conditions).toEqual(Prisma.sql`\"userId\" = ${testData.user.id}`);\n \n       await testData.cleanup();\n     });\n@@ -461,90 +426,15 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n       });\n \n       const conditions = await service.getFilterConditions();\n-      expect(conditions).toEqual({\n-        AND: [\n-          {\n-            OR: [{ eventTypeId: testData.eventType.id }, { eventParentId: testData.eventType.id }],\n-          },\n-          {\n-            userId: testData.user.id,\n-          },\n-        ],\n-      });\n-\n-      await testData.cleanup();\n-    });\n-  });\n-\n-  describe(\"Caching\", () => {\n-    it(\"should cache authorization conditions\", async () => {\n-      const testData = await createTestData({\n-        teamRole: MembershipRole.OWNER,\n-        orgRole: MembershipRole.OWNER,\n-      });\n-\n-      const service = new InsightsBookingService({\n-        prisma,\n-        options: {\n-          scope: \"user\",\n-          userId: testData.user.id,\n-          orgId: testData.org.id,\n-        },\n-      });\n-\n-      // First call should build conditions\n-      const conditions1 = await service.getAuthorizationConditions();\n-      expect(conditions1).toEqual({\n-        AND: [\n-          {\n-            userId: testData.user.id,\n-            teamId: null,\n-          },\n-        ],\n-      });\n-\n-      // Second call should use cached conditions\n-      const conditions2 = await service.getAuthorizationConditions();\n-      expect(conditions2).toEqual(conditions1);\n-\n-      // Clean up\n-      await testData.cleanup();\n-    });\n-\n-    it(\"should cache filter conditions\", async () => {\n-      const testData = await createTestData();\n-\n-      const service = new InsightsBookingService({\n-        prisma,\n-        options: {\n-          scope: \"user\",\n-          userId: testData.user.id,\n-          orgId: testData.org.id,\n-        },\n-        filters: {\n-          eventTypeId: testData.eventType.id,\n-        },\n-      });\n-\n-      // First call should build conditions\n-      const conditions1 = await service.getFilterConditions();\n-      expect(conditions1).toEqual({\n-        AND: [\n-          {\n-            OR: [{ eventTypeId: testData.eventType.id }, { eventParentId: testData.eventType.id }],\n-          },\n-        ],\n-      });\n-\n-      // Second call should use cached conditions\n-      const conditions2 = await service.getFilterConditions();\n-      expect(conditions2).toEqual(conditions1);\n+      expect(conditions).toEqual(\n+        Prisma.sql`((\"eventTypeId\" = ${testData.eventType.id}) OR (\"eventParentId\" = ${testData.eventType.id})) AND (\"userId\" = ${testData.user.id})`\n+      );\n \n       await testData.cleanup();\n     });\n   });\n \n-  describe(\"findMany\", () => {\n+  describe(\"getBaseConditions\", () => {\n     it(\"should combine authorization and filter conditions\", async () => {\n       const testData = await createTestData({\n         teamRole: MembershipRole.OWNER,\n@@ -587,16 +477,18 @@ describe(\"InsightsBookingService Integration Tests\", () => {\n         },\n       });\n \n-      const results = await service.findMany({\n-        select: {\n-          id: true,\n-          title: true,\n-        },\n-      });\n+      const baseConditions = await service.getBaseConditions();\n+      const results = await prisma.$queryRaw<{ id: number }[]>`\n+        SELECT id FROM \"BookingTimeStatusDenormalized\"\n+        WHERE ${baseConditions}\n+      `;\n \n       // Should return the user booking since it matches both conditions\n-      expect(results).toHaveLength(1);\n-      expect(results[0]?.id).toBe(userBooking.id);\n+      expect(results).toEqual([\n+        {\n+          id: userBooking.id,\n+        },\n+      ]);\n \n       // Clean up\n       await prisma.booking.delete({\ndiff --git a/packages/lib/server/service/insightsBooking.ts b/packages/lib/server/service/insightsBooking.ts\nindex 6d9bb04f40e..f0858f4142b 100644\n--- a/packages/lib/server/service/insightsBooking.ts\n+++ b/packages/lib/server/service/insightsBooking.ts\n@@ -1,4 +1,4 @@\n-import type { Prisma } from \"@prisma/client\";\n+import { Prisma } from \"@prisma/client\";\n import { z } from \"zod\";\n \n import type { readonlyPrisma } from \"@calcom/prisma\";\n@@ -26,6 +26,13 @@ export const insightsBookingServiceOptionsSchema = z.discriminatedUnion(\"scope\",\n   }),\n ]);\n \n+export type InsightsBookingServicePublicOptions = {\n+  scope: \"user\" | \"org\" | \"team\";\n+  userId: number;\n+  orgId: number;\n+  teamId?: number;\n+};\n+\n export type InsightsBookingServiceOptions = z.infer<typeof insightsBookingServiceOptionsSchema>;\n \n export type InsightsBookingServiceFilterOptions = {\n@@ -33,16 +40,14 @@ export type InsightsBookingServiceFilterOptions = {\n   memberUserId?: number;\n };\n \n-const NOTHING = {\n-  id: -1,\n-} as const;\n+const NOTHING_CONDITION = Prisma.sql`1=0`;\n \n export class InsightsBookingService {\n   private prisma: typeof readonlyPrisma;\n   private options: InsightsBookingServiceOptions | null;\n   private filters?: InsightsBookingServiceFilterOptions;\n-  private cachedAuthConditions?: Prisma.BookingTimeStatusDenormalizedWhereInput;\n-  private cachedFilterConditions?: Prisma.BookingTimeStatusDenormalizedWhereInput | null;\n+  private cachedAuthConditions?: Prisma.Sql;\n+  private cachedFilterConditions?: Prisma.Sql | null;\n \n   constructor({\n     prisma,\n@@ -50,7 +55,7 @@ export class InsightsBookingService {\n     filters,\n   }: {\n     prisma: typeof readonlyPrisma;\n-    options: InsightsBookingServiceOptions;\n+    options: InsightsBookingServicePublicOptions;\n     filters?: InsightsBookingServiceFilterOptions;\n   }) {\n     this.prisma = prisma;\n@@ -60,89 +65,86 @@ export class InsightsBookingService {\n     this.filters = filters;\n   }\n \n-  async findMany(findManyArgs: Prisma.BookingTimeStatusDenormalizedFindManyArgs) {\n+  async getBaseConditions(): Promise<Prisma.Sql> {\n     const authConditions = await this.getAuthorizationConditions();\n     const filterConditions = await this.getFilterConditions();\n \n-    return this.prisma.bookingTimeStatusDenormalized.findMany({\n-      ...findManyArgs,\n-      where: {\n-        ...findManyArgs.where,\n-        AND: [authConditions, filterConditions].filter(\n-          (c): c is Prisma.BookingTimeStatusDenormalizedWhereInput => c !== null\n-        ),\n-      },\n-    });\n+    if (authConditions && filterConditions) {\n+      return Prisma.sql`(${authConditions}) AND (${filterConditions})`;\n+    } else if (authConditions) {\n+      return authConditions;\n+    } else if (filterConditions) {\n+      return filterConditions;\n+    } else {\n+      return NOTHING_CONDITION;\n+    }\n   }\n \n-  async getAuthorizationConditions(): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput> {\n+  async getAuthorizationConditions(): Promise<Prisma.Sql> {\n     if (this.cachedAuthConditions === undefined) {\n       this.cachedAuthConditions = await this.buildAuthorizationConditions();\n     }\n     return this.cachedAuthConditions;\n   }\n \n-  async getFilterConditions(): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput | null> {\n+  async getFilterConditions(): Promise<Prisma.Sql | null> {\n     if (this.cachedFilterConditions === undefined) {\n       this.cachedFilterConditions = await this.buildFilterConditions();\n     }\n     return this.cachedFilterConditions;\n   }\n \n-  async buildFilterConditions(): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput | null> {\n-    const conditions: Prisma.BookingTimeStatusDenormalizedWhereInput[] = [];\n+  async buildFilterConditions(): Promise<Prisma.Sql | null> {\n+    const conditions: Prisma.Sql[] = [];\n \n     if (!this.filters) {\n       return null;\n     }\n \n     if (this.filters.eventTypeId) {\n-      conditions.push({\n-        OR: [{ eventTypeId: this.filters.eventTypeId }, { eventParentId: this.filters.eventTypeId }],\n-      });\n+      conditions.push(\n+        Prisma.sql`(\"eventTypeId\" = ${this.filters.eventTypeId}) OR (\"eventParentId\" = ${this.filters.eventTypeId})`\n+      );\n     }\n \n     if (this.filters.memberUserId) {\n-      conditions.push({\n-        userId: this.filters.memberUserId,\n-      });\n+      conditions.push(Prisma.sql`\"userId\" = ${this.filters.memberUserId}`);\n     }\n \n-    return conditions.length > 0 ? { AND: conditions } : null;\n+    if (conditions.length === 0) {\n+      return null;\n+    }\n+\n+    // Join all conditions with AND\n+    return conditions.reduce((acc, condition, index) => {\n+      if (index === 0) return condition;\n+      return Prisma.sql`(${acc}) AND (${condition})`;\n+    });\n   }\n \n-  async buildAuthorizationConditions(): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput> {\n+  async buildAuthorizationConditions(): Promise<Prisma.Sql> {\n     if (!this.options) {\n-      return NOTHING;\n+      return NOTHING_CONDITION;\n     }\n     const isOwnerOrAdmin = await this.isOrgOwnerOrAdmin(this.options.userId, this.options.orgId);\n     if (!isOwnerOrAdmin) {\n-      return NOTHING;\n+      return NOTHING_CONDITION;\n     }\n \n-    const conditions: Prisma.BookingTimeStatusDenormalizedWhereInput[] = [];\n-\n     if (this.options.scope === \"user\") {\n-      conditions.push({\n-        userId: this.options.userId,\n-        teamId: null,\n-      });\n+      return Prisma.sql`(\"userId\" = ${this.options.userId}) AND (\"teamId\" IS NULL)`;\n     } else if (this.options.scope === \"org\") {\n-      conditions.push(await this.buildOrgAuthorizationCondition(this.options));\n+      return await this.buildOrgAuthorizationCondition(this.options);\n     } else if (this.options.scope === \"team\") {\n-      conditions.push(await this.buildTeamAuthorizationCondition(this.options));\n+      return await this.buildTeamAuthorizationCondition(this.options);\n     } else {\n-      return NOTHING;\n+      return NOTHING_CONDITION;\n     }\n-\n-    return {\n-      AND: conditions,\n-    };\n   }\n \n   private async buildOrgAuthorizationCondition(\n     options: Extract<InsightsBookingServiceOptions, { scope: \"org\" }>\n-  ): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput> {\n+  ): Promise<Prisma.Sql> {\n     // Get all teams from the organization\n     const teamRepo = new TeamRepository(this.prisma);\n     const teamsFromOrg = await teamRepo.findAllByParentId({\n@@ -159,31 +161,22 @@ export class InsightsBookingService {\n           )\n         : [];\n \n-    return {\n-      OR: [\n-        {\n-          teamId: {\n-            in: teamIds,\n-          },\n-          isTeamBooking: true,\n-        },\n-        ...(userIdsFromOrg.length > 0\n-          ? [\n-              {\n-                userId: {\n-                  in: Array.from(new Set(userIdsFromOrg)),\n-                },\n-                isTeamBooking: false,\n-              },\n-            ]\n-          : []),\n-      ],\n-    };\n+    const conditions: Prisma.Sql[] = [Prisma.sql`(\"teamId\" = ANY(${teamIds})) AND (\"isTeamBooking\" = true)`];\n+\n+    if (userIdsFromOrg.length > 0) {\n+      const uniqueUserIds = Array.from(new Set(userIdsFromOrg));\n+      conditions.push(Prisma.sql`(\"userId\" = ANY(${uniqueUserIds})) AND (\"isTeamBooking\" = false)`);\n+    }\n+\n+    return conditions.reduce((acc, condition, index) => {\n+      if (index === 0) return condition;\n+      return Prisma.sql`(${acc}) OR (${condition})`;\n+    });\n   }\n \n   private async buildTeamAuthorizationCondition(\n     options: Extract<InsightsBookingServiceOptions, { scope: \"team\" }>\n-  ): Promise<Prisma.BookingTimeStatusDenormalizedWhereInput> {\n+  ): Promise<Prisma.Sql> {\n     const teamRepo = new TeamRepository(this.prisma);\n     const childTeamOfOrg = await teamRepo.findByIdAndParentId({\n       id: options.teamId,\n@@ -191,7 +184,7 @@ export class InsightsBookingService {\n       select: { id: true },\n     });\n     if (!childTeamOfOrg) {\n-      return NOTHING;\n+      return NOTHING_CONDITION;\n     }\n \n     const usersFromTeam = await MembershipRepository.findAllByTeamIds({\n@@ -200,20 +193,18 @@ export class InsightsBookingService {\n     });\n     const userIdsFromTeam = usersFromTeam.map((u) => u.userId);\n \n-    return {\n-      OR: [\n-        {\n-          teamId: options.teamId,\n-          isTeamBooking: true,\n-        },\n-        {\n-          userId: {\n-            in: userIdsFromTeam,\n-          },\n-          isTeamBooking: false,\n-        },\n-      ],\n-    };\n+    const conditions: Prisma.Sql[] = [\n+      Prisma.sql`(\"teamId\" = ${options.teamId}) AND (\"isTeamBooking\" = true)`,\n+    ];\n+\n+    if (userIdsFromTeam.length > 0) {\n+      conditions.push(Prisma.sql`(\"userId\" = ANY(${userIdsFromTeam})) AND (\"isTeamBooking\" = false)`);\n+    }\n+\n+    return conditions.reduce((acc, condition, index) => {\n+      if (index === 0) return condition;\n+      return Prisma.sql`(${acc}) OR (${condition})`;\n+    });\n   }\n \n   private async isOrgOwnerOrAdmin(userId: number, orgId: number): Promise<boolean> {\n@@ -223,7 +214,7 @@ export class InsightsBookingService {\n       membership &&\n         membership.accepted &&\n         membership.role &&\n-        ([MembershipRole.OWNER, MembershipRole.ADMIN] as const).includes(membership.role)\n+        (membership.role === MembershipRole.OWNER || membership.role === MembershipRole.ADMIN)\n     );\n   }\n }\n", "gold_issues": [{"pr_url": "https://github.com/calcom/cal.com/pull/22345", "source_repo": "cal.dot.com", "pr_title": "feat: convert InsightsBookingService to use Prisma.sql raw queries", "issue_index": 0, "comment": "In getBaseConditions(), the else if (filterConditions) and final else branches are unreachable. This is because getAuthorizationConditions() always returns a non-null Prisma.Sql object, making authConditions always truthy, which means only the first two if/else if conditions are ever evaluated.", "severity": "Low"}, {"pr_url": "https://github.com/calcom/cal.com/pull/22345", "source_repo": "cal.dot.com", "pr_title": "feat: convert InsightsBookingService to use Prisma.sql raw queries", "issue_index": 1, "comment": "Fetching userIdsFromOrg only when teamsFromOrg.length > 0 can exclude org-level members for orgs without child teams; consider deriving from teamIds (which includes orgId) or removing the guard so org-only orgs still include member user bookings.", "severity": "Medium"}]}
{"task_id": "https://github.com/calcom/cal.com/pull/7232", "pr_url": "https://github.com/calcom/cal.com/pull/7232", "source_repo": "cal.dot.com", "pr_title": "Comprehensive workflow reminder management for booking lifecycle events", "diff": "diff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts\nindex 2e53fd2b463..acd85d3d128 100644\n--- a/packages/features/bookings/lib/handleCancelBooking.ts\n+++ b/packages/features/bookings/lib/handleCancelBooking.ts\n@@ -1,8 +1,6 @@\n import {\n   BookingStatus,\n   MembershipRole,\n-  Prisma,\n-  PrismaPromise,\n   WebhookTriggerEvents,\n   WorkflowMethods,\n   WorkflowReminder,\n@@ -483,29 +481,18 @@ async function handler(req: NextApiRequest & { userId?: number }) {\n     cancelScheduledJobs(booking);\n   });\n \n-  //Workflows - delete all reminders for bookings\n-  const remindersToDelete: PrismaPromise<Prisma.BatchPayload>[] = [];\n+  //Workflows - cancel all reminders for cancelled bookings\n   updatedBookings.forEach((booking) => {\n     booking.workflowReminders.forEach((reminder) => {\n-      if (reminder.scheduled && reminder.referenceId) {\n-        if (reminder.method === WorkflowMethods.EMAIL) {\n-          deleteScheduledEmailReminder(reminder.referenceId);\n-        } else if (reminder.method === WorkflowMethods.SMS) {\n-          deleteScheduledSMSReminder(reminder.referenceId);\n-        }\n+      if (reminder.method === WorkflowMethods.EMAIL) {\n+        deleteScheduledEmailReminder(reminder.id, reminder.referenceId);\n+      } else if (reminder.method === WorkflowMethods.SMS) {\n+        deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n       }\n-      const reminderToDelete = prisma.workflowReminder.deleteMany({\n-        where: {\n-          id: reminder.id,\n-        },\n-      });\n-      remindersToDelete.push(reminderToDelete);\n     });\n   });\n \n-  const prismaPromises: Promise<unknown>[] = [attendeeDeletes, bookingReferenceDeletes].concat(\n-    remindersToDelete\n-  );\n+  const prismaPromises: Promise<unknown>[] = [attendeeDeletes, bookingReferenceDeletes];\n \n   await Promise.all(prismaPromises.concat(apiDeletes));\n \ndiff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.ts\nindex 2149b8395d1..58b7ea4483e 100644\n--- a/packages/features/bookings/lib/handleNewBooking.ts\n+++ b/packages/features/bookings/lib/handleNewBooking.ts\n@@ -1,5 +1,13 @@\n-import type { App, Credential, EventTypeCustomInput, Prisma } from \"@prisma/client\";\n-import { BookingStatus, SchedulingType, WebhookTriggerEvents } from \"@prisma/client\";\n+import {\n+  App,\n+  BookingStatus,\n+  Credential,\n+  EventTypeCustomInput,\n+  Prisma,\n+  SchedulingType,\n+  WebhookTriggerEvents,\n+  WorkflowMethods,\n+} from \"@prisma/client\";\n import async from \"async\";\n import { isValidPhoneNumber } from \"libphonenumber-js\";\n import { cloneDeep } from \"lodash\";\n@@ -28,7 +36,9 @@ import {\n   sendScheduledEmails,\n   sendScheduledSeatsEmails,\n } from \"@calcom/emails\";\n+import { deleteScheduledEmailReminder } from \"@calcom/features/ee/workflows/lib/reminders/emailReminderManager\";\n import { scheduleWorkflowReminders } from \"@calcom/features/ee/workflows/lib/reminders/reminderScheduler\";\n+import { deleteScheduledSMSReminder } from \"@calcom/features/ee/workflows/lib/reminders/smsReminderManager\";\n import getWebhooks from \"@calcom/features/webhooks/lib/getWebhooks\";\n import { isPrismaObjOrUndefined, parseRecurringEvent } from \"@calcom/lib\";\n import { getVideoCallUrl } from \"@calcom/lib/CalEventParser\";\n@@ -759,6 +769,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {\n           },\n         },\n         payment: true,\n+        workflowReminders: true,\n       },\n     });\n   }\n@@ -950,6 +961,19 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {\n   let videoCallUrl;\n \n   if (originalRescheduledBooking?.uid) {\n+    try {\n+      // cancel workflow reminders from previous rescheduled booking\n+      originalRescheduledBooking.workflowReminders.forEach((reminder) => {\n+        if (reminder.method === WorkflowMethods.EMAIL) {\n+          deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);\n+        } else if (reminder.method === WorkflowMethods.SMS) {\n+          deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n+        }\n+      });\n+    } catch (error) {\n+      log.error(\"Error while canceling scheduled workflow reminders\", error);\n+    }\n+\n     // Use EventManager to conditionally use all needed integrations.\n     const updateManager = await eventManager.reschedule(\n       evt,\ndiff --git a/packages/features/ee/workflows/api/scheduleEmailReminders.ts b/packages/features/ee/workflows/api/scheduleEmailReminders.ts\nindex b1ef72f1f43..5125c9fb1b2 100644\n--- a/packages/features/ee/workflows/api/scheduleEmailReminders.ts\n+++ b/packages/features/ee/workflows/api/scheduleEmailReminders.ts\n@@ -7,6 +7,7 @@ import type { NextApiRequest, NextApiResponse } from \"next\";\n import dayjs from \"@calcom/dayjs\";\n import { defaultHandler } from \"@calcom/lib/server\";\n import prisma from \"@calcom/prisma\";\n+import { Prisma, WorkflowReminder } from \"@calcom/prisma/client\";\n import { bookingMetadataSchema } from \"@calcom/prisma/zod-utils\";\n \n import customTemplate, { VariablesType } from \"../lib/reminders/templates/customTemplate\";\n@@ -39,6 +40,42 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {\n     },\n   });\n \n+  //cancel reminders for cancelled/rescheduled bookings that are scheduled within the next hour\n+  const remindersToCancel = await prisma.workflowReminder.findMany({\n+    where: {\n+      cancelled: true,\n+      scheduledDate: {\n+        lte: dayjs().add(1, \"hour\").toISOString(),\n+      },\n+    },\n+  });\n+\n+  try {\n+    const workflowRemindersToDelete: Prisma.Prisma__WorkflowReminderClient<WorkflowReminder, never>[] = [];\n+\n+    for (const reminder of remindersToCancel) {\n+      await client.request({\n+        url: \"/v3/user/scheduled_sends\",\n+        method: \"POST\",\n+        body: {\n+          batch_id: reminder.referenceId,\n+          status: \"cancel\",\n+        },\n+      });\n+\n+      const workflowReminderToDelete = prisma.workflowReminder.delete({\n+        where: {\n+          id: reminder.id,\n+        },\n+      });\n+\n+      workflowRemindersToDelete.push(workflowReminderToDelete);\n+    }\n+    await Promise.all(workflowRemindersToDelete);\n+  } catch (error) {\n+    console.log(`Error cancelling scheduled Emails: ${error}`);\n+  }\n+\n   //find all unscheduled Email reminders\n   const unscheduledReminders = await prisma.workflowReminder.findMany({\n     where: {\ndiff --git a/packages/features/ee/workflows/components/WorkflowStepContainer.tsx b/packages/features/ee/workflows/components/WorkflowStepContainer.tsx\nindex 3fd3e6f7f85..3b13904cdb7 100644\n--- a/packages/features/ee/workflows/components/WorkflowStepContainer.tsx\n+++ b/packages/features/ee/workflows/components/WorkflowStepContainer.tsx\n@@ -387,81 +387,75 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {\n                   }}\n                 />\n               </div>\n-              {(isPhoneNumberNeeded || isSenderIdNeeded) && (\n+              {isPhoneNumberNeeded && (\n                 <div className=\"mt-2 rounded-md bg-gray-50 p-4 pt-0\">\n-                  {isPhoneNumberNeeded && (\n+                  <Label className=\"pt-4\">{t(\"custom_phone_number\")}</Label>\n+                  <div className=\"block sm:flex\">\n+                    <PhoneInput<FormValues>\n+                      control={form.control}\n+                      name={`steps.${step.stepNumber - 1}.sendTo`}\n+                      placeholder={t(\"phone_number\")}\n+                      id={`steps.${step.stepNumber - 1}.sendTo`}\n+                      className=\"min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent\"\n+                      required\n+                      onChange={() => {\n+                        const isAlreadyVerified = !!verifiedNumbers\n+                          ?.concat([])\n+                          .find((number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`));\n+                        setNumberVerified(isAlreadyVerified);\n+                      }}\n+                    />\n+                    <Button\n+                      color=\"secondary\"\n+                      disabled={numberVerified || false}\n+                      className={classNames(\n+                        \"-ml-[3px] h-[40px] min-w-fit sm:block sm:rounded-tl-none sm:rounded-bl-none \",\n+                        numberVerified ? \"hidden\" : \"mt-3 sm:mt-0\"\n+                      )}\n+                      onClick={() =>\n+                        sendVerificationCodeMutation.mutate({\n+                          phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || \"\",\n+                        })\n+                      }>\n+                      {t(\"send_code\")}\n+                    </Button>\n+                  </div>\n+\n+                  {form.formState.errors.steps &&\n+                    form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (\n+                      <p className=\"mt-1 text-xs text-red-500\">\n+                        {form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || \"\"}\n+                      </p>\n+                    )}\n+                  {numberVerified ? (\n+                    <div className=\"mt-1\">\n+                      <Badge variant=\"green\">{t(\"number_verified\")}</Badge>\n+                    </div>\n+                  ) : (\n                     <>\n-                      <Label className=\"pt-4\">{t(\"custom_phone_number\")}</Label>\n-                      <div className=\"block sm:flex\">\n-                        <PhoneInput<FormValues>\n-                          control={form.control}\n-                          name={`steps.${step.stepNumber - 1}.sendTo`}\n-                          placeholder={t(\"phone_number\")}\n-                          id={`steps.${step.stepNumber - 1}.sendTo`}\n-                          className=\"min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent\"\n-                          required\n-                          onChange={() => {\n-                            const isAlreadyVerified = !!verifiedNumbers\n-                              ?.concat([])\n-                              .find(\n-                                (number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)\n-                              );\n-                            setNumberVerified(isAlreadyVerified);\n+                      <div className=\"mt-3 flex\">\n+                        <TextField\n+                          className=\" border-r-transparent\"\n+                          placeholder=\"Verification code\"\n+                          value={verificationCode}\n+                          onChange={(e) => {\n+                            setVerificationCode(e.target.value);\n                           }}\n+                          required\n                         />\n                         <Button\n                           color=\"secondary\"\n-                          disabled={numberVerified || false}\n-                          className={classNames(\n-                            \"-ml-[3px] h-[40px] min-w-fit sm:block sm:rounded-tl-none sm:rounded-bl-none \",\n-                            numberVerified ? \"hidden\" : \"mt-3 sm:mt-0\"\n-                          )}\n-                          onClick={() =>\n-                            sendVerificationCodeMutation.mutate({\n+                          className=\"-ml-[3px] rounded-tl-none rounded-bl-none \"\n+                          disabled={verifyPhoneNumberMutation.isLoading}\n+                          onClick={() => {\n+                            verifyPhoneNumberMutation.mutate({\n                               phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || \"\",\n-                            })\n-                          }>\n-                          {t(\"send_code\")}\n+                              code: verificationCode,\n+                            });\n+                          }}>\n+                          Verify\n                         </Button>\n                       </div>\n-\n-                      {form.formState.errors.steps &&\n-                        form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (\n-                          <p className=\"mt-1 text-xs text-red-500\">\n-                            {form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || \"\"}\n-                          </p>\n-                        )}\n-                      {numberVerified ? (\n-                        <div className=\"mt-1\">\n-                          <Badge variant=\"green\">{t(\"number_verified\")}</Badge>\n-                        </div>\n-                      ) : (\n-                        <>\n-                          <div className=\"mt-3 flex\">\n-                            <TextField\n-                              className=\" border-r-transparent\"\n-                              placeholder=\"Verification code\"\n-                              value={verificationCode}\n-                              onChange={(e) => {\n-                                setVerificationCode(e.target.value);\n-                              }}\n-                              required\n-                            />\n-                            <Button\n-                              color=\"secondary\"\n-                              className=\"-ml-[3px] rounded-tl-none rounded-bl-none \"\n-                              disabled={verifyPhoneNumberMutation.isLoading}\n-                              onClick={() => {\n-                                verifyPhoneNumberMutation.mutate({\n-                                  phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || \"\",\n-                                  code: verificationCode,\n-                                });\n-                              }}>\n-                              Verify\n-                            </Button>\n-                          </div>\n-                        </>\n-                      )}\n                     </>\n                   )}\n                 </div>\ndiff --git a/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts b/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts\nindex 14ffc893586..e84373b6907 100644\n--- a/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts\n+++ b/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts\n@@ -194,20 +194,41 @@ export const scheduleEmailReminder = async (\n   }\n };\n \n-export const deleteScheduledEmailReminder = async (referenceId: string) => {\n+export const deleteScheduledEmailReminder = async (\n+  reminderId: number,\n+  referenceId: string | null,\n+  immediateDelete?: boolean\n+) => {\n   try {\n-    await client.request({\n-      url: \"/v3/user/scheduled_sends\",\n-      method: \"POST\",\n-      body: {\n-        batch_id: referenceId,\n-        status: \"cancel\",\n-      },\n-    });\n+    if (!referenceId) {\n+      await prisma.workflowReminder.delete({\n+        where: {\n+          id: reminderId,\n+        },\n+      });\n+\n+      return;\n+    }\n \n-    await client.request({\n-      url: `/v3/user/scheduled_sends/${referenceId}`,\n-      method: \"DELETE\",\n+    if (immediateDelete) {\n+      await client.request({\n+        url: \"/v3/user/scheduled_sends\",\n+        method: \"POST\",\n+        body: {\n+          batch_id: referenceId,\n+          status: \"cancel\",\n+        },\n+      });\n+      return;\n+    }\n+\n+    await prisma.workflowReminder.update({\n+      where: {\n+        id: reminderId,\n+      },\n+      data: {\n+        cancelled: true,\n+      },\n     });\n   } catch (error) {\n     console.log(`Error canceling reminder with error ${error}`);\ndiff --git a/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts b/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts\nindex fad4d945bcd..6b17c0dbb0b 100644\n--- a/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts\n+++ b/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts\n@@ -174,9 +174,16 @@ export const scheduleSMSReminder = async (\n   }\n };\n \n-export const deleteScheduledSMSReminder = async (referenceId: string) => {\n+export const deleteScheduledSMSReminder = async (reminderId: number, referenceId: string | null) => {\n   try {\n-    await twilio.cancelSMS(referenceId);\n+    if (referenceId) {\n+      await twilio.cancelSMS(referenceId);\n+    }\n+    await prisma.workflowReminder.delete({\n+      where: {\n+        id: reminderId,\n+      },\n+    });\n   } catch (error) {\n     console.log(`Error canceling reminder with error ${error}`);\n   }\ndiff --git a/packages/prisma/migrations/20230217230604_add_cancelled_to_workflow_reminder/migration.sql b/packages/prisma/migrations/20230217230604_add_cancelled_to_workflow_reminder/migration.sql\nnew file mode 100644\nindex 00000000000..600081f994e\n--- /dev/null\n+++ b/packages/prisma/migrations/20230217230604_add_cancelled_to_workflow_reminder/migration.sql\n@@ -0,0 +1,2 @@\n+-- AlterTable\n+ALTER TABLE \"WorkflowReminder\" ADD COLUMN     \"cancelled\" BOOLEAN;\ndiff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma\nindex 043f4f16a27..8e34f78988c 100644\n--- a/packages/prisma/schema.prisma\n+++ b/packages/prisma/schema.prisma\n@@ -641,6 +641,7 @@ model WorkflowReminder {\n   scheduled      Boolean\n   workflowStepId Int\n   workflowStep   WorkflowStep    @relation(fields: [workflowStepId], references: [id], onDelete: Cascade)\n+  cancelled      Boolean?\n }\n \n enum WorkflowTemplates {\ndiff --git a/packages/trpc/server/routers/viewer/bookings.tsx b/packages/trpc/server/routers/viewer/bookings.tsx\nindex d3d36bb8374..0d58bbbf819 100644\n--- a/packages/trpc/server/routers/viewer/bookings.tsx\n+++ b/packages/trpc/server/routers/viewer/bookings.tsx\n@@ -5,7 +5,6 @@ import type {\n   Workflow,\n   WorkflowsOnEventTypes,\n   WorkflowStep,\n-  PrismaPromise,\n } from \"@prisma/client\";\n import {\n   BookingStatus,\n@@ -482,30 +481,18 @@ export const bookingsRouter = router({\n           },\n         });\n \n-        // delete scheduled jobs of cancelled bookings\n+        // delete scheduled jobs of previous booking\n         cancelScheduledJobs(bookingToReschedule);\n \n-        //cancel workflow reminders\n-        const remindersToDelete: PrismaPromise<Prisma.BatchPayload>[] = [];\n-\n+        //cancel workflow reminders of previous booking\n         bookingToReschedule.workflowReminders.forEach((reminder) => {\n-          if (reminder.scheduled && reminder.referenceId) {\n-            if (reminder.method === WorkflowMethods.EMAIL) {\n-              deleteScheduledEmailReminder(reminder.referenceId);\n-            } else if (reminder.method === WorkflowMethods.SMS) {\n-              deleteScheduledSMSReminder(reminder.referenceId);\n-            }\n+          if (reminder.method === WorkflowMethods.EMAIL) {\n+            deleteScheduledEmailReminder(reminder.id, reminder.referenceId);\n+          } else if (reminder.method === WorkflowMethods.SMS) {\n+            deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n           }\n-          const reminderToDelete = prisma.workflowReminder.deleteMany({\n-            where: {\n-              id: reminder.id,\n-            },\n-          });\n-          remindersToDelete.push(reminderToDelete);\n         });\n \n-        await Promise.all(remindersToDelete);\n-\n         const [mainAttendee] = bookingToReschedule.attendees;\n         // @NOTE: Should we assume attendees language?\n         const tAttendees = await getTranslation(mainAttendee.locale ?? \"en\", \"common\");\ndiff --git a/packages/trpc/server/routers/viewer/workflows.tsx b/packages/trpc/server/routers/viewer/workflows.tsx\nindex c3441ea713a..639b2c764e1 100644\n--- a/packages/trpc/server/routers/viewer/workflows.tsx\n+++ b/packages/trpc/server/routers/viewer/workflows.tsx\n@@ -1,11 +1,12 @@\n-import type { Prisma, PrismaPromise } from \"@prisma/client\";\n import {\n+  PrismaPromise,\n   WorkflowTemplates,\n   WorkflowActions,\n   WorkflowTriggerEvents,\n   BookingStatus,\n   WorkflowMethods,\n   TimeUnit,\n+  Prisma\n } from \"@prisma/client\";\n import { z } from \"zod\";\n \n@@ -23,7 +24,6 @@ import {\n   scheduleEmailReminder,\n } from \"@calcom/features/ee/workflows/lib/reminders/emailReminderManager\";\n import {\n-  //  BookingInfo,\n   deleteScheduledSMSReminder,\n   scheduleSMSReminder,\n } from \"@calcom/features/ee/workflows/lib/reminders/smsReminderManager\";\n@@ -208,13 +208,12 @@ export const workflowsRouter = router({\n           },\n         });\n \n+        //cancel workflow reminders of deleted workflow\n         scheduledReminders.forEach((reminder) => {\n-          if (reminder.referenceId) {\n-            if (reminder.method === WorkflowMethods.EMAIL) {\n-              deleteScheduledEmailReminder(reminder.referenceId);\n-            } else if (reminder.method === WorkflowMethods.SMS) {\n-              deleteScheduledSMSReminder(reminder.referenceId);\n-            }\n+          if (reminder.method === WorkflowMethods.EMAIL) {\n+            deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);\n+          } else if (reminder.method === WorkflowMethods.SMS) {\n+            deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n           }\n         });\n \n@@ -373,29 +372,15 @@ export const workflowsRouter = router({\n \n       const remindersToDelete = await Promise.all(remindersToDeletePromise);\n \n-      const deleteReminderPromise: PrismaPromise<Prisma.BatchPayload>[] = [];\n+      //cancel workflow reminders for all bookings from event types that got disabled\n       remindersToDelete.flat().forEach((reminder) => {\n-        //already scheduled reminders\n-        if (reminder.referenceId) {\n-          if (reminder.method === WorkflowMethods.EMAIL) {\n-            deleteScheduledEmailReminder(reminder.referenceId);\n-          } else if (reminder.method === WorkflowMethods.SMS) {\n-            deleteScheduledSMSReminder(reminder.referenceId);\n-          }\n+        if (reminder.method === WorkflowMethods.EMAIL) {\n+          deleteScheduledEmailReminder(reminder.id, reminder.referenceId);\n+        } else if (reminder.method === WorkflowMethods.SMS) {\n+          deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n         }\n-        const deleteReminder = ctx.prisma.workflowReminder.deleteMany({\n-          where: {\n-            id: reminder.id,\n-            booking: {\n-              userId: ctx.user.id,\n-            },\n-          },\n-        });\n-        deleteReminderPromise.push(deleteReminder);\n       });\n \n-      await Promise.all(deleteReminderPromise);\n-\n       //update active on & reminders for new eventTypes\n       await ctx.prisma.workflowsOnEventTypes.deleteMany({\n         where: {\n@@ -529,15 +514,13 @@ export const workflowsRouter = router({\n         });\n         //step was deleted\n         if (!newStep) {\n-          //delete already scheduled reminders\n+          // cancel all workflow reminders from deleted steps\n           if (remindersFromStep.length > 0) {\n             remindersFromStep.forEach((reminder) => {\n-              if (reminder.referenceId) {\n-                if (reminder.method === WorkflowMethods.EMAIL) {\n-                  deleteScheduledEmailReminder(reminder.referenceId);\n-                } else if (reminder.method === WorkflowMethods.SMS) {\n-                  deleteScheduledSMSReminder(reminder.referenceId);\n-                }\n+              if (reminder.method === WorkflowMethods.EMAIL) {\n+                deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);\n+              } else if (reminder.method === WorkflowMethods.SMS) {\n+                deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n               }\n             });\n           }\n@@ -586,19 +569,14 @@ export const workflowsRouter = router({\n               return reminder;\n             }\n           });\n+\n+          //cancel all workflow reminders from steps that were edited\n           remindersToUpdate.forEach(async (reminder) => {\n-            if (reminder.referenceId) {\n-              if (reminder.method === WorkflowMethods.EMAIL) {\n-                deleteScheduledEmailReminder(reminder.referenceId);\n-              } else if (reminder.method === WorkflowMethods.SMS) {\n-                deleteScheduledSMSReminder(reminder.referenceId);\n-              }\n+            if (reminder.method === WorkflowMethods.EMAIL) {\n+              deleteScheduledEmailReminder(reminder.id, reminder.referenceId);\n+            } else if (reminder.method === WorkflowMethods.SMS) {\n+              deleteScheduledSMSReminder(reminder.id, reminder.referenceId);\n             }\n-            await ctx.prisma.workflowReminder.deleteMany({\n-              where: {\n-                id: reminder.id,\n-              },\n-            });\n           });\n           const eventTypesToUpdateReminders = activeOn.filter((eventTypeId) => {\n             if (!newEventTypes.includes(eventTypeId)) {\n@@ -923,63 +901,63 @@ export const workflowsRouter = router({\n     if (isSMSAction(step.action) /*|| step.action === WorkflowActions.EMAIL_ADDRESS*/ /*) {\n const hasTeamPlan = (await ctx.prisma.membership.count({ where: { userId: user.id } })) > 0;\n if (!hasTeamPlan) {\n-  throw new TRPCError({ code: \"UNAUTHORIZED\", message: \"Team plan needed\" });\n+throw new TRPCError({ code: \"UNAUTHORIZED\", message: \"Team plan needed\" });\n }\n }\n \n const booking = await ctx.prisma.booking.findFirst({\n orderBy: {\n-  createdAt: \"desc\",\n+createdAt: \"desc\",\n },\n where: {\n-  userId: ctx.user.id,\n+userId: ctx.user.id,\n },\n include: {\n-  attendees: true,\n-  user: true,\n+attendees: true,\n+user: true,\n },\n });\n \n let evt: BookingInfo;\n if (booking) {\n evt = {\n-  uid: booking?.uid,\n-  attendees:\n-    booking?.attendees.map((attendee) => {\n-      return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };\n-    }) || [],\n-  organizer: {\n-    language: {\n-      locale: booking?.user?.locale || \"\",\n-    },\n-    name: booking?.user?.name || \"\",\n-    email: booking?.user?.email || \"\",\n-    timeZone: booking?.user?.timeZone || \"\",\n-  },\n-  startTime: booking?.startTime.toISOString() || \"\",\n-  endTime: booking?.endTime.toISOString() || \"\",\n-  title: booking?.title || \"\",\n-  location: booking?.location || null,\n-  additionalNotes: booking?.description || null,\n-  customInputs: booking?.customInputs,\n+uid: booking?.uid,\n+attendees:\n+booking?.attendees.map((attendee) => {\n+return { name: attendee.name, email: attendee.email, timeZone: attendee.timeZone };\n+}) || [],\n+organizer: {\n+language: {\n+locale: booking?.user?.locale || \"\",\n+},\n+name: booking?.user?.name || \"\",\n+email: booking?.user?.email || \"\",\n+timeZone: booking?.user?.timeZone || \"\",\n+},\n+startTime: booking?.startTime.toISOString() || \"\",\n+endTime: booking?.endTime.toISOString() || \"\",\n+title: booking?.title || \"\",\n+location: booking?.location || null,\n+additionalNotes: booking?.description || null,\n+customInputs: booking?.customInputs,\n };\n } else {\n //if no booking exists create an example booking\n evt = {\n-  attendees: [{ name: \"John Doe\", email: \"john.doe@example.com\", timeZone: \"Europe/London\" }],\n-  organizer: {\n-    language: {\n-      locale: ctx.user.locale,\n-    },\n-    name: ctx.user.name || \"\",\n-    email: ctx.user.email,\n-    timeZone: ctx.user.timeZone,\n-  },\n-  startTime: dayjs().add(10, \"hour\").toISOString(),\n-  endTime: dayjs().add(11, \"hour\").toISOString(),\n-  title: \"Example Booking\",\n-  location: \"Office\",\n-  additionalNotes: \"These are additional notes\",\n+attendees: [{ name: \"John Doe\", email: \"john.doe@example.com\", timeZone: \"Europe/London\" }],\n+organizer: {\n+language: {\n+locale: ctx.user.locale,\n+},\n+name: ctx.user.name || \"\",\n+email: ctx.user.email,\n+timeZone: ctx.user.timeZone,\n+},\n+startTime: dayjs().add(10, \"hour\").toISOString(),\n+endTime: dayjs().add(11, \"hour\").toISOString(),\n+title: \"Example Booking\",\n+location: \"Office\",\n+additionalNotes: \"These are additional notes\",\n };\n }\n \n", "gold_issues": [{"pr_url": "https://github.com/calcom/cal.com/pull/7232", "source_repo": "cal.dot.com", "pr_title": "Comprehensive workflow reminder management for booking lifecycle events", "issue_index": 0, "comment": "Asynchronous functions deleteScheduledEmailReminder and deleteScheduledSMSReminder are called without await inside forEach loops. This occurs during booking rescheduling/cancellation, and workflow/workflow step deletion/updates. Consequently, scheduled workflow reminders may not be reliably cancelled, potentially leaving them active.", "severity": "Medium"}, {"pr_url": "https://github.com/calcom/cal.com/pull/7232", "source_repo": "cal.dot.com", "pr_title": "Comprehensive workflow reminder management for booking lifecycle events", "issue_index": 1, "comment": "When immediateDelete is true, the deleteScheduledEmailReminder function cancels the SendGrid email but fails to delete the corresponding WorkflowReminder record from the database. This creates orphaned database entries and is inconsistent with the immediateDelete: false path, which marks the record as cancelled. The SendGrid DELETE API call is also omitted in this path.", "severity": "High"}]}