chore: Disables syncing of calendarList on overlay calendar fetch (#27020)

* chore: Disables syncing of calendarList on overlay calendar fetch

* Unwrap ToggledConnectedCalendars

* Pick the right type for connectedCalendars

* further type amends

* Type fixes, tons of em

* Some further fixups consistent with what was before

* fix: resolve type incompatibility in getConnectedDestinationCalendars return type

Co-Authored-By: [email protected] <[email protected]>

* fix: update DestinationCalendarProps to accept tRPC handler return type

Co-Authored-By: [email protected] <[email protected]>

* fix: use generic type for DestinationCalendarProps to accept tRPC enriched types

Co-Authored-By: [email protected] <[email protected]>

* fix: simplify DestinationCalendarProps type for better compatibility

Co-Authored-By: [email protected] <[email protected]>

* fix: export ConnectedCalendar type for consistent type inference

Co-Authored-By: [email protected] <[email protected]>

* fix: use permissive type for connectedCalendars to accept tRPC enriched types

Co-Authored-By: [email protected] <[email protected]>

* fix: export ConnectedCalendar and ConnectedDestinationCalendars types from platform-libraries

Co-Authored-By: [email protected] <[email protected]>

* fix: update ConnectedCalendar type to use boolean | null for primary field

Co-Authored-By: [email protected] <[email protected]>

* Update ConnectedCalendarItem

* Undo some of Devins fixes, more fixes

* Fixup the destination calendar return type, historically not null

* Change init to undefined to deal with null

* Approach to connect selected calendars with the right credential

* This return type is used way too much everywhere, not refactoring

* Add the selectedCalendars to the type

* Actually fix overlay calendar

* set calendarsToLoad param as required

* Apply suggestion from @cubic-dev-ai[bot]

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Add new translation for 'Calendar Settings'

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-28 14:20:19 -03:00
1 parent c62f333337
commit c9bd18e866
22 files changed
+486 -428

No files matched your search

@@ -1,6 +1,5 @@
import { create } from "zustand";
import type { EventBusyDate } from "@calcom/types/Calendar";
import { createWithEqualityFn } from "zustand/traditional";
interface IOverlayCalendarStore {
overlayBusyDates: EventBusyDate[] | undefined;
@@ -11,7 +10,7 @@ interface IOverlayCalendarStore {
setCalendarSettingsOverlayModal: (value: boolean) => void;
}
export const useOverlayCalendarStore = create<IOverlayCalendarStore>((set) => ({
export const useOverlayCalendarStore = createWithEqualityFn<IOverlayCalendarStore>((set) => ({
overlayBusyDates: undefined,
setOverlayBusyDates: (busyDates: EventBusyDate[]) => {
set({ overlayBusyDates: busyDates });
@@ -1,23 +1,16 @@
import { useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { shallow } from "zustand/shallow";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { localStorage } from "@calcom/lib/webstorage";
import { trpc } from "@calcom/trpc/react";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { shallow } from "zustand/shallow";
import { useBookerStore } from "../../store";
import type { ToggledConnectedCalendars } from "../../types";
import { useOverlayCalendarStore } from "../OverlayCalendar/store";
import { useLocalSet } from "./useLocalSet";
export type UseCalendarsReturnType = ReturnType<typeof useCalendars>;
type UseCalendarsProps = {
hasSession: boolean;
};
export type ToggledConnectedCalendars = Set<{
credentialId: number;
externalId: string;
}>;
export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
const searchParams = useSearchParams();
@@ -26,11 +19,11 @@ export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
const switchEnabled =
searchParams?.get("overlayCalendar") === "true" ||
localStorage?.getItem("overlayCalendarSwitchDefault") === "true";
const { set, clearSet } = useLocalSet<{
credentialId: number;
externalId: string;
}>("toggledConnectedCalendars", []);
const utils = trpc.useUtils();
const [set, setSet] = useState<Set<ToggledConnectedCalendars>>(() => {
const storedValue = localStorage.getItem("toggledConnectedCalendars");
return storedValue ? new Set(JSON.parse(storedValue)) : new Set([]);
});
const [calendarSettingsOverlay] = useOverlayCalendarStore(
(state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
@@ -55,22 +48,25 @@ export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
useEffect(
function refactorMeWithoutEffect() {
if (!isError) return;
clearSet();
setSet(new Set([]));
},
[isError]
);
const { data, isPending } = trpc.viewer.calendars.connectedCalendars.useQuery(undefined, {
enabled: !!calendarSettingsOverlay || Boolean(searchParams?.get("overlayCalendar")),
});
const { data, isPending } = trpc.viewer.calendars.connectedCalendars.useQuery(
{
skipSync: true,
},
{
enabled: !!calendarSettingsOverlay || Boolean(searchParams?.get("overlayCalendar")),
}
);
return {
overlayBusyDates,
isOverlayCalendarEnabled: switchEnabled,
connectedCalendars: data?.connectedCalendars || [],
loadingConnectedCalendar: isPending,
onToggleCalendar: (data: ToggledConnectedCalendars) => {
utils.viewer.availability.calendarOverlay.reset();
},
onToggleCalendar: setSet,
};
};
@@ -1,24 +1,30 @@
import { useEffect, useState } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { useEffect, useState } from "react";
import { shallow } from "zustand/shallow";
import type { ToggledConnectedCalendars, WrappedBookerPropsMain } from "../../types";
import { useOverlayCalendarStore } from "../OverlayCalendar/store";
import type { UseCalendarsReturnType } from "./useCalendars";
import { useLocalSet } from "./useLocalSet";
export type UseOverlayCalendarReturnType = ReturnType<typeof useOverlayCalendar>;
export const useOverlayCalendar = ({
connectedCalendars,
overlayBusyDates,
onToggleCalendar,
}: Pick<UseCalendarsReturnType, "connectedCalendars" | "overlayBusyDates" | "onToggleCalendar">) => {
const { set, toggleValue, hasItem } = useLocalSet<{
credentialId: number;
externalId: string;
}>("toggledConnectedCalendars", []);
}: Pick<
WrappedBookerPropsMain["calendars"],
"overlayBusyDates" | "onToggleCalendar" | "connectedCalendars"
>): {
isOpenOverlayContinueModal: boolean;
isOpenOverlaySettingsModal: boolean;
handleCloseContinueModal: (val: boolean) => void;
handleCloseSettingsModal: (val: boolean) => void;
handleToggleConnectedCalendar: (externalCalendarId: string, credentialId: number) => void;
checkIsCalendarToggled: (externalId: string, credentialId: number) => boolean;
} => {
const { set, toggleValue, hasItem } = useLocalSet<ToggledConnectedCalendars>(
"toggledConnectedCalendars",
[]
);
const [initalised, setInitalised] = useState(false);
const [continueWithProvider, setContinueWithProvider] = useOverlayCalendarStore(
(state) => [state.continueWithProviderModal, state.setContinueWithProviderModal],
@@ -65,7 +71,7 @@ export const useOverlayCalendar = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasItem, set, initalised]);
const handleToggleConnectedCalendar = (externalCalendarId: string, credentialId: number) => {
const handleToggleConnectedCalendar = (externalCalendarId: string, credentialId: number): void => {
const calendarsToLoad = toggleValue({
credentialId: credentialId,
externalId: externalCalendarId,
+35 -2
View File
@@ -1,13 +1,13 @@
import type { UseBookerLayoutType } from "@calcom/features/bookings/Booker/components/hooks/useBookerLayout";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import type { UseBookingsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { UseCalendarsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useCalendars";
import type { UseSlotsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useSlots";
import type { UseVerifyCodeReturnType } from "@calcom/features/bookings/Booker/components/hooks/useVerifyCode";
import type { UseVerifyEmailReturnType } from "@calcom/features/bookings/Booker/components/hooks/useVerifyEmail";
import type { useScheduleForEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
import type { BookerEventQuery } from "@calcom/features/bookings/types";
import type { IntlSupportedTimeZones } from "@calcom/lib/timeZones";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type React from "react";
import type { GetBookingType } from "../lib/get-booking";
@@ -105,6 +105,11 @@ export interface BookerProps {
useApiV2?: boolean;
}
export type ToggledConnectedCalendars = {
credentialId: number;
externalId: string;
};
export type WrappedBookerPropsMain = {
sessionUsername?: string | null;
rescheduleUid: string | null;
@@ -121,7 +126,35 @@ export type WrappedBookerPropsMain = {
extraOptions: Record<string, string | string[]>;
bookings: UseBookingsReturnType;
slots: UseSlotsReturnType;
calendars: UseCalendarsReturnType;
calendars: {
overlayBusyDates?: EventBusyDate[];
isOverlayCalendarEnabled: boolean;
connectedCalendars: {
calendars?: {
name?: string;
integrationTitle?: string;
externalId: string;
primary: boolean | null;
}[];
credentialId: number;
delegationCredentialId?: string | null;
cacheUpdatedAt: null;
error?: {
message: string | null;
};
primary?: {
email?: string;
};
integration: {
slug: string;
name?: string | undefined;
title?: string;
logo: string;
};
}[];
loadingConnectedCalendar: boolean;
onToggleCalendar: (calendarsToLoad: Set<ToggledConnectedCalendars>) => void;
};
bookerForm: UseBookingFormReturnType;
event: BookerEventQuery;
schedule: useScheduleForEventReturnType;
@@ -1,14 +1,13 @@
import classNames from "classnames";
import { useEffect, useState } from "react";
import type { OptionProps, SingleValueProps } from "react-select";
import { components } from "react-select";
import type { SelectClassNames } from "@calcom/features/eventtypes/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Select } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import classNames from "classnames";
import { useEffect, useState } from "react";
import type { OptionProps, SingleValueProps } from "react-select";
import { components } from "react-select";
interface Props {
onChange: (value: { externalId: string; integration: string }) => void;
@@ -88,8 +87,7 @@ const DestinationCalendarSelector = ({
useEffect(() => {
const selected = connectedCalendarsList
?.map((connected) => connected.calendars ?? [])
.flat()
?.flatMap((connected) => connected.calendars ?? [])
.find((cal) => cal.externalId === value);
if (selected) {
@@ -140,7 +138,7 @@ const DestinationCalendarSelector = ({
`${t("create_events_on")}`
) : (
<span className="text-default min-w-0 overflow-hidden truncate whitespace-nowrap">
<Badge variant="blue">Default</Badge>{" "}
<Badge variant="blue">{t("default")}</Badge>{" "}
{destinationCalendar?.name &&
`${destinationCalendar.name} (${destinationCalendar?.integrationTitle} - ${destinationCalendar.primaryEmail})`}
</span>
@@ -1,5 +1,3 @@
import { sortBy } from "lodash";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { MeetLocationType } from "@calcom/app-store/locations";
import getApps from "@calcom/app-store/utils";
@@ -7,8 +5,7 @@ import dayjs from "@calcom/dayjs";
import getCalendarsEvents, {
getCalendarsEventsWithTimezones,
} from "@calcom/features/calendars/lib/getCalendarsEvents";
import { getUid } from "@calcom/lib/CalEventParser";
import { getRichDescription } from "@calcom/lib/CalEventParser";
import { getRichDescription, getUid } from "@calcom/lib/CalEventParser";
import { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
import { ORGANIZER_EMAIL_EXEMPT_DOMAINS } from "@calcom/lib/constants";
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential";
@@ -27,9 +24,60 @@ import type {
} from "@calcom/types/Calendar";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import type { EventResult } from "@calcom/types/EventManager";
import { sortBy } from "lodash";
const log = logger.getSubLogger({ prefix: ["CalendarManager"] });
/**
* Process the calendar event by generating description and removing attendees if needed
*/
const processEvent = (calEvent: CalendarEvent): CalendarServiceEvent => {
if (calEvent.seatsPerTimeSlot) {
calEvent.responses = null;
calEvent.userFieldsResponses = null;
calEvent.additionalNotes = null;
calEvent.customInputs = null;
}
// Generate the calendar event description
const calendarEvent: CalendarServiceEvent = {
...calEvent,
calendarDescription: getRichDescription(calEvent),
};
const isMeetLocationType = calEvent.location === MeetLocationType;
// Determine if the calendar event should include attendees
const isOrganizerExempt = ORGANIZER_EMAIL_EXEMPT_DOMAINS?.split(",")
.filter((domain) => domain.trim() !== "")
.some((domain) => calEvent.organizer.email.toLowerCase().endsWith(domain.toLowerCase()));
if (calEvent.hideOrganizerEmail && !isOrganizerExempt && !isMeetLocationType) {
calendarEvent.attendees = [];
}
return calendarEvent;
};
type IntegrationWithCredentials = Awaited<
ReturnType<typeof getCalendarCredentials>
>[number]["integration"] & {
credentials?: CredentialPayload[];
credential?: CredentialPayload;
};
type CleanIntegration = Omit<IntegrationWithCredentials, "credentials" | "credential">;
/**
* Important function to prevent leaking credentials to the client
* @param appIntegration
* @returns App
*/
export const cleanIntegrationKeys = (appIntegration: IntegrationWithCredentials): CleanIntegration => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { credentials, credential, ...rest } = appIntegration;
return rest;
};
export const getCalendarCredentials = (credentials: Array<CredentialForCalendarService>) => {
const calendarCredentials = getApps(credentials, true)
.filter((app) => app.type.endsWith("_calendar"))
@@ -49,11 +97,31 @@ export const getCalendarCredentialsWithoutDelegation = (credentials: CredentialP
return getCalendarCredentials(buildNonDelegationCredentials(credentials));
};
export type ConnectedCalendar = Omit<IntegrationCalendar, "primary"> & {
primary: boolean | null;
isSelected: boolean;
readOnly: boolean;
credentialId: number;
delegationCredentialId: string | null;
};
export const getConnectedCalendars = async (
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
selectedCalendars: { externalId: string }[],
destinationCalendarExternalId?: string
) => {
): Promise<{
connectedCalendars: {
integration: CleanIntegration;
calendars?: ConnectedCalendar[];
credentialId: number;
delegationCredentialId?: string | null;
error?: {
message: string;
};
primary?: ConnectedCalendar;
}[];
destinationCalendar: IntegrationCalendar | undefined;
}> => {
const connectedCalendars = await Promise.all(
calendarCredentials.map(async (item) => {
try {
@@ -82,7 +150,7 @@ export const getConnectedCalendars = async (
};
}
const cals = await calendarInstance.listCalendars();
const calendars = sortBy(
const calendars: ConnectedCalendar[] = sortBy(
cals.map((cal: IntegrationCalendar) => {
return {
...cal,
@@ -165,22 +233,6 @@ export const getConnectedCalendars = async (
return { connectedCalendars, destinationCalendar };
};
/**
* Important function to prevent leaking credentials to the client
* @param appIntegration
* @returns App
*/
const cleanIntegrationKeys = (
appIntegration: Awaited<ReturnType<typeof getCalendarCredentials>>[number]["integration"] & {
credentials?: Array<CredentialPayload>;
credential: CredentialPayload;
}
) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { credentials, credential, ...rest } = appIntegration;
return rest;
};
/**
* This function deduplicates credentials based on selected calendars
* It removes regular credentials for which corresponding delegation credentials exist which can be identified only associating them with selected calendars
@@ -311,7 +363,7 @@ export const createEvent = async (
const uid: string = getUid(formattedEvent.uid);
const calendar = await getCalendar(credential, "booking");
let success = true;
let calError: string | undefined = undefined;
let calError: string | undefined;
log.debug(
"Creating calendar event",
@@ -410,7 +462,7 @@ export const updateEvent = async (
const uid = getUid(calEvent.uid);
const calendar = await getCalendar(credential, "booking");
let success = false;
let calError: string | undefined = undefined;
let calError: string | undefined;
let calWarnings: string[] | undefined = [];
log.debug(
"Updating calendar event",
@@ -513,33 +565,3 @@ export const deleteEvent = async ({
return Promise.resolve({});
};
/**
* Process the calendar event by generating description and removing attendees if needed
*/
const processEvent = (calEvent: CalendarEvent): CalendarServiceEvent => {
if (calEvent.seatsPerTimeSlot) {
calEvent.responses = null;
calEvent.userFieldsResponses = null;
calEvent.additionalNotes = null;
calEvent.customInputs = null;
}
// Generate the calendar event description
const calendarEvent: CalendarServiceEvent = {
...calEvent,
calendarDescription: getRichDescription(calEvent),
};
const isMeetLocationType = calEvent.location === MeetLocationType;
// Determine if the calendar event should include attendees
const isOrganizerExempt = ORGANIZER_EMAIL_EXEMPT_DOMAINS?.split(",")
.filter((domain) => domain.trim() !== "")
.some((domain) => calEvent.organizer.email.toLowerCase().endsWith(domain.toLowerCase()));
if (calEvent.hideOrganizerEmail && !isOrganizerExempt && !isMeetLocationType) {
calendarEvent.attendees = [];
}
return calendarEvent;
};
@@ -1,5 +1,7 @@
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import type { CredentialDataWithTeamName } from "@calcom/app-store/utils";
import {
cleanIntegrationKeys,
getCalendarCredentials,
getConnectedCalendars,
} from "@calcom/features/calendars/lib/CalendarManager";
@@ -12,28 +14,13 @@ import prisma from "@calcom/prisma";
import type { DestinationCalendar, SelectedCalendar, User } from "@calcom/prisma/client";
import { AppCategories } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { IntegrationCalendar } from "@calcom/types/Calendar";
const log = logger.getSubLogger({ prefix: ["getConnectedDestinationCalendarsAndEnsureDefaultsInDb"] });
type ReturnTypeGetConnectedCalendars = Awaited<ReturnType<typeof getConnectedCalendars>>;
type ConnectedCalendarsFromGetConnectedCalendars = ReturnTypeGetConnectedCalendars["connectedCalendars"];
export type UserWithCalendars = Pick<User, "id" | "email"> & {
allSelectedCalendars: Pick<
SelectedCalendar,
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
>[];
userLevelSelectedCalendars: Pick<
SelectedCalendar,
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
>[];
destinationCalendar: DestinationCalendar | null;
};
export type ConnectedDestinationCalendars = Awaited<
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
>;
/**
* Ensures that when DelegationCredential is enabled and there is already a calendar connected for the corresponding domain, we only allow the DelegationCredential calendar to be returned
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DelegationCredential connection to be shown because we don't want users to be able to work with individual calendars
@@ -51,7 +38,7 @@ const _ensureNoConflictingNonDelegatedConnectedCalendar = <
connectedCalendars: T[];
loggedInUser: { email: string };
}) => {
return connectedCalendars.filter((connectedCalendar, index, array) => {
return connectedCalendars.filter((connectedCalendar, _index, array) => {
const allCalendarsWithSameAppSlug = array.filter(
(cal) => cal.integration.slug === connectedCalendar.integration.slug
);
@@ -213,12 +200,13 @@ function findMatchingCalendar({
}: {
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
calendar: DestinationCalendar;
}) {
}): Required<ConnectedCalendarsFromGetConnectedCalendars[number]>["calendars"][number] | undefined {
// Check if destinationCalendar exists in connectedCalendars
const allCals = connectedCalendars.flatMap((cal) => cal.calendars ?? []);
const matchingCalendar = allCals.find(
(cal) => cal.externalId === calendar.externalId && cal.integration === calendar.integration
);
if (!matchingCalendar) return;
return matchingCalendar;
}
@@ -254,13 +242,32 @@ function getSelectedCalendars({
}: {
user: UserWithCalendars;
eventTypeId: number | null;
}): Pick<SelectedCalendar, "externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId">[] {
}): Pick<
SelectedCalendar,
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId" | "id"
>[] {
if (eventTypeId) {
return user.allSelectedCalendars.filter((calendar) => calendar.eventTypeId === eventTypeId);
}
return user.userLevelSelectedCalendars;
}
export type UserWithCalendars = Pick<User, "id" | "email"> & {
allSelectedCalendars: Pick<
SelectedCalendar,
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId" | "id"
>[];
userLevelSelectedCalendars: Pick<
SelectedCalendar,
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId" | "id"
>[];
destinationCalendar: DestinationCalendar | null;
};
export type ConnectedDestinationCalendars = Awaited<
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
>;
/**
* Fetches the calendars for the authenticated user or the event-type if provided
* It also takes care of updating the destination calendar in some edge cases
@@ -270,12 +277,17 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
onboarding,
eventTypeId,
prisma,
skipSync,
}: {
user: UserWithCalendars;
onboarding: boolean;
eventTypeId?: number | null;
prisma: PrismaClient;
}) {
skipSync?: boolean;
}): Promise<{
destinationCalendar: DestinationCalendar & Omit<IntegrationCalendar, "id" | "userId">;
connectedCalendars: Awaited<ReturnType<typeof getConnectedCalendars>>["connectedCalendars"];
}> {
const userCredentials = await prisma.credential.findMany({
where: {
userId: user.id,
@@ -284,84 +296,124 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
enabled: true,
},
},
select: credentialForCalendarServiceSelect,
select: {
selectedCalendars: {
select: {
id: true,
},
},
...credentialForCalendarServiceSelect,
},
});
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
let connectedCalendars: Awaited<ReturnType<typeof getConnectedCalendars>>["connectedCalendars"] = [];
let destinationCalendar: IntegrationCalendar | undefined;
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
user: { id: user.id, email: user.email, credentials: userCredentials },
});
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
// get user's credentials + their connected integrations
const calendarCredentials = getCalendarCredentials(allCredentials);
// get all the connected integrations' calendars (from third party)
const getConnectedCalendarsResult = await getConnectedCalendars(
calendarCredentials,
selectedCalendars,
user.destinationCalendar?.externalId
);
let connectedCalendars = getConnectedCalendarsResult.connectedCalendars;
const destinationCalendar = getConnectedCalendarsResult.destinationCalendar;
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
if (connectedCalendars.length === 0) {
user = await handleNoConnectedCalendars(user);
} else if (!user.destinationCalendar) {
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
await handleNoDestinationCalendar({
user,
connectedCalendars,
onboarding,
}));
} else {
/* There are connected calendars and a destination calendar */
log.debug(
`There are connected calendars and a destination calendar, so check if destinationCalendar exists in connectedCalendars for user ${user.id}`
if (!skipSync) {
// get all the connected integrations' calendars (from third party)
const getConnectedCalendarsResult = await getConnectedCalendars(
calendarCredentials,
selectedCalendars,
user.destinationCalendar?.externalId
);
const destinationCal = findMatchingCalendar({ connectedCalendars, calendar: user.destinationCalendar });
if (!destinationCal) {
connectedCalendars = getConnectedCalendarsResult.connectedCalendars;
destinationCalendar = getConnectedCalendarsResult.destinationCalendar;
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
if (connectedCalendars.length === 0) {
user = await handleNoConnectedCalendars(user);
} else if (!user.destinationCalendar) {
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
await handleDestinationCalendarNotInConnectedCalendars({
await handleNoDestinationCalendar({
user,
connectedCalendars,
onboarding,
}));
} else if (onboarding && !destinationCal.isSelected) {
} else {
/* There are connected calendars and a destination calendar */
log.debug(
`Onboarding:Destination calendar is not selected, but in connectedCalendars, so mark it as selected in the calendar list for user ${user.id}`
`There are connected calendars and a destination calendar, so check if destinationCalendar exists in connectedCalendars for user ${user.id}`
);
// Mark the destination calendar as selected in the calendar list
// We use every so that we can exit early once we find the matching calendar
connectedCalendars.every((cal) => {
const index = (cal.calendars || []).findIndex(
(calendar) =>
calendar.externalId === destinationCal.externalId &&
calendar.integration === destinationCal.integration
);
if (index >= 0 && cal.calendars) {
cal.calendars[index].isSelected = true;
calendarToEnsureIsEnabledForConflictCheck = {
externalId: destinationCal.externalId,
integration: destinationCal.integration || "",
};
return false;
}
return true;
const destinationCal = findMatchingCalendar({ connectedCalendars, calendar: user.destinationCalendar });
if (!destinationCal) {
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
await handleDestinationCalendarNotInConnectedCalendars({
user,
connectedCalendars,
onboarding,
}));
} else if (onboarding && !destinationCal.isSelected) {
log.debug(
`Onboarding:Destination calendar is not selected, but in connectedCalendars, so mark it as selected in the calendar list for user ${user.id}`
);
// Mark the destination calendar as selected in the calendar list
// We use every so that we can exit early once we find the matching calendar
connectedCalendars.every((cal) => {
const index = (cal.calendars || []).findIndex(
(calendar) =>
calendar.externalId === destinationCal.externalId &&
calendar.integration === destinationCal.integration
);
if (index >= 0 && cal.calendars) {
cal.calendars[index].isSelected = true;
calendarToEnsureIsEnabledForConflictCheck = {
externalId: destinationCal.externalId,
integration: destinationCal.integration || "",
};
return false;
}
return true;
});
}
}
// Insert the newly toggled record to the DB
if (calendarToEnsureIsEnabledForConflictCheck) {
await ensureSelectedCalendarIsInDb({
user,
selectedCalendar: calendarToEnsureIsEnabledForConflictCheck,
eventTypeId: eventTypeId ?? null,
});
}
}
// very explicit about skipping sync.
if (skipSync) {
// TODO: Make calendar types more flexible so this isn't needed
calendarCredentials.map(async (item) => {
const { integration } = item;
// TODO: Make calendar types more flexible somehow so this isn't needed
const credential: typeof item.credential & { selectedCalendars: { id: string }[] } =
item.credential as CredentialDataWithTeamName & { selectedCalendars: { id: string }[] };
// Insert the newly toggled record to the DB
if (calendarToEnsureIsEnabledForConflictCheck) {
await ensureSelectedCalendarIsInDb({
user,
selectedCalendar: calendarToEnsureIsEnabledForConflictCheck,
eventTypeId: eventTypeId ?? null,
const safeToSendIntegration = cleanIntegrationKeys(integration);
connectedCalendars.push({
integration: safeToSendIntegration,
credentialId: credential.id,
delegationCredentialId: credential.delegationCredentialId,
calendars: selectedCalendars
.filter((cal) =>
credential.selectedCalendars.some((appSelectedCal) => appSelectedCal.id === cal.id)
)
.map((cal) => ({
...cal,
isSelected: true,
readOnly: false,
primary: null,
credentialId: credential.id,
delegationCredentialId: credential.delegationCredentialId,
})),
});
});
}
@@ -369,11 +421,18 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
connectedCalendars,
loggedInUser: { email: user.email },
});
let destinationCalendarWithoutIdAndUserId: Omit<IntegrationCalendar, "id" | "userId"> | null = null;
if (destinationCalendar) {
// ID and userID will be provided by user.destinationCalendar
const { id: _id, userId: _userId, ...partialDestCal } = destinationCalendar;
destinationCalendarWithoutIdAndUserId = partialDestCal;
}
return {
connectedCalendars: noConflictingNonDelegatedConnectedCalendars,
destinationCalendar: {
...(user.destinationCalendar as DestinationCalendar),
...destinationCalendar,
// biome-ignore lint/style/noNonNullAssertion: destinationCalendar is guaranteed to be non null here
...user.destinationCalendar!,
...destinationCalendarWithoutIdAndUserId,
},
};
}
@@ -1110,6 +1110,7 @@ export class UserRepository {
movedToProfileId: true,
selectedCalendars: {
select: {
id: true,
eventTypeId: true,
externalId: true,
integration: true,