Scheduling infrastructure for absolutely everyone.
test: Delete credential endpoint (#15322)
Joe Au-Yeung9a1a86ed3ab4
diff --git a/apps/web/test/utils/bookingScenario/bookingScenario.ts b/apps/web/test/utils/bookingScenario/bookingScenario.tsindex 702e9799fb4..871a17ae309 100644--- a/apps/web/test/utils/bookingScenario/bookingScenario.ts+++ b/apps/web/test/utils/bookingScenario/bookingScenario.ts@@ -211,6 +211,7 @@ export async function addEventTypesToDb(id?: number;// eslint-disable-next-line @typescript-eslint/no-explicit-anyusers?: any[];+ userId?: number;// eslint-disable-next-line @typescript-eslint/no-explicit-anyworkflows?: any[];// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -597,7 +598,7 @@ export async function addTeamsToDb(teams: NonNullable<InputUser["teams"]>[numberreturn addedTeams;}-async function addUsers(users: InputUser[]) {+export async function addUsers(users: InputUser[]) {const prismaUsersCreate = [];for (let i = 0; i < users.length; i++) {const newUser = users[i];diff --git a/packages/features/credentials/deleteCredential.test.ts b/packages/features/credentials/deleteCredential.test.tsnew file mode 100644index 00000000000..4d1d0b304c2--- /dev/null+++ b/packages/features/credentials/deleteCredential.test.ts@@ -0,0 +1,132 @@+import {+ addEventTypesToDb,+ mockNoTranslations,+} from "@calcom/web/test/utils/bookingScenario/bookingScenario";++import { describe, test, expect, beforeEach } from "vitest";++import { AppRepository } from "@calcom/lib/server/repository/app";+import { CredentialRepository } from "@calcom/lib/server/repository/credential";+import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";+import { EventTypeRepository } from "@calcom/lib/server/repository/eventType";+import { UserRepository } from "@calcom/lib/server/repository/user";++const testUser = {+ email: "[email protected]",+ username: "test-user",+ organizationId: null,+};++const setupCredential = async (credentialInput) => {+ const exampleCredential = {+ id: 123,+ type: "test-credential",+ appId: "test-credential",+ userId: null,+ teamId: null,+ };++ return await CredentialRepository.create({ ...exampleCredential, ...credentialInput });+};++describe("deleteCredential", () => {+ beforeEach(async () => {+ mockNoTranslations();+ });++ describe("individual credentials", () => {+ test("Delete video credential", async () => {+ const handleDeleteCredential = (await import("./handleDeleteCredential")).default;++ const user = await UserRepository.create({+ ...testUser,+ });++ await addEventTypesToDb([+ {+ id: 1,+ userId: user.id,+ locations: [{ type: "integrations:zoom" }],+ },+ {+ id: 2,+ userId: user.id,+ locations: [{ type: "integrations:msteams" }],+ },+ ]);++ await AppRepository.seedApp("zoomvideo");++ await setupCredential({ userId: user.id, type: "zoom_video", appId: "zoom" });++ await handleDeleteCredential({ userId: user.id, userMetadata: user.metadata, credentialId: 123 });+ const eventTypeQuery = await EventTypeRepository.findAllByUserId({ userId: user.id });++ // Ensure that the event type with the deleted app was converted back to daily+ const changedEventType = eventTypeQuery.find((eventType) => eventType.id === 1)?.locations;+ expect(changedEventType).toBeDefined();+ expect(changedEventType![0]).toEqual({ type: "integrations:daily" });++ const nonChangedEventType = eventTypeQuery.find((eventType) => eventType.id === 2)?.locations;+ expect(nonChangedEventType).toBeDefined();+ expect(nonChangedEventType![0]).toEqual({ type: "integrations:msteams" });+ });+ test("Delete calendar credential", async () => {+ const handleDeleteCredential = (await import("./handleDeleteCredential")).default;++ const user = await UserRepository.create({+ ...testUser,+ });++ const eventTypes = await addEventTypesToDb([+ {+ id: 1,+ userId: testUser.id,+ },+ ]);++ await AppRepository.seedApp("googlecalendar");++ const credential = await setupCredential({+ userId: user.id,+ type: "google_calendar",+ appId: "google-calendar",+ });++ await DestinationCalendarRepository.create({+ id: 1,+ integration: "google_calendar",+ externalId: "[email protected]",+ primaryId: "[email protected]",+ userId: user.id,+ credentialId: credential.id,+ });++ await DestinationCalendarRepository.create({+ id: 2,+ integration: "google_calendar",+ externalId: "[email protected]",+ primaryId: "[email protected]",+ eventTypeId: eventTypes[0].id,+ credentialId: credential.id,+ });++ const userCalendar = await DestinationCalendarRepository.getByUserId(user.id);+ expect(userCalendar).toBeDefined();++ const eventTypeCalendar = await DestinationCalendarRepository.getByEventTypeId(eventTypes[0].id);+ expect(eventTypeCalendar).toBeDefined();++ await handleDeleteCredential({ userId: user.id, userMetadata: user.metadata, credentialId: 123 });++ const userCalendarAfter = await DestinationCalendarRepository.getByUserId(user.id);+ expect(userCalendarAfter).toBeNull();++ const eventTypeCalendarAfter = await DestinationCalendarRepository.getByEventTypeId(eventTypes[0].id);+ expect(eventTypeCalendarAfter).toBeNull();+ });++ // TODO: Add test for payment apps+ // TODO: Add test for event type apps+ });+});diff --git a/packages/features/credentials/handleDeleteCredential.ts b/packages/features/credentials/handleDeleteCredential.tsnew file mode 100644index 00000000000..bf69811dfe1--- /dev/null+++ b/packages/features/credentials/handleDeleteCredential.ts@@ -0,0 +1,458 @@+import type { Prisma } from "@prisma/client";+import z from "zod";++import { getCalendar } from "@calcom/app-store/_utils/getCalendar";+import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";+import { DailyLocationType } from "@calcom/core/location";+import { sendCancelledEmails } from "@calcom/emails";+import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";+import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/scheduleTrigger";+import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";+import { deletePayment } from "@calcom/lib/payment/deletePayment";+import { getTranslation } from "@calcom/lib/server/i18n";+import { bookingMinimalSelect, prisma } from "@calcom/prisma";+import { AppCategories, BookingStatus } from "@calcom/prisma/enums";+import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";+import type { EventTypeAppMetadataSchema } from "@calcom/prisma/zod-utils";+import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";+import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";++type App = {+ slug: string;+ categories: AppCategories[];+ dirName: string;+} | null;++const isVideoOrConferencingApp = (app: App) =>+ app?.categories.includes(AppCategories.video) || app?.categories.includes(AppCategories.conferencing);++const getRemovedIntegrationNameFromAppSlug = (slug: string) =>+ slug === "msteams" ? "office365_video" : slug.split("-")[0];++const locationsSchema = z.array(z.object({ type: z.string() }));+type TlocationsSchema = z.infer<typeof locationsSchema>;++const handleDeleteCredential = async ({+ userId,+ userMetadata,+ credentialId,+ teamId,+}: {+ userId: number;+ userMetadata: Prisma.JsonValue;+ credentialId: number;+ teamId?: number;+}) => {+ const credential = await prisma.credential.findFirst({+ where: {+ id: credentialId,+ ...(teamId ? { teamId } : { userId }),+ },+ select: {+ ...credentialForCalendarServiceSelect,+ app: {+ select: {+ slug: true,+ categories: true,+ dirName: true,+ },+ },+ },+ });++ if (!credential) {+ throw new Error("Credential not found");+ }++ const eventTypes = await prisma.eventType.findMany({+ where: {+ OR: [+ {+ ...(teamId ? { teamId } : { userId }),+ },+ // for managed events+ {+ parent: {+ teamId,+ },+ },+ ],+ },+ select: {+ id: true,+ locations: true,+ destinationCalendar: {+ include: {+ credential: true,+ },+ },+ price: true,+ currency: true,+ metadata: true,+ },+ });++ // TODO: Improve this uninstallation cleanup per event by keeping a relation of EventType to App which has the data.+ for (const eventType of eventTypes) {+ // If it's a video, replace the location with Cal video+ if (eventType.locations && isVideoOrConferencingApp(credential.app)) {+ // Find the user's event types++ const integrationQuery = getRemovedIntegrationNameFromAppSlug(credential.app?.slug ?? "");++ // Check if the event type uses the deleted integration++ // To avoid type errors, need to stringify and parse JSON to use array methods+ const locations = locationsSchema.parse(eventType.locations);++ const doesDailyVideoAlreadyExists = locations.some((location) =>+ location.type.includes(DailyLocationType)+ );++ const updatedLocations: TlocationsSchema = locations.reduce((acc: TlocationsSchema, location) => {+ if (location.type.includes(integrationQuery)) {+ if (!doesDailyVideoAlreadyExists) acc.push({ type: DailyLocationType });+ } else {+ acc.push(location);+ }+ return acc;+ }, []);++ await prisma.eventType.update({+ where: {+ id: eventType.id,+ },+ data: {+ locations: updatedLocations,+ },+ });+ }++ // If it's a calendar, remove the destination calendar from the event type+ if (+ credential.app?.categories.includes(AppCategories.calendar) &&+ eventType.destinationCalendar?.credential?.appId === credential.appId+ ) {+ const destinationCalendar = await prisma.destinationCalendar.findFirst({+ where: {+ id: eventType.destinationCalendar?.id,+ },+ });++ if (destinationCalendar) {+ await prisma.destinationCalendar.delete({+ where: {+ id: destinationCalendar.id,+ },+ });+ }+ }++ if (credential.app?.categories.includes(AppCategories.crm)) {+ const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);+ const appSlugToDelete = credential.app?.slug;++ if (appSlugToDelete) {+ const appMetadata = removeAppFromEventTypeMetadata(appSlugToDelete, metadata);++ await prisma.$transaction(async () => {+ await prisma.eventType.update({+ where: {+ id: eventType.id,+ },+ data: {+ hidden: true,+ metadata: {+ ...metadata,+ apps: {+ ...appMetadata,+ },+ },+ },+ });+ });+ }+ }++ // If it's a payment, hide the event type and set the price to 0. Also cancel all pending bookings+ if (credential.app?.categories.includes(AppCategories.payment)) {+ const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);+ const appSlug = credential.app?.slug;+ if (appSlug) {+ const appMetadata = removeAppFromEventTypeMetadata(appSlug, metadata);++ await prisma.$transaction(async () => {+ await prisma.eventType.update({+ where: {+ id: eventType.id,+ },+ data: {+ hidden: true,+ metadata: {+ ...metadata,+ apps: {+ ...appMetadata,+ },+ },+ },+ });++ // Assuming that all bookings under this eventType need to be paid+ const unpaidBookings = await prisma.booking.findMany({+ where: {+ userId: userId,+ eventTypeId: eventType.id,+ status: "PENDING",+ paid: false,+ payment: {+ every: {+ success: false,+ },+ },+ },+ select: {+ ...bookingMinimalSelect,+ recurringEventId: true,+ userId: true,+ responses: true,+ user: {+ select: {+ id: true,+ credentials: true,+ email: true,+ timeZone: true,+ name: true,+ destinationCalendar: true,+ locale: true,+ },+ },+ location: true,+ references: {+ select: {+ uid: true,+ type: true,+ externalCalendarId: true,+ },+ },+ payment: true,+ paid: true,+ eventType: {+ select: {+ recurringEvent: true,+ title: true,+ bookingFields: true,+ seatsPerTimeSlot: true,+ seatsShowAttendees: true,+ eventName: true,+ },+ },+ uid: true,+ eventTypeId: true,+ destinationCalendar: true,+ },+ });++ for (const booking of unpaidBookings) {+ await prisma.booking.update({+ where: {+ id: booking.id,+ },+ data: {+ status: BookingStatus.CANCELLED,+ cancellationReason: "Payment method removed",+ },+ });++ for (const payment of booking.payment) {+ try {+ await deletePayment(payment.id, credential);+ } catch (e) {+ console.error(e);+ }+ await prisma.payment.delete({+ where: {+ id: payment.id,+ },+ });+ }++ await prisma.attendee.deleteMany({+ where: {+ bookingId: booking.id,+ },+ });++ await prisma.bookingReference.deleteMany({+ where: {+ bookingId: booking.id,+ },+ });++ const attendeesListPromises = booking.attendees.map(async (attendee) => {+ return {+ name: attendee.name,+ email: attendee.email,+ timeZone: attendee.timeZone,+ language: {+ translate: await getTranslation(attendee.locale ?? "en", "common"),+ locale: attendee.locale ?? "en",+ },+ };+ });++ const attendeesList = await Promise.all(attendeesListPromises);+ const tOrganizer = await getTranslation(booking?.user?.locale ?? "en", "common");+ await sendCancelledEmails(+ {+ type: booking?.eventType?.title as string,+ title: booking.title,+ description: booking.description,+ customInputs: isPrismaObjOrUndefined(booking.customInputs),+ ...getCalEventResponses({+ bookingFields: booking.eventType?.bookingFields ?? null,+ booking,+ }),+ startTime: booking.startTime.toISOString(),+ endTime: booking.endTime.toISOString(),+ organizer: {+ email: booking?.userPrimaryEmail ?? (booking?.user?.email as string),+ name: booking?.user?.name ?? "Nameless",+ timeZone: booking?.user?.timeZone as string,+ language: { translate: tOrganizer, locale: booking?.user?.locale ?? "en" },+ },+ attendees: attendeesList,+ uid: booking.uid,+ recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),+ location: booking.location,+ destinationCalendar: booking.destinationCalendar+ ? [booking.destinationCalendar]+ : booking.user?.destinationCalendar+ ? [booking.user?.destinationCalendar]+ : [],+ cancellationReason: "Payment method removed by organizer",+ seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot,+ seatsShowAttendees: booking.eventType?.seatsShowAttendees,+ },+ {+ eventName: booking?.eventType?.eventName,+ }+ );+ }+ });+ }+ } else if (+ appStoreMetadata[credential.app?.slug as keyof typeof appStoreMetadata]?.extendsFeature === "EventType"+ ) {+ const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);+ const appSlug = credential.app?.slug;+ if (appSlug) {+ await prisma.eventType.update({+ where: {+ id: eventType.id,+ },+ data: {+ hidden: true,+ metadata: {+ ...metadata,+ apps: {+ ...metadata?.apps,+ [appSlug]: undefined,+ },+ },+ },+ });+ }+ }+ }++ // if zapier get disconnected, delete zapier apiKey, delete zapier webhooks and cancel all scheduled jobs from zapier+ if (credential.app?.slug === "zapier") {+ await prisma.apiKey.deleteMany({+ where: {+ userId: userId,+ appId: "zapier",+ },+ });+ await prisma.webhook.deleteMany({+ where: {+ userId: userId,+ appId: "zapier",+ },+ });++ deleteWebhookScheduledTriggers({+ appId: credential.appId,+ userId: teamId ? undefined : userId,+ teamId,+ });+ }++ let metadata = userMetadataSchema.parse(userMetadata);++ if (credential.app?.slug === metadata?.defaultConferencingApp?.appSlug) {+ metadata = {+ ...metadata,+ defaultConferencingApp: undefined,+ };+ await prisma.user.update({+ where: {+ id: userId,+ },+ data: {+ metadata,+ },+ });+ }++ // Backwards compatibility. Selected calendars cascade on delete when deleting a credential+ // If it's a calendar remove it from the SelectedCalendars+ if (credential.app?.categories.includes(AppCategories.calendar)) {+ try {+ const calendar = await getCalendar(credential);++ const calendars = await calendar?.listCalendars();++ const calendarIds = calendars?.map((cal) => cal.externalId);++ await prisma.selectedCalendar.deleteMany({+ where: {+ userId: userId,+ integration: credential.type as string,+ externalId: {+ in: calendarIds,+ },+ },+ });+ } catch (error) {+ console.warn(+ `Error deleting selected calendars for userId: ${userId} integration: ${credential.type}`,+ error+ );+ }+ }++ // Validated that credential is user's above+ await prisma.credential.delete({+ where: {+ id: credentialId,+ },+ });+};++const removeAppFromEventTypeMetadata = (+ appSlugToDelete: string,+ eventTypeMetadata: z.infer<typeof EventTypeMetaDataSchema>+) => {+ const appMetadata = eventTypeMetadata?.apps+ ? Object.entries(eventTypeMetadata.apps).reduce((filteredApps, [appName, appData]) => {+ if (appName !== appSlugToDelete) {+ filteredApps[appName as keyof typeof eventTypeMetadata.apps] = appData;+ }+ return filteredApps;+ }, {} as z.infer<typeof EventTypeAppMetadataSchema>)+ : {};++ return appMetadata;+};++export default handleDeleteCredential;diff --git a/packages/lib/server/repository/app.ts b/packages/lib/server/repository/app.tsnew file mode 100644index 00000000000..b60d5378a37--- /dev/null+++ b/packages/lib/server/repository/app.ts@@ -0,0 +1,24 @@+import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";+import logger from "@calcom/lib/logger";+import { prisma } from "@calcom/prisma";++const log = logger.getSubLogger({ prefix: ["repository/eventType"] });+export class AppRepository {+ static async seedApp(dirName: string, keys?: any) {+ const appMetadata = appStoreMetadata[dirName as keyof typeof appStoreMetadata];++ if (!appMetadata) {+ throw new Error(`App ${dirName} not found`);+ }++ await prisma.app.create({+ data: {+ slug: appMetadata.slug,+ categories: appMetadata.categories,+ dirName: dirName,+ keys,+ enabled: true,+ },+ });+ }+}diff --git a/packages/lib/server/repository/credential.ts b/packages/lib/server/repository/credential.tsnew file mode 100644index 00000000000..b5a81f36a3d--- /dev/null+++ b/packages/lib/server/repository/credential.ts@@ -0,0 +1,9 @@+import type { Prisma } from "@prisma/client";++import { prisma } from "@calcom/prisma";++export class CredentialRepository {+ static async create(data: Prisma.CredentialCreateInput) {+ return await prisma.credential.create({ data });+ }+}diff --git a/packages/lib/server/repository/destinationCalendar.ts b/packages/lib/server/repository/destinationCalendar.tsnew file mode 100644index 00000000000..b45e7ea4e5d--- /dev/null+++ b/packages/lib/server/repository/destinationCalendar.ts@@ -0,0 +1,27 @@+import type { Prisma } from "@prisma/client";++import { prisma } from "@calcom/prisma";++export class DestinationCalendarRepository {+ static async create(data: Prisma.DestinationCalendarCreateInput) {+ return await prisma.destinationCalendar.create({+ data,+ });+ }++ static async getByUserId(userId: string) {+ return await prisma.destinationCalendar.findFirst({+ where: {+ userId,+ },+ });+ }++ static async getByEventTypeId(eventTypeId: number) {+ return await prisma.destinationCalendar.findFirst({+ where: {+ eventTypeId,+ },+ });+ }+}diff --git a/packages/lib/server/repository/eventType.ts b/packages/lib/server/repository/eventType.tsindex 8cd75eb046c..c6ab13d513d 100644--- a/packages/lib/server/repository/eventType.ts+++ b/packages/lib/server/repository/eventType.ts@@ -32,7 +32,7 @@ const userSelect = Prisma.validator<Prisma.UserSelect>()({});export class EventTypeRepository {- static async create(data: IEventType) {+ private static generateCreateEventTypeData = (eventTypeCreateData: IEventType) => {const {userId,profileId,@@ -45,45 +45,56 @@ export class EventTypeRepository {bookingFields,durationLimits,...rest- } = data;- return await prisma.eventType.create({- data: {- ...rest,- ...(userId ? { owner: { connect: { id: userId } } } : null),- ...(profileId- ? {- profile: {- connect: {- id: profileId,- },+ } = eventTypeCreateData;++ return {+ ...rest,+ ...(userId ? { owner: { connect: { id: userId } } } : null),+ ...(profileId+ ? {+ profile: {+ connect: {+ id: profileId,},- }- : null),- ...(teamId ? { team: { connect: { id: teamId } } } : null),- ...(parentId ? { parent: { connect: { id: parentId } } } : null),- ...(scheduleId ? { schedule: { connect: { id: scheduleId } } } : null),- ...(metadata ? { metadata: metadata } : null),- ...(bookingLimits- ? {- bookingLimits,- }- : null),- ...(recurringEvent- ? {- recurringEvent,- }- : null),- ...(bookingFields- ? {- bookingFields,- }- : null),- ...(durationLimits- ? {- durationLimits,- }- : null),- },+ },+ }+ : null),+ ...(teamId ? { team: { connect: { id: teamId } } } : null),+ ...(parentId ? { parent: { connect: { id: parentId } } } : null),+ ...(scheduleId ? { schedule: { connect: { id: scheduleId } } } : null),+ ...(metadata ? { metadata: metadata } : null),+ ...(bookingLimits+ ? {+ bookingLimits,+ }+ : null),+ ...(recurringEvent+ ? {+ recurringEvent,+ }+ : null),+ ...(bookingFields+ ? {+ bookingFields,+ }+ : null),+ ...(durationLimits+ ? {+ durationLimits,+ }+ : null),+ };+ };++ static async create(data: IEventType) {+ return await prisma.eventType.create({+ data: this.generateCreateEventTypeData(data),+ });+ }++ static async createMany(data: IEventType[]) {+ return await prisma.eventType.createMany({+ data: data.map((d) => this.generateCreateEventTypeData(d)),});}diff --git a/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts b/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.tsindex f2fc7b6c961..cd28ff9b652 100644--- a/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts+++ b/packages/trpc/server/routers/loggedInViewer/deleteCredential.handler.ts@@ -1,24 +1,6 @@-import z from "zod";--import { getCalendar } from "@calcom/app-store/_utils/getCalendar";-import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";-import { DailyLocationType } from "@calcom/core/location";-import { sendCancelledEmails } from "@calcom/emails";-import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";-import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/scheduleTrigger";-import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";-import { deletePayment } from "@calcom/lib/payment/deletePayment";-import { getTranslation } from "@calcom/lib/server/i18n";-import { bookingMinimalSelect, prisma } from "@calcom/prisma";-import { AppCategories, BookingStatus } from "@calcom/prisma/enums";-import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";-import type { EventTypeAppMetadataSchema } from "@calcom/prisma/zod-utils";-import { userMetadata } from "@calcom/prisma/zod-utils";-import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";+import handleDeleteCredential from "@calcom/features/credentials/handleDeleteCredential";import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";-import { TRPCError } from "@trpc/server";-import type { TDeleteCredentialInputSchema } from "./deleteCredential.schema";type DeleteCredentialOptions = {@@ -28,433 +10,9 @@ type DeleteCredentialOptions = {input: TDeleteCredentialInputSchema;};-type App = {- slug: string;- categories: AppCategories[];- dirName: string;-} | null;--const isVideoOrConferencingApp = (app: App) =>- app?.categories.includes(AppCategories.video) || app?.categories.includes(AppCategories.conferencing);--const getRemovedIntegrationNameFromAppSlug = (slug: string) =>- slug === "msteams" ? "office365_video" : slug.split("-")[0];--const locationsSchema = z.array(z.object({ type: z.string() }));-type TlocationsSchema = z.infer<typeof locationsSchema>;-export const deleteCredentialHandler = async ({ ctx, input }: DeleteCredentialOptions) => {const { user } = ctx;const { id, teamId } = input;- const credential = await prisma.credential.findFirst({- where: {- id: id,- ...(teamId ? { teamId } : { userId: ctx.user.id }),- },- select: {- ...credentialForCalendarServiceSelect,- app: {- select: {- slug: true,- categories: true,- dirName: true,- },- },- },- });-- if (!credential) {- throw new TRPCError({ code: "NOT_FOUND" });- }-- const eventTypes = await prisma.eventType.findMany({- where: {- OR: [- {- ...(teamId ? { teamId } : { userId: ctx.user.id }),- },- // for managed events- {- parent: {- teamId,- },- },- ],- },- select: {- id: true,- locations: true,- destinationCalendar: {- include: {- credential: true,- },- },- price: true,- currency: true,- metadata: true,- },- });-- // TODO: Improve this uninstallation cleanup per event by keeping a relation of EventType to App which has the data.- for (const eventType of eventTypes) {- // If it's a video, replace the location with Cal video- if (eventType.locations && isVideoOrConferencingApp(credential.app)) {- // Find the user's event types-- const integrationQuery = getRemovedIntegrationNameFromAppSlug(credential.app?.slug ?? "");-- // Check if the event type uses the deleted integration-- // To avoid type errors, need to stringify and parse JSON to use array methods- const locations = locationsSchema.parse(eventType.locations);-- const doesDailyVideoAlreadyExists = locations.some((location) =>- location.type.includes(DailyLocationType)- );-- const updatedLocations: TlocationsSchema = locations.reduce((acc: TlocationsSchema, location) => {- if (location.type.includes(integrationQuery)) {- if (!doesDailyVideoAlreadyExists) acc.push({ type: DailyLocationType });- } else {- acc.push(location);- }- return acc;- }, []);-- await prisma.eventType.update({- where: {- id: eventType.id,- },- data: {- locations: updatedLocations,- },- });- }-- // If it's a calendar, remove the destination calendar from the event type- if (- credential.app?.categories.includes(AppCategories.calendar) &&- eventType.destinationCalendar?.credential?.appId === credential.appId- ) {- const destinationCalendar = await prisma.destinationCalendar.findFirst({- where: {- id: eventType.destinationCalendar?.id,- },- });-- if (destinationCalendar) {- await prisma.destinationCalendar.delete({- where: {- id: destinationCalendar.id,- },- });- }- }-- if (credential.app?.categories.includes(AppCategories.crm)) {- const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);- const appSlugToDelete = credential.app?.slug;-- if (appSlugToDelete) {- const appMetadata = removeAppFromEventTypeMetadata(appSlugToDelete, metadata);-- await prisma.$transaction(async () => {- await prisma.eventType.update({- where: {- id: eventType.id,- },- data: {- hidden: true,- metadata: {- ...metadata,- apps: {- ...appMetadata,- },- },- },- });- });- }- }-- // If it's a payment, hide the event type and set the price to 0. Also cancel all pending bookings- if (credential.app?.categories.includes(AppCategories.payment)) {- const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);- const appSlug = credential.app?.slug;- if (appSlug) {- const appMetadata = removeAppFromEventTypeMetadata(appSlug, metadata);-- await prisma.$transaction(async () => {- await prisma.eventType.update({- where: {- id: eventType.id,- },- data: {- hidden: true,- metadata: {- ...metadata,- apps: {- ...appMetadata,- },- },- },- });-- // Assuming that all bookings under this eventType need to be paid- const unpaidBookings = await prisma.booking.findMany({- where: {- userId: ctx.user.id,- eventTypeId: eventType.id,- status: "PENDING",- paid: false,- payment: {- every: {- success: false,- },- },- },- select: {- ...bookingMinimalSelect,- recurringEventId: true,- userId: true,- responses: true,- user: {- select: {- id: true,- credentials: true,- email: true,- timeZone: true,- name: true,- destinationCalendar: true,- locale: true,- },- },- location: true,- references: {- select: {- uid: true,- type: true,- externalCalendarId: true,- },- },- payment: true,- paid: true,- eventType: {- select: {- recurringEvent: true,- title: true,- bookingFields: true,- seatsPerTimeSlot: true,- seatsShowAttendees: true,- eventName: true,- },- },- uid: true,- eventTypeId: true,- destinationCalendar: true,- },- });-- for (const booking of unpaidBookings) {- await prisma.booking.update({- where: {- id: booking.id,- },- data: {- status: BookingStatus.CANCELLED,- cancellationReason: "Payment method removed",- },- });-- for (const payment of booking.payment) {- try {- await deletePayment(payment.id, credential);- } catch (e) {- console.error(e);- }- await prisma.payment.delete({- where: {- id: payment.id,- },- });- }-- await prisma.attendee.deleteMany({- where: {- bookingId: booking.id,- },- });-- await prisma.bookingReference.deleteMany({- where: {- bookingId: booking.id,- },- });-- const attendeesListPromises = booking.attendees.map(async (attendee) => {- return {- name: attendee.name,- email: attendee.email,- timeZone: attendee.timeZone,- language: {- translate: await getTranslation(attendee.locale ?? "en", "common"),- locale: attendee.locale ?? "en",- },- };- });-- const attendeesList = await Promise.all(attendeesListPromises);- const tOrganizer = await getTranslation(booking?.user?.locale ?? "en", "common");- await sendCancelledEmails(- {- type: booking?.eventType?.title as string,- title: booking.title,- description: booking.description,- customInputs: isPrismaObjOrUndefined(booking.customInputs),- ...getCalEventResponses({- bookingFields: booking.eventType?.bookingFields ?? null,- booking,- }),- startTime: booking.startTime.toISOString(),- endTime: booking.endTime.toISOString(),- organizer: {- email: booking?.userPrimaryEmail ?? (booking?.user?.email as string),- name: booking?.user?.name ?? "Nameless",- timeZone: booking?.user?.timeZone as string,- language: { translate: tOrganizer, locale: booking?.user?.locale ?? "en" },- },- attendees: attendeesList,- uid: booking.uid,- recurringEvent: parseRecurringEvent(booking.eventType?.recurringEvent),- location: booking.location,- destinationCalendar: booking.destinationCalendar- ? [booking.destinationCalendar]- : booking.user?.destinationCalendar- ? [booking.user?.destinationCalendar]- : [],- cancellationReason: "Payment method removed by organizer",- seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot,- seatsShowAttendees: booking.eventType?.seatsShowAttendees,- },- {- eventName: booking?.eventType?.eventName,- }- );- }- });- }- } else if (- appStoreMetadata[credential.app?.slug as keyof typeof appStoreMetadata]?.extendsFeature === "EventType"- ) {- const metadata = EventTypeMetaDataSchema.parse(eventType.metadata);- const appSlug = credential.app?.slug;- if (appSlug) {- await prisma.eventType.update({- where: {- id: eventType.id,- },- data: {- hidden: true,- metadata: {- ...metadata,- apps: {- ...metadata?.apps,- [appSlug]: undefined,- },- },- },- });- }- }- }-- // if zapier get disconnected, delete zapier apiKey, delete zapier webhooks and cancel all scheduled jobs from zapier- if (credential.app?.slug === "zapier") {- await prisma.apiKey.deleteMany({- where: {- userId: ctx.user.id,- appId: "zapier",- },- });- await prisma.webhook.deleteMany({- where: {- userId: ctx.user.id,- appId: "zapier",- },- });-- deleteWebhookScheduledTriggers({- appId: credential.appId,- userId: teamId ? undefined : ctx.user.id,- teamId,- });- }-- let metadata = userMetadata.parse(user.metadata);-- if (credential.app?.slug === metadata?.defaultConferencingApp?.appSlug) {- metadata = {- ...metadata,- defaultConferencingApp: undefined,- };- await prisma.user.update({- where: {- id: user.id,- },- data: {- metadata,- },- });- }-- // Backwards compatibility. Selected calendars cascade on delete when deleting a credential- // If it's a calendar remove it from the SelectedCalendars- if (credential.app?.categories.includes(AppCategories.calendar)) {- try {- const calendar = await getCalendar(credential);-- const calendars = await calendar?.listCalendars();-- const calendarIds = calendars?.map((cal) => cal.externalId);-- await prisma.selectedCalendar.deleteMany({- where: {- userId: user.id,- integration: credential.type as string,- externalId: {- in: calendarIds,- },- },- });- } catch (error) {- console.warn(- `Error deleting selected calendars for userId: ${user.id} integration: ${credential.type}`,- error- );- }- }-- // Validated that credential is user's above- await prisma.credential.delete({- where: {- id: id,- },- });-};--const removeAppFromEventTypeMetadata = (- appSlugToDelete: string,- eventTypeMetadata: z.infer<typeof EventTypeMetaDataSchema>-) => {- const appMetadata = eventTypeMetadata?.apps- ? Object.entries(eventTypeMetadata.apps).reduce((filteredApps, [appName, appData]) => {- if (appName !== appSlugToDelete) {- filteredApps[appName as keyof typeof eventTypeMetadata.apps] = appData;- }- return filteredApps;- }, {} as z.infer<typeof EventTypeAppMetadataSchema>)- : {};-- return appMetadata;+ await handleDeleteCredential({ userId: user.id, userMetadata: user.metadata, credentialId: id, teamId });};