feat: Enable Apps for Teams & Orgs [CAL-1782] (#9337)

* Initial commit

* Adding feature flag

* Add schema relation for teams and credentials

* feat: Orgs Schema Changing `scopedMembers` to `orgUsers` (#9209)

* Change scopedMembers to orgMembers

* Change to orgUsers

* Create getUserAdminTeams function & tRPC endpoint

* Get user admin teams on app store page

* Create UserAdminTeams type

* Add user query to getUserAdminTeams

* Letting duplicate slugs for teams to support orgs

* Covering null on unique clauses

* Add dropdown to install button on app store

* Supporting having the orgId in the session cookie

* On app page, only show dropdown if there are teams

* Add teamId to OAuth state

* Create team credential for OAuth flow

* Create team credential for GCal

* Add create user or team credential for Stripe

* Create webex credentials for users or teams

* Fix type error on useAddAppMutation

* Hubspot create credential on user or team

* Zoho create create credential for user or team

* Zoom create credentials on user or team

* Salesforce create credential on user or teams

* OAuth create credentials for user or teams

* Revert Outlook changes

* Revert GCal changes

* Default app instal, create credential on user or team

* Add teamId to credential creation

* Disable installing for teams for calendars

* Include teams when querying installed apps

* Render team credentials on installed page

* Uninstall team apps

* Type fix on app card

* Add input to include user in teams query

* Add dropdown to install app page  for user or team

* Type fixes on category page

* Install app from eventType page to user or team

* Render user and team apps on event type app page

* feat: organization event type filter (#9253)

Signed-off-by: Udit Takkar <[email protected]>

* Missing changes to support orgs schema changes

* Render user and team apps on event type app page

* Add credentialOwner to eventTypeAppCard types

* Type fixes

* Create hook to check if app is enabled

* Clean up console.logs

* Fix useIsAppEnabled by returning not an array

* Convert event type apps to useIsAppEnabled

* Abstract credential owner type

* Remove console.logs

* On installed app page, show apps if only team credential is installed

* Clean up commented lines

* Handle installing app to just an team event from event type page

* Fix early return when creating team app credential

* Zoom add state to callback

* Get team location credentials and save credential id to location

* feat: Onboarding process to create an organization (#9184)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Making sure we check requestedSlug now

---------

Co-authored-by: sean-brydon <[email protected]>

* Type fix

* Grab team location credentials

* Add isInstalled to eventType apps query

* feat: [CAL-1816] Organization subdomain support (#9345)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* Covering users and subteams, excluding non-org users

* Unpublished teams shows correctly

* Create subdomain in Vercel

* feedback

* Renaming Vercel env vars

* Vercel domain check before creation

* Supporting cal-staging.com

* Change to have vercel detect it

* vercel domain check data message error

* Remove check domain

* Making sure we check requestedSlug now

* Feedback and unneeded code

* Reverting unneeded changes

* Unneeded changes

---------

Co-authored-by: sean-brydon <[email protected]>

* Vercel subdomain creation in PROD only

* Enable payment apps for team credentials

* Fix for team-user apps for event types

* Fix layout and add teamId to app card

* Disable apps on managed event types

* Add managed event type fields to event type apps

* Include organizations in query

* Change createAppCredential to createOAuthAppCredential

* Show app installed on teams

* Making sure we let localhost still work

* UI show installed for which team

* Type fixes

* For team events move use host location to top

* Add around to appStore

* New team event types organizer default conf app

* Fix app card bug

* Clean up

* Search for teamId or userId when deleting credential

* Type fixes

* Type fixes

* Type fixes

* Type fixes

* Address feedback

* Feedback

* Type check fixes

* feat: Organization branding in side menu (#9279)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Org branding provider used in shell sidebar

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Using org avatar (temp)

* Not showing org logo if not set

* User onboarding with org branding (slug)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Feedback

* Org public profile

* Public profiles for team event types

* Added setup profile alert

* Using org avatar on subteams avatar

* Making sure we show the set up profile on org only

* Profile username availability rely on org hook

* Update apps/web/pages/team/[slug].tsx

Co-authored-by: sean-brydon <[email protected]>

* Update apps/web/pages/team/[slug].tsx

Co-authored-by: sean-brydon <[email protected]>

---------

Co-authored-by: sean-brydon <[email protected]>

* feat: Organization support for event types page (#9449)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Org branding provider used in shell sidebar

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Using org avatar (temp)

* Not showing org logo if not set

* User onboarding with org branding (slug)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Feedback

* Org public profile

* Public profiles for team event types

* Added setup profile alert

* Using org avatar on subteams avatar

* Processing orgs and children as profile options

* Reverting change not belonging to this PR

* Making sure we show the set up profile on org only

* Removing console.log

* Comparing memberships to choose the highest one

---------

Co-authored-by: sean-brydon <[email protected]>

* Type errors

* Refactor and type fixes

* Update orgDomains.ts

* Feedback

* Reverting

* NIT

* Address feedback

* fix issue getting org slug from domain

* Improving orgDomains util

* Host comes with port

* Update useRouterQuery.ts

* Fix app card bug

* Fix schema

* Type fixes

* Revert changes to location apps

* Remove console.log

* Fix app store test

* Handle install app dropdown

* Add CalendarApp to `getCalendar`

* Add PaymentApp type fix

* Payment type fix

* Type fixes

* Match with main

* Change type to account for team

* Fix app count for team events

* Type fixes

* More type fixes

* Type fix?

* Fix the type fix

* Remove UserAdminTeams empty array union

* Type fix

* Type fix

* Type fix

* Uses type predicates

* Use teamId. Fixes installation for teams after user installation

* Fix Team Events not working

* Get embed for org events working

* Fix rewrites

* Address feedback

* Type fix

* Fixes

* Add useAppContextWithSchema in useIsAppEnabled

* Type fix for apps using useIsAppEnabled

* Integrations.handler change credentialIds to userCredentialIds

* Remove apps endpoint

* Add LockedIcon and disabled props to event type app context

* Type fixes

* Type fix

* Type fixes

* Show team installed apps for members

* Type fix

* Reverting findFirst

* Revert findFirst

* Avoid a possible 500

* Fix missing tanslation

* Avoid possible 500

* Undo default app for teams

* Type fix

* Fix test

* Update package.json

* feat: Fix invite bug - added tests (#9945)

Co-authored-by: Hariom Balhara <[email protected]>

* chore: Button Component Tidy up (#9888)

Co-authored-by: Peer Richelsen <[email protected]>

* feat: Make Team Private

## What does this PR do?

Fixes https://github.com/calcom/cal.com/issues/8974

1) When user is admin

<img width="1440" alt="Screenshot 2023-07-03 at 6 45 50 PM" src="https://github.com/calcom/cal.com/assets/53316345/ce15158f-d278-4f1a-ba2e-8b63e4274793">

2) When user is not admin and team is private

<img width="1440" alt="Screenshot 2023-07-03 at 6 47 15 PM" src="https://github.com/calcom/cal.com/assets/53316345/ce23560e-690a-4c42-a76d-49691260aa4d">

3) 
<img width="1440" alt="Screenshot 2023-07-03 at 6 51 56 PM" src="https://github.com/calcom/cal.com/assets/53316345/13af38f8-5618-4dae-b359-b24dc91e4eb4">


## Type of change

<!-- Please delete bullets that are not relevant. -->

- New feature (non-breaking change which adds functionality)

## How should this be tested?

1) go to Team members page and turn on switch Make Team Private.

Now after making the team private only admin would be able to see all the members list in the settings. There will not be a button to Book a team member instead on the team page like before.


## Mandatory Tasks

- [ ] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected.

---------

Signed-off-by: Udit Takkar <[email protected]>
Co-authored-by: Leo Giovanetti <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Alan <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Efraín Rochín <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
138 files changed
+1817 -785

No files matched your search

+9 -2
View File
@@ -3,8 +3,15 @@ import type { z, ZodType } from "zod";
export type GetAppData = (key: string) => unknown;
export type SetAppData = (key: string, value: unknown) => void;
type LockedIcon = JSX.Element | false | undefined;
type Disabled = boolean | undefined;
// eslint-disable-next-line @typescript-eslint/no-empty-function
const EventTypeAppContext = React.createContext<[GetAppData, SetAppData]>([() => ({}), () => {}]);
const EventTypeAppContext = React.createContext<[GetAppData, SetAppData, LockedIcon, Disabled]>([
() => ({}),
() => ({}),
undefined,
undefined,
]);
export type SetAppDataGeneric<TAppData extends ZodType> = <
TKey extends keyof z.infer<TAppData>,
@@ -22,7 +29,7 @@ export const useAppContextWithSchema = <TAppData extends ZodType>() => {
type GetAppData = GetAppDataGeneric<TAppData>;
type SetAppData = SetAppDataGeneric<TAppData>;
// TODO: Not able to do it without type assertion here
const context = React.useContext(EventTypeAppContext) as [GetAppData, SetAppData];
const context = React.useContext(EventTypeAppContext) as [GetAppData, SetAppData, LockedIcon, Disabled];
return context;
};
export default EventTypeAppContext;
+11 -2
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { getAppFromSlug } from "@calcom/app-store/utils";
import type { UserAdminTeams } from "@calcom/features/ee/teams/lib/getUserAdminTeams";
import prisma, { safeAppSelect, safeCredentialSelect } from "@calcom/prisma";
import { userMetadata } from "@calcom/prisma/zod-utils";
import type { AppFrontendPayload as App } from "@calcom/types/App";
@@ -56,13 +57,21 @@ export async function getAppRegistry() {
return apps;
}
export async function getAppRegistryWithCredentials(userId: number) {
export async function getAppRegistryWithCredentials(userId: number, userAdminTeams: UserAdminTeams = []) {
// Get teamIds to grab existing credentials
const teamIds = [];
for (const team of userAdminTeams) {
if (!team.isUser) {
teamIds.push(team.id);
}
}
const dbApps = await prisma.app.findMany({
where: { enabled: true },
select: {
...safeAppSelect,
credentials: {
where: { userId },
where: { OR: [{ userId }, { teamId: { in: teamIds } }] },
select: safeCredentialSelect,
},
},
+47 -21
View File
@@ -3,10 +3,11 @@ import Link from "next/link";
import { classNames } from "@calcom/lib";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Switch } from "@calcom/ui";
import { Switch, Badge, Avatar } from "@calcom/ui";
import type { SetAppDataGeneric } from "../EventTypeAppContext";
import type { eventTypeAppCardZod } from "../eventTypeAppCardZod";
import type { CredentialOwner } from "../types";
import OmniInstallAppButton from "./OmniInstallAppButton";
export default function AppCard({
@@ -17,14 +18,20 @@ export default function AppCard({
children,
setAppData,
returnTo,
teamId,
disableSwitch,
LockedIcon,
}: {
app: RouterOutputs["viewer"]["apps"][number];
app: RouterOutputs["viewer"]["integrations"]["items"][number] & { credentialOwner?: CredentialOwner };
description?: React.ReactNode;
switchChecked?: boolean;
switchOnClick?: (e: boolean) => void;
children?: React.ReactNode;
setAppData: SetAppDataGeneric<typeof eventTypeAppCardZod>;
returnTo?: string;
teamId?: number;
disableSwitch?: boolean;
LockedIcon?: React.ReactNode;
}) {
const [animationRef] = useAutoAnimate<HTMLDivElement>();
@@ -55,26 +62,45 @@ export default function AppCard({
{description || app?.description}
</p>
</div>
{app?.isInstalled ? (
<div className="ml-auto flex items-center">
<Switch
disabled={!app.enabled}
onCheckedChange={(enabled) => {
if (switchOnClick) {
switchOnClick(enabled);
}
setAppData("enabled", enabled);
}}
checked={switchChecked}
<div className="ml-auto flex items-center space-x-2">
{app.credentialOwner && (
<div className="ml-auto">
<Badge variant="gray">
<div className="flex items-center">
<Avatar
className="mr-2"
alt={app.credentialOwner.name || "Credential Owner Name"}
size="sm"
imageSrc={app.credentialOwner.avatar}
/>
{app.credentialOwner.name}
</div>
</Badge>
</div>
)}
{app?.isInstalled || app.credentialOwner ? (
<div className="ml-auto flex items-center">
<Switch
disabled={!app.enabled || disableSwitch}
onCheckedChange={(enabled) => {
if (switchOnClick) {
switchOnClick(enabled);
}
setAppData("enabled", enabled);
}}
checked={switchChecked}
LockedIcon={LockedIcon}
/>
</div>
) : (
<OmniInstallAppButton
className="ml-auto flex items-center"
appId={app.slug}
returnTo={returnTo}
teamId={teamId}
/>
</div>
) : (
<OmniInstallAppButton
className="ml-auto flex items-center"
appId={app.slug}
returnTo={returnTo}
/>
)}
)}
</div>
</div>
</div>
<div ref={animationRef}>
@@ -4,19 +4,22 @@ import { EventTypeAddonMap } from "@calcom/app-store/apps.browser.generated";
import type { RouterOutputs } from "@calcom/trpc/react";
import { ErrorBoundary } from "@calcom/ui";
import type { EventTypeAppCardComponentProps } from "../types";
import type { EventTypeAppCardComponentProps, CredentialOwner } from "../types";
import { DynamicComponent } from "./DynamicComponent";
export const EventTypeAppCard = (props: {
app: RouterOutputs["viewer"]["apps"][number];
app: RouterOutputs["viewer"]["integrations"]["items"][number] & { credentialOwner?: CredentialOwner };
eventType: EventTypeAppCardComponentProps["eventType"];
getAppData: GetAppData;
setAppData: SetAppData;
// For event type apps, get these props from shouldLockDisableProps
LockedIcon?: JSX.Element | false;
disabled?: boolean;
}) => {
const { app, getAppData, setAppData } = props;
const { app, getAppData, setAppData, LockedIcon, disabled } = props;
return (
<ErrorBoundary message={`There is some problem with ${app.name} App`}>
<EventTypeAppContext.Provider value={[getAppData, setAppData]}>
<EventTypeAppContext.Provider value={[getAppData, setAppData, LockedIcon, disabled]}>
<DynamicComponent
slug={app.slug === "stripe" ? "stripepayment" : app.slug}
componentMap={EventTypeAddonMap}
@@ -16,10 +16,12 @@ export default function OmniInstallAppButton({
appId,
className,
returnTo,
teamId,
}: {
appId: string;
className: string;
returnTo?: string;
teamId?: number;
}) {
const { t } = useLocale();
const { data: app } = useApp(appId);
@@ -30,7 +32,10 @@ export default function OmniInstallAppButton({
onSuccess: (data) => {
//TODO: viewer.appById might be replaced with viewer.apps so that a single query needs to be invalidated.
utils.viewer.appById.invalidate({ appId });
utils.viewer.apps.invalidate({ extendsFeature: "EventType" });
utils.viewer.integrations.invalidate({
extendsFeature: "EventType",
...(teamId && { teamId }),
});
if (data?.setupPending) return;
showToast(t("app_successfully_installed"), "success");
},
@@ -53,7 +58,13 @@ export default function OmniInstallAppButton({
props = {
...props,
onClick: () => {
mutation.mutate({ type: app.type, variant: app.variant, slug: app.slug, isOmniInstall: true });
mutation.mutate({
type: app.type,
variant: app.variant,
slug: app.slug,
isOmniInstall: true,
...(teamId && { teamId }),
});
},
};
}
@@ -0,0 +1,65 @@
import type { NextApiRequest } from "next";
import prisma from "@calcom/prisma";
import { decodeOAuthState } from "./decodeOAuthState";
/**
* This function is used to create app credentials for either a user or a team
*
* @param appData information about the app
* @param appData.type the app slug
* @param appData.appId the app slug
* @param key the keys for the app's credentials
* @param req the request object from the API call. Used to determine if the credential belongs to a user or a team
*/
const createOAuthAppCredential = async (
appData: { type: string; appId: string },
key: unknown,
req: NextApiRequest
) => {
const userId = req.session?.user.id;
// For OAuth flows, see if a teamId was passed through the state
const state = decodeOAuthState(req);
if (state?.teamId) {
// Check that the user belongs to the team
const team = await prisma.team.findFirst({
where: {
id: state.teamId,
members: {
some: {
userId: req.session?.user.id,
accepted: true,
},
},
},
select: { id: true, members: { select: { userId: true } } },
});
if (!team) throw new Error("User does not belong to the team");
await prisma.credential.create({
data: {
type: appData.type,
key: key || {},
teamId: state.teamId,
appId: appData.appId,
},
});
return;
}
await prisma.credential.create({
data: {
type: appData.type,
key: key || {},
userId,
appId: appData.appId,
},
});
return;
};
export default createOAuthAppCredential;
+20 -2
View File
@@ -1,11 +1,28 @@
import logger from "@calcom/lib/logger";
import type { Calendar } from "@calcom/types/Calendar";
import type { Calendar, CalendarClass } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import appStore from "..";
interface CalendarApp {
lib: {
CalendarService: CalendarClass;
};
}
const log = logger.getChildLogger({ prefix: ["CalendarManager"] });
/**
* @see [Using type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
*/
const isCalendarService = (x: unknown): x is CalendarApp =>
!!x &&
typeof x === "object" &&
"lib" in x &&
typeof x.lib === "object" &&
!!x.lib &&
"CalendarService" in x.lib;
export const getCalendar = async (credential: CredentialPayload | null): Promise<Calendar | null> => {
if (!credential || !credential.key) return null;
let { type: calendarType } = credential;
@@ -20,7 +37,8 @@ export const getCalendar = async (credential: CredentialPayload | null): Promise
}
const calendarApp = await calendarAppImportFn();
if (!(calendarApp && "lib" in calendarApp && "CalendarService" in calendarApp.lib)) {
if (!isCalendarService(calendarApp)) {
log.warn(`calendar of type ${calendarType} is not implemented`);
return null;
}
+3 -1
View File
@@ -20,17 +20,19 @@ export async function createDefaultInstallation({
userId,
slug,
key = {},
teamId,
}: {
appType: string;
userId: number;
slug: string;
key?: Prisma.InputJsonValue;
teamId?: number;
}) {
const installation = await prisma.credential.create({
data: {
type: appType,
key,
userId,
...(teamId ? { teamId } : { userId }),
appId: slug,
},
});
@@ -31,10 +31,11 @@ function useAddAppMutation(_type: App["type"] | null, allOptions?: UseAddAppMuta
const mutation = useMutation<
AddAppMutationData,
Error,
{ type?: App["type"]; variant?: string; slug?: string; isOmniInstall?: boolean } | ""
{ type?: App["type"]; variant?: string; slug?: string; isOmniInstall?: boolean; teamId?: number } | ""
>(async (variables) => {
let type: string | null | undefined;
let isOmniInstall;
const teamId = variables && variables.teamId ? variables.teamId : undefined;
if (variables === "") {
type = _type;
} else {
@@ -57,9 +58,11 @@ function useAddAppMutation(_type: App["type"] | null, allOptions?: UseAddAppMuta
location.search
),
...(type === "google_calendar" && { installGoogleVideo: options?.installGoogleVideo }),
...(teamId && { teamId }),
};
const stateStr = encodeURIComponent(JSON.stringify(state));
const searchParams = `?state=${stateStr}`;
const searchParams = `?state=${stateStr}${teamId ? `&teamId=${teamId}` : ""}`;
const res = await fetch(`/api/integrations/${type}/add` + searchParams);
@@ -70,7 +73,6 @@ function useAddAppMutation(_type: App["type"] | null, allOptions?: UseAddAppMuta
const json = await res.json();
const externalUrl = /https?:\/\//.test(json.url) && !json.url.startsWith(window.location.origin);
if (!isOmniInstall) {
gotoUrl(json.url, json.newTab);
return { setupPending: externalUrl || json.url.endsWith("/setup") };
@@ -0,0 +1,34 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import type { EventTypeAppCardApp } from "../types";
function useIsAppEnabled(app: EventTypeAppCardApp) {
const [getAppData, setAppData] = useAppContextWithSchema();
const [enabled, setEnabled] = useState(() => {
if (!app.credentialOwner) {
return getAppData("enabled");
}
const credentialId = getAppData("credentialId");
const isAppEnabledForCredential =
app.userCredentialIds.some((id) => id === credentialId) ||
app.credentialOwner.credentialId === credentialId;
return isAppEnabledForCredential;
});
const updateEnabled = (newValue: boolean) => {
if (!newValue) {
setAppData("credentialId", undefined);
}
if (newValue && (app.userCredentialIds?.length || app.credentialOwner?.credentialId)) {
setAppData("credentialId", app.credentialOwner?.credentialId || app.userCredentialIds[0]);
}
setEnabled(newValue);
};
return { enabled, updateEnabled };
}
export default useIsAppEnabled;
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://amie.so/signup",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2
View File
@@ -12,6 +12,7 @@ export async function getHandler(req: NextApiRequest) {
const slug = appConfig.slug;
const variant = appConfig.variant;
const appType = appConfig.type;
const teamId = req.query.teamId ? Number(req.query.teamId) : undefined;
await checkInstalled(slug, session.user.id);
await createDefaultInstallation({
@@ -19,6 +20,7 @@ export async function getHandler(req: NextApiRequest) {
userId: session.user.id,
slug,
key: {},
teamId,
});
return { url: getInstalledAppPath({ variant, slug }) };
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://cron.com",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -62,6 +62,7 @@ export const FAKE_DAILY_CREDENTIAL: CredentialPayload & { invalid: boolean } = {
userId: +new Date().getTime(),
appId: "daily-video",
invalid: false,
teamId: undefined,
};
export const fetcher = async (endpoint: string, init?: RequestInit | undefined) => {
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -3,6 +3,7 @@ import { z } from "zod";
export const eventTypeAppCardZod = z.object({
enabled: z.boolean().optional(),
credentialId: z.number().optional(),
});
export const appKeysSchema = z.object({});
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,32 +1,31 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
} else {
setEnabled(true);
}
updateEnabled(e);
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Tracking ID"
value={trackingId}
disabled={disabled}
onChange={(e) => {
setAppData("trackingId", e.target.value);
}}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,32 +1,31 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
} else {
setEnabled(true);
}
updateEnabled(e);
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Tracking ID"
value={trackingId}
disabled={disabled}
onChange={(e) => {
setAppData("trackingId", e.target.value);
}}
+5 -2
View File
@@ -14,11 +14,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(401).json({ message: "You must be logged in to do this" });
}
const appType = "giphy_other";
const credentialOwner = req.query.teamId
? { teamId: Number(req.query.teamId) }
: { userId: req.session.user.id };
try {
const alreadyInstalled = await prisma.credential.findFirst({
where: {
type: appType,
userId: req.session.user.id,
...credentialOwner,
},
});
if (alreadyInstalled) {
@@ -28,7 +31,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
data: {
type: appType,
key: {},
userId: req.session.user.id,
...credentialOwner,
appId: "giphy",
},
});
@@ -1,17 +1,17 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import { SelectGifInput } from "@calcom/app-store/giphy/components";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const thankYouPage = getAppData("thankYouPage");
const [showGifSelection, setShowGifSelection] = useState(getAppData("enabled"));
const { enabled: showGifSelection, updateEnabled: setShowGifSelection } = useIsAppEnabled(app);
const { t } = useLocale();
return (
@@ -19,13 +19,17 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
setAppData={setAppData}
app={app}
description={t("confirmation_page_gif")}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
setShowGifSelection(e);
}}
switchChecked={showGifSelection}>
switchChecked={showGifSelection}
teamId={eventType.team?.id || undefined}>
{showGifSelection && (
<SelectGifInput
defaultValue={thankYouPage}
disabled={disabled}
onChange={(url: string) => {
setAppData("thankYouPage", url);
}}
@@ -9,6 +9,7 @@ import { SearchDialog } from "./SearchDialog";
interface ISelectGifInput {
defaultValue?: string | null;
onChange: (url: string) => void;
disabled?: boolean;
}
export default function SelectGifInput(props: ISelectGifInput) {
const { t } = useLocale();
@@ -24,11 +25,21 @@ export default function SelectGifInput(props: ISelectGifInput) {
)}
<div className="flex">
{selectedGif ? (
<Button color="minimal" type="button" StartIcon={Edit} onClick={() => setShowDialog(true)}>
<Button
color="minimal"
type="button"
StartIcon={Edit}
onClick={() => setShowDialog(true)}
disabled={props.disabled}>
Change
</Button>
) : (
<Button color="minimal" type="button" StartIcon={Plus} onClick={() => setShowDialog(true)}>
<Button
color="minimal"
type="button"
StartIcon={Plus}
onClick={() => setShowDialog(true)}
disabled={props.disabled}>
Add from Giphy
</Button>
)}
@@ -41,7 +52,8 @@ export default function SelectGifInput(props: ISelectGifInput) {
onClick={() => {
setSelectedGif("");
props.onChange("");
}}>
}}
disabled={props.disabled}>
{t("remove")}
</Button>
)}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,32 +1,31 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
} else {
setEnabled(true);
}
updateEnabled(e);
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Tracking ID"
value={trackingId}
disabled={disabled}
onChange={(e) => {
setAppData("trackingId", e.target.value);
}}
+3 -10
View File
@@ -4,8 +4,8 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -46,15 +46,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// set expiry date as offset from current time.
hubspotToken.expiryDate = Math.round(Date.now() + hubspotToken.expiresIn * 1000);
await prisma.credential.create({
data: {
type: "hubspot_other_calendar",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: hubspotToken as any,
userId: req.session.user.id,
appId: "hubspot",
},
});
createOAuthAppCredential({ appId: "hubspot", type: "hubspot_other_calendar" }, hubspotToken as any, req);
const state = decodeOAuthState(req);
res.redirect(
+1
View File
@@ -1,6 +1,7 @@
const appStore = {
// example: () => import("./example"),
applecalendar: () => import("./applecalendar"),
aroundvideo: () => import("./around"),
caldavcalendar: () => import("./caldavcalendar"),
closecom: () => import("./closecom"),
dailyvideo: () => import("./dailyvideo"),
+1
View File
@@ -165,6 +165,7 @@ export type LocationObject = {
type: string;
address?: string;
displayLocationPublicly?: boolean;
credentialId?: number;
} & Partial<
Record<"address" | "attendeeAddress" | "link" | "hostPhoneNumber" | "hostDefault" | "phone", string>
>;
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,22 +1,29 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard setAppData={setAppData} app={app} switchOnClick={setEnabled} switchChecked={enabled}>
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={updateEnabled}
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Pixel ID"
value={trackingId}
disabled={disabled}
onChange={(e) => {
setAppData("trackingId", e.target.value);
}}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
url: "https://n8n.io/integrations/cal-trigger/",
newTab: true,
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -4,6 +4,7 @@ import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -92,14 +93,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
}
await prisma.credential.create({
data: {
type: "office365_video",
key: responseBody,
userId,
appId: "msteams",
},
});
createOAuthAppCredential({ appId: "msteams", type: "office365_video" }, responseBody, req);
const state = decodeOAuthState(req);
return res.redirect(
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://pipedream.com/apps/cal-com",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,40 +1,40 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const plausibleUrl = getAppData("PLAUSIBLE_URL");
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
} else {
setEnabled(true);
}
updateEnabled(e);
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Plausible URL"
defaultValue="https://plausible.io/js/script.js"
placeholder="https://plausible.io/js/script.js"
value={plausibleUrl}
disabled={disabled}
onChange={(e) => {
setAppData("PLAUSIBLE_URL", e.target.value);
}}
/>
<TextField
disabled={disabled}
name="Tracked Domain"
placeholder="yourdomain.com"
value={trackingId}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -2,6 +2,7 @@ import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Tooltip, TextField } from "@calcom/ui";
@@ -10,9 +11,9 @@ import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ eventType, app }) {
const { t } = useLocale();
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const [enabled, setEnabled] = useState(getAppData("enabled"));
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const [additionalParameters, setAdditionalParameters] = useState("");
const { enabled, updateEnabled } = useIsAppEnabled(app);
const query = additionalParameters !== "" ? `?${additionalParameters}` : "";
const eventTypeURL = eventType.URL + query;
@@ -38,18 +39,18 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
} else {
setEnabled(true);
}
updateEnabled(e);
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<div className="flex w-full flex-col gap-2 text-sm">
<div className="flex w-full">
<TextField
name="hello"
disabled={disabled}
value={additionalParameters}
onChange={(e) => setAdditionalParameters(e.target.value)}
label={t("additional_url_parameters")}
+2 -2
View File
@@ -12,8 +12,8 @@ const handler: AppDeclarativeHandler = {
redirect: {
url: "raycast://extensions/eluce2/cal-com-share-meeting-links?source=webstore",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -9,12 +9,12 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: async ({ user, appType, slug }) => {
createCredential: async ({ user, appType, slug, teamId }) => {
return await prisma.credential.create({
data: {
type: appType,
key: {},
userId: user.id,
...(teamId ? { teamId } : { userId: user.id }),
appId: slug,
},
});
@@ -8,7 +8,7 @@ import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { classNames } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import getOrgAwareUrlOnClient from "@calcom/lib/getOrgAwareUrl";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
@@ -195,7 +195,6 @@ function Dialogs({
deleteDialogFormId: string | null;
}) {
const utils = trpc.useContext();
const router = useRouter();
const { t } = useLocale();
const deleteMutation = trpc.viewer.appRoutingForms.deleteForm.useMutation({
onMutate: async ({ id: formId }) => {
@@ -402,11 +401,11 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
const dropdownCtxValue = useContext(dropdownCtx);
const dropdown = dropdownCtxValue?.dropdown;
const embedLink = `forms/${routingForm?.id}`;
const formLink = `${CAL_URL}/${embedLink}`;
let redirectUrl = `${CAL_URL}/router?form=${routingForm?.id}`;
const formRelativeLink = `/${embedLink}`;
let relativeRedirectUrl = `/router?form=${routingForm?.id}`;
routingForm?.fields?.forEach((field) => {
redirectUrl += `&${getFieldIdentifier(field)}={Recalled_Response_For_This_Field}`;
relativeRedirectUrl += `&${getFieldIdentifier(field)}={Recalled_Response_For_This_Field}`;
});
const { t } = useLocale();
@@ -416,12 +415,12 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
ButtonProps & { as?: React.ElementType; render?: FormActionProps<unknown>["render"] }
> = {
preview: {
href: formLink,
href: formRelativeLink,
},
copyLink: {
onClick: () => {
showToast(t("link_copied"), "success");
navigator.clipboard.writeText(formLink);
navigator.clipboard.writeText(getOrgAwareUrlOnClient(formRelativeLink));
},
},
duplicate: {
@@ -448,7 +447,7 @@ export const FormAction = forwardRef(function FormAction<T extends typeof Button
},
copyRedirectUrl: {
onClick: () => {
navigator.clipboard.writeText(redirectUrl);
navigator.clipboard.writeText(getOrgAwareUrlOnClient(relativeRedirectUrl));
showToast(t("typeform_redirect_url_copied"), "success");
},
},
@@ -186,6 +186,7 @@ test.describe("Routing Forms", () => {
// Install app
await page.goto(`/apps/routing-forms`);
await page.click('[data-testid="install-app-button"]');
(await page.waitForSelector('[data-testid="install-app-button-personal"]')).click();
await page.waitForURL((url) => url.pathname === `/apps/routing-forms/forms`);
});
@@ -217,6 +218,7 @@ test.describe("Routing Forms", () => {
// Install app
await page.goto(`/apps/routing-forms`);
await page.click('[data-testid="install-app-button"]');
(await page.waitForSelector('[data-testid="install-app-button-personal"]')).click();
await page.waitForURL((url) => url.pathname === `/apps/routing-forms/forms`);
return user;
};
+6 -10
View File
@@ -3,8 +3,8 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -38,15 +38,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const salesforceTokenInfo = await conn.oauth2.requestToken(code as string);
await prisma.credential.create({
data: {
type: "salesforce_other_calendar",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: salesforceTokenInfo as any,
userId: req.session.user.id,
appId: "salesforce",
},
});
createOAuthAppCredential(
{ appId: "salesforce", type: "salesforce_other_calendar" },
salesforceTokenInfo as any,
req
);
const state = decodeOAuthState(req);
res.redirect(
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -2,8 +2,8 @@ import type { Prisma } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { stringify } from "querystring";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import type { StripeData } from "../lib/server";
import stripe from "../lib/server";
@@ -31,6 +31,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(401).json({ message: "You must be logged in to do this" });
}
const state = decodeOAuthState(req);
const response = await stripe.oauth.token({
grant_type: "authorization_code",
code: code?.toString(),
@@ -42,14 +44,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
data["default_currency"] = account.default_currency;
}
await prisma.credential.create({
data: {
type: "stripe_payment",
key: data as unknown as Prisma.InputJsonObject,
userId: req.session.user.id,
appId: "stripe",
},
});
createOAuthAppCredential(
{ appId: "stripe", type: "stripe_payment" },
data as unknown as Prisma.InputJsonObject,
req
);
const returnTo = getReturnToValueFromQueryState(req);
res.redirect(returnTo || getInstalledAppPath({ variant: "payment", slug: "stripe" }));
@@ -1,8 +1,8 @@
import { useRouter } from "next/router";
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -15,12 +15,13 @@ type Option = { value: string; label: string };
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const { asPath } = useRouter();
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const price = getAppData("price");
const currency = getAppData("currency");
const paymentOption = getAppData("paymentOption");
const paymentOptionSelectValue = paymentOptions.find((option) => paymentOption === option.value);
const [requirePayment, setRequirePayment] = useState(getAppData("enabled"));
const { enabled: requirePayment, updateEnabled: setRequirePayment } = useIsAppEnabled(app);
const { t } = useLocale();
const recurringEventDefined = eventType.recurringEvent?.count !== undefined;
const seatsEnabled = !!eventType.seatsPerTimeSlot;
@@ -39,6 +40,8 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
returnTo={WEBAPP_URL + asPath}
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchChecked={requirePayment}
switchOnClick={(enabled) => {
setRequirePayment(enabled);
@@ -55,48 +58,48 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
</>
}>
<>
{recurringEventDefined ? (
{recurringEventDefined && (
<Alert className="mt-2" severity="warning" title={t("warning_recurring_event_payment")} />
) : (
requirePayment && (
<>
<div className="mt-2 block items-center justify-start sm:flex sm:space-x-2">
<TextField
label=""
className="h-[38px]"
addOnLeading={<>{currency ? getCurrencySymbol("en", currency) : ""}</>}
addOnClassname="h-[38px]"
step="0.01"
min="0.5"
type="number"
required
placeholder="Price"
onChange={(e) => {
setAppData("price", Number(e.target.value) * 100);
}}
value={price > 0 ? price / 100 : undefined}
/>
<Select<Option>
defaultValue={
paymentOptionSelectValue
? { ...paymentOptionSelectValue, label: t(paymentOptionSelectValue.label) }
: { ...paymentOptions[0], label: t(paymentOptions[0].label) }
}
options={paymentOptions.map((option) => {
return { ...option, label: t(option.label) || option.label };
})}
onChange={(input) => {
if (input) setAppData("paymentOption", input.value);
}}
className="mb-1 h-[38px] w-full"
isDisabled={seatsEnabled}
/>
</div>
{seatsEnabled && paymentOption === "HOLD" && (
<Alert className="mt-2" severity="warning" title={t("seats_and_no_show_fee_error")} />
)}
</>
)
)}
{!recurringEventDefined && requirePayment && (
<>
<div className="mt-2 block items-center justify-start sm:flex sm:space-x-2">
<TextField
label=""
className="h-[38px]"
addOnLeading={<>{currency ? getCurrencySymbol("en", currency) : ""}</>}
addOnClassname="h-[38px]"
step="0.01"
min="0.5"
type="number"
required
placeholder="Price"
disabled={disabled}
onChange={(e) => {
setAppData("price", Number(e.target.value) * 100);
}}
value={price > 0 ? price / 100 : undefined}
/>
<Select<Option>
defaultValue={
paymentOptionSelectValue
? { ...paymentOptionSelectValue, label: t(paymentOptionSelectValue.label) }
: { ...paymentOptions[0], label: t(paymentOptions[0].label) }
}
options={paymentOptions.map((option) => {
return { ...option, label: t(option.label) || option.label };
})}
onChange={(input) => {
if (input) setAppData("paymentOption", input.value);
}}
className="mb-1 h-[38px] w-full"
isDisabled={seatsEnabled || disabled}
/>
</div>
{seatsEnabled && paymentOption === "HOLD" && (
<Alert className="mt-2" severity="warning" title={t("seats_and_no_show_fee_error")} />
)}
</>
)}
</>
</AppCard>
+4 -16
View File
@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -59,21 +60,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
await prisma.user.update({
where: {
id: req.session?.user.id,
},
data: {
credentials: {
create: {
type: "tandem_video",
key: responseBody,
appId: "tandem",
},
},
},
});
}
createOAuthAppCredential({ appId: "tandem", type: "tandem_video" }, responseBody, req);
res.redirect(getInstalledAppPath({ variant: "conferencing", slug: "tandem" }));
res.redirect(getInstalledAppPath({ variant: "conferencing", slug: "tandem" }));
}
}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -7,7 +7,7 @@ import { TextField } from "@calcom/ui";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app }) {
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ app, eventType }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const trackingId = getAppData("trackingId");
const [enabled, setEnabled] = useState(getAppData("enabled"));
@@ -23,7 +23,8 @@ const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({
setEnabled(true);
}
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<TextField
name="Tracking ID"
value={trackingId}
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -1,31 +1,33 @@
import { useState } from "react";
import { useAppContextWithSchema } from "@calcom/app-store/EventTypeAppContext";
import AppCard from "@calcom/app-store/_components/AppCard";
import useIsAppEnabled from "@calcom/app-store/_utils/useIsAppEnabled";
import type { EventTypeAppCardComponent } from "@calcom/app-store/types";
import { Sunrise, Sunset } from "@calcom/ui/components/icon";
import type { appDataSchema } from "../zod";
const EventTypeAppCard: EventTypeAppCardComponent = function EventTypeAppCard({ eventType, app }) {
const [getAppData, setAppData] = useAppContextWithSchema<typeof appDataSchema>();
const [getAppData, setAppData, LockedIcon, disabled] = useAppContextWithSchema<typeof appDataSchema>();
const isSunrise = getAppData("isSunrise");
const [enabled, setEnabled] = useState(getAppData("enabled"));
const { enabled, updateEnabled } = useIsAppEnabled(app);
return (
<AppCard
setAppData={setAppData}
app={app}
disableSwitch={disabled}
LockedIcon={LockedIcon}
switchOnClick={(e) => {
if (!e) {
setEnabled(false);
updateEnabled(false);
setAppData("isSunrise", false);
} else {
setEnabled(true);
updateEnabled(true);
setAppData("isSunrise", true);
}
}}
switchChecked={enabled}>
switchChecked={enabled}
teamId={eventType.team?.id || undefined}>
<div className="mt-2 text-sm">
<div className="flex">
<span className="ltr:mr-2 rtl:ml-2">{isSunrise ? <Sunrise /> : <Sunset />}</span>I am an AppCard for
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://example.com/link",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -2
View File
@@ -12,8 +12,8 @@ const handler: AppDeclarativeHandler = {
redirect: {
url: "/apps/typeform/how-to-use",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -19,9 +19,11 @@ const installApps = async (page: Page, users: Fixtures["users"]) => {
await user.login();
await page.goto(`/apps/routing-forms`);
await page.click('[data-testid="install-app-button"]');
(await page.waitForSelector('[data-testid="install-app-button-personal"]')).click();
await page.waitForURL((url) => url.pathname === `/apps/routing-forms/forms`);
await page.goto(`/apps/typeform`);
await page.click('[data-testid="install-app-button"]');
(await page.waitForSelector('[data-testid="install-app-button-personal"]')).click();
await page.waitForURL((url) => url.pathname === `/apps/typeform/how-to-use`);
};
+19 -4
View File
@@ -1,13 +1,26 @@
import type React from "react";
import type { z } from "zod";
import type { _EventTypeModel } from "@calcom/prisma/zod";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
export type IntegrationOAuthCallbackState = {
returnTo: string;
installGoogleVideo?: boolean;
teamId?: number;
};
export type CredentialOwner = {
name: string | null;
avatar?: string | null;
teamId?: number;
credentialId?: number;
readOnly?: boolean;
};
export type EventTypeAppCardApp = RouterOutputs["viewer"]["integrations"]["items"][number] & {
credentialOwner?: CredentialOwner;
credentialIds?: number[];
};
type AppScript = { attrs?: Record<string, string> } & { src?: string; content?: string };
@@ -29,11 +42,13 @@ export interface InstallAppButtonProps {
export type EventTypeAppCardComponentProps = {
// Limit what data should be accessible to apps
eventType: Pick<
z.infer<typeof _EventTypeModel>,
"id" | "title" | "description" | "teamId" | "length" | "recurringEvent" | "seatsPerTimeSlot"
z.infer<typeof EventTypeModel>,
"id" | "title" | "description" | "teamId" | "length" | "recurringEvent" | "seatsPerTimeSlot" | "team"
> & {
URL: string;
};
app: RouterOutputs["viewer"]["apps"][number];
app: EventTypeAppCardApp;
disabled?: boolean;
LockedIcon?: JSX.Element | false;
};
export type EventTypeAppCardComponent = React.FC<EventTypeAppCardComponentProps>;
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://cal.com/blog/cal-plus-vimcal",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
+2 -14
View File
@@ -3,6 +3,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import config from "../config.json";
import { getWebexAppKeys } from "../lib/getWebexAppKeys";
@@ -80,20 +81,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
}
await prisma.user.update({
where: {
id: req.session?.user.id,
},
data: {
credentials: {
create: {
type: config.type,
key: responseBody,
appId: config.slug,
},
},
},
});
createOAuthAppCredential({ appId: config.slug, type: config.type }, responseBody, req);
res.redirect(getInstalledAppPath({ variant: config.variant, slug: config.slug }));
}
+2 -2
View File
@@ -9,8 +9,8 @@ const handler: AppDeclarativeHandler = {
slug: appConfig.slug,
supportsMultipleInstalls: false,
handlerType: "add",
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -23,7 +23,7 @@ const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
}
const wipeMyCalCredentials = data?.items.find((item: { type: string }) => item.type === "wipemycal_other");
const [credentialId] = wipeMyCalCredentials?.credentialIds || [false];
const [credentialId] = wipeMyCalCredentials?.userCredentialIds || [false];
return (
<>
+2 -2
View File
@@ -13,8 +13,8 @@ const handler: AppDeclarativeHandler = {
newTab: true,
url: "https://wordpress.org/plugins/cal-com/",
},
createCredential: ({ appType, user, slug }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {} }),
createCredential: ({ appType, user, slug, teamId }) =>
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
};
export default handler;
@@ -22,10 +22,10 @@ export default function ZapierSetup(props: IZapierSetupProps) {
const oldApiKey = trpc.viewer.apiKeys.findKeyOfType.useQuery({ appId: ZAPIER });
const deleteApiKey = trpc.viewer.apiKeys.delete.useMutation();
const zapierCredentials: { credentialIds: number[] } | undefined = integrations.data?.items.find(
const zapierCredentials: { userCredentialIds: number[] } | undefined = integrations.data?.items.find(
(item: { type: string }) => item.type === "zapier_automation"
);
const [credentialId] = zapierCredentials?.credentialIds || [false];
const [credentialId] = zapierCredentials?.userCredentialIds || [false];
const showContent = integrations.data && integrations.isSuccess && credentialId;
const isCalDev = process.env.NEXT_PUBLIC_WEBAPP_URL === "https://app.cal.dev";
@@ -4,8 +4,8 @@ import qs from "qs";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -52,14 +52,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
tokenInfo.data.expiryDate = Math.round(Date.now() + tokenInfo.data.expires_in);
tokenInfo.data.accountServer = accountsServer;
await prisma.credential.create({
data: {
type: appConfig.type,
key: tokenInfo.data,
userId: req.session.user.id,
appId: appConfig.slug,
},
});
createOAuthAppCredential({ appId: appConfig.slug, type: appConfig.type }, tokenInfo.data, req);
const state = decodeOAuthState(req);
res.redirect(
+6 -10
View File
@@ -4,8 +4,8 @@ import qs from "qs";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import { decodeOAuthState } from "../../_utils/decodeOAuthState";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
@@ -51,15 +51,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
zohoCrmTokenInfo.data.expiryDate = Math.round(Date.now() + 60 * 60);
zohoCrmTokenInfo.data.accountServer = req.query["accounts-server"];
await prisma.credential.create({
data: {
type: "zohocrm_other_calendar",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
key: zohoCrmTokenInfo.data as any,
userId: req.session.user.id,
appId: "zohocrm",
},
});
createOAuthAppCredential(
{ appId: "zohocrm", type: "zohocrm_other_calendar" },
zohoCrmTokenInfo.data as any,
req
);
const state = decodeOAuthState(req);
res.redirect(
+3
View File
@@ -5,6 +5,7 @@ import { WEBAPP_URL } from "@calcom/lib/constants";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { encodeOAuthState } from "../../_utils/encodeOAuthState";
import { getZoomAppKeys } from "../lib";
async function handler(req: NextApiRequest) {
@@ -19,11 +20,13 @@ async function handler(req: NextApiRequest) {
});
const { client_id } = await getZoomAppKeys();
const state = encodeOAuthState(req);
const params = {
response_type: "code",
client_id,
redirect_uri: WEBAPP_URL + "/api/integrations/zoomvideo/callback",
state,
};
const query = stringify(params);
const url = `https://zoom.us/oauth/authorize?${query}`;
+2 -14
View File
@@ -3,6 +3,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import createOAuthAppCredential from "../../_utils/createOAuthAppCredential";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import { getZoomAppKeys } from "../lib";
@@ -69,20 +70,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
}
await prisma.user.update({
where: {
id: req.session?.user.id,
},
data: {
credentials: {
create: {
type: "zoom_video",
key: responseBody,
appId: "zoom",
},
},
},
});
createOAuthAppCredential({ appId: "zoom", type: "zoom_video" }, responseBody, req);
res.redirect(getInstalledAppPath({ variant: "conferencing", slug: "zoom" }));
}
+2 -2
View File
@@ -404,7 +404,7 @@ export default class EventManager {
* @param event
* @private
*/
private createVideoEvent(event: CalendarEvent) {
private async createVideoEvent(event: CalendarEvent) {
const credential = this.getVideoCredential(event);
if (credential) {
@@ -538,7 +538,7 @@ export default class EventManager {
* @param booking
* @private
*/
private updateVideoEvent(event: CalendarEvent, booking: PartialBooking) {
private async updateVideoEvent(event: CalendarEvent, booking: PartialBooking) {
const credential = this.getVideoCredential(event);
if (credential) {
@@ -6,12 +6,14 @@ interface DisconnectIntegrationModalProps {
credentialId: number | null;
isOpen: boolean;
handleModelClose: () => void;
teamId?: number;
}
export default function DisconnectIntegrationModal({
credentialId,
isOpen,
handleModelClose,
teamId,
}: DisconnectIntegrationModalProps) {
const { t } = useLocale();
const utils = trpc.useContext();
@@ -31,17 +33,17 @@ export default function DisconnectIntegrationModal({
return (
<Dialog open={isOpen} onOpenChange={handleModelClose}>
<ConfirmationDialogContent
variety="danger"
title={t("remove_app")}
confirmBtnText={t("yes_remove_app")}
onConfirm={() => {
if (credentialId) {
mutation.mutate({ id: credentialId });
}
}}>
<p className="mt-5">{t("are_you_sure_you_want_to_remove_this_app")}</p>
</ConfirmationDialogContent>
<ConfirmationDialogContent
variety="danger"
title={t("remove_app")}
confirmBtnText={t("yes_remove_app")}
onConfirm={() => {
if (credentialId) {
mutation.mutate({ id: credentialId, teamId });
}
}}>
<p className="mt-5">{t("are_you_sure_you_want_to_remove_this_app")}</p>
</ConfirmationDialogContent>
</Dialog>
);
}
@@ -25,7 +25,7 @@ import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import { BookingStatus, MembershipRole, WorkflowMethods } from "@calcom/prisma/enums";
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
import type { IAbstractPaymentService, PaymentApp } from "@calcom/types/PaymentService";
async function getBookingToDelete(id: number | undefined, uid: string | undefined) {
return await prisma.booking.findUnique({
@@ -445,7 +445,10 @@ async function handler(req: CustomRequest) {
/** TODO: Remove this without breaking functionality */
if (bookingToDelete.location === DailyLocationType) {
bookingToDelete.user.credentials.push(FAKE_DAILY_CREDENTIAL);
bookingToDelete.user.credentials.push({
...FAKE_DAILY_CREDENTIAL,
teamId: bookingToDelete.eventType?.teamId || null,
});
}
const apiDeletes = [];
@@ -593,8 +596,10 @@ async function handler(req: CustomRequest) {
}
// Posible to refactor TODO:
const paymentApp = await appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore]();
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
const paymentApp = (await appStore[
paymentAppCredential?.app?.dirName as keyof typeof appStore
]()) as PaymentApp;
if (!paymentApp?.lib?.PaymentService) {
console.warn(`payment App service of type ${paymentApp} is not implemented`);
return null;
}
@@ -1544,7 +1544,9 @@ async function handler(
if (!Number.isNaN(paymentAppData.price) && paymentAppData.price > 0 && !!booking) {
const credentialPaymentAppCategories = await prisma.credential.findMany({
where: {
userId: organizerUser.id,
...(paymentAppData.credentialId
? { id: paymentAppData.credentialId }
: { userId: organizerUser.id }),
app: {
categories: {
hasSome: ["payment"],
@@ -1769,7 +1771,9 @@ async function handler(
await prisma.credential.findFirstOrThrow({
where: {
appId: paymentAppData.appId,
userId: organizerUser.id,
...(paymentAppData.credentialId
? { id: paymentAppData.credentialId }
: { userId: organizerUser.id }),
},
select: {
id: true,
@@ -2084,7 +2088,7 @@ async function handler(
// Load credentials.app.categories
const credentialPaymentAppCategories = await prisma.credential.findMany({
where: {
userId: organizerUser.id,
...(paymentAppData.credentialId ? { id: paymentAppData.credentialId } : { userId: organizerUser.id }),
app: {
categories: {
hasSome: ["payment"],
@@ -8,7 +8,7 @@ import type { _EventTypeModel } from "@calcom/prisma/zod/eventtype";
import { Tooltip } from "@calcom/ui";
import { Lock } from "@calcom/ui/components/icon";
const Indicator = (label: string) => (
export const LockedIndicator = (label: string) => (
<Tooltip content={<>{label}</>}>
<div className="bg -mt-0.5 ml-1 inline-flex h-4 w-4 rounded-sm p-0.5">
<Lock className="text-subtle hover:text-muted h-3 w-3" />
@@ -39,7 +39,7 @@ const useLockedFieldsManager = (
} else {
locked = locked && unlockedFields[fieldName as keyof Omit<Prisma.EventTypeSelect, "id">] === undefined;
}
return locked && Indicator(isManagedEventType ? adminLabel : memberLabel);
return locked && LockedIndicator(isManagedEventType ? adminLabel : memberLabel);
};
const shouldLockDisableProps = (fieldName: string) => {
@@ -90,7 +90,7 @@ export const AddNewTeamsForm = () => {
disabled={createTeamsMutation.isLoading}
onClick={() => {
if (inputValues.includes("")) {
showToast(t("team_name_empty"), "error");
showToast(t("team_names_empty"), "error");
} else {
const duplicates = inputValues.filter((item, index) => inputValues.indexOf(item) !== index);
if (duplicates.length) {
@@ -0,0 +1,91 @@
import type { Prisma } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
export type UserAdminTeams = (Prisma.TeamGetPayload<{
select: {
id: true;
name: true;
logo: true;
credentials?: true;
parent?: {
select: {
id: true;
name: true;
logo: true;
credentials: true;
};
};
};
}> & { isUser?: boolean })[];
/** Get a user's team & orgs they are admins/owners of. Abstracted to a function to call in tRPC endpoint and SSR. */
const getUserAdminTeams = async ({
userId,
getUserInfo,
getParentInfo,
includeCredentials = false,
}: {
userId: number;
getUserInfo?: boolean;
getParentInfo?: boolean;
includeCredentials?: boolean;
}): Promise<UserAdminTeams> => {
const teams = await prisma.team.findMany({
where: {
members: {
some: {
userId: userId,
accepted: true,
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
},
},
},
select: {
id: true,
name: true,
logo: true,
...(includeCredentials && { credentials: true }),
...(getParentInfo && {
parent: {
select: {
id: true,
name: true,
logo: true,
credentials: true,
},
},
}),
},
});
if (teams.length && getUserInfo) {
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
id: true,
name: true,
avatar: true,
...(includeCredentials && { credentials: true }),
},
});
if (user) {
const userObject = {
id: user.id,
name: user.name || "Nameless",
logo: user?.avatar,
isUser: true,
...(includeCredentials && { credentials: user.credentials }),
};
teams.unshift(userObject);
}
}
return teams;
};
export default getUserAdminTeams;
+3
View File
@@ -109,10 +109,13 @@ export default async function getEventTypeById({
teamId: true,
},
},
teamId: true,
team: {
select: {
id: true,
name: true,
slug: true,
parentId: true,
members: {
where: {
accepted: true,
+20
View File
@@ -0,0 +1,20 @@
import { CAL_URL, WEBAPP_URL } from "./constants";
/**
* It is a simpler(no HTTP request) alternative to get full URL of a path
* Should be used on app.cal.com Pages and not Booking Pages(which can be accessed through website URL also)
*/
export function getOrgAwareUrlOnClient(path: string) {
if (!path.startsWith("/")) {
throw new Error("path must start with /");
}
const documentURLObj = new URL(document.URL);
const webAppUrlObj = new URL(WEBAPP_URL);
const isNonOrgDomain = documentURLObj.host === webAppUrlObj.host;
if (isNonOrgDomain) {
return `${CAL_URL}${path}`;
}
return `${documentURLObj.href.replace(/\/$/, "")}${path}`;
}
export default getOrgAwareUrlOnClient;
+9 -1
View File
@@ -28,6 +28,7 @@ export default function getPaymentAppData(
currency: string;
appId: EventTypeAppsList | null;
paymentOption: typeof paymentOptionEnum;
credentialId?: number;
} | null = null;
for (const appId of paymentAppIds) {
const appData = getEventTypeAppData(eventType, appId, forcedGet);
@@ -41,6 +42,13 @@ export default function getPaymentAppData(
// This is the current expectation of system to have price and currency set always(using DB Level defaults).
// Newly added apps code should assume that their app data might not be set.
return (
paymentAppData || { enabled: false, price: 0, currency: "usd", appId: null, paymentOption: "ON_BOOKING" }
paymentAppData || {
enabled: false,
price: 0,
currency: "usd",
appId: null,
paymentOption: "ON_BOOKING",
credentialId: undefined,
}
);
}
+5 -3
View File
@@ -2,7 +2,7 @@ import type { Payment, Prisma } from "@prisma/client";
import appStore from "@calcom/app-store";
import type { AppCategories } from "@calcom/prisma/enums";
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
import type { IAbstractPaymentService, PaymentApp } from "@calcom/types/PaymentService";
const deletePayment = async (
paymentId: Payment["id"],
@@ -15,8 +15,10 @@ const deletePayment = async (
} | null;
}
): Promise<boolean> => {
const paymentApp = await appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore]();
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
const paymentApp = (await appStore[
paymentAppCredentials?.app?.dirName as keyof typeof appStore
]()) as PaymentApp;
if (!paymentApp?.lib?.PaymentService) {
console.warn(`payment App service of type ${paymentApp} is not implemented`);
return false;
}
+5 -3
View File
@@ -4,7 +4,7 @@ import appStore from "@calcom/app-store";
import type { EventTypeAppsList } from "@calcom/app-store/utils";
import type { EventTypeModel } from "@calcom/prisma/zod";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
import type { IAbstractPaymentService, PaymentApp } from "@calcom/types/PaymentService";
const handlePayment = async (
evt: CalendarEvent,
@@ -25,8 +25,10 @@ const handlePayment = async (
},
bookerEmail: string
) => {
const paymentApp = await appStore[paymentAppCredentials?.app?.dirName as keyof typeof appStore]();
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
const paymentApp = (await appStore[
paymentAppCredentials?.app?.dirName as keyof typeof appStore
]()) as PaymentApp;
if (!paymentApp?.lib?.PaymentService) {
console.warn(`payment App service of type ${paymentApp} is not implemented`);
return null;
}
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "Credential" ADD COLUMN "teamId" INTEGER;
-- AddForeignKey
ALTER TABLE "Credential" ADD CONSTRAINT "Credential_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+3
View File
@@ -126,6 +126,8 @@ model Credential {
key Json
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
teamId Int?
app App? @relation(fields: [appId], references: [slug], onDelete: Cascade)
// How to make it a required column?
appId String?
@@ -274,6 +276,7 @@ model Team {
timeZone String @default("Europe/London")
weekStart String @default("Sunday")
routingForms App_RoutingForms_Form[]
credentials Credential[]
@@unique([slug, parentId])
}
+1
View File
@@ -6,6 +6,7 @@ export const safeCredentialSelect = Prisma.validator<Prisma.CredentialSelect>()(
/** Omitting to avoid frontend leaks */
// key: true,
userId: true,
teamId: true,
appId: true,
invalid: true,
});
+1
View File
@@ -136,6 +136,7 @@ export const eventTypeLocations = z.array(
link: z.string().url().optional(),
displayLocationPublicly: z.boolean().optional(),
hostPhoneNumber: z.string().optional(),
credentialId: z.number().optional(),
})
);
@@ -51,6 +51,7 @@ export async function getUserFromSession(ctx: TRPCContextInner, session: Maybe<S
userId: true,
appId: true,
invalid: true,
teamId: true,
},
orderBy: {
id: "asc",
@@ -2,7 +2,6 @@ import authedProcedure from "../../procedures/authedProcedure";
import { router } from "../../trpc";
import { ZAppByIdInputSchema } from "./appById.schema";
import { ZAppCredentialsByTypeInputSchema } from "./appCredentialsByType.schema";
import { ZAppsInputSchema } from "./apps.schema";
import { ZAwayInputSchema } from "./away.schema";
import { ZConnectedCalendarsInputSchema } from "./connectedCalendars.schema";
import { ZDeleteCredentialInputSchema } from "./deleteCredential.schema";
@@ -11,6 +10,7 @@ import { ZEventTypeOrderInputSchema } from "./eventTypeOrder.schema";
import { ZGetCalVideoRecordingsInputSchema } from "./getCalVideoRecordings.schema";
import { ZGetDownloadLinkOfCalVideoRecordingsInputSchema } from "./getDownloadLinkOfCalVideoRecordings.schema";
import { ZIntegrationsInputSchema } from "./integrations.schema";
import { ZLocationOptionsInputSchema } from "./locationOptions.schema";
import { ZSetDestinationCalendarInputSchema } from "./setDestinationCalendar.schema";
import { ZSubmitFeedbackInputSchema } from "./submitFeedback.schema";
import { ZUpdateProfileInputSchema } from "./updateProfile.schema";
@@ -27,7 +27,6 @@ type AppsRouterHandlerCache = {
setDestinationCalendar?: typeof import("./setDestinationCalendar.handler").setDestinationCalendarHandler;
integrations?: typeof import("./integrations.handler").integrationsHandler;
appById?: typeof import("./appById.handler").appByIdHandler;
apps?: typeof import("./apps.handler").appsHandler;
appCredentialsByType?: typeof import("./appCredentialsByType.handler").appCredentialsByTypeHandler;
stripeCustomer?: typeof import("./stripeCustomer.handler").stripeCustomerHandler;
updateProfile?: typeof import("./updateProfile.handler").updateProfileHandler;
@@ -171,19 +170,6 @@ export const loggedInViewerRouter = router({
return UNSTABLE_HANDLER_CACHE.appById({ ctx, input });
}),
apps: authedProcedure.input(ZAppsInputSchema).query(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.apps) {
UNSTABLE_HANDLER_CACHE.apps = (await import("./apps.handler")).appsHandler;
}
// Unreachable code but required for type safety
if (!UNSTABLE_HANDLER_CACHE.apps) {
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.apps({ ctx, input });
}),
appCredentialsByType: authedProcedure
.input(ZAppCredentialsByTypeInputSchema)
.query(async ({ ctx, input }) => {
@@ -260,7 +246,7 @@ export const loggedInViewerRouter = router({
return UNSTABLE_HANDLER_CACHE.submitFeedback({ ctx, input });
}),
locationOptions: authedProcedure.query(async ({ ctx }) => {
locationOptions: authedProcedure.input(ZLocationOptionsInputSchema).query(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.locationOptions) {
UNSTABLE_HANDLER_CACHE.locationOptions = (
await import("./locationOptions.handler")
@@ -272,7 +258,7 @@ export const loggedInViewerRouter = router({
throw new Error("Failed to load handler");
}
return UNSTABLE_HANDLER_CACHE.locationOptions({ ctx });
return UNSTABLE_HANDLER_CACHE.locationOptions({ ctx, input });
}),
deleteCredential: authedProcedure.input(ZDeleteCredentialInputSchema).mutation(async ({ ctx, input }) => {
@@ -1,3 +1,5 @@
import getUserAdminTeams from "@calcom/features/ee/teams/lib/getUserAdminTeams";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TAppCredentialsByTypeInputSchema } from "./appCredentialsByType.schema";
@@ -9,7 +11,34 @@ type AppCredentialsByTypeOptions = {
input: TAppCredentialsByTypeInputSchema;
};
/** Used for grabbing credentials on specific app pages */
export const appCredentialsByTypeHandler = async ({ ctx, input }: AppCredentialsByTypeOptions) => {
const { user } = ctx;
return user.credentials.filter((app) => app.type == input.appType).map((credential) => credential.id);
const userAdminTeams = await getUserAdminTeams({ userId: ctx.user.id, getUserInfo: true });
const teamIds = userAdminTeams.reduce((teamIds, team) => {
if (!team.isUser) teamIds.push(team.id);
return teamIds;
}, [] as number[]);
const credentials = await prisma.credential.findMany({
where: {
OR: [
{ userId: user.id },
{
teamId: {
in: teamIds,
},
},
],
type: input.appType,
},
});
// For app pages need to return which teams the user can install the app on
// return user.credentials.filter((app) => app.type == input.appType).map((credential) => credential.id);
return {
credentials,
userAdminTeams,
};
};
@@ -1,24 +0,0 @@
import getEnabledApps from "@calcom/lib/apps/getEnabledApps";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TAppsInputSchema } from "./apps.schema";
type AppsOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TAppsInputSchema;
};
export const appsHandler = async ({ ctx, input }: AppsOptions) => {
const { user } = ctx;
const { credentials } = user;
const apps = await getEnabledApps(credentials);
return apps
.filter((app) => app.extendsFeature?.includes(input.extendsFeature))
.map((app) => ({
...app,
isInstalled: !!app.credentials?.length,
}));
};
@@ -1,7 +0,0 @@
import { z } from "zod";
export const ZAppsInputSchema = z.object({
extendsFeature: z.literal("EventType"),
});
export type TAppsInputSchema = z.infer<typeof ZAppsInputSchema>;
@@ -26,12 +26,12 @@ type DeleteCredentialOptions = {
};
export const deleteCredentialHandler = async ({ ctx, input }: DeleteCredentialOptions) => {
const { id, externalId } = input;
const { id, externalId, teamId } = input;
const credential = await prisma.credential.findFirst({
where: {
id: id,
userId: ctx.user.id,
...(teamId ? { teamId } : { userId: ctx.user.id }),
},
select: {
key: true,
@@ -3,6 +3,7 @@ import { z } from "zod";
export const ZDeleteCredentialInputSchema = z.object({
id: z.number(),
externalId: z.string().optional(),
teamId: z.number().optional(),
});
export type TDeleteCredentialInputSchema = z.infer<typeof ZDeleteCredentialInputSchema>;
@@ -1,7 +1,10 @@
import getEnabledApps from "@calcom/lib/apps/getEnabledApps";
import prisma from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TIntegrationsInputSchema } from "./integrations.schema";
import type { Prisma, Credential } from ".prisma/client";
type IntegrationsOptions = {
ctx: {
@@ -10,23 +13,129 @@ type IntegrationsOptions = {
input: TIntegrationsInputSchema;
};
type TeamQuery = Prisma.TeamGetPayload<{
select: {
id: true;
credentials?: true;
name: true;
logo: true;
members: {
select: {
role: true;
};
};
};
}>;
// type TeamQueryWithParent = TeamQuery & {
// parent?: TeamQuery | null;
// };
export const integrationsHandler = async ({ ctx, input }: IntegrationsOptions) => {
const { user } = ctx;
const { variant, exclude, onlyInstalled } = input;
const { credentials } = user;
const { variant, exclude, onlyInstalled, includeTeamInstalledApps, extendsFeature, teamId } = input;
let { credentials } = 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: true,
name: true,
logo: true,
members: {
where: {
userId: user.id,
},
select: {
role: true,
},
},
parent: {
select: {
id: true,
credentials: true,
name: true,
logo: 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);
parentTeams.push(parent);
}
});
}
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials: Credential[] = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? teamApp.credentials.flat() : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
} else {
credentials = credentials.concat(teamAppCredentials);
}
}
const enabledApps = await getEnabledApps(credentials);
//TODO: Refactor this to pick up only needed fields and prevent more leaking
let apps = enabledApps.map(
({ credentials: _, credential: _1, key: _2 /* don't leak to frontend */, ...app }) => {
const credentialIds = credentials.filter((c) => c.type === app.type).map((c) => c.id);
const userCredentialIds = credentials.filter((c) => c.type === app.type && !c.teamId).map((c) => c.id);
const invalidCredentialIds = credentials
.filter((c) => c.type === app.type && c.invalid)
.map((c) => c.id);
const teams = credentials
.filter((c) => c.type === app.type && c.teamId)
.map((c) => {
const team = userTeams.find((team) => team.id === c.teamId);
if (!team) {
return null;
}
return {
teamId: team.id,
name: team.name,
logo: team.logo,
credentialId: c.id,
isAdmin:
team.members[0].role === MembershipRole.ADMIN || team.members[0].role === MembershipRole.OWNER,
};
});
return {
...app,
credentialIds,
...(teams.length && { credentialOwner: { name: user.name, avatar: user.avatar } }),
userCredentialIds,
invalidCredentialIds,
teams,
isInstalled: !!userCredentialIds.length || !!teams.length || app.isGlobal,
};
}
);
@@ -44,8 +153,20 @@ export const integrationsHandler = async ({ ctx, input }: IntegrationsOptions) =
}
if (onlyInstalled) {
apps = apps.flatMap((item) => (item.credentialIds.length > 0 || item.isGlobal ? [item] : []));
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,
}));
}
return {
items: apps,
};
@@ -4,6 +4,9 @@ export const ZIntegrationsInputSchema = z.object({
variant: z.string().optional(),
exclude: z.array(z.string()).optional(),
onlyInstalled: z.boolean().optional(),
includeTeamInstalledApps: z.boolean().optional(),
extendsFeature: z.literal("EventType").optional(),
teamId: z.union([z.number(), z.null()]).optional(),
});
export type TIntegrationsInputSchema = z.infer<typeof ZIntegrationsInputSchema>;
@@ -2,18 +2,27 @@ import { getLocationGroupedOptions } from "@calcom/app-store/utils";
import getEnabledApps from "@calcom/lib/apps/getEnabledApps";
import { getTranslation } from "@calcom/lib/server/i18n";
import { prisma } from "@calcom/prisma";
import { AppCategories } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TLocationOptionsInputSchema } from "./locationOptions.schema";
type LocationOptionsOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TLocationOptionsInputSchema;
};
export const locationOptionsHandler = async ({ ctx }: LocationOptionsOptions) => {
export const locationOptionsHandler = async ({ ctx, input }: LocationOptionsOptions) => {
const credentials = await prisma.credential.findMany({
where: {
userId: ctx.user.id,
app: {
categories: {
has: AppCategories.video,
},
},
},
select: {
id: true,
@@ -30,6 +39,14 @@ export const locationOptionsHandler = async ({ ctx }: LocationOptionsOptions) =>
const t = await getTranslation(ctx.user.locale ?? "en", "common");
const locationOptions = getLocationGroupedOptions(integrations, t);
// If it is a team event then move the "use host location" option to top
if (input.teamId) {
const conferencingIndex = locationOptions.findIndex((option) => option.label === "Conferencing");
if (conferencingIndex !== -1) {
const conferencingObject = locationOptions.splice(conferencingIndex, 1)[0];
locationOptions.unshift(conferencingObject);
}
}
return locationOptions;
};
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more