feat: Event Type Atom base pr (#16831)

* feat: Event Type Atom base pr

* fixup! Merge branch 'main' into chore-event-type-atom-platform-wrapper-base-pr

* Update EventTypeWebWrapper.tsx

---------

Co-authored-by: Somay Chauhan <[email protected]>
This commit is contained in:
MorganandSomay Chauhan authored and GitHub committed 2024-09-30 13:44:11 +03:00
1 parent ac300ff670
commit ad347cb59f
29 files changed
+1148 -357

No files matched your search

@@ -0,0 +1,27 @@
import { useQuery } from "@tanstack/react-query";
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import { useAtomsContext } from "../../hooks/useAtomsContext";
import http from "../../lib/http";
export const QUERY_KEY = "use-event-by-id";
export const useAtomsEventTypeById = (id: number | null) => {
const pathname = `/atoms/${V2_ENDPOINTS.eventTypes}/${id}`;
const { isInit, accessToken } = useAtomsContext();
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => {
return http?.get<ApiResponse<EventTypeSetupProps>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<EventTypeSetupProps>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: !!id && isInit && !!accessToken,
});
};
@@ -0,0 +1,42 @@
import { useMutation } from "@tanstack/react-query";
import type { EventTypeUpdateInput } from "@calcom/features/eventtypes/lib/types";
import { V2_ENDPOINTS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import type { EventType } from "@calcom/prisma/client";
import http from "../../lib/http";
export const QUERY_KEY = "use-event-by-id";
export type UseAtomUpdateEventTypeProps = {
onSuccess?: () => void;
onError?: (err: Error) => void;
onSettled?: () => void;
};
export const useAtomUpdateEventType = ({
onSuccess = () => {
return;
},
onError = () => {
return;
},
onSettled = () => {
return;
},
}: UseAtomUpdateEventTypeProps) => {
return useMutation({
onSuccess,
onError,
onSettled,
mutationFn: (data: EventTypeUpdateInput) => {
if (!data.id) throw new Error("Event type id is required");
const pathname = `/atoms/${V2_ENDPOINTS.eventTypes}/${data.id}`;
return http?.patch<ApiResponse<EventType>>(pathname, data).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<EventType>).data;
}
throw new Error(res.data.error.message);
});
},
});
};
@@ -0,0 +1,168 @@
"use client";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import type { TFunction } from "next-i18next";
import { useMemo, useState, useEffect } from "react";
import type { UseFormReturn } from "react-hook-form";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import type { EventTypeSetupProps, FormValues } from "@calcom/features/eventtypes/lib/types";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { VerticalTabItemProps } from "@calcom/ui";
import type { PlatformTabs } from "../wrappers/EventTypePlatformWrapper";
type Props = {
formMethods: UseFormReturn<FormValues>;
eventType: EventTypeSetupProps["eventType"];
team: EventTypeSetupProps["team"];
tabs: PlatformTabs[];
};
export const usePlatformTabsNavigations = ({ formMethods, eventType, team, tabs }: Props) => {
const [url, setUrl] = useState("");
const [currentTab, setCurrentTab] = useState<PlatformTabs>(tabs[0]);
useEffect(() => {
// Get the current URL from window.location
const currentUrl = window.location.href;
setUrl(currentUrl);
}, []);
const { t } = useLocale();
const length = formMethods.watch("length");
const multipleDuration = formMethods.watch("metadata")?.multipleDuration;
const watchSchedulingType = formMethods.watch("schedulingType");
const watchChildrenCount = formMethods.watch("children").length;
const availability = formMethods.watch("availability");
const { isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager({
eventType,
translate: t,
formMethods,
});
const paymentAppData = getPaymentAppData(eventType);
const requirePayment = paymentAppData.price > 0;
const EventTypeTabs = useMemo(() => {
const navigation: VerticalTabItemProps[] = getNavigation({
t,
length,
multipleDuration,
id: formMethods.getValues("id"),
tabs,
url,
onClick: (tab) => {
setCurrentTab(tab);
},
});
if (!requirePayment) {
navigation.splice(3, 0, {
name: "recurring",
onClick: () => setCurrentTab("recurring"),
href: `${url}?tabName=recurring`,
icon: "repeat",
info: `recurring_event_tab_description`,
});
}
navigation.splice(1, 0, {
name: "availability",
onClick: () => setCurrentTab("availability"),
href: `${url}?tabName=availability`,
icon: "calendar",
info:
isManagedEventType || isChildrenManagedEventType
? formMethods.getValues("schedule") === null
? "members_default_schedule"
: isChildrenManagedEventType
? `${
formMethods.getValues("scheduleName")
? `${formMethods.getValues("scheduleName")} - ${t("managed")}`
: `default_schedule_name`
}`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`,
});
// If there is a team put this navigation item within the tabs
if (team) {
navigation.splice(2, 0, {
name: "assignment",
onClick: () => setCurrentTab("team"),
href: `${url}?tabName=team`,
icon: "users",
info: `${t(watchSchedulingType?.toLowerCase() ?? "")}${
isManagedEventType ? ` - ${t("number_member", { count: watchChildrenCount || 0 })}` : ""
}`,
});
}
return navigation;
}, [
t,
availability,
isManagedEventType,
isChildrenManagedEventType,
team,
length,
requirePayment,
multipleDuration,
formMethods.getValues("id"),
watchSchedulingType,
watchChildrenCount,
url,
tabs,
currentTab,
]);
return { tabsNavigation: EventTypeTabs, currentTab };
};
type getNavigationProps = {
t: TFunction;
length: number;
id: number;
multipleDuration?: EventTypeSetupProps["eventType"]["metadata"]["multipleDuration"];
tabs: PlatformTabs[];
url: string;
onClick: (tab: PlatformTabs) => void;
};
function getNavigation({ length, multipleDuration, t, tabs, url, onClick }: getNavigationProps) {
const duration = multipleDuration?.map((duration) => ` ${duration}`) || length;
const tabsNavigation: VerticalTabItemProps[] = [];
tabs.includes("setup") &&
tabsNavigation.push({
name: "event_setup_tab_title",
onClick: () => onClick("setup"),
href: `${url}?tabName=setup`,
icon: "link",
info: `${duration} ${t("minute_timeUnit")}`, // TODO: Get this from props
});
tabs.includes("limits") &&
tabsNavigation.push({
name: "event_limit_tab_title",
onClick: () => onClick("limits"),
href: `${url}?tabName=limits`,
icon: "clock",
info: `event_limit_tab_description`,
});
tabs.includes("advanced") &&
tabsNavigation.push({
name: "event_advanced_tab_title",
onClick: () => onClick("advanced"),
href: `${url}?tabName=advanced`,
icon: "sliders-vertical",
info: `event_advanced_tab_description`,
});
return tabsNavigation;
}
@@ -0,0 +1,220 @@
"use client";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import type { TFunction } from "next-i18next";
import { useMemo } from "react";
import type { UseFormReturn } from "react-hook-form";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import type {
EventTypeSetupProps,
AvailabilityOption,
FormValues,
EventTypeApps,
} from "@calcom/features/eventtypes/lib/types";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { VerticalTabItemProps } from "@calcom/ui";
type Props = {
formMethods: UseFormReturn<FormValues>;
eventType: EventTypeSetupProps["eventType"];
team: EventTypeSetupProps["team"];
eventTypeApps?: EventTypeApps;
allActiveWorkflows?: Workflow[];
};
export const useTabsNavigations = ({
formMethods,
eventType,
team,
eventTypeApps,
allActiveWorkflows,
}: Props) => {
const { t } = useLocale();
const length = formMethods.watch("length");
const multipleDuration = formMethods.watch("metadata")?.multipleDuration;
const watchSchedulingType = formMethods.watch("schedulingType");
const watchChildrenCount = formMethods.watch("children").length;
const availability = formMethods.watch("availability");
const appsMetadata = formMethods.getValues("metadata")?.apps;
const { isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager({
eventType,
translate: t,
formMethods,
});
let enabledAppsNumber = 0;
if (appsMetadata) {
enabledAppsNumber = Object.entries(appsMetadata).filter(
([appId, appData]) =>
eventTypeApps?.items.find((app) => app.slug === appId)?.isInstalled && appData.enabled
).length;
}
const paymentAppData = getPaymentAppData(eventType);
const requirePayment = paymentAppData.price > 0;
const activeWebhooksNumber = eventType.webhooks.filter((webhook) => webhook.active).length;
const installedAppsNumber = eventTypeApps?.items.length || 0;
const enabledWorkflowsNumber = allActiveWorkflows ? allActiveWorkflows.length : 0;
const EventTypeTabs = useMemo(() => {
const navigation: VerticalTabItemProps[] = getNavigation({
t,
length,
multipleDuration,
id: formMethods.getValues("id"),
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
availability,
});
if (!requirePayment) {
navigation.splice(3, 0, {
name: "recurring",
href: `/event-types/${formMethods.getValues("id")}?tabName=recurring`,
icon: "repeat",
info: `recurring_event_tab_description`,
});
}
navigation.splice(1, 0, {
name: "availability",
href: `/event-types/${formMethods.getValues("id")}?tabName=availability`,
icon: "calendar",
info:
isManagedEventType || isChildrenManagedEventType
? formMethods.getValues("schedule") === null
? "members_default_schedule"
: isChildrenManagedEventType
? `${
formMethods.getValues("scheduleName")
? `${formMethods.getValues("scheduleName")} - ${t("managed")}`
: `default_schedule_name`
}`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`
: formMethods.getValues("scheduleName") ?? `default_schedule_name`,
});
// If there is a team put this navigation item within the tabs
if (team) {
navigation.splice(2, 0, {
name: "assignment",
href: `/event-types/${formMethods.getValues("id")}?tabName=team`,
icon: "users",
info: `${t(watchSchedulingType?.toLowerCase() ?? "")}${
isManagedEventType ? ` - ${t("number_member", { count: watchChildrenCount || 0 })}` : ""
}`,
});
}
const showWebhooks = !(isManagedEventType || isChildrenManagedEventType);
if (showWebhooks) {
if (team) {
navigation.push({
name: "instant_tab_title",
href: `/event-types/${eventType.id}?tabName=instant`,
icon: "phone-call",
info: `instant_event_tab_description`,
});
}
navigation.push({
name: "webhooks",
href: `/event-types/${formMethods.getValues("id")}?tabName=webhooks`,
icon: "webhook",
info: `${activeWebhooksNumber} ${t("active")}`,
});
}
const hidden = true; // hidden while in alpha trial. you can access it with tabName=ai
if (team && hidden) {
navigation.push({
name: "Cal.ai",
href: `/event-types/${eventType.id}?tabName=ai`,
icon: "sparkles",
info: "cal_ai_event_tab_description", // todo `cal_ai_event_tab_description`,
});
}
return navigation;
}, [
t,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
availability,
isManagedEventType,
isChildrenManagedEventType,
team,
length,
requirePayment,
multipleDuration,
formMethods.getValues("id"),
watchSchedulingType,
watchChildrenCount,
activeWebhooksNumber,
]);
return { tabsNavigation: EventTypeTabs };
};
type getNavigationProps = {
t: TFunction;
length: number;
id: number;
multipleDuration?: EventTypeSetupProps["eventType"]["metadata"]["multipleDuration"];
enabledAppsNumber: number;
enabledWorkflowsNumber: number;
installedAppsNumber: number;
availability: AvailabilityOption | undefined;
};
function getNavigation({
length,
id,
multipleDuration,
t,
enabledAppsNumber,
installedAppsNumber,
enabledWorkflowsNumber,
}: getNavigationProps) {
const duration = multipleDuration?.map((duration) => ` ${duration}`) || length;
return [
{
name: "event_setup_tab_title",
href: `/event-types/${id}?tabName=setup`,
icon: "link",
info: `${duration} ${t("minute_timeUnit")}`, // TODO: Get this from props
},
{
name: "event_limit_tab_title",
href: `/event-types/${id}?tabName=limits`,
icon: "clock",
info: `event_limit_tab_description`,
},
{
name: "event_advanced_tab_title",
href: `/event-types/${id}?tabName=advanced`,
icon: "sliders-vertical",
info: `event_advanced_tab_description`,
},
{
name: "apps",
href: `/event-types/${id}?tabName=apps`,
icon: "grid-3x3",
//TODO: Handle proper translation with count handling
info: `${installedAppsNumber} apps, ${enabledAppsNumber} ${t("active")}`,
},
{
name: "workflows",
href: `/event-types/${id}?tabName=workflows`,
icon: "zap",
info: `${enabledWorkflowsNumber} ${t("active")}`,
},
] satisfies VerticalTabItemProps[];
}
@@ -0,0 +1,10 @@
import React from "react";
import type { EventSetupTabProps } from "@calcom/features/eventtypes/components/tabs/setup/EventSetupTab";
import { EventSetupTab } from "@calcom/features/eventtypes/components/tabs/setup/EventSetupTab";
const EventSetupTabPlatformWrapper = (props: EventSetupTabProps) => {
return <EventSetupTab {...props} urlPrefix="" hasOrgBranding={false} />;
};
export default EventSetupTabPlatformWrapper;
@@ -1,8 +1,14 @@
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import type { EventSetupTabProps } from "@calcom/features/eventtypes/components/tabs/setup/EventSetupTab";
import { EventSetupTab } from "@calcom/features/eventtypes/components/tabs/setup/EventSetupTab";
import { WEBSITE_URL } from "@calcom/lib/constants";
const EventSetupTabWebWrapper = (props: EventSetupTabProps) => {
return <EventSetupTab {...props} />;
const orgBranding = useOrgBranding();
const urlPrefix = orgBranding
? orgBranding?.fullDomain.replace(/^(https?:|)\/\//, "")
: `${WEBSITE_URL?.replace(/^(https?:|)\/\//, "")}`;
return <EventSetupTab urlPrefix={urlPrefix} hasOrgBranding={!!orgBranding} {...props} />;
};
export default EventSetupTabWebWrapper;
@@ -0,0 +1,167 @@
"use client";
import { useRef, useState } from "react";
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
import { EventType as EventTypeComponent } from "@calcom/features/eventtypes/components/EventType";
import ManagedEventTypeDialog from "@calcom/features/eventtypes/components/dialogs/ManagedEventDialog";
import type { EventTypeSetupProps, TabMap } from "@calcom/features/eventtypes/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { SchedulingType } from "@calcom/prisma/enums";
import { AtomsWrapper } from "../../src/components/atoms-wrapper";
import { useToast } from "../../src/components/ui/use-toast";
import { useAtomsEventTypeById } from "../hooks/useAtomEventTypeById";
import { useAtomUpdateEventType } from "../hooks/useAtomUpdateEventType";
import { useEventTypeForm } from "../hooks/useEventTypeForm";
import { useHandleRouteChange } from "../hooks/useHandleRouteChange";
import { usePlatformTabsNavigations } from "../hooks/usePlatformTabsNavigations";
import SetupTab from "./EventSetupTabPlatformWrapper";
export type PlatformTabs = keyof Omit<TabMap, "workflows" | "webhooks" | "instant" | "ai" | "apps">;
export type EventTypePlatformWrapperProps = {
id: number;
tabs?: PlatformTabs[];
};
const EventType = ({
tabs = ["setup", "availability", "team", "limits", "advanced"],
...props
}: EventTypeSetupProps & EventTypePlatformWrapperProps) => {
const { t } = useLocale();
const { toast } = useToast();
const isTeamEventTypeDeleted = useRef(false);
const leaveWithoutAssigningHosts = useRef(false);
const [isOpenAssignmentWarnDialog, setIsOpenAssignmentWarnDialog] = useState<boolean>(false);
const [pendingRoute, setPendingRoute] = useState("");
const { eventType, locationOptions, team, teamMembers, destinationCalendar } = props;
const [slugExistsChildrenDialogOpen, setSlugExistsChildrenDialogOpen] = useState<ChildrenEventType[]>([]);
const updateMutation = useAtomUpdateEventType({
onSuccess: async () => {
const currentValues = form.getValues();
currentValues.children = currentValues.children.map((child) => ({
...child,
created: true,
}));
currentValues.assignAllTeamMembers = currentValues.assignAllTeamMembers || false;
// Reset the form with these values as new default values to ensure the correct comparison for dirtyFields eval
form.reset(currentValues);
toast({ description: t("event_type_updated_successfully", { eventTypeTitle: eventType.title }) });
},
async onSettled() {
return;
},
onError: (err: Error) => {
const message = err?.message;
toast({ description: message ? t(message) : t(err.message) });
},
});
const { form, handleSubmit } = useEventTypeForm({ eventType, onSubmit: updateMutation.mutate });
const slug = form.watch("slug") ?? eventType.slug;
const tabMap = {
setup: tabs.includes("setup") ? (
<SetupTab
eventType={eventType}
locationOptions={locationOptions}
team={team}
teamMembers={teamMembers}
destinationCalendar={destinationCalendar}
/>
) : (
<></>
),
availability: <></>,
team: <></>,
limits: <></>,
advanced: <></>,
instant: <></>,
recurring: <></>,
apps: <></>,
workflows: <></>,
webhooks: <></>,
ai: <></>,
} as const;
useHandleRouteChange({
watchTrigger: null,
isTeamEventTypeDeleted: isTeamEventTypeDeleted.current,
isleavingWithoutAssigningHosts: leaveWithoutAssigningHosts.current,
isTeamEventType: !!team,
assignedUsers: eventType.children,
hosts: eventType.hosts,
assignAllTeamMembers: eventType.assignAllTeamMembers,
isManagedEventType: eventType.schedulingType === SchedulingType.MANAGED,
onError: (url) => {
setIsOpenAssignmentWarnDialog(true);
setPendingRoute(url);
},
onStart: () => {
return;
},
onEnd: () => {
return;
},
});
const onDelete = () => {
isTeamEventTypeDeleted.current = true;
};
const onConflict = (conflicts: ChildrenEventType[]) => {
setSlugExistsChildrenDialogOpen(conflicts);
};
const { tabsNavigation, currentTab } = usePlatformTabsNavigations({
formMethods: form,
eventType,
team,
tabs,
});
return (
<AtomsWrapper>
<EventTypeComponent
{...props}
tabMap={tabMap}
onDelete={onDelete}
onConflict={onConflict}
handleSubmit={handleSubmit}
formMethods={form}
isUpdating={updateMutation.isPending}
isPlatform
tabName={currentTab}
tabsNavigation={tabsNavigation}>
<>
{slugExistsChildrenDialogOpen.length ? (
<ManagedEventTypeDialog
slugExistsChildrenDialogOpen={slugExistsChildrenDialogOpen}
isPending={form.formState.isSubmitting}
onOpenChange={() => {
setSlugExistsChildrenDialogOpen([]);
}}
slug={slug}
onConfirm={(e: { preventDefault: () => void }) => {
e.preventDefault();
handleSubmit(form.getValues());
setSlugExistsChildrenDialogOpen([]);
}}
/>
) : null}
</>
</EventTypeComponent>
</AtomsWrapper>
);
};
export const EventTypePlatformWrapper = ({ id, tabs }: EventTypePlatformWrapperProps) => {
const { data: eventTypeQueryData } = useAtomsEventTypeById(id);
if (!eventTypeQueryData) return null;
return <EventType {...eventTypeQueryData} id={id} tabs={tabs} />;
};
@@ -1,27 +1,31 @@
"use client";
import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import dynamic from "next/dynamic";
import { usePathname } from "next/navigation";
import { usePathname, useRouter as useAppRouter } from "next/navigation";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import { useRouter as usePageRouter } from "next/router";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import type { NextRouter as NextPageRouter } from "next/router";
import React, { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
import { EventType as EventTypeComponent } from "@calcom/features/eventtypes/components/EventType";
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import { HttpError } from "@calcom/lib/http-error";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import { SchedulingType } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { trpc, TRPCClientError } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { showToast } from "@calcom/ui";
import { useEventTypeForm } from "../hooks/useEventTypeForm";
import { useHandleRouteChange } from "../hooks/useHandleRouteChange";
import { useTabsNavigations } from "../hooks/useTabsNavigations";
const ManagedEventTypeDialog = dynamic(
() => import("@calcom/features/eventtypes/components/dialogs/ManagedEventDialog")
@@ -97,6 +101,7 @@ type EventTypeAppComponentProp = {
isAppDir: true;
pathname: string;
pageRouter: null;
appRouter: AppRouterInstance;
};
// discriminative factor: isAppDir
@@ -105,6 +110,7 @@ type EventTypePageComponentProp = {
isAppDir: false;
pageRouter: NextPageRouter;
pathname: null;
appRouter: null;
};
type EventTypeAppPageComponentProp = EventTypeAppComponentProp | EventTypePageComponentProp;
@@ -123,18 +129,31 @@ export const EventTypeWebWrapper = ({ id, isAppDir }: EventTypeWebWrapperProps &
const EventTypePageWrapper = ({ id, ...rest }: EventTypeSetupProps & { id: number }) => {
const router = usePageRouter();
return <EventTypeWeb {...rest} id={id} isAppDir={false} pageRouter={router} pathname={null} />;
return (
<EventTypeWeb {...rest} id={id} isAppDir={false} pageRouter={router} pathname={null} appRouter={null} />
);
};
const EventTypeAppWrapper = ({ id, ...rest }: EventTypeSetupProps & { id: number }) => {
const pathname = usePathname();
return <EventTypeWeb {...rest} id={id} isAppDir={true} pathname={pathname ?? ""} pageRouter={null} />;
const router = useAppRouter();
return (
<EventTypeWeb
{...rest}
id={id}
isAppDir={true}
pathname={pathname ?? ""}
pageRouter={null}
appRouter={router}
/>
);
};
const EventTypeWeb = ({
id,
isAppDir,
pageRouter,
appRouter,
pathname,
...rest
}: EventTypeSetupProps & EventTypeAppPageComponentProp) => {
@@ -305,23 +324,78 @@ const EventTypeWeb = ({
};
}, []);
const onDelete = () => {
isTeamEventTypeDeleted.current = true;
};
const onConflict = (conflicts: ChildrenEventType[]) => {
setSlugExistsChildrenDialogOpen(conflicts);
};
const querySchema = z.object({
tabName: z
.enum([
"setup",
"availability",
"team",
"limits",
"advanced",
"instant",
"recurring",
"apps",
"workflows",
"webhooks",
"ai",
])
.optional()
.default("setup"),
});
const {
data: { tabName },
} = useTypedQuery(querySchema);
const deleteMutation = trpc.viewer.eventTypes.delete.useMutation({
onSuccess: async () => {
await utils.viewer.eventTypes.invalidate();
showToast(t("event_type_deleted_successfully"), "success");
isTeamEventTypeDeleted.current = true;
isAppDir ? appRouter.push("/event-types") : pageRouter.push("/event-types");
setSlugExistsChildrenDialogOpen([]);
setIsOpenAssignmentWarnDialog(false);
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
setSlugExistsChildrenDialogOpen([]);
} else if (err instanceof TRPCClientError) {
showToast(err.message, "error");
}
},
});
const { tabsNavigation } = useTabsNavigations({
formMethods: form,
eventType,
team,
eventTypeApps,
allActiveWorkflows,
});
return (
<EventTypeComponent
{...rest}
allActiveWorkflows={allActiveWorkflows}
tabMap={tabMap}
onDelete={onDelete}
onDelete={(id) => {
deleteMutation.mutate({ id });
}}
isDeleting={deleteMutation.isPending}
onConflict={onConflict}
handleSubmit={handleSubmit}
eventTypeApps={eventTypeApps}
formMethods={form}
isUpdating={updateMutation.isPending}>
isUpdating={updateMutation.isPending}
isPlatform={false}
tabName={tabName}
tabsNavigation={tabsNavigation}>
<>
{slugExistsChildrenDialogOpen.length ? (
<ManagedEventTypeDialog
+1
View File
@@ -24,3 +24,4 @@ export { SelectedCalendarsSettingsPlatformWrapper as SelectedCalendarsSettings }
export { DestinationCalendarSettingsPlatformWrapper as DestinationCalendarSettings } from "./destination-calendar/index";
export { CalendarSettingsPlatformWrapper as CalendarSettings } from "./calendar-settings/index";
export type { UpdateScheduleInput_2024_06_11 as UpdateScheduleBody } from "@calcom/platform-types";
export { EventTypePlatformWrapper as EventTypeSettings } from "./event-types/wrappers/EventTypePlatformWrapper";
+1
View File
@@ -11,3 +11,4 @@ export { DestinationCalendarSettingsWebWrapper } from "./destination-calendar/wr
export * from "./availability";
export { EventTypeWebWrapper as EventType } from "./event-types/wrappers/EventTypeWebWrapper";
export type { UpdateScheduleInput_2024_06_11 as UpdateScheduleBody } from "@calcom/platform-types";
export { Shell } from "./src/components/ui/shell";
+3
View File
@@ -24,6 +24,9 @@ export default defineConfig(({ mode }) => {
define: {
"process.env.NEXT_PUBLIC_WEBAPP_URL": `"${webAppUrl}"`,
},
ssr: {
noExternal: ["turndown"], // Example if you want to disable SSR for your library
},
build: {
commonjsOptions: {
include: [/@calcom\/lib/, /@calcom\/features/, /node_modules/],
@@ -22,6 +22,9 @@ export function Navbar({ username }: { username?: string }) {
<li>
<Link href="/availability">Availability</Link>
</li>
<li>
<Link href="/event-types">EventTypes</Link>
</li>
<li>
<Link href="/booking">Book Me</Link>
</li>
@@ -0,0 +1,94 @@
import { Navbar } from "@/components/Navbar";
import { Inter } from "next/font/google";
// eslint-disable-next-line @calcom/eslint/deprecated-imports-next-router
import { useRouter } from "next/router";
import { useState } from "react";
import { useEventTypes, useTeamEventTypes, useTeams, EventTypeSettings } from "@calcom/atoms";
const inter = Inter({ subsets: ["latin"] });
export default function Bookings(props: { calUsername: string; calEmail: string }) {
const [eventTypeId, setEventTypeId] = useState<number | null>(null);
const [isTeamEvent, setIsTeamEvent] = useState<boolean>(false);
const router = useRouter();
const { isLoading: isLoadingEvents, data: eventTypes } = useEventTypes(props.calUsername);
const { data: teams } = useTeams();
const { isLoading: isLoadingTeamEvents, data: teamEventTypes } = useTeamEventTypes(teams?.[0]?.id || 0);
const rescheduleUid = (router.query.rescheduleUid as string) ?? "";
return (
<main
className={`flex min-h-screen flex-col ${inter.className} main text-default flex min-h-full w-full flex-col items-center overflow-visible`}>
<Navbar username={props.calUsername} />
<div>
<h1 className="mx-10 my-4 text-2xl font-semibold">
EventTypes{eventTypeId ? `: ${eventTypeId}` : ""}
</h1>
{isLoadingEvents && !eventTypeId && <p>Loading...</p>}
{!isLoadingEvents && !eventTypeId && Boolean(eventTypes?.length) && !rescheduleUid && (
<div className="flex flex-col gap-4">
<h1>User event types</h1>
{eventTypes?.map(
(event: { id: number; slug: string; title: string; lengthInMinutes: number }) => {
const formatEventSlug = event.slug
.split("-")
.map((item) => `${item[0].toLocaleUpperCase()}${item.slice(1)}`)
.join(" ");
return (
<div
onClick={() => {
setEventTypeId(event.id);
setIsTeamEvent(false);
}}
className="mx-10 w-[80vw] cursor-pointer rounded-md border-[0.8px] border-black px-10 py-4"
key={event.id}>
<h1 className="text-lg font-semibold">{formatEventSlug}</h1>
<p>{`/${event.slug}`}</p>
<span className="border-none bg-gray-800 px-2 text-white">{event?.lengthInMinutes}</span>
</div>
);
}
)}
</div>
)}
{!isLoadingTeamEvents && !eventTypeId && Boolean(teamEventTypes?.length) && !rescheduleUid && (
<div className="flex flex-col gap-4">
<h1>Team event types</h1>
{teamEventTypes?.map(
(event: { id: number; slug: string; title: string; lengthInMinutes: number }) => {
const formatEventSlug = event.slug
.split("-")
.map((item) => `${item[0].toLocaleUpperCase()}${item.slice(1)}`)
.join(" ");
return (
<div
onClick={() => {
setEventTypeId(event.id);
setIsTeamEvent(true);
}}
className="mx-10 w-[80vw] cursor-pointer rounded-md border-[0.8px] border-black px-10 py-4"
key={event.id}>
<h1 className="text-lg font-semibold">{formatEventSlug}</h1>
<p>{`/${event.slug}`}</p>
<span className="border-none bg-gray-800 px-2 text-white">{event?.lengthInMinutes}</span>
</div>
);
}
)}
</div>
)}
{eventTypeId && (
<div>
<EventTypeSettings id={eventTypeId} tabs={["setup"]} />
</div>
)}
</div>
</main>
);
}
+1 -1
View File
@@ -83,7 +83,7 @@ export type { CityTimezones } from "@calcom/lib/cityTimezonesHandler";
export { TRPCError } from "@trpc/server";
export type { TUpdateInputSchema } from "@calcom/trpc/server/routers/viewer/availability/schedule/update.schema";
export type { TUpdateInputSchema as TUpdateEventTypeInputSchema } from "@calcom/trpc/server/routers/viewer/eventTypes/update.schema";
export { createNewUsersConnectToOrgIfExists, sendSignupToOrganizationEmail };
export { getAllUserBookings };