Fix type name clashing for eslint parser (#10491)

This commit is contained in:
Danila authored and GitHub committed 2023-08-01 15:55:31 +00:00
1 parent 17855251ff
commit 7c64b6a6e2
3 files changed
+111 -89

No files matched your search

+42 -31
View File
@@ -1,23 +1,22 @@
import Link from "next/link"; import Link from "next/link";
import type { IframeHTMLAttributes } from "react"; import type { IframeHTMLAttributes } from "react";
import React, { useState, useEffect } from "react"; import React, { useState } from "react";
import { useRouter } from "next/router";
import { CAL_URL } from "@calcom/lib/constants";
import type { RouterOutputs } from "@calcom/trpc/react";
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation"; import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
import { InstallAppButton, AppDependencyComponent } from "@calcom/app-store/components"; import { InstallAppButton, AppDependencyComponent } from "@calcom/app-store/components";
import DisconnectIntegration from "@calcom/features/apps/components/DisconnectIntegration"; import DisconnectIntegration from "@calcom/features/apps/components/DisconnectIntegration";
import { Spinner } from "@calcom/features/calendars/weeklyview/components/spinner/Spinner";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired"; import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import type { UserAdminTeams } from "@calcom/features/ee/teams/lib/getUserAdminTeams"; import type { UserAdminTeams } from "@calcom/features/ee/teams/lib/getUserAdminTeams";
import Shell from "@calcom/features/shell/Shell"; import Shell from "@calcom/features/shell/Shell";
import classNames from "@calcom/lib/classNames"; import classNames from "@calcom/lib/classNames";
import { CAL_URL } from "@calcom/lib/constants";
import { APP_NAME, COMPANY_NAME, SUPPORT_MAIL_ADDRESS } from "@calcom/lib/constants"; import { APP_NAME, COMPANY_NAME, SUPPORT_MAIL_ADDRESS } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react"; import { trpc } from "@calcom/trpc/react";
import type { App as AppType } from "@calcom/types/App"; import type { App as AppType, AppFrontendPayload } from "@calcom/types/App";
import type { ButtonProps } from "@calcom/ui"; import type { ButtonProps } from "@calcom/ui";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import { Button, showToast, SkeletonButton, SkeletonText, HeadSeo, Badge } from "@calcom/ui"; import { Button, showToast, SkeletonButton, SkeletonText, HeadSeo, Badge } from "@calcom/ui";
import { import {
Dropdown, Dropdown,
@@ -28,9 +27,7 @@ import {
DropdownItem, DropdownItem,
Avatar, Avatar,
} from "@calcom/ui"; } from "@calcom/ui";
import { BookOpen, Check, ExternalLink, File, Flag, Mail, Plus, Shield } from "@calcom/ui/components/icon"; import { BookOpen, Check, ExternalLink, File, Flag, Mail, Shield } from "@calcom/ui/components/icon";
import { Spinner } from "@calcom/features/calendars/weeklyview/components/spinner/Spinner";
/* These app slugs all require Google Cal to be installed */ /* These app slugs all require Google Cal to be installed */
@@ -82,9 +79,11 @@ const Component = ({
{ appType: type }, { appType: type },
{ {
onSettled(data) { onSettled(data) {
const credentialsCount = data?.credentials.length || 0 const credentialsCount = data?.credentials.length || 0;
setShowDisconnectIntegration(data?.userAdminTeams.length ? credentialsCount >= data?.userAdminTeams.length : credentialsCount > 0); setShowDisconnectIntegration(
setExistingCredentials(data?.credentials.map(credential => credential.id) || []); data?.userAdminTeams.length ? credentialsCount >= data?.userAdminTeams.length : credentialsCount > 0
);
setExistingCredentials(data?.credentials.map((credential) => credential.id) || []);
}, },
} }
); );
@@ -186,7 +185,13 @@ const Component = ({
}; };
} }
return ( return (
<InstallAppButtonChild appCategories={categories} userAdminTeams={appDbQuery.data?.userAdminTeams} addAppMutationInput={{ type, variant, slug }} multiInstall {...props} /> <InstallAppButtonChild
appCategories={categories}
userAdminTeams={appDbQuery.data?.userAdminTeams}
addAppMutationInput={{ type, variant, slug }}
multiInstall
{...props}
/>
); );
}} }}
/> />
@@ -217,7 +222,13 @@ const Component = ({
}; };
} }
return ( return (
<InstallAppButtonChild appCategories={categories} userAdminTeams={appDbQuery.data?.userAdminTeams} addAppMutationInput={{ type, variant, slug }} credentials={appDbQuery.data?.credentials} {...props} /> <InstallAppButtonChild
appCategories={categories}
userAdminTeams={appDbQuery.data?.userAdminTeams}
addAppMutationInput={{ type, variant, slug }}
credentials={appDbQuery.data?.credentials}
{...props}
/>
); );
}} }}
/> />
@@ -398,13 +409,12 @@ const InstallAppButtonChild = ({
...props ...props
}: { }: {
userAdminTeams?: UserAdminTeams; userAdminTeams?: UserAdminTeams;
addAppMutationInput: { type: App["type"]; variant: string; slug: string }; addAppMutationInput: { type: AppFrontendPayload["type"]; variant: string; slug: string };
appCategories: string[]; appCategories: string[];
multiInstall?: boolean; multiInstall?: boolean;
credentials?: RouterOutputs["viewer"]["appCredentialsByType"]["credentials"]; credentials?: RouterOutputs["viewer"]["appCredentialsByType"]["credentials"];
} & ButtonProps) => { } & ButtonProps) => {
const { t } = useLocale(); const { t } = useLocale();
const router = useRouter();
const mutation = useAddAppMutation(null, { const mutation = useAddAppMutation(null, {
onSuccess: (data) => { onSuccess: (data) => {
@@ -416,8 +426,12 @@ const InstallAppButtonChild = ({
}, },
}); });
if (!userAdminTeams?.length || appCategories.some((category) => ["calendar", "conferencing"].includes(category))) { if (
return <Button !userAdminTeams?.length ||
appCategories.some((category) => ["calendar", "conferencing"].includes(category))
) {
return (
<Button
data-testid="install-app-button" data-testid="install-app-button"
{...props} {...props}
// @TODO: Overriding color and size prevent us from // @TODO: Overriding color and size prevent us from
@@ -426,7 +440,7 @@ const InstallAppButtonChild = ({
size="base"> size="base">
{multiInstall ? t("install_another") : t("install_app")} {multiInstall ? t("install_another") : t("install_app")}
</Button> </Button>
);
} }
return ( return (
@@ -446,8 +460,7 @@ const InstallAppButtonChild = ({
<DropdownMenuContent <DropdownMenuContent
onInteractOutside={(event) => { onInteractOutside={(event) => {
if (mutation.isLoading) event.preventDefault(); if (mutation.isLoading) event.preventDefault();
}} }}>
>
{mutation.isLoading && ( {mutation.isLoading && (
<div className="z-1 fixed inset-0 flex items-center justify-center bg-black bg-opacity-50"> <div className="z-1 fixed inset-0 flex items-center justify-center bg-black bg-opacity-50">
<Spinner /> <Spinner />
@@ -455,20 +468,18 @@ const InstallAppButtonChild = ({
)} )}
<DropdownMenuLabel>{t("install_app_on")}</DropdownMenuLabel> <DropdownMenuLabel>{t("install_app_on")}</DropdownMenuLabel>
{userAdminTeams.map((team) => { {userAdminTeams.map((team) => {
const isInstalled =
const isInstalled = credentials && credentials &&
credentials.some((credential) => credentials.some((credential) =>
credential?.teamId ? credential?.teamId === team.id : credential.userId === team.id credential?.teamId ? credential?.teamId === team.id : credential.userId === team.id
) );
return ( return (
<DropdownItem <DropdownItem
type="button" type="button"
data-testid={team.isUser ? "install-app-button-personal" : "anything else"} data-testid={team.isUser ? "install-app-button-personal" : "anything else"}
key={team.id} key={team.id}
disabled={ disabled={isInstalled}
isInstalled
}
StartIcon={(props) => ( StartIcon={(props) => (
<Avatar <Avatar
alt={team.logo || ""} alt={team.logo || ""}
@@ -482,11 +493,11 @@ const InstallAppButtonChild = ({
team.isUser ? addAppMutationInput : { ...addAppMutationInput, teamId: team.id } team.isUser ? addAppMutationInput : { ...addAppMutationInput, teamId: team.id }
); );
}}> }}>
<p>{team.name}{" "} <p>
{isInstalled && {team.name} {isInstalled && `(${t("installed")})`}
`(${t("installed")})`}</p> </p>
</DropdownItem> </DropdownItem>
) );
})} })}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenuPortal> </DropdownMenuPortal>
+5 -1
View File
@@ -47,7 +47,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// set expiry date as offset from current time. // set expiry date as offset from current time.
hubspotToken.expiryDate = Math.round(Date.now() + hubspotToken.expiresIn * 1000); hubspotToken.expiryDate = Math.round(Date.now() + hubspotToken.expiresIn * 1000);
await createOAuthAppCredential({ appId: "hubspot", type: "hubspot_other_calendar" }, hubspotToken as any, req); await createOAuthAppCredential(
{ appId: "hubspot", type: "hubspot_other_calendar" },
hubspotToken as any,
req
);
const state = decodeOAuthState(req); const state = decodeOAuthState(req);
res.redirect( res.redirect(
@@ -1,11 +1,22 @@
import { describe, it, vi, expect } from "vitest"; import { describe, it, vi, expect } from "vitest";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { checkInputEmailIsValid, checkPermissions, getEmailsToInvite, getIsOrgVerified, getOrgConnectionInfo, throwIfInviteIsToOrgAndUserExists,createAndAutoJoinIfInOrg } from "./utils";
import { MembershipRole } from "@calcom/prisma/enums";
import { isTeamAdmin } from "@calcom/lib/server/queries"; import { isTeamAdmin } from "@calcom/lib/server/queries";
import { TRPCError } from "@trpc/server"; import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import type { TeamWithParent } from "./types";
import type { User } from "@calcom/prisma/client"; import type { User } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import type { TeamWithParent } from "./types";
import {
checkInputEmailIsValid,
checkPermissions,
getEmailsToInvite,
getIsOrgVerified,
getOrgConnectionInfo,
throwIfInviteIsToOrgAndUserExists,
createAndAutoJoinIfInOrg,
} from "./utils";
vi.mock("@calcom/lib/server/queries", () => { vi.mock("@calcom/lib/server/queries", () => {
return { return {
@@ -19,7 +30,14 @@ vi.mock("@calcom/lib/server/queries/organisations", () => {
}; };
}); });
const mockedReturnSuccessCheckPerms = { accepted: true, disableImpersonation: false, id: 1, role: MembershipRole.ADMIN, userId: 1, teamId: 1 } const mockedReturnSuccessCheckPerms = {
accepted: true,
disableImpersonation: false,
id: 1,
role: MembershipRole.ADMIN,
userId: 1,
teamId: 1,
};
const mockedTeam: TeamWithParent = { const mockedTeam: TeamWithParent = {
id: 1, id: 1,
@@ -41,20 +59,20 @@ const mockedTeam: TeamWithParent = {
metadata: null, metadata: null,
parentId: null, parentId: null,
parent: null, parent: null,
isPrivate:false isPrivate: false,
}; };
const mockUser: User = { const mockUser: User = {
id: 4, id: 4,
username: 'pro', username: "pro",
name: 'Pro Example', name: "Pro Example",
email: '[email protected]', email: "[email protected]",
emailVerified: new Date(), emailVerified: new Date(),
password: '', password: "",
bio: null, bio: null,
avatar: null, avatar: null,
timeZone: 'Europe/London', timeZone: "Europe/London",
weekStart: 'Sunday', weekStart: "Sunday",
startTime: 0, startTime: 0,
endTime: 1440, endTime: 1440,
bufferTime: 0, bufferTime: 0,
@@ -64,78 +82,76 @@ const mockUser: User = {
trialEndsAt: null, trialEndsAt: null,
defaultScheduleId: null, defaultScheduleId: null,
completedOnboarding: true, completedOnboarding: true,
locale: 'en', locale: "en",
timeFormat: 12, timeFormat: 12,
twoFactorSecret: null, twoFactorSecret: null,
twoFactorEnabled: false, twoFactorEnabled: false,
identityProvider: 'CAL', identityProvider: "CAL",
identityProviderId: null, identityProviderId: null,
invitedTo: null, invitedTo: null,
brandColor: '#292929', brandColor: "#292929",
darkBrandColor: '#fafafa', darkBrandColor: "#fafafa",
away: false, away: false,
allowDynamicBooking: true, allowDynamicBooking: true,
metadata: null, metadata: null,
verified: false, verified: false,
role: 'USER', role: "USER",
disableImpersonation: false, disableImpersonation: false,
organizationId: null organizationId: null,
} };
describe("Invite Member Utils", () => { describe("Invite Member Utils", () => {
describe("checkPermissions", () => { describe("checkPermissions", () => {
it("It should throw an error if the user is not an admin of the ORG", async () => { it("It should throw an error if the user is not an admin of the ORG", async () => {
vi.mocked(isOrganisationAdmin).mockResolvedValue(false); vi.mocked(isOrganisationAdmin).mockResolvedValue(false);
await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).rejects.toThrow(); await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).rejects.toThrow();
}) });
it("It should NOT throw an error if the user is an admin of the ORG", async () => { it("It should NOT throw an error if the user is an admin of the ORG", async () => {
vi.mocked(isOrganisationAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms); vi.mocked(isOrganisationAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms);
await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).resolves.not.toThrow(); await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).resolves.not.toThrow();
}) });
it("It should throw an error if the user is not an admin of the team", async () => { it("It should throw an error if the user is not an admin of the team", async () => {
vi.mocked(isTeamAdmin).mockResolvedValue(false); vi.mocked(isTeamAdmin).mockResolvedValue(false);
await expect(checkPermissions({ userId: 1, teamId: 1 })).rejects.toThrow(); await expect(checkPermissions({ userId: 1, teamId: 1 })).rejects.toThrow();
}) });
it("It should NOT throw an error if the user is an admin of a team", async () => { it("It should NOT throw an error if the user is an admin of a team", async () => {
vi.mocked(isTeamAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms); vi.mocked(isTeamAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms);
await expect(checkPermissions({ userId: 1, teamId: 1 })).resolves.not.toThrow(); await expect(checkPermissions({ userId: 1, teamId: 1 })).resolves.not.toThrow();
}) });
}) });
describe('getEmailsToInvite', () => { describe("getEmailsToInvite", () => {
it('should throw a TRPCError with code BAD_REQUEST if no emails are provided', async () => { it("should throw a TRPCError with code BAD_REQUEST if no emails are provided", async () => {
await expect(getEmailsToInvite([])).rejects.toThrow(TRPCError); await expect(getEmailsToInvite([])).rejects.toThrow(TRPCError);
}); });
it('should return an array with one email if a string is provided', async () => { it("should return an array with one email if a string is provided", async () => {
const result = await getEmailsToInvite('[email protected]'); const result = await getEmailsToInvite("[email protected]");
expect(result).toEqual(['[email protected]']); expect(result).toEqual(["[email protected]"]);
}); });
it('should return an array with multiple emails if an array is provided', async () => { it("should return an array with multiple emails if an array is provided", async () => {
const result = await getEmailsToInvite(['[email protected]', '[email protected]']); const result = await getEmailsToInvite(["[email protected]", "[email protected]"]);
expect(result).toEqual(['[email protected]', '[email protected]']); expect(result).toEqual(["[email protected]", "[email protected]"]);
}); });
}); });
describe('checkInputEmailIsValid', () => { describe("checkInputEmailIsValid", () => {
it('should throw a TRPCError with code BAD_REQUEST if the email is invalid', () => { it("should throw a TRPCError with code BAD_REQUEST if the email is invalid", () => {
const invalidEmail = 'invalid-email'; const invalidEmail = "invalid-email";
expect(() => checkInputEmailIsValid(invalidEmail)).toThrow(TRPCError); expect(() => checkInputEmailIsValid(invalidEmail)).toThrow(TRPCError);
expect(() => checkInputEmailIsValid(invalidEmail)).toThrowError( expect(() => checkInputEmailIsValid(invalidEmail)).toThrowError(
'Invite failed because invalid-email is not a valid email address' "Invite failed because invalid-email is not a valid email address"
); );
}); });
it('should not throw an error if the email is valid', () => { it("should not throw an error if the email is valid", () => {
const validEmail = '[email protected]'; const validEmail = "[email protected]";
expect(() => checkInputEmailIsValid(validEmail)).not.toThrow(); expect(() => checkInputEmailIsValid(validEmail)).not.toThrow();
}); });
}); });
describe("getOrgConnectionInfo", () => { describe("getOrgConnectionInfo", () => {
const orgAutoAcceptDomain = "example.com"; const orgAutoAcceptDomain = "example.com";
const usersEmail = "[email protected]"; const usersEmail = "[email protected]";
it("should return orgId and autoAccept as true if team has parent and usersEmail domain matches orgAutoAcceptDomain and orgVerified is true", () => { it("should return orgId and autoAccept as true if team has parent and usersEmail domain matches orgAutoAcceptDomain and orgVerified is true", () => {
const result = getOrgConnectionInfo({ const result = getOrgConnectionInfo({
orgAutoAcceptDomain, orgAutoAcceptDomain,
@@ -264,7 +280,6 @@ describe("Invite Member Utils", () => {
}; };
const isOrg = false; const isOrg = false;
it("should not throw when inviting an existing user to the same organization", () => { it("should not throw when inviting an existing user to the same organization", () => {
const inviteeWithOrg: User = { const inviteeWithOrg: User = {
...invitee, ...invitee,
@@ -273,10 +288,8 @@ describe("Invite Member Utils", () => {
const teamWithOrg = { const teamWithOrg = {
...mockedTeam, ...mockedTeam,
parentId: 2, parentId: 2,
} };
expect(() => expect(() => throwIfInviteIsToOrgAndUserExists(inviteeWithOrg, teamWithOrg, isOrg)).not.toThrow();
throwIfInviteIsToOrgAndUserExists(inviteeWithOrg, teamWithOrg, isOrg)
).not.toThrow();
}); });
it("should throw a TRPCError with code FORBIDDEN if the invitee is already a member of another organization", () => { it("should throw a TRPCError with code FORBIDDEN if the invitee is already a member of another organization", () => {
const inviteeWithOrg: User = { const inviteeWithOrg: User = {
@@ -286,23 +299,17 @@ describe("Invite Member Utils", () => {
const teamWithOrg = { const teamWithOrg = {
...mockedTeam, ...mockedTeam,
parentId: 3, parentId: 3,
} };
expect(() => expect(() => throwIfInviteIsToOrgAndUserExists(inviteeWithOrg, teamWithOrg, isOrg)).toThrow(TRPCError);
throwIfInviteIsToOrgAndUserExists(inviteeWithOrg, teamWithOrg, isOrg)
).toThrow(TRPCError);
}); });
it("should throw a TRPCError with code FORBIDDEN if the invitee already exists in Cal.com and is being invited to an organization", () => { it("should throw a TRPCError with code FORBIDDEN if the invitee already exists in Cal.com and is being invited to an organization", () => {
const isOrg = true; const isOrg = true;
expect(() => expect(() => throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)).toThrow(TRPCError);
throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)
).toThrow(TRPCError);
}); });
it("should not throw an error if the invitee does not already belong to another organization and is not being invited to an organization", () => { it("should not throw an error if the invitee does not already belong to another organization and is not being invited to an organization", () => {
expect(() => expect(() => throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)).not.toThrow();
throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)
).not.toThrow();
}); });
}); });
describe("createAndAutoJoinIfInOrg", () => { describe("createAndAutoJoinIfInOrg", () => {
@@ -325,4 +332,4 @@ describe("Invite Member Utils", () => {
}); });
// TODO: Add test for when the user is already a member of the organization - need to mock prisma response value // TODO: Add test for when the user is already a member of the organization - need to mock prisma response value
}); });
}) });