chore: fix all Typescript warnings (#8618)

* [CAL-1517] fix all Typescript warnings

* solve conflicts

* Update stripeCheckoutSession.handler.ts

Parse is a guard, so even though the variable is unused the parse itself is needed.

* Update ToolbarPlugin.tsx

Don't change dependency tree

---------

Co-authored-by: gitstart-calcom <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-06-06 11:59:57 +00:00
1 parent 87e1ad7115
commit 2dbc73c75b
106 files changed
+425 -319

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ export const SnippedGenerator = {
// extend some internals to gain information about current path, method and spec in the generator function metioned later
spec: {
wrapSelectors: {
requestFor: (ori, system) => (state, path, method) => {
requestFor: (ori) => (state, path, method) => {
return ori(path, method)
?.set("spec", state.get("json", {}))
?.setIn(["oasPathMethod", "path"], path)
+1
View File
@@ -60,6 +60,7 @@ export default function AppListCard(props: AppListCardProps) {
timeoutRef.current = null;
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
+1 -1
View File
@@ -15,7 +15,7 @@ import { seoConfig } from "@lib/config/next-seo.config";
import I18nLanguageHandler from "@components/I18nLanguageHandler";
export interface CalPageWrapper {
(props?: any): JSX.Element;
(props?: AppProps): JSX.Element;
PageWrapper?: AppProps["Component"]["PageWrapper"];
}
@@ -1,3 +1,5 @@
import type { FunctionComponent, SVGProps } from "react";
import { InstallAppButton } from "@calcom/app-store/components";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
@@ -55,7 +57,7 @@ const AdditionalCalendarSelector = ({ isLoading }: AdditionalCalendarSelectorPro
<InstallAppButton
type={data.type}
render={(installProps) => {
const props = { ...installProps } as any;
const props = { ...installProps } as FunctionComponent<SVGProps<SVGSVGElement>>;
return (
<DropdownItem {...props} color="minimal" type="button">
<span className="flex items-center gap-x-2">
@@ -2,60 +2,12 @@ import type { ComponentProps } from "react";
import React from "react";
import AppCategoryNavigation from "@calcom/app-store/_components/AppCategoryNavigation";
import type { InstalledAppVariants } from "@calcom/app-store/utils";
import Shell from "@calcom/features/shell/Shell";
import { trpc } from "@calcom/trpc/react";
import type { HorizontalTabItemProps, VerticalTabItemProps } from "@calcom/ui";
import { BarChart, Calendar, CreditCard, Grid, Share2, Video } from "@calcom/ui/components/icon";
const tabs: (VerticalTabItemProps | HorizontalTabItemProps)[] = [
{
name: "calendar",
href: "/apps/installed/calendar",
icon: Calendar,
},
{
name: "conferencing",
href: "/apps/installed/conferencing",
icon: Video,
},
{
name: "payment",
href: "/apps/installed/payment",
icon: CreditCard,
},
{
name: "automation",
href: "/apps/installed/automation",
icon: Share2,
},
{
name: "analytics",
href: "/apps/installed/analytics",
icon: BarChart,
},
{
name: "other",
href: "/apps/installed/other",
icon: Grid,
},
];
export default function InstalledAppsLayout({
children,
...rest
}: { children: React.ReactNode } & ComponentProps<typeof Shell>) {
const variant: (typeof InstalledAppVariants)[number] = "payment";
const query = trpc.viewer.integrations.useQuery({
variant,
onlyInstalled: true,
});
let actualTabs = tabs;
if (query.data?.items.length === 0) {
actualTabs = tabs.filter((tab) => tab.name !== variant);
}
return (
<Shell {...rest} hideHeadingOnMobile>
<AppCategoryNavigation baseURL="/apps/installed" containerClassname="min-w-0 w-full">
@@ -65,7 +65,7 @@ export const EventAdvancedTab = ({ eventType, team }: Pick<EventTypeSetupProps,
const [requiresConfirmation, setRequiresConfirmation] = useState(eventType.requiresConfirmation);
const placeholderHashedLink = `${CAL_URL}/d/${hashedUrl}/${eventType.slug}`;
const seatsEnabled = formMethods.watch("seatsPerTimeSlotEnabled");
const noShowFeeEnabled = eventType.metadata.apps?.stripe?.paymentOption === "HOLD";
const noShowFeeEnabled = eventType.metadata?.apps?.stripe?.paymentOption === "HOLD";
useEffect(() => {
!hashedUrl && setHashedUrl(generateHashedLink(eventType.users[0]?.id ?? team?.id));
@@ -115,7 +115,7 @@ export const EventSetupTab = (
const [showLocationModal, setShowLocationModal] = useState(false);
const [editingLocationType, setEditingLocationType] = useState<string>("");
const [selectedLocation, setSelectedLocation] = useState<LocationOption | undefined>(undefined);
const [multipleDuration, setMultipleDuration] = useState(eventType.metadata.multipleDuration);
const [multipleDuration, setMultipleDuration] = useState(eventType.metadata?.multipleDuration);
const locationOptions = props.locationOptions.filter((option) => {
return !team ? option.label !== "Conferencing" : true;
@@ -75,8 +75,7 @@ function getNavigation(props: {
installedAppsNumber: number;
availability: AvailabilityOption | undefined;
}) {
const { eventType, t, enabledAppsNumber, installedAppsNumber, enabledWorkflowsNumber, availability } =
props;
const { eventType, t, enabledAppsNumber, installedAppsNumber, enabledWorkflowsNumber } = props;
const duration =
eventType.metadata?.multipleDuration?.map((duration) => ` ${duration}`) || eventType.length;
@@ -221,7 +220,18 @@ function EventTypeSingleLayout({
});
}
return navigation;
}, [t, eventType, installedAppsNumber, enabledAppsNumber, enabledWorkflowsNumber, team, availability]);
}, [
t,
eventType,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
availability,
isManagedEventType,
isChildrenManagedEventType,
team,
formMethods,
]);
const permalink = `${CAL_URL}/${team ? `team/${team.slug}` : eventType.users[0].username}/${
eventType.slug
@@ -237,7 +247,7 @@ function EventTypeSingleLayout({
heading={eventType.title}
CTA={
<div className="flex items-center justify-end">
{!eventType.metadata.managedEventConfig && (
{!eventType.metadata?.managedEventConfig && (
<>
<div
className={classNames(
@@ -39,6 +39,7 @@ export default function RequiresConfirmationController({
if (!requiresConfirmation) {
formMethods.setValue("metadata.requiresConfirmationThreshold", undefined);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [requiresConfirmation]);
const { shouldLockDisableProps } = useLockedFieldsManager(
@@ -24,7 +24,7 @@ interface IUserProfileProps {
const UserProfile = (props: IUserProfileProps) => {
const { user } = props;
const { t } = useLocale();
const avatarRef = useRef<HTMLInputElement>(null!);
const avatarRef = useRef<HTMLInputElement>(null);
const { setValue, handleSubmit, getValues } = useForm<FormData>({
defaultValues: { bio: user?.bio || "" },
});
@@ -76,7 +76,7 @@ const UserProfile = (props: IUserProfileProps) => {
async function updateProfileHandler(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const enteredAvatar = avatarRef.current.value;
const enteredAvatar = avatarRef.current?.value;
mutation.mutate({
avatar: enteredAvatar,
});
@@ -127,14 +127,16 @@ const UserProfile = (props: IUserProfileProps) => {
id="avatar-upload"
buttonMsg={t("add_profile_photo")}
handleAvatarChange={(newAvatar) => {
avatarRef.current.value = newAvatar;
if (avatarRef.current) {
avatarRef.current.value = newAvatar;
}
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
)?.set;
nativeInputValueSetter?.call(avatarRef.current, newAvatar);
const ev2 = new Event("input", { bubbles: true });
avatarRef.current.dispatchEvent(ev2);
avatarRef.current?.dispatchEvent(ev2);
updateProfileHandler(ev2 as unknown as FormEvent<HTMLFormElement>);
setImageSrc(newAvatar);
}}
+4 -2
View File
@@ -66,6 +66,7 @@ export function QueryCell<TData, TError extends ErrorLike>(
if ("empty" in opts && (query.data == null || (Array.isArray(query.data) && query.data.length === 0))) {
return opts.empty(query);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return opts.success(query as any);
}
@@ -88,9 +89,10 @@ const withQuery = <
TInput = inferProcedureInput<TQuery>,
TOutput = inferProcedureOutput<TQuery>
>(
queryProcedure: DecorateProcedure<TQuery, any, any>,
queryProcedure: DecorateProcedure<TQuery, inferProcedureInput<TQuery>, inferProcedureOutput<TQuery>>,
input?: TInput,
params?: UseTRPCQueryOptions<any, TInput, TOutput, TOutput, TError>
params?: UseTRPCQueryOptions<TQuery, TInput, TOutput, TOutput, TError>
) => {
return function WithQuery(
opts: Omit<
+2 -1
View File
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
type GetSSRResult<TProps> =
//
{ props: TProps } | { redirect: any } | { notFound: boolean };
{ props: TProps } | { redirect: { destination: string; permanent: boolean } } | { notFound: boolean };
type GetSSRFn<TProps> = (...args: any[]) => Promise<GetSSRResult<TProps>>;
+1
View File
@@ -19,6 +19,7 @@ export default function Page() {
callbackUrl: "/",
code,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
+4 -2
View File
@@ -111,8 +111,10 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
const ret = await samlTenantProduct(prisma, emailParam);
tenant = ret.tenant;
product = ret.product;
} catch (e: any) {
error = e.message;
} catch (e) {
if (e instanceof Error) {
error = e.message;
}
}
}
}
+2
View File
@@ -18,6 +18,7 @@ export default function Page({ samlTenantID, samlProductID }: inferSSRProps<type
if (HOSTED_CAL_FEATURES) {
router.push("/auth/login");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
@@ -29,6 +30,7 @@ export default function Page({ samlTenantID, samlProductID }: inferSSRProps<type
},
{ tenant: samlTenantID, product: samlProductID }
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
+2 -1
View File
@@ -105,7 +105,8 @@ export function AvailabilityList({ schedules }: RouterOutputs["viewer"]["availab
);
}
const WithQuery = withQuery(trpc.viewer.availability.list);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const WithQuery = withQuery(trpc.viewer.availability.list as any);
export default function AvailabilityPage() {
const { t } = useLocale();
+1 -1
View File
@@ -26,7 +26,7 @@ const AvailabilityView = ({ user }: { user: User }) => {
const { data, isLoading } = trpc.viewer.availability.user.useQuery(
{
username: user.username!,
username: user.username || "",
dateFrom: selectedDate.startOf("day").utc().format(),
dateTo: selectedDate.endOf("day").utc().format(),
withSource: true,
+1 -1
View File
@@ -102,7 +102,6 @@ export default function Success(props: SuccessProps) {
allRemainingBookings,
isSuccessBookingPage,
cancel: isCancellationMode,
changes,
formerTime,
email,
seatReferenceUid,
@@ -222,6 +221,7 @@ export default function Success(props: SuccessProps) {
setCalculatedDuration(
dayjs(props.bookingInfo.endTime).diff(dayjs(props.bookingInfo.startTime), "minutes")
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function eventLink(): string {
+42 -42
View File
@@ -3,7 +3,7 @@ import { useAutoAnimate } from "@formkit/auto-animate/react";
import { zodResolver } from "@hookform/resolvers/zod";
import type { GetServerSidePropsContext } from "next";
import { Trans } from "next-i18next";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
@@ -184,17 +184,17 @@ const EventTypePage = (props: EventTypeSetupProps) => {
const metadata = eventType.metadata;
// fallback to !!eventType.schedule when 'useHostSchedulesForTeamEvent' is undefined
if (!!team) {
if (!!team && metadata !== null) {
metadata.config = {
...metadata.config,
useHostSchedulesForTeamEvent:
typeof eventType.metadata.config?.useHostSchedulesForTeamEvent !== "undefined"
? eventType.metadata.config?.useHostSchedulesForTeamEvent === true
typeof eventType.metadata?.config?.useHostSchedulesForTeamEvent !== "undefined"
? eventType.metadata?.config?.useHostSchedulesForTeamEvent === true
: !!eventType.schedule,
};
} else {
// Make sure non-team events NEVER have this config key;
delete metadata.config?.useHostSchedulesForTeamEvent;
delete metadata?.config?.useHostSchedulesForTeamEvent;
}
const bookingFields: Prisma.JsonObject = {};
@@ -203,41 +203,43 @@ const EventTypePage = (props: EventTypeSetupProps) => {
bookingFields[name] = name;
});
const defaultValues = {
title: eventType.title,
locations: eventType.locations || [],
recurringEvent: eventType.recurringEvent || null,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
durationLimits: eventType.durationLimits || undefined,
length: eventType.length,
offsetStart: eventType.offsetStart,
hidden: eventType.hidden,
periodDates: {
startDate: periodDates.startDate,
endDate: periodDates.endDate,
},
bookingFields: eventType.bookingFields,
periodType: eventType.periodType,
periodCountCalendarDays: eventType.periodCountCalendarDays ? "1" : "0",
schedulingType: eventType.schedulingType,
minimumBookingNotice: eventType.minimumBookingNotice,
metadata,
hosts: eventType.hosts,
children: eventType.children.map((ch) => ({
...ch,
created: true,
owner: {
...ch.owner,
eventTypeSlugs:
eventType.team?.members
.find((mem) => mem.user.id === ch.owner.id)
?.user.eventTypes.map((evTy) => evTy.slug)
.filter((slug) => slug !== eventType.slug) ?? [],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const defaultValues: any = useMemo(() => {
return {
title: eventType.title,
locations: eventType.locations || [],
recurringEvent: eventType.recurringEvent || null,
description: eventType.description ?? undefined,
schedule: eventType.schedule || undefined,
bookingLimits: eventType.bookingLimits || undefined,
durationLimits: eventType.durationLimits || undefined,
length: eventType.length,
hidden: eventType.hidden,
periodDates: {
startDate: periodDates.startDate,
endDate: periodDates.endDate,
},
})),
} as const;
bookingFields: eventType.bookingFields,
periodType: eventType.periodType,
periodCountCalendarDays: eventType.periodCountCalendarDays ? "1" : "0",
schedulingType: eventType.schedulingType,
minimumBookingNotice: eventType.minimumBookingNotice,
metadata,
hosts: eventType.hosts,
children: eventType.children.map((ch) => ({
...ch,
created: true,
owner: {
...ch.owner,
eventTypeSlugs:
eventType.team?.members
.find((mem) => mem.user.id === ch.owner.id)
?.user.eventTypes.map((evTy) => evTy.slug)
.filter((slug) => slug !== eventType.slug) ?? [],
},
})),
};
}, [eventType, periodDates, metadata]);
const formMethods = useForm<FormValues>({
defaultValues,
@@ -270,6 +272,7 @@ const EventTypePage = (props: EventTypeSetupProps) => {
//TODO: What's the best way to sync the form with backend
formMethods.setValue("bookingFields", defaultValues.bookingFields);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [defaultValues]);
const appsMetadata = formMethods.getValues("metadata")?.apps;
@@ -415,9 +418,6 @@ const EventTypePage = (props: EventTypeSetupProps) => {
// We don't need to send send these values to the backend
// eslint-disable-next-line @typescript-eslint/no-unused-vars
seatsPerTimeSlotEnabled,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
minimumBookingNoticeInDurationType,
availability,
...input
} = values;
+11 -7
View File
@@ -393,11 +393,13 @@ export const EventTypeList = ({ group, groupIndex, readOnly, types }: EventTypeL
className="relative top-1 right-3"
size="sm"
truncateAfter={4}
items={type.users.map((organizer: { name: any; username: any }) => ({
alt: organizer.name || "",
image: `${WEBAPP_URL}/${organizer.username}/avatar.png`,
title: organizer.name || "",
}))}
items={type.users.map(
(organizer: { name: string | null; username: string | null }) => ({
alt: organizer.name || "",
image: `${WEBAPP_URL}/${organizer.username}/avatar.png`,
title: organizer.name || "",
})
)}
/>
)}
{isManagedEventType && (
@@ -780,7 +782,8 @@ const CTA = () => {
);
};
const WithQuery = withQuery(trpc.viewer.eventTypes.getByViewer);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const WithQuery = withQuery(trpc.viewer.eventTypes.getByViewer as any);
const EventTypesPage = () => {
const { t } = useLocale();
@@ -793,6 +796,7 @@ const EventTypesPage = () => {
if (query?.openIntercom && query?.openIntercom === "true") {
open();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
@@ -816,7 +820,7 @@ const EventTypesPage = () => {
{isMobile ? (
<MobileTeamsTab eventTypeGroups={data.eventTypeGroups} />
) : (
data.eventTypeGroups.map((group, index) => (
data.eventTypeGroups.map((group: EventTypeGroup, index: number) => (
<div className="flex flex-col" key={group.profile.slug}>
<EventTypeListHeading
profile={group.profile}
@@ -46,7 +46,10 @@ interface GeneralViewProps {
user: RouterOutputs["viewer"]["me"];
}
const WithQuery = withQuery(trpc.viewer.public.i18n, undefined, { trpc: { context: { skipBatch: true } } });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const WithQuery = withQuery(trpc.viewer.public.i18n as any, undefined, {
trpc: { context: { skipBatch: true } },
});
const GeneralQueryView = () => {
const { t } = useLocale();
@@ -34,7 +34,7 @@ const PasswordView = () => {
onSettled: () => {
utils.viewer.me.invalidate();
},
onMutate: async ({ metadata }) => {
onMutate: async () => {
await utils.viewer.me.cancel();
const previousValue = utils.viewer.me.getData();
const previousMetadata = userMetadata.parse(previousValue?.metadata);
+2
View File
@@ -64,6 +64,7 @@ export default function JoinCall(props: JoinCallPageProps) {
return () => {
callFrame.destroy();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onRecordingStopped = () => {
@@ -169,6 +170,7 @@ function ProgressBar(props: ProgressBarProps) {
intervalRef.current = null;
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const prev = startDuration - duration;
@@ -15,10 +15,11 @@ test("Can delete user account", async ({ page, users }) => {
await page.goto(`/settings/my-account/profile`);
await page.waitForLoadState("networkidle");
await page.click("[data-testid=delete-account]");
if (!user.username) throw Error(`Test user doesn't have a username`);
expect(user.username).toBeTruthy();
const $passwordField = page.locator("[data-testid=password]");
await $passwordField.fill(user.username);
await $passwordField.fill(String(user.username));
await Promise.all([
page.waitForURL((url) => url.pathname === "/auth/logout"),
@@ -5,9 +5,10 @@ import { test } from "../lib/fixtures";
test.afterEach(({ users }) => users.deleteAll());
test("Can reset forgotten password", async ({ page, users }) => {
// eslint-disable-next-line playwright/no-skipped-test
test.skip(process.env.NEXT_PUBLIC_IS_E2E !== "1", "It shouldn't if we can't skip email");
const user = await users.create();
const newPassword = `${user.username!}-123`;
const newPassword = `${user.username}-123`;
// Got to reset password flow
await page.goto("/auth/forgot-password");
+3 -2
View File
@@ -10,12 +10,13 @@ test.describe("Change Password Test", () => {
await pro.login();
// Go to http://localhost:3000/settings/security
await page.goto("/settings/security/password");
if (!pro.username) throw Error("Test user doesn't have a username");
expect(pro.username).toBeTruthy();
await page.waitForLoadState("networkidle");
// Fill form
await page.locator('[name="oldPassword"]').fill(pro.username);
await page.locator('[name="oldPassword"]').fill(String(pro.username));
const $newPasswordField = page.locator('[name="newPassword"]');
$newPasswordField.fill(`${pro.username}Aa1111`);
@@ -50,6 +50,7 @@ test.describe("Change username on settings", () => {
test("User can update to PREMIUM username", async ({ page, users }, testInfo) => {
// eslint-disable-next-line playwright/no-skipped-test
test.skip(!IS_STRIPE_ENABLED, "It should only run if Stripe is installed");
// eslint-disable-next-line playwright/no-skipped-test
test.skip(IS_SELF_HOSTED, "It shouldn't run on self hosted");
const user = await users.create();
@@ -11,6 +11,7 @@ test.afterEach(({ users }) => users.deleteAll());
// Due to some reason for Dynamic booking cancellation, daily video api_key is not set which causes cancellation to fail.
// This test is skipped until the issue is resolved in GH actions.
// eslint-disable-next-line playwright/no-skipped-test
test.skip("dynamic booking", async ({ page, users }) => {
const pro = await users.create();
await pro.login();
+1 -1
View File
@@ -69,7 +69,7 @@ test.describe("Event Types tests", () => {
'[data-testid="event-types"] a[href^="/event-types/"] >> nth=0'
);
const href = await firstElement.getAttribute("href");
if (!href) throw new Error("No href found for event type");
expect(href).toBeTruthy();
const [eventTypeId] = new URL(WEBAPP_URL + href).pathname.split("/").reverse();
const firstTitle = await page.locator(`[data-testid=event-type-title-${eventTypeId}]`).innerText();
const firstFullSlug = await page.locator(`[data-testid=event-type-slug-${eventTypeId}]`).innerText();
+3 -3
View File
@@ -58,7 +58,7 @@ export const createBookingsFixture = (page: Page) => {
status,
},
});
const bookingFixture = createBookingFixture(booking, store.page!);
const bookingFixture = createBookingFixture(booking, store.page);
store.bookings.push(bookingFixture);
return bookingFixture;
},
@@ -80,7 +80,7 @@ const createBookingFixture = (booking: Booking, page: Page) => {
return {
id: store.booking.id,
uid: store.booking.uid,
self: async () => (await prisma.booking.findUnique({ where: { id: store.booking.id } }))!,
delete: async () => (await prisma.booking.delete({ where: { id: store.booking.id } }))!,
self: async () => await prisma.booking.findUnique({ where: { id: store.booking.id } }),
delete: async () => await prisma.booking.delete({ where: { id: store.booking.id } }),
};
};
+3 -3
View File
@@ -36,7 +36,7 @@ export const createPaymentsFixture = (page: Page) => {
},
},
});
const paymentFixture = createPaymentFixture(payment, store.page!);
const paymentFixture = createPaymentFixture(payment, store.page);
store.payments.push(paymentFixture);
return paymentFixture;
},
@@ -57,7 +57,7 @@ const createPaymentFixture = (payment: Payment, page: Page) => {
// self is a reflective method that return the Prisma object that references this fixture.
return {
id: store.payment.id,
self: async () => (await prisma.payment.findUnique({ where: { id: store.payment.id } }))!,
delete: async () => (await prisma.payment.delete({ where: { id: store.payment.id } }))!,
self: async () => await prisma.payment.findUnique({ where: { id: store.payment.id } }),
delete: async () => await prisma.payment.delete({ where: { id: store.payment.id } }),
};
};
+3 -2
View File
@@ -233,7 +233,7 @@ export const createUsersFixture = (page: Page, workerInfo: WorkerInfo) => {
},
});
}
const userFixture = createUserFixture(user, store.page!);
const userFixture = createUserFixture(user, store.page);
store.users.push(userFixture);
return userFixture;
},
@@ -261,6 +261,7 @@ const createUserFixture = (user: UserWithIncludes, page: Page) => {
// self is a reflective method that return the Prisma object that references this fixture.
const self = async () =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
(await prisma.user.findUnique({ where: { id: store.user.id }, include: { eventTypes: true } }))!;
return {
id: user.id,
@@ -277,7 +278,7 @@ const createUserFixture = (user: UserWithIncludes, page: Page) => {
debug: async (message: string | Record<string, JSONValue>) => {
await prisma.user.update({ where: { id: store.user.id }, data: { metadata: { debug: message } } });
},
delete: async () => (await prisma.user.delete({ where: { id: store.user.id } }))!,
delete: async () => await prisma.user.delete({ where: { id: store.user.id } }),
};
};
@@ -38,12 +38,12 @@ test.describe("Stripe integration", () => {
test("Can book a paid booking", async ({ page, users }) => {
const user = await users.create();
const eventType = user.eventTypes.find((e) => e.slug === "paid")!;
const eventType = user.eventTypes.find((e) => e.slug === "paid");
await user.login();
await page.goto("/apps/installed");
await user.getPaymentCredential();
await page.goto(`${user.username}/${eventType.slug}`);
await page.goto(`${user.username}/${eventType?.slug}`);
await selectFirstAvailableTimeSlotNextMonth(page);
// --- fill form
await page.fill('[name="name"]', "Stripe Stripeson");
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Page, Route } from "@playwright/test";
import { expect } from "@playwright/test";
import type { DefaultBodyType } from "msw";
import { rest } from "msw";
import { setupServer } from "msw/node";
import { v4 as uuidv4 } from "uuid";
@@ -42,7 +43,7 @@ const addOauthBasedIntegration = async function ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
verify: (config: { requestHeaders: any; params: URLSearchParams; code: string }) => {
status: number;
body: any;
body: DefaultBodyType;
};
};
}) {
+3 -3
View File
@@ -24,11 +24,11 @@ export const deleteAllBookingsByEmail = async (
});
export const deleteEventTypeByTitle = async (title: string) => {
const event = (await prisma.eventType.findFirst({
const event = await prisma.eventType.findFirst({
select: { id: true },
where: { title: title },
}))!;
await prisma.eventType.delete({ where: { id: event.id } });
});
await prisma.eventType.delete({ where: { id: event?.id } });
};
export const deleteAllWebhooksByEmail = async (email: string) => {
+1
View File
@@ -46,6 +46,7 @@ export function createHttpServer(opts: { requestHandler?: RequestHandler } = {})
// listen on random port
server.listen(0);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const port: number = (server.address() as any).port;
const url = `http://localhost:${port}`;
return {
@@ -65,7 +65,7 @@ test.describe("Manage Booking Questions", () => {
},
});
const teamId = team?.id ?? 0;
const teamId = team?.id;
const webhookReceiver = await addWebhook(undefined, teamId);
await test.step("Go to First Team Event", async () => {
@@ -86,7 +86,8 @@ async function runTestStepsCommonForTeamAndUserEventType(
webhookReceiver: {
port: number;
close: () => import("http").Server;
requestList: (import("http").IncomingMessage & { body?: unknown })[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
requestList: (import("http").IncomingMessage & { body?: any })[];
url: string;
},
bookerVariant: BookerVariants
@@ -175,7 +176,7 @@ async function runTestStepsCommonForTeamAndUserEventType(
const [request] = webhookReceiver.requestList;
const payload = (request.body as any).payload as any;
const payload = request.body.payload;
expect(payload.responses).toMatchObject({
email: {
@@ -212,7 +213,9 @@ async function runTestStepsCommonForTeamAndUserEventType(
await test.step("Do a reschedule and notice that we can't book without giving a value for rescheduleReason", async () => {
const page = previewTabPage;
await rescheduleFromTheLinkOnPage({ page, bookerVariant });
await rescheduleFromTheLinkOnPage({ page });
// eslint-disable-next-line playwright/no-page-pause
await page.pause();
await expectErrorToBeThereFor({ page, name: "rescheduleReason" });
});
}
@@ -368,7 +371,7 @@ async function rescheduleFromTheLinkOnPage({
bookerVariant,
}: {
page: Page;
bookerVariant: BookerVariants;
bookerVariant?: BookerVariants;
}) {
await page.locator('[data-testid="reschedule-link"]').click();
await page.waitForLoadState();
+1 -3
View File
@@ -76,9 +76,7 @@ test.describe("Onboarding", () => {
const userComplete = await user.self();
const userCompleteBio = userComplete.bio ? userComplete.bio : "";
expect(userCompleteBio.replace("<p><br></p>", "").length).toBe(0);
expect(userComplete.bio?.replace("<p><br></p>", "").length).toBe(0);
});
});
});
+3 -3
View File
@@ -39,9 +39,9 @@ testBothBookers.describe("Reschedule Tests", async () => {
const updatedBooking = await booking.self();
expect(updatedBooking.rescheduled).toBe(true);
expect(updatedBooking.cancellationReason).toBe("I can't longer have it");
expect(updatedBooking.status).toBe(BookingStatus.CANCELLED);
expect(updatedBooking?.rescheduled).toBe(true);
expect(updatedBooking?.cancellationReason).toBe("I can't longer have it");
expect(updatedBooking?.status).toBe(BookingStatus.CANCELLED);
await booking.delete();
});
+4 -2
View File
@@ -14,7 +14,7 @@ test.describe("BOOKING_CREATED", async () => {
test("add webhook & test that creating an event triggers a webhook call", async ({
page,
users,
}, testInfo) => {
}, _testInfo) => {
const webhookReceiver = createHttpServer();
const user = await users.create();
const [eventType] = user.eventTypes;
@@ -51,7 +51,8 @@ test.describe("BOOKING_CREATED", async () => {
});
const [request] = webhookReceiver.requestList;
const body = request.body as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body: any = request.body;
// remove dynamic properties that differs depending on where you run the tests
const dynamic = "[redacted/dynamic]";
@@ -305,6 +306,7 @@ test.describe("BOOKING_REQUESTED", async () => {
expect(webhookReceiver.requestList.length).toBe(1);
});
const [request] = webhookReceiver.requestList;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = request.body as any;
// remove dynamic properties that differs depending on where you run the tests
+5 -1
View File
@@ -1,5 +1,9 @@
import { execSync } from "child_process";
type Err = {
stdout: string;
};
const diff = execSync(`git diff --name-only origin/main HEAD`).toString();
const files = diff
@@ -18,7 +22,7 @@ try {
console.log("😻 No errors!");
} catch (_err) {
const err = _err as any;
const err = _err as Err;
const output = err.stdout.toString() as string;
+1
View File
@@ -492,6 +492,7 @@ describe("getSchedule", () => {
});
// FIXME: Fix minimumBookingNotice is respected test
// eslint-disable-next-line playwright/no-skipped-test
test.skip("minimumBookingNotice is respected", async () => {
vi.useFakeTimers().setSystemTime(
(() => {
@@ -295,16 +295,24 @@ describe("handleChildrenEventTypes", () => {
describe("Workflows", () => {
it("Links workflows to new and existing assigned members", async () => {
const { schedulingType, id, teamId, locations, timeZone, parentId, userId, ...evType } =
mockFindFirstEventType({
metadata: { managedEventConfig: {} },
locations: [],
workflows: [
{
workflowId: 11,
} as CompleteWorkflowsOnEventTypes,
],
});
const {
schedulingType: _schedulingType,
id: _id,
teamId: _teamId,
locations: _locations,
timeZone: _timeZone,
parentId: _parentId,
userId: _userId,
...evType
} = mockFindFirstEventType({
metadata: { managedEventConfig: {} },
locations: [],
workflows: [
{
workflowId: 11,
} as CompleteWorkflowsOnEventTypes,
],
});
prismaMock.$transaction.mockResolvedValue([{ id: 2 }]);
await updateChildrenEventTypes({
eventTypeId: 1,