feat: conferencing atoms (#17988)

* added api/v2 for zoom connect

* Update conferencing.controller.ts

* fix: added api for ConferencingAppsViewPlatformWrapper

* type fixes

* added getBulkEventTypes api for bulk-update default location

* added bulk-update-to-default-location

* fix:bulk-update-to-default-location

* invalidated

* fixed returnTo and onErrorReturnTo

* make logos work for conferencing atoms

* smalll improvements

* fixup

* share common types

* type fix, and fixed a typo

* fix: type-error

* fix: json.parse(json.parse())

* fix: invalidate query

* fix: removing app throws error in the main app

* undo platform-libraries-1.2.3

* update platform-libraries version

---------

Co-authored-by: Morgan <[email protected]>
This commit is contained in:
Somay ChauhanandMorgan authored and GitHub committed 2024-12-06 19:03:04 +05:30
1 parent 44115ac7fa
commit 063400fcbc
54 files changed
+1898 -413

No files matched your search

+37 -18
View File
@@ -5,12 +5,16 @@ import { InstallAppButton } from "@calcom/app-store/components";
import { getLocationFromApp, type EventLocationType } from "@calcom/app-store/locations";
import type { CredentialOwner } from "@calcom/app-store/types";
import AppListCard from "@calcom/features/apps/components/AppListCard";
import type { UpdateUsersDefaultConferencingAppParams } from "@calcom/features/apps/components/AppSetDefaultLinkDialog";
import { AppSetDefaultLinkDialog } from "@calcom/features/apps/components/AppSetDefaultLinkDialog";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import type {
BulkUpdatParams,
EventTypes,
} from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import { trpc, type RouterOutputs } from "@calcom/trpc";
import { type RouterOutputs } from "@calcom/trpc";
import type { App } from "@calcom/types/App";
import {
Alert,
@@ -24,17 +28,21 @@ import {
showToast,
} from "@calcom/ui";
export type UpdateDefaultConferencingAppParams = { appSlug: string; callback: () => void };
export type HandleDisconnect = (credentialId: number, app: App["slug"], teamId?: number) => void;
interface AppListProps {
variant?: AppCategories;
data: RouterOutputs["viewer"]["integrations"];
handleDisconnect: (credentialId: number) => void;
handleDisconnect: HandleDisconnect;
listClassName?: string;
defaultConferencingApp: RouterOutputs["viewer"]["getUsersDefaultConferencingApp"];
handleUpdateDefaultConferencingApp: (params: UpdateDefaultConferencingAppParams) => void;
handleUpdateUserDefaultConferencingApp: (params: UpdateUsersDefaultConferencingAppParams) => void;
handleBulkUpdateDefaultLocation: (params: BulkUpdatParams) => void;
isBulkUpdateDefaultLocationPending: boolean;
eventTypes?: EventTypes;
isEventTypesFetching?: boolean;
handleConnectDisconnectIntegrationMenuToggle: () => void;
handleBulkEditDialogToggle: () => void;
}
export const AppList = ({
@@ -43,15 +51,18 @@ export const AppList = ({
variant,
listClassName,
defaultConferencingApp,
handleUpdateDefaultConferencingApp,
handleUpdateUserDefaultConferencingApp,
handleBulkUpdateDefaultLocation,
isBulkUpdateDefaultLocationPending,
eventTypes,
isEventTypesFetching,
handleConnectDisconnectIntegrationMenuToggle,
handleBulkEditDialogToggle,
}: AppListProps) => {
const [bulkUpdateModal, setBulkUpdateModal] = useState(false);
const [locationType, setLocationType] = useState<(EventLocationType & { slug: string }) | undefined>(
undefined
);
const onSuccessCallback = useCallback(() => {
setBulkUpdateModal(true);
showToast("Default app updated successfully", "success");
@@ -98,9 +109,12 @@ export const AppList = ({
if (locationType?.linkType === "static") {
setLocationType({ ...locationType, slug: appSlug });
} else {
handleUpdateDefaultConferencingApp({
handleUpdateUserDefaultConferencingApp({
appSlug,
callback: () => setBulkUpdateModal(true),
onSuccessCallback: () => setBulkUpdateModal(true),
onErrorCallback: () => {
return;
},
});
}
}}>
@@ -111,11 +125,15 @@ export const AppList = ({
<ConnectOrDisconnectIntegrationMenuItem
credentialId={item.credentialOwner?.credentialId || item.userCredentialIds[0]}
type={item.type}
app={item.slug}
isGlobal={item.isGlobal}
installed
invalidCredentialIds={item.invalidCredentialIds}
handleDisconnect={handleDisconnect}
teamId={item.credentialOwner ? item.credentialOwner?.teamId : undefined}
handleConnectDisconnectIntegrationMenuToggle={
handleConnectDisconnectIntegrationMenuToggle
}
/>
</DropdownMenuContent>
</Dropdown>
@@ -171,6 +189,7 @@ export const AppList = ({
locationType={locationType}
setLocationType={() => setLocationType(undefined)}
onSuccess={onSuccessCallback}
handleUpdateUserDefaultConferencingApp={handleUpdateUserDefaultConferencingApp}
/>
)}
@@ -181,6 +200,9 @@ export const AppList = ({
setOpen={setBulkUpdateModal}
isPending={isBulkUpdateDefaultLocationPending}
description={t("default_conferencing_bulk_description")}
eventTypes={eventTypes}
isEventTypesFetching={isEventTypesFetching}
handleBulkEditDialogToggle={handleBulkEditDialogToggle}
/>
)}
</>
@@ -194,22 +216,19 @@ function ConnectOrDisconnectIntegrationMenuItem(props: {
installed?: boolean;
invalidCredentialIds?: number[];
teamId?: number;
handleDisconnect: (credentialId: number, teamId?: number) => void;
app: App["slug"];
handleDisconnect: HandleDisconnect;
handleConnectDisconnectIntegrationMenuToggle: () => void;
}) {
const { type, credentialId, isGlobal, installed, handleDisconnect, teamId } = props;
const { type, credentialId, isGlobal, installed, handleDisconnect, teamId, app } = props;
const { t } = useLocale();
const utils = trpc.useUtils();
const handleOpenChange = () => {
utils.viewer.integrations.invalidate();
};
if (credentialId || type === "stripe_payment" || isGlobal) {
return (
<DropdownMenuItem>
<DropdownItem
color="destructive"
onClick={() => handleDisconnect(credentialId, teamId)}
onClick={() => handleDisconnect(credentialId, app, teamId)}
disabled={isGlobal}
StartIcon="trash">
{t("remove_app")}
@@ -234,7 +253,7 @@ function ConnectOrDisconnectIntegrationMenuItem(props: {
{t("install")}
</Button>
)}
onChanged={handleOpenChange}
onChanged={props.handleConnectDisconnectIntegrationMenuToggle}
/>
);
}
@@ -37,7 +37,8 @@ export type AppListCardProps = {
const schema = z.object({ hl: z.string().optional() });
function AppListCardPlatformWrapper(props: AppListCardProps) {
return <AppListCardComponent {...props} />;
const logo = `https://app.cal.com${props.logo}`;
return <AppListCardComponent {...props} logo={logo} />;
}
function AppListCardWebWrapper(props: AppListCardProps) {
const { slug, shouldHighlight } = props;
@@ -6,7 +6,6 @@ import { z } from "zod";
import type { EventLocationType } from "@calcom/app-store/locations";
import { getEventLocationType } from "@calcom/app-store/locations";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Dialog,
@@ -18,6 +17,13 @@ import {
TextField,
} from "@calcom/ui";
export type UpdateUsersDefaultConferencingAppParams = {
appSlug: string;
appLink?: string;
onSuccessCallback: () => void;
onErrorCallback: () => void;
};
type LocationTypeSetLinkDialogFormProps = {
link?: string;
type: EventLocationType["type"];
@@ -27,10 +33,12 @@ export function AppSetDefaultLinkDialog({
locationType,
setLocationType,
onSuccess,
handleUpdateUserDefaultConferencingApp,
}: {
locationType: EventLocationType & { slug: string };
setLocationType: Dispatch<SetStateAction<(EventLocationType & { slug: string }) | undefined>>;
onSuccess: () => void;
handleUpdateUserDefaultConferencingApp: (params: UpdateUsersDefaultConferencingAppParams) => void;
}) {
const { t } = useLocale();
const eventLocationTypeOptions = getEventLocationType(locationType.type);
@@ -41,15 +49,6 @@ export function AppSetDefaultLinkDialog({
),
});
const updateDefaultAppMutation = trpc.viewer.updateUserDefaultConferencingApp.useMutation({
onSuccess: () => {
onSuccess();
},
onError: () => {
showToast(`Invalid App Link Format`, "error");
},
});
return (
<Dialog open={!!locationType} onOpenChange={() => setLocationType(undefined)}>
<DialogContent
@@ -60,9 +59,15 @@ export function AppSetDefaultLinkDialog({
<Form
form={form}
handleSubmit={(values) => {
updateDefaultAppMutation.mutate({
handleUpdateUserDefaultConferencingApp({
appSlug: locationType.slug,
appLink: values.link,
onSuccessCallback: () => {
onSuccess();
},
onErrorCallback: () => {
showToast(`Invalid App Link Format`, "error");
},
});
setLocationType(undefined);
}}>
@@ -1,23 +1,33 @@
import { useIsPlatform } from "@calcom/atoms/monorepo";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { App } from "@calcom/types/App";
import { Dialog, ConfirmationDialogContent } from "@calcom/ui";
export type RemoveAppParams = { credentialId: number; teamId?: number; callback: () => void };
export type RemoveAppParams = {
credentialId: number;
app?: App["slug"];
teamId?: number;
callback: () => void;
};
interface DisconnectIntegrationModalProps {
credentialId: number | null;
isOpen: boolean;
handleModelClose: () => void;
teamId?: number;
handleRemoveApp: (params: RemoveAppParams) => void;
app?: App["slug"] | null;
}
export default function DisconnectIntegrationModal({
credentialId,
app,
isOpen,
handleModelClose,
teamId,
handleRemoveApp,
}: DisconnectIntegrationModalProps) {
const { t } = useLocale();
const isPlatform = useIsPlatform();
return (
<Dialog open={isOpen} onOpenChange={handleModelClose}>
<ConfirmationDialogContent
@@ -25,7 +35,9 @@ export default function DisconnectIntegrationModal({
title={t("remove_app")}
confirmBtnText={t("yes_remove_app")}
onConfirm={() => {
if (credentialId) {
if (isPlatform && app && credentialId) {
handleRemoveApp({ credentialId, app, teamId, callback: () => handleModelClose() });
} else if (credentialId) {
handleRemoveApp({ credentialId, teamId, callback: () => handleModelClose() });
}
}}>
@@ -39,7 +39,7 @@ const handleDeleteCredential = async ({
teamId,
}: {
userId: number;
userMetadata: Prisma.JsonValue;
userMetadata?: Prisma.JsonValue;
credentialId: number;
teamId?: number;
}) => {
@@ -1,5 +1,5 @@
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { Meta, SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui";
import { SkeletonButton, SkeletonContainer, SkeletonText } from "@calcom/ui";
export const AppearanceSkeletonLoader = () => {
return (
@@ -17,7 +17,6 @@ import {
DropdownMenuItem,
Icon,
showToast,
useMeta,
} from "@calcom/ui";
import { DeleteAttributeModal } from "./DeleteAttributeModal";
@@ -14,7 +14,7 @@ import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Button, Form, Meta, showToast, SettingsToggle } from "@calcom/ui";
import { Button, Form, showToast, SettingsToggle } from "@calcom/ui";
import ThemeLabel from "../../../settings/ThemeLabel";
@@ -1,7 +1,6 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Meta } from "@calcom/ui";
import { TeamsListing } from "../components";
@@ -8,7 +8,6 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { Meta } from "@calcom/ui";
import DisableTeamImpersonation from "../components/DisableTeamImpersonation";
import InviteLinkSettingsModal from "../components/InviteLinkSettingsModal";
@@ -35,7 +35,6 @@ import {
ImageUploader,
Label,
LinkIconButton,
Meta,
showToast,
SkeletonAvatar,
SkeletonButton,
@@ -3,7 +3,6 @@ import { useForm } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Dialog, DialogContent, Form, DialogFooter, DialogClose, Button, CheckboxField } from "@calcom/ui";
export const BulkUpdateEventSchema = z.object({
@@ -11,28 +10,35 @@ export const BulkUpdateEventSchema = z.object({
});
export type BulkUpdatParams = { eventTypeIds: number[]; callback: () => void };
export type EventTypes = Array<{ id: number; title: string }>;
export function BulkEditDefaultForEventsModal(props: {
export function BulkEditDefaultForEventsModal({
eventTypes,
isEventTypesFetching,
...props
}: {
open: boolean;
setOpen: (open: boolean) => void;
bulkUpdateFunction: (params: BulkUpdatParams) => void;
isPending: boolean;
description: string;
isEventTypesFetching?: boolean;
eventTypes?: EventTypes;
handleBulkEditDialogToggle: () => void;
}) {
const { t } = useLocale();
const utils = trpc.useUtils();
const { data, isFetching } = trpc.viewer.eventTypes.bulkEventFetch.useQuery();
const form = useForm({
resolver: zodResolver(BulkUpdateEventSchema),
defaultValues: {
eventTypeIds: data?.eventTypes.map((e) => e.id) ?? [],
eventTypeIds: eventTypes?.map((e) => e.id) ?? [],
},
});
const eventTypesSelected = form.watch("eventTypeIds");
const isButtonDisabled = eventTypesSelected.length === 0;
if (isFetching || !open || !data?.eventTypes) return null;
if (isEventTypesFetching || !open || !eventTypes) return null;
return (
<Dialog name="Bulk Default Location Update" open={props.open} onOpenChange={props.setOpen}>
@@ -50,19 +56,19 @@ export function BulkEditDefaultForEventsModal(props: {
});
}}>
<div className="flex flex-col space-y-2">
{data.eventTypes.length > 0 && (
{eventTypes.length > 0 && (
<div className="flex items-center space-x-2 rounded-md px-3 pb-2.5 pt-1">
<CheckboxField
description={t("select_all")}
descriptionAsLabel
onChange={(e) => {
form.setValue("eventTypeIds", e.target.checked ? data.eventTypes.map((e) => e.id) : []);
form.setValue("eventTypeIds", e.target.checked ? eventTypes.map((e) => e.id) : []);
}}
checked={eventTypesSelected.length === data.eventTypes.length}
checked={eventTypesSelected.length === eventTypes.length}
/>
</div>
)}
{data.eventTypes.map((eventType) => (
{eventTypes.map((eventType) => (
<div key={eventType.id} className="bg-muted flex items-center space-x-2 rounded-md px-3 py-2.5">
<CheckboxField
description={eventType.title}
@@ -83,7 +89,7 @@ export function BulkEditDefaultForEventsModal(props: {
<DialogFooter showDivider className="mt-10">
<DialogClose
onClick={() => {
utils.viewer.getUsersDefaultConferencingApp.invalidate();
props.handleBulkEditDialogToggle();
}}
/>
<Button type="submit" color="primary" loading={props.isPending} disabled={isButtonDisabled}>
@@ -0,0 +1,59 @@
import type { LocationObject } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
import type { PrismaClient } from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
export const bulkUpdateEventsToDefaultLocation = async ({
eventTypeIds,
user,
prisma,
}: {
eventTypeIds: number[];
user: Pick<User, "id" | "metadata">;
prisma: PrismaClient;
}) => {
const defaultApp = userMetadataSchema.parse(user.metadata)?.defaultConferencingApp;
if (!defaultApp) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Default conferencing app not set",
});
}
const foundApp = getAppFromSlug(defaultApp.appSlug);
const appType = foundApp?.appData?.location?.type;
if (!appType) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Default conferencing app '${defaultApp.appSlug}' doesnt exist.`,
});
}
const credential = await prisma.credential.findFirst({
where: {
userId: user.id,
appId: foundApp.slug,
},
select: {
id: true,
},
});
return await prisma.eventType.updateMany({
where: {
id: {
in: eventTypeIds,
},
userId: user.id,
},
data: {
locations: [
{ type: appType, link: defaultApp.appLink, credentialId: credential?.id },
] as LocationObject[],
},
});
};
+232
View File
@@ -0,0 +1,232 @@
import appStore from "@calcom/app-store";
import type { TDependencyData } from "@calcom/app-store/_appRegistry";
import type { CredentialOwner } from "@calcom/app-store/types";
import { getAppFromSlug } from "@calcom/app-store/utils";
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import getInstallCountPerApp from "@calcom/lib/apps/getInstallCountPerApp";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import type { PrismaClient } from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TeamQuery } from "@calcom/trpc/server/routers/loggedInViewer/integrations.handler";
import type { TIntegrationsInputSchema } from "@calcom/trpc/server/routers/loggedInViewer/integrations.schema";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PaymentApp } from "@calcom/types/PaymentService";
export type ConnectedApps = Awaited<ReturnType<typeof getConnectedApps>>;
export async function getConnectedApps({
user,
prisma,
input,
}: {
user: Pick<User, "id" | "name" | "avatarUrl"> & { avatar?: string };
prisma: PrismaClient;
input: TIntegrationsInputSchema;
}) {
const {
variant,
exclude,
onlyInstalled,
includeTeamInstalledApps,
extendsFeature,
teamId,
sortByMostPopular,
appId,
} = input;
let credentials = await getUsersCredentials(user);
let userTeams: TeamQuery[] = [];
if (includeTeamInstalledApps || teamId) {
const teamsQuery = await prisma.team.findMany({
where: {
members: {
some: {
userId: user.id,
accepted: true,
},
},
},
select: {
id: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
name: true,
logoUrl: true,
members: {
where: {
userId: user.id,
},
select: {
role: true,
},
},
parent: {
select: {
id: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
name: true,
logoUrl: true,
members: {
where: {
userId: user.id,
},
select: {
role: true,
},
},
},
},
},
});
// If a team is a part of an org then include those apps
// Don't want to iterate over these parent teams
const filteredTeams: TeamQuery[] = [];
const parentTeams: TeamQuery[] = [];
// Only loop and grab parent teams if a teamId was given. If not then all teams will be queried
if (teamId) {
teamsQuery.forEach((team) => {
if (team?.parent) {
const { parent, ...filteredTeam } = team;
filteredTeams.push(filteredTeam);
// Only add parent team if it's not already in teamsQuery
if (!teamsQuery.some((t) => t.id === parent.id)) {
parentTeams.push(parent);
}
}
});
}
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials: CredentialPayload[] = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? teamApp.credentials.flat() : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
} else {
credentials = credentials.concat(teamAppCredentials);
}
}
const enabledApps = await getEnabledAppsFromCredentials(credentials, {
filterOnCredentials: onlyInstalled,
...(appId ? { where: { slug: appId } } : {}),
});
//TODO: Refactor this to pick up only needed fields and prevent more leaking
let apps = await Promise.all(
enabledApps.map(async ({ credentials: _, credential, key: _2 /* don't leak to frontend */, ...app }) => {
const userCredentialIds = credentials.filter((c) => c.appId === app.slug && !c.teamId).map((c) => c.id);
const invalidCredentialIds = credentials
.filter((c) => c.appId === app.slug && c.invalid)
.map((c) => c.id);
const teams = await Promise.all(
credentials
.filter((c) => c.appId === app.slug && c.teamId)
.map(async (c) => {
const team = userTeams.find((team) => team.id === c.teamId);
if (!team) {
return null;
}
return {
teamId: team.id,
name: team.name,
logoUrl: team.logoUrl,
credentialId: c.id,
isAdmin:
team.members[0].role === MembershipRole.ADMIN ||
team.members[0].role === MembershipRole.OWNER,
};
})
);
// type infer as CredentialOwner
const credentialOwner: CredentialOwner = {
name: user.name,
avatar: user?.avatar ?? user?.avatarUrl,
};
// We need to know if app is payment type
// undefined it means that app don't require app/setup/page
let isSetupAlready = undefined;
if (credential && app.categories.includes("payment")) {
const paymentApp = (await appStore[app.dirName as keyof typeof appStore]?.()) as PaymentApp | null;
if (paymentApp && "lib" in paymentApp && paymentApp?.lib && "PaymentService" in paymentApp?.lib) {
const PaymentService = paymentApp.lib.PaymentService;
const paymentInstance = new PaymentService(credential);
isSetupAlready = paymentInstance.isSetupAlready();
}
}
let dependencyData: TDependencyData = [];
if (app.dependencies?.length) {
dependencyData = app.dependencies.map((dependency) => {
const dependencyInstalled = enabledApps.some(
(dbAppIterator) => dbAppIterator.credentials.length && dbAppIterator.slug === dependency
);
// If the app marked as dependency is simply deleted from the codebase, we can have the situation where App is marked installed in DB but we couldn't get the app.
const dependencyName = getAppFromSlug(dependency)?.name;
return { name: dependencyName, installed: dependencyInstalled };
});
}
return {
...app,
...(teams.length && {
credentialOwner,
}),
userCredentialIds,
invalidCredentialIds,
teams,
isInstalled: !!userCredentialIds.length || !!teams.length || app.isGlobal,
isSetupAlready,
...(app.dependencies && { dependencyData }),
};
})
);
if (variant) {
// `flatMap()` these work like `.filter()` but infers the types correctly
apps = apps
// variant check
.flatMap((item) => (item.variant.startsWith(variant) ? [item] : []));
}
if (exclude) {
// exclusion filter
apps = apps.filter((item) => (exclude ? !exclude.includes(item.variant) : true));
}
if (onlyInstalled) {
apps = apps.flatMap((item) =>
item.userCredentialIds.length > 0 || item.teams.length || item.isGlobal ? [item] : []
);
}
if (extendsFeature) {
apps = apps
.filter((app) => app.extendsFeature?.includes(extendsFeature))
.map((app) => ({
...app,
isInstalled: !!app.userCredentialIds?.length || !!app.teams?.length || app.isGlobal,
}));
}
if (sortByMostPopular) {
const installCountPerApp = await getInstallCountPerApp();
// sort the apps array by the most popular apps
apps.sort((a, b) => {
const aCount = installCountPerApp[a.slug] || 0;
const bCount = installCountPerApp[b.slug] || 0;
return bCount - aCount;
});
}
return {
items: apps,
};
}
@@ -5,7 +5,10 @@ import { useMemo, useState } from "react";
import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import type {
BulkUpdatParams,
EventTypes,
} from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { DateOverrideInputDialog, DateOverrideList } from "@calcom/features/schedules";
import WebSchedule, {
@@ -109,6 +112,9 @@ type AvailabilitySettingsProps = {
setIsOpen: Dispatch<SetStateAction<boolean>>;
save: (params: BulkUpdatParams) => void;
isSaving: boolean;
eventTypes?: EventTypes;
isEventTypesFetching?: boolean;
handleBulkEditDialogToggle: () => void;
};
};
@@ -365,6 +371,9 @@ export function AvailabilitySettings({
setOpen={bulkUpdateModalProps.setIsOpen}
bulkUpdateFunction={bulkUpdateModalProps?.save}
description={t("default_schedules_bulk_description")}
eventTypes={bulkUpdateModalProps?.eventTypes}
isEventTypesFetching={bulkUpdateModalProps?.isEventTypesFetching}
handleBulkEditDialogToggle={bulkUpdateModalProps.handleBulkEditDialogToggle}
/>
)}
@@ -0,0 +1,264 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
import { useReducer } from "react";
import { AppList } from "@calcom/features/apps/components/AppList";
import DisconnectIntegrationModal from "@calcom/features/apps/components/DisconnectIntegrationModal";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { GOOGLE_MEET, ZOOM } from "@calcom/platform-constants";
import { QueryCell } from "@calcom/trpc/components/QueryCell";
import type { App } from "@calcom/types/App";
import {
Button,
SkeletonContainer,
SkeletonText,
Dropdown,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownItem,
EmptyScreen,
} from "@calcom/ui";
import { AtomsWrapper } from "../../src/components/atoms-wrapper";
import { useToast } from "../../src/components/ui/use-toast";
import type {
BulkUpdatParams,
UpdateUsersDefaultConferencingAppParams,
} from "./ConferencingAppsViewWebWrapper";
import { useAtomBulkUpdateEventTypesToDefaultLocation } from "./hooks/useAtomBulkUpdateEventTypesToDefaultLocation";
import { useAtomGetEventTypes } from "./hooks/useAtomGetEventTypes";
import {
useAtomsGetInstalledConferencingApps,
QUERY_KEY as atomsConferencingAppsQueryKey,
} from "./hooks/useAtomsGetInstalledConferencingApps";
import { useConnect } from "./hooks/useConnect";
import { useDeleteCredential } from "./hooks/useDeleteCredential";
import {
useGetDefaultConferencingApp,
QUERY_KEY as defaultConferencingAppQueryKey,
} from "./hooks/useGetDefaultConferencingApp";
import { useUpdateUserDefaultConferencingApp } from "./hooks/useUpdateUserDefaultConferencingApp";
type ConferencingAppsViewPlatformWrapperProps = {
disableToasts?: boolean;
returnTo?: string;
onErrorReturnTo?: string;
};
type RemoveAppParams = { callback: () => void; app?: App["slug"] };
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="divide-subtle border-subtle space-y-6 rounded-b-lg border border-t-0 px-6 py-4">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
</div>
</SkeletonContainer>
);
};
type ModalState = {
isOpen: boolean;
credentialId: null | number;
app: App["slug"] | null;
};
export const ConferencingAppsViewPlatformWrapper = ({
disableToasts = false,
returnTo,
onErrorReturnTo,
}: ConferencingAppsViewPlatformWrapperProps) => {
const { t } = useLocale();
const queryClient = useQueryClient();
const { toast } = useToast();
const showToast = (message: string, variant: "success" | "warning" | "error") => {
if (!disableToasts) {
toast({ description: message });
}
};
const [modal, updateModal] = useReducer(
(data: ModalState, partialData: Partial<ModalState>) => ({ ...data, ...partialData }),
{
isOpen: false,
credentialId: null,
app: null,
}
);
const handleModelClose = () => {
updateModal({ isOpen: false, credentialId: null, app: null });
};
const handleDisconnect = (credentialId: number, app: App["slug"]) => {
updateModal({ isOpen: true, credentialId, app });
};
const installedIntegrationsQuery = useAtomsGetInstalledConferencingApps();
const { data: defaultConferencingApp } = useGetDefaultConferencingApp();
const { data: eventTypesQuery, isFetching: isEventTypesFetching } = useAtomGetEventTypes();
const deleteCredentialMutation = useDeleteCredential({
onSuccess: () => {
showToast(t("app_removed_successfully"), "success");
handleModelClose();
queryClient.invalidateQueries({
queryKey: [atomsConferencingAppsQueryKey],
});
queryClient.resetQueries({
queryKey: [defaultConferencingAppQueryKey],
});
},
onError: () => {
showToast(t("error_removing_app"), "error");
handleModelClose();
},
});
const updateDefaultAppMutation = useUpdateUserDefaultConferencingApp({});
const bulkUpdateEventTypesToDefaultLocation = useAtomBulkUpdateEventTypesToDefaultLocation({});
const handleRemoveApp = ({ app }: RemoveAppParams) => {
!!app && deleteCredentialMutation.mutate(app);
};
const handleUpdateUserDefaultConferencingApp = ({
appSlug,
onSuccessCallback,
onErrorCallback,
}: UpdateUsersDefaultConferencingAppParams) => {
updateDefaultAppMutation.mutate(appSlug, {
onSuccess: () => {
showToast("Default app updated successfully", "success");
queryClient.invalidateQueries({ queryKey: [defaultConferencingAppQueryKey] });
onSuccessCallback();
},
onError: (error) => {
showToast(`Error: ${error.message}`, "error");
onErrorCallback();
},
});
};
const handleBulkUpdateDefaultLocation = ({ eventTypeIds, callback }: BulkUpdatParams) => {
bulkUpdateEventTypesToDefaultLocation.mutate(eventTypeIds, {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [defaultConferencingAppQueryKey] });
callback();
},
});
};
const handleConnectDisconnectIntegrationMenuToggle = () => {
queryClient.invalidateQueries({ queryKey: [atomsConferencingAppsQueryKey] });
};
const handleBulkEditDialogToggle = () => {
queryClient.invalidateQueries({ queryKey: [defaultConferencingAppQueryKey] });
};
const { connect } = useConnect({
onSuccess: () => {
showToast("app installed successfully", "success");
queryClient.invalidateQueries({ queryKey: [atomsConferencingAppsQueryKey] });
},
onError: () => {
queryClient.invalidateQueries({ queryKey: [atomsConferencingAppsQueryKey] });
showToast(`Error: unable to install app`, "error");
},
returnTo,
onErrorReturnTo,
});
const AddConferencingButtonPlatform = ({ installedApps }: { installedApps?: Array<{ slug: string }> }) => {
return (
<Dropdown>
<DropdownMenuTrigger asChild>
<Button color="secondary" StartIcon="plus">
{t("add")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{installedApps && !installedApps.find((app) => app.slug == GOOGLE_MEET) && (
<DropdownMenuItem>
<DropdownItem color="secondary" onClick={() => connect(GOOGLE_MEET)}>
{t("google_meet")}
</DropdownItem>
</DropdownMenuItem>
)}
{installedApps && !installedApps?.find((app) => app.slug == ZOOM) && (
<DropdownMenuItem>
<DropdownItem color="secondary" onClick={() => connect(ZOOM)}>
{t("zoom")}
</DropdownItem>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</Dropdown>
);
};
return (
<AtomsWrapper>
<SettingsHeader
title={t("conferencing")}
description={t("conferencing_description")}
CTA={<AddConferencingButtonPlatform installedApps={installedIntegrationsQuery.data?.items} />}
borderInShellHeader={true}>
<>
<div className="bg-default w-full sm:mx-0 xl:mt-0">
<QueryCell
query={installedIntegrationsQuery}
customLoader={<SkeletonLoader />}
success={({ data }) => {
if (!data.items.length) {
return (
<EmptyScreen
Icon="calendar"
headline={t("no_category_apps", {
category: t("conferencing").toLowerCase(),
})}
description={t("no_category_apps_description_conferencing")}
buttonRaw={<AddConferencingButtonPlatform installedApps={data?.items} />}
/>
);
}
return (
<AppList
listClassName="rounded-lg rounded-t-none border-t-0 max-w-full"
handleDisconnect={handleDisconnect}
data={data}
variant="conferencing"
defaultConferencingApp={defaultConferencingApp}
handleUpdateUserDefaultConferencingApp={handleUpdateUserDefaultConferencingApp}
handleBulkUpdateDefaultLocation={handleBulkUpdateDefaultLocation}
isBulkUpdateDefaultLocationPending={bulkUpdateEventTypesToDefaultLocation?.isPending}
eventTypes={eventTypesQuery?.eventTypes}
isEventTypesFetching={isEventTypesFetching}
handleConnectDisconnectIntegrationMenuToggle={
handleConnectDisconnectIntegrationMenuToggle
}
handleBulkEditDialogToggle={handleBulkEditDialogToggle}
/>
);
}}
/>
</div>
<DisconnectIntegrationModal
handleModelClose={handleModelClose}
isOpen={modal.isOpen}
credentialId={modal.credentialId}
app={modal.app}
handleRemoveApp={handleRemoveApp}
/>
</>
</SettingsHeader>
</AtomsWrapper>
);
};
@@ -16,8 +16,14 @@ type ConferencingAppsViewWebWrapperProps = {
add: string;
};
type UpdateDefaultConferencingAppParams = { appSlug: string; callback: () => void };
type BulkUpdatParams = { eventTypeIds: number[]; callback: () => void };
export type UpdateUsersDefaultConferencingAppParams = {
appSlug: string;
appLink?: string;
onSuccessCallback: () => void;
onErrorCallback: () => void;
};
export type BulkUpdatParams = { eventTypeIds: number[]; callback: () => void };
type RemoveAppParams = { credentialId: number; teamId?: number; callback: () => void };
const SkeletonLoader = () => {
@@ -73,6 +79,9 @@ export const ConferencingAppsViewWebWrapper = ({
const updateLocationsMutation = trpc.viewer.eventTypes.bulkUpdateToDefaultLocation.useMutation();
const { data: eventTypesQueryData, isFetching: isEventTypesFetching } =
trpc.viewer.eventTypes.bulkEventFetch.useQuery();
const handleRemoveApp = ({ credentialId, teamId, callback }: RemoveAppParams) => {
deleteCredentialMutation.mutate(
{ id: credentialId, teamId },
@@ -91,17 +100,31 @@ export const ConferencingAppsViewWebWrapper = ({
);
};
const handleUpdateDefaultConferencingApp = ({ appSlug, callback }: UpdateDefaultConferencingAppParams) => {
const handleConnectDisconnectIntegrationMenuToggle = () => {
utils.viewer.integrations.invalidate();
};
const handleBulkEditDialogToggle = () => {
utils.viewer.getUsersDefaultConferencingApp.invalidate();
};
const handleUpdateUserDefaultConferencingApp = ({
appSlug,
appLink,
onSuccessCallback,
onErrorCallback,
}: UpdateUsersDefaultConferencingAppParams) => {
updateDefaultAppMutation.mutate(
{ appSlug },
{ appSlug, appLink },
{
onSuccess: () => {
showToast("Default app updated successfully", "success");
utils.viewer.getUsersDefaultConferencingApp.invalidate();
callback();
onSuccessCallback();
},
onError: (error) => {
showToast(`Error: ${error.message}`, "error");
onErrorCallback();
},
}
);
@@ -167,9 +190,13 @@ export const ConferencingAppsViewWebWrapper = ({
data={data}
variant="conferencing"
defaultConferencingApp={defaultConferencingApp}
handleUpdateDefaultConferencingApp={handleUpdateDefaultConferencingApp}
handleUpdateUserDefaultConferencingApp={handleUpdateUserDefaultConferencingApp}
handleBulkUpdateDefaultLocation={handleBulkUpdateDefaultLocation}
isBulkUpdateDefaultLocationPending={updateDefaultAppMutation.isPending}
eventTypes={eventTypesQueryData?.eventTypes}
isEventTypesFetching={isEventTypesFetching}
handleConnectDisconnectIntegrationMenuToggle={handleConnectDisconnectIntegrationMenuToggle}
handleBulkEditDialogToggle={handleBulkEditDialogToggle}
/>
);
}}
@@ -0,0 +1,43 @@
import { useMutation } from "@tanstack/react-query";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiSuccessResponse } from "@calcom/platform-types";
import type { EventType } from "@calcom/prisma/client";
import http from "../../../lib/http";
export const QUERY_KEY = "bulk-update-event-types-to-default-location";
export type UseAtomBulkUpdateEventTypesToDefaultLocationProps = {
onSuccess?: () => void;
onError?: (err: Error) => void;
onSettled?: () => void;
};
export const useAtomBulkUpdateEventTypesToDefaultLocation = ({
onSuccess = () => {
return;
},
onError = () => {
return;
},
onSettled = () => {
return;
},
}: UseAtomBulkUpdateEventTypesToDefaultLocationProps) => {
return useMutation({
onSuccess,
onError,
onSettled,
mutationFn: (eventTypeIds: number[]) => {
if (!eventTypeIds || eventTypeIds.length < 1) throw new Error("Event type ids are required");
const pathname = `/atoms/${V2_ENDPOINTS.eventTypes}/bulk-update-to-default-location`;
return http?.patch(pathname, { eventTypeIds }).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<EventType>).data;
}
throw new Error(res.data.error.message);
});
},
});
};
@@ -0,0 +1,29 @@
import { useQuery } from "@tanstack/react-query";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import { useAtomsContext } from "../../../hooks/useAtomsContext";
import http from "../../../lib/http";
export const QUERY_KEY = "use-get-event-types";
type ResponseEventType = { eventTypes: Array<{ id: number; title: string }> };
export const useAtomGetEventTypes = () => {
const pathname = `/atoms/${V2_ENDPOINTS.eventTypes}/`;
const { isInit, accessToken } = useAtomsContext();
return useQuery({
queryKey: [QUERY_KEY],
queryFn: () => {
return http?.get<ApiResponse<ResponseEventType>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<ResponseEventType>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: isInit && !!accessToken,
});
};
@@ -0,0 +1,28 @@
import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ConnectedApps } from "@calcom/platform-libraries";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import { useAtomsContext } from "../../../hooks/useAtomsContext";
import http from "../../../lib/http";
export const QUERY_KEY = "get-installed-conferencing-apps";
export const useAtomsGetInstalledConferencingApps = () => {
const pathname = `/atoms/conferencing`;
const { isInit, accessToken } = useAtomsContext();
return useQuery({
queryKey: [QUERY_KEY],
queryFn: () => {
return http?.get<ApiResponse<ConnectedApps>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<ConnectedApps>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: isInit && !!accessToken,
});
};
@@ -0,0 +1,93 @@
import { useQuery } from "@tanstack/react-query";
import { useMutation } from "@tanstack/react-query";
import { SUCCESS_STATUS, ERROR_STATUS, ZOOM, GOOGLE_MEET } from "@calcom/platform-constants";
import type { ApiErrorResponse, ApiResponse } from "@calcom/platform-types";
import type { App } from "@calcom/types/App";
import http from "../../../lib/http";
export type UseGetOauthAuthUrlProps = {
returnTo?: string;
onErrorReturnTo?: string;
};
export const useGetOauthAuthUrl = ({ returnTo, onErrorReturnTo }: UseGetOauthAuthUrlProps) => {
return useQuery({
queryKey: ["get-zoom-auth-url"],
staleTime: Infinity,
enabled: false,
queryFn: () => {
return http
?.get<ApiResponse<{ url: string }>>(
`conferencing/${ZOOM}/oauth/auth-url${returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : ""}${
onErrorReturnTo ? `&onErrorReturnTo=${encodeURIComponent(onErrorReturnTo)}` : ""
}`
)
.then(({ data: responseBody }) => {
if (responseBody.status === SUCCESS_STATUS) {
return responseBody.data.url;
}
if (responseBody.status === ERROR_STATUS) throw new Error(responseBody.error.message);
return "";
});
},
});
};
export type UseConnectGoogleMeetProps = {
onSuccess?: (res: ApiResponse) => void;
onError?: (err: ApiErrorResponse) => void;
returnTo?: string;
onErrorReturnTo?: string;
};
export const useConnectNonOauthApp = (
{ onSuccess, onError }: UseConnectGoogleMeetProps = {
onSuccess: () => {
return;
},
onError: () => {
return;
},
}
) => {
return useMutation({
mutationFn: (app: string) => {
const pathname = `/conferencing/${app}/connect`;
return http?.post(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return { status: res.data };
} else {
throw new Error(res.data.error.message);
}
});
},
onSuccess,
onError,
});
};
export const useConnect = ({ returnTo, onErrorReturnTo, ...props }: UseConnectGoogleMeetProps) => {
const { refetch } = useGetOauthAuthUrl({ returnTo, onErrorReturnTo });
const connectNonOauthApp = useConnectNonOauthApp(props);
const connect = async (app: App["slug"]) => {
switch (app) {
case ZOOM:
const redirectUri = await refetch();
if (redirectUri.data) {
window.location.href = redirectUri.data;
}
break;
case GOOGLE_MEET:
connectNonOauthApp.mutate(app);
default:
break;
}
};
return { connect };
};
@@ -0,0 +1,30 @@
import { useMutation } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { App } from "@calcom/types/App";
import http from "../../../lib/http";
export const QUERY_KEY = "use-delete-credential";
export type UseDeleteEventTypeProps = {
onSuccess?: () => void;
onError?: (err: Error) => void;
onSettled?: () => void;
};
export const useDeleteCredential = ({ onSuccess, onError, onSettled }: UseDeleteEventTypeProps) => {
return useMutation({
onSuccess,
onError,
onSettled,
mutationFn: (app: App["slug"]) => {
if (!app) throw new Error("app is required");
const pathname = `/conferencing/${app}/disconnect`;
return http?.delete(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return;
}
throw new Error(res.data.error.message);
});
},
});
};
@@ -0,0 +1,34 @@
import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiSuccessResponse } from "@calcom/platform-types";
import type { ApiResponse } from "@calcom/platform-types";
import { useAtomsContext } from "../../../hooks/useAtomsContext";
import http from "../../../lib/http";
export const QUERY_KEY = "use-get-default-conferencing-app";
type ResponseDataType =
| {
appSlug?: string;
appLink?: string;
}
| undefined;
export const useGetDefaultConferencingApp = () => {
const pathname = `/conferencing/default`;
const { isInit, accessToken } = useAtomsContext();
return useQuery({
queryKey: [QUERY_KEY],
queryFn: () => {
return http?.get<ApiResponse<ResponseDataType>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<ResponseDataType>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: isInit && !!accessToken,
});
};
@@ -0,0 +1,34 @@
import { useMutation } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { App } from "@calcom/types/App";
import http from "../../../lib/http";
export const QUERY_KEY = "use-update-user-default-conferencing-app";
export type UseUpdateUserDefaultConferencingAppProps = {
onSuccess?: () => void;
onError?: (err: Error) => void;
onSettled?: () => void;
};
export const useUpdateUserDefaultConferencingApp = ({
onSuccess,
onError,
onSettled,
}: UseUpdateUserDefaultConferencingAppProps) => {
return useMutation({
onSuccess,
onError,
onSettled,
mutationFn: (app: App["slug"]) => {
if (!app) throw new Error("app is required");
const pathname = `/conferencing/${app}/default`;
return http?.post(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return;
}
throw new Error(res.data.error.message);
});
},
});
};
+1
View File
@@ -25,6 +25,7 @@ export { DestinationCalendarSettingsPlatformWrapper as DestinationCalendarSettin
export { CalendarSettingsPlatformWrapper as CalendarSettings } from "./calendar-settings/index";
export type { UpdateScheduleInput_2024_06_11 as UpdateScheduleBody } from "@calcom/platform-types";
export { EventTypePlatformWrapper as EventTypeSettings } from "./event-types/wrappers/EventTypePlatformWrapper";
export { ConferencingAppsViewPlatformWrapper as ConferencingAppsSettings } from "./connect/conferencing-apps/ConferencingAppsViewPlatformWrapper";
export { StripeConnect } from "./connect/stripe/StripeConnect";
export { CreateEventTypePlatformWrapper as CreateEventType } from "./event-types/wrappers/CreateEventTypePlatformWrapper";
export { PaymentForm } from "./event-types/payments/PaymentForm";
+5 -1
View File
@@ -17,8 +17,12 @@ export const GOOGLE_MEET = "google-meet";
export const GOOGLE_MEET_TYPE = "google_video";
export const GOOGLE_MEET_ID = "google-meet";
export const CONFERENCING_APPS = [GOOGLE_MEET];
export const ZOOM = "zoom";
export const ZOOM_TYPE = "zoom_video";
export const CAL_VIDEO = "daily-video";
export const CONFERENCING_APPS = [GOOGLE_MEET, ZOOM];
export const APPS_TYPE_ID_MAPPING = {
[GOOGLE_CALENDAR_TYPE]: GOOGLE_CALENDAR_ID,
[OFFICE_365_CALENDAR_TYPE]: OFFICE_365_CALENDAR_ID,
@@ -34,6 +34,10 @@ export function Navbar({ username }: { username?: string }) {
<li>
<Link href="/embed">Embed</Link>
</li>
<li>
<Link href="/conferencing-apps">Conferencing Apps</Link>
</li>
</ul>
</div>
</nav>
@@ -0,0 +1,22 @@
import { Navbar } from "@/components/Navbar";
import { Inter } from "next/font/google";
import { usePathname } from "next/navigation";
import { ConferencingAppsSettings } from "@calcom/atoms";
const inter = Inter({ subsets: ["latin"] });
export default function ConferencingApps(props: { calUsername: string; calEmail: string }) {
const pathname = usePathname();
const callbackUri = `${window.location.origin}${pathname}`;
return (
<main
className={`flex min-h-screen flex-col ${inter.className} main text-default flex min-h-full w-full flex-col items-center overflow-visible`}>
<Navbar username={props.calUsername} />
<div className="my-8">
<ConferencingAppsSettings returnTo={callbackUri} onErrorReturnTo={callbackUri} />
</div>
</main>
);
}
+8
View File
@@ -20,6 +20,7 @@ import { getBookingForReschedule } from "@calcom/features/bookings/lib/get-booki
import getBookingInfo from "@calcom/features/bookings/lib/getBookingInfo";
import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking";
import * as newBookingMethods from "@calcom/features/bookings/lib/handleNewBooking";
import handleDeleteCredential from "@calcom/features/credentials/handleDeleteCredential";
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
import { getPublicEvent } from "@calcom/features/eventtypes/lib/getPublicEvent";
import { handleCreatePhoneCall } from "@calcom/features/handleCreatePhoneCall";
@@ -28,6 +29,7 @@ import * as instantMeetingMethods from "@calcom/features/instant-meeting/handleI
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings";
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
import getBulkEventTypes from "@calcom/lib/event-types/getBulkEventTypes";
import { getTranslation } from "@calcom/lib/server/i18n";
import { MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -81,6 +83,10 @@ export { handleNewRecurringBooking } from "@calcom/features/bookings/lib/handleN
export { getConnectedDestinationCalendars } from "@calcom/lib/getConnectedDestinationCalendars";
export type { ConnectedDestinationCalendars } from "@calcom/lib/getConnectedDestinationCalendars";
export { getConnectedApps } from "@calcom/lib/getConnectedApps";
export { bulkUpdateEventsToDefaultLocation } from "@calcom/lib/bulkUpdateEventsToDefaultLocation";
export type { ConnectedApps } from "@calcom/lib/getConnectedApps";
export { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
export {
@@ -218,3 +224,5 @@ export { AttendeeUpdatedEmail };
export { OrganizerRequestEmail };
export { AttendeeRequestEmail };
export { handleDeleteCredential };
export { getBulkEventTypes };
@@ -1,18 +1,8 @@
import type { Prisma } from "@prisma/client";
import appStore from "@calcom/app-store";
import type { TDependencyData } from "@calcom/app-store/_appRegistry";
import type { CredentialOwner } from "@calcom/app-store/types";
import { getAppFromSlug } from "@calcom/app-store/utils";
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import getInstallCountPerApp from "@calcom/lib/apps/getInstallCountPerApp";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import prisma from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { getConnectedApps } from "@calcom/lib/getConnectedApps";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PaymentApp } from "@calcom/types/PaymentService";
import type { TIntegrationsInputSchema } from "./integrations.schema";
@@ -39,214 +29,7 @@ export type TeamQuery = Prisma.TeamGetPayload<{
};
}>;
// type TeamQueryWithParent = TeamQuery & {
// parent?: TeamQuery | null;
// };
export const integrationsHandler = async ({ ctx, input }: IntegrationsOptions) => {
const { user } = ctx;
const {
variant,
exclude,
onlyInstalled,
includeTeamInstalledApps,
extendsFeature,
teamId,
sortByMostPopular,
appId,
} = input;
let credentials = await getUsersCredentials(user);
let userTeams: TeamQuery[] = [];
if (includeTeamInstalledApps || teamId) {
const teamsQuery = await prisma.team.findMany({
where: {
members: {
some: {
userId: user.id,
accepted: true,
},
},
},
select: {
id: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
name: true,
logoUrl: true,
members: {
where: {
userId: user.id,
},
select: {
role: true,
},
},
parent: {
select: {
id: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
name: true,
logoUrl: true,
members: {
where: {
userId: user.id,
},
select: {
role: true,
},
},
},
},
},
});
// If a team is a part of an org then include those apps
// Don't want to iterate over these parent teams
const filteredTeams: TeamQuery[] = [];
const parentTeams: TeamQuery[] = [];
// Only loop and grab parent teams if a teamId was given. If not then all teams will be queried
if (teamId) {
teamsQuery.forEach((team) => {
if (team?.parent) {
const { parent, ...filteredTeam } = team;
filteredTeams.push(filteredTeam);
// Only add parent team if it's not already in teamsQuery
if (!teamsQuery.some((t) => t.id === parent.id)) {
parentTeams.push(parent);
}
}
});
}
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials: CredentialPayload[] = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? teamApp.credentials.flat() : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
} else {
credentials = credentials.concat(teamAppCredentials);
}
}
const enabledApps = await getEnabledAppsFromCredentials(credentials, {
filterOnCredentials: onlyInstalled,
...(appId ? { where: { slug: appId } } : {}),
});
//TODO: Refactor this to pick up only needed fields and prevent more leaking
let apps = await Promise.all(
enabledApps.map(async ({ credentials: _, credential, key: _2 /* don't leak to frontend */, ...app }) => {
const userCredentialIds = credentials.filter((c) => c.appId === app.slug && !c.teamId).map((c) => c.id);
const invalidCredentialIds = credentials
.filter((c) => c.appId === app.slug && c.invalid)
.map((c) => c.id);
const teams = await Promise.all(
credentials
.filter((c) => c.appId === app.slug && c.teamId)
.map(async (c) => {
const team = userTeams.find((team) => team.id === c.teamId);
if (!team) {
return null;
}
return {
teamId: team.id,
name: team.name,
logoUrl: team.logoUrl,
credentialId: c.id,
isAdmin:
team.members[0].role === MembershipRole.ADMIN ||
team.members[0].role === MembershipRole.OWNER,
};
})
);
// type infer as CredentialOwner
const credentialOwner: CredentialOwner = {
name: user.name,
avatar: user.avatar,
};
// We need to know if app is payment type
// undefined it means that app don't require app/setup/page
let isSetupAlready = undefined;
if (credential && app.categories.includes("payment")) {
const paymentApp = (await appStore[app.dirName as keyof typeof appStore]?.()) as PaymentApp | null;
if (paymentApp && "lib" in paymentApp && paymentApp?.lib && "PaymentService" in paymentApp?.lib) {
const PaymentService = paymentApp.lib.PaymentService;
const paymentInstance = new PaymentService(credential);
isSetupAlready = paymentInstance.isSetupAlready();
}
}
let dependencyData: TDependencyData = [];
if (app.dependencies?.length) {
dependencyData = app.dependencies.map((dependency) => {
const dependencyInstalled = enabledApps.some(
(dbAppIterator) => dbAppIterator.credentials.length && dbAppIterator.slug === dependency
);
// If the app marked as dependency is simply deleted from the codebase, we can have the situation where App is marked installed in DB but we couldn't get the app.
const dependencyName = getAppFromSlug(dependency)?.name;
return { name: dependencyName, installed: dependencyInstalled };
});
}
return {
...app,
...(teams.length && {
credentialOwner,
}),
userCredentialIds,
invalidCredentialIds,
teams,
isInstalled: !!userCredentialIds.length || !!teams.length || app.isGlobal,
isSetupAlready,
...(app.dependencies && { dependencyData }),
};
})
);
if (variant) {
// `flatMap()` these work like `.filter()` but infers the types correctly
apps = apps
// variant check
.flatMap((item) => (item.variant.startsWith(variant) ? [item] : []));
}
if (exclude) {
// exclusion filter
apps = apps.filter((item) => (exclude ? !exclude.includes(item.variant) : true));
}
if (onlyInstalled) {
apps = apps.flatMap((item) =>
item.userCredentialIds.length > 0 || item.teams.length || item.isGlobal ? [item] : []
);
}
if (extendsFeature) {
apps = apps
.filter((app) => app.extendsFeature?.includes(extendsFeature))
.map((app) => ({
...app,
isInstalled: !!app.userCredentialIds?.length || !!app.teams?.length || app.isGlobal,
}));
}
if (sortByMostPopular) {
const installCountPerApp = await getInstallCountPerApp();
// sort the apps array by the most popular apps
apps.sort((a, b) => {
const aCount = installCountPerApp[a.slug] || 0;
const bCount = installCountPerApp[b.slug] || 0;
return bCount - aCount;
});
}
return {
items: apps,
};
const user = ctx.user;
return getConnectedApps({ user, input, prisma });
};
@@ -1,9 +1,5 @@
import type { LocationObject } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
import { bulkUpdateEventsToDefaultLocation } from "@calcom/lib/bulkUpdateEventsToDefaultLocation";
import { prisma } from "@calcom/prisma";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../trpc";
import type { TBulkUpdateToDefaultLocationInputSchema } from "./bulkUpdateToDefaultLocation.schema";
@@ -15,50 +11,11 @@ type BulkUpdateToDefaultLocationOptions = {
input: TBulkUpdateToDefaultLocationInputSchema;
};
export const bulkUpdateToDefaultLocationHandler = async ({
ctx,
input,
}: BulkUpdateToDefaultLocationOptions) => {
export const bulkUpdateToDefaultLocationHandler = ({ ctx, input }: BulkUpdateToDefaultLocationOptions) => {
const { eventTypeIds } = input;
const defaultApp = userMetadataSchema.parse(ctx.user.metadata)?.defaultConferencingApp;
if (!defaultApp) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Default conferencing app not set",
});
}
const foundApp = getAppFromSlug(defaultApp.appSlug);
const appType = foundApp?.appData?.location?.type;
if (!appType) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Default conferencing app '${defaultApp.appSlug}' doesnt exist.`,
});
}
const credential = await prisma.credential.findFirst({
where: {
userId: ctx.user.id,
appId: foundApp.slug,
},
select: {
id: true,
},
});
return await prisma.eventType.updateMany({
where: {
id: {
in: eventTypeIds,
},
userId: ctx.user.id,
},
data: {
locations: [
{ type: appType, link: defaultApp.appLink, credentialId: credential?.id },
] as LocationObject[],
},
return bulkUpdateEventsToDefaultLocation({
eventTypeIds,
user: ctx.user,
prisma,
});
};