refactor: Move trpc-dependent components from features to web [1] (#25859)
* refactor: migrate UnconfirmedBookingBadge from features to apps/web Move UnconfirmedBookingBadge.tsx from packages/features/bookings/ to apps/web/modules/bookings/components/ as part of the architectural refactor to remove trpc client imports from the features layer. Also removes unused preserveBookingsQueryParams function from Navigation.tsx. Co-Authored-By: [email protected] <[email protected]> * refactor: move shell navigation and badges to apps/web Move shell navigation components and trpc-using badges from packages/features to apps/web/modules to fix circular dependency: - Move navigation folder to apps/web/modules/shell/navigation/ - Move TeamInviteBadge.tsx to apps/web/modules/shell/ - Create Shell wrapper in apps/web that provides MobileNavigationContainer - Update all Shell imports in apps/web to use the new wrapper - Remove MobileNavigationContainer default from features Shell.tsx - Fix pre-existing lint warnings in touched files This establishes the pattern for migrating React components that use trpc hooks from the features layer to the web app layer, ensuring proper dependency direction: apps/web imports from packages/features, never the reverse. Co-Authored-By: [email protected] <[email protected]> * fix: move SideBar.tsx to apps/web to fix build error SideBar.tsx was importing Navigation from the moved navigation folder, causing a build error. Moving SideBar.tsx to apps/web and updating the features Shell to not have a default SidebarContainer fixes this. The web Shell wrapper now provides both the default SidebarContainer and MobileNavigationContainer, maintaining the injection pattern. Co-Authored-By: [email protected] <[email protected]> * revert * revert * revert * wip * wip * wip * wip * wip * wip * not used anywhere * wip * wip * wip * wip * fix * fix * wip * wip * wip * wip * wip * fix * fix * fix * fix * migrate * migrate admin-adpi * wip * feat: migrate organization settings components from packages/features to apps/web/modules - Migrate profile.tsx, appearance.tsx, general.tsx, privacy.tsx, guest-notifications.tsx, delegationCredential.tsx, other-team-members-view.tsx, other-team-profile-view.tsx - Migrate attributes directory (AttributesForm.tsx, DeleteAttributeModal.tsx, ListSkeleton.tsx, attributes-create-view.tsx, attributes-edit-view.tsx, attributes-list-view.tsx) - Migrate admin directory (AdminOrgEditPage.tsx, AdminOrgPage.tsx, WorkspacePlatformPage.tsx) - Update all page imports to use new paths from ~/settings/organizations/ - Update relative imports in migrated files to use @calcom/features paths - Fix lint warnings in migrated files Co-Authored-By: [email protected] <[email protected]> * fix: update test import path after migration Co-Authored-By: [email protected] <[email protected]> * fix: remove unnecessary test-setup import (already in vitest config) Co-Authored-By: [email protected] <[email protected]> * wip * refactor: delete original files after migration to apps/web/modules Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * wip * refactor more * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * mv * update import paths * wip * wip * fix * fix * fix * fix * fix * fix * fix * mv * mv * mv * fix * wip * wip * fix * fix * fix * fix: make test mocks resilient to vi.resetAllMocks() Co-Authored-By: [email protected] <[email protected]> * fix: fix AttributeForm test failures Co-Authored-By: [email protected] <[email protected]> * fix * fix * refactor: move ee files to apps/web/modules/ee/ folder - Move teams, workflows, and organizations folders to apps/web/modules/ee/ - Add LICENSE file to apps/web/modules/ee/ - Update all import paths from ~/teams/ to ~/ee/teams/ - Update all import paths from ~/settings/organizations/ to ~/ee/organizations/ - Remove duplicate MemberInvitationModal copy.tsx file Co-Authored-By: [email protected] <[email protected]> * fix: move useHasPaidPlan and dependent files to apps/web/modules - Move useHasPaidPlan.ts from packages/features/billing/hooks to apps/web/modules/billing/hooks - Move intercom files from packages/features/ee/support to apps/web/modules/ee/support - Move ContactMenuItem.tsx and dependencies (freshchat, helpscout, zendesk) to apps/web/modules/ee/support - Move ViewRecordingsDialog.tsx and RecordingListSkeleton to apps/web/modules/ee/video - Move CalVideoSettings.tsx to apps/web/modules/eventtypes/components/locations - Move CreateOrEditOutOfOfficeModal.tsx to apps/web/modules/settings/outOfOffice - Refactor UpgradeTeamsBadge to accept props and create wrapper in apps/web/modules/billing - Update all callers to use new file locations - Add eslint-disable comments for pre-existing lint warnings This fixes the tRPC server build failure caused by circular dependency where the server build was traversing into packages/features and pulling in React hooks that depend on @calcom/trpc/react types. Co-Authored-By: [email protected] <[email protected]> * fix: correct UpgradeTeamsBadge import path to use package export Co-Authored-By: [email protected] <[email protected]> * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * fix * fix * fix * fix * fix * fix * fix * fix: pass plan state through SelectProps to UpgradeTeamsBadge - Add upgradeTeamsBadgeProps field to ExtendedOption type in Select component - Update OptionComponent to spread upgradeTeamsBadgeProps to UpgradeTeamsBadge - Update getOptions.ts to accept PlanState object and include upgradeTeamsBadgeProps - Update WorkflowStepContainer.tsx to pass planState to getWorkflowTriggerOptions/getWorkflowTemplateOptions - Update WorkflowDetailsPage.tsx to pass upgradeTeamsBadgeProps in transformed action options - Update AddActionDialog.tsx interface and mapping to include upgradeTeamsBadgeProps - Add eslint-disable comments for pre-existing React Hook dependency warnings This fixes the UpgradeTeamsBadge refactoring issue where the badge was always showing 'upgrade' text instead of the correct text based on plan state (trial_mode, inactive_team_plan, etc.) Co-Authored-By: [email protected] <[email protected]> * fix: update import paths to use /ee/ folder for workflows and organizations Co-Authored-By: [email protected] <[email protected]> * fix: update workflow component imports to use /ee/ folder Co-Authored-By: [email protected] <[email protected]> * fix: add missing types.ts for LocationInput.tsx Co-Authored-By: [email protected] <[email protected]> * fix: extract BookingRedirectForm type to shared location Co-Authored-By: [email protected] <[email protected]> * fix * wip * wip * fix: update BookingRedirectForm import to use local types file Co-Authored-By: [email protected] <[email protected]> * wip * fix * fix --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
7847177e8b
commit
8afe87ff75
374 files changed
+1213
-1417
No files matched your search
@@ -1,154 +0,0 @@
|
||||
import { isValidPhoneNumber } from "libphonenumber-js/max";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import { TeamEventTypeForm } from "@calcom/features/ee/teams/components/TeamEventTypeForm";
|
||||
import { useCreateEventType } from "@calcom/features/eventtypes/hooks/useCreateEventType";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
|
||||
import type { EventType } from "@calcom/prisma/client";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import CreateEventTypeForm from "./CreateEventTypeForm";
|
||||
|
||||
// this describes the uniform data needed to create a new event type on Profile or Team
|
||||
export interface EventTypeParent {
|
||||
teamId: number | null | undefined; // if undefined, then it's a profile
|
||||
membershipRole?: MembershipRole | null;
|
||||
name?: string | null;
|
||||
slug?: string | null;
|
||||
image?: string | null;
|
||||
}
|
||||
|
||||
export interface ProfileOption {
|
||||
teamId: number | null | undefined;
|
||||
label: string | null;
|
||||
image: string;
|
||||
membershipRole: MembershipRole | null | undefined;
|
||||
slug: string | null;
|
||||
permissions: {
|
||||
canCreateEventType: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const locationFormSchema = z.array(
|
||||
z.object({
|
||||
locationType: z.string(),
|
||||
locationAddress: z.string().optional(),
|
||||
displayLocationPublicly: z.boolean().optional(),
|
||||
locationPhoneNumber: z
|
||||
.string()
|
||||
.refine((val) => isValidPhoneNumber(val))
|
||||
.optional(),
|
||||
locationLink: z.string().url().optional(), // URL validates as new URL() - which requires HTTPS:// In the input field
|
||||
})
|
||||
);
|
||||
|
||||
const querySchema = z.object({
|
||||
eventPage: z.string().optional(),
|
||||
teamId: z.union([z.string().transform((val) => +val), z.number()]).optional(),
|
||||
title: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
length: z.union([z.string().transform((val) => +val), z.number()]).optional(),
|
||||
description: z.string().optional(),
|
||||
schedulingType: z.nativeEnum(SchedulingType).optional(),
|
||||
locations: z
|
||||
.string()
|
||||
.transform((jsonString) => locationFormSchema.parse(JSON.parse(jsonString)))
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function CreateEventTypeDialog({ profileOptions }: { profileOptions: ProfileOption[] }) {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
const {
|
||||
data: { teamId, eventPage: pageSlug },
|
||||
} = useTypedQuery(querySchema);
|
||||
|
||||
const teamProfile = profileOptions.find((profile) => profile.teamId === teamId);
|
||||
|
||||
const permissions = teamProfile?.permissions ?? { canCreateEventType: false };
|
||||
|
||||
const onSuccessMutation = (eventType: EventType) => {
|
||||
router.replace(`/event-types/${eventType.id}${teamId ? "?tabName=team" : ""}`);
|
||||
showToast(
|
||||
t("event_type_created_successfully", {
|
||||
eventTypeTitle: eventType.title,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
};
|
||||
|
||||
const onErrorMutation = (err: string) => {
|
||||
showToast(err, "error");
|
||||
};
|
||||
|
||||
const SubmitButton = (isPending: boolean) => {
|
||||
return (
|
||||
<DialogFooter showDivider>
|
||||
<DialogClose />
|
||||
<Button type="submit" loading={isPending}>
|
||||
{t("continue")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
);
|
||||
};
|
||||
|
||||
const { form, createMutation, isManagedEventType } = useCreateEventType(onSuccessMutation, onErrorMutation);
|
||||
|
||||
const urlPrefix = orgBranding?.fullDomain ?? process.env.NEXT_PUBLIC_WEBSITE_URL;
|
||||
|
||||
const { data: team } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: teamId ?? -1, isOrg: false },
|
||||
{ enabled: !!teamId }
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
name="new"
|
||||
clearQueryParamsOnClose={["eventPage", "type", "description", "title", "length", "slug", "locations"]}>
|
||||
<DialogContent
|
||||
type="creation"
|
||||
enableOverflow
|
||||
title={teamId ? t("add_new_team_event_type") : t("add_new_event_type")}
|
||||
description={t("new_event_type_to_book_description")}>
|
||||
{teamId ? (
|
||||
<TeamEventTypeForm
|
||||
teamSlug={team?.slug}
|
||||
teamId={teamId}
|
||||
permissions={permissions}
|
||||
urlPrefix={urlPrefix}
|
||||
isPending={createMutation.isPending}
|
||||
form={form}
|
||||
isManagedEventType={isManagedEventType}
|
||||
handleSubmit={(values) => {
|
||||
createMutation.mutate(values);
|
||||
}}
|
||||
SubmitButton={SubmitButton}
|
||||
/>
|
||||
) : (
|
||||
<CreateEventTypeForm
|
||||
urlPrefix={urlPrefix}
|
||||
isPending={createMutation.isPending}
|
||||
form={form}
|
||||
isManagedEventType={isManagedEventType}
|
||||
handleSubmit={(values) => {
|
||||
createMutation.mutate(values);
|
||||
}}
|
||||
SubmitButton={SubmitButton}
|
||||
pageSlug={pageSlug}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hook
|
||||
import { EventTypeEmbedButton, EventTypeEmbedDialog } from "@calcom/features/embed/EventTypeEmbed";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
import WebShell from "@calcom/features/shell/Shell";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
@@ -28,6 +27,7 @@ import type { VerticalTabItemProps } from "@calcom/ui/components/navigation";
|
||||
import { Skeleton } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import WebShell from "@calcom/web/modules/shell/Shell";
|
||||
|
||||
import { Shell as PlatformShell } from "../../../platform/atoms/src/components/ui/shell";
|
||||
import { DeleteDialog } from "./dialogs/DeleteDialog";
|
||||
@@ -276,11 +276,12 @@ function EventTypeSingleLayout({
|
||||
</Button>
|
||||
</div>
|
||||
}>
|
||||
<Suspense fallback={
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<Icon name="loader" className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
}>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<Icon name="loader" className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
}>
|
||||
<div className="flex flex-col xl:flex-row xl:space-x-6">
|
||||
<div className="hidden xl:block">
|
||||
<VerticalTabs
|
||||
|
||||
@@ -39,7 +39,7 @@ const mockTeamMembers: TeamMember[] = [
|
||||
];
|
||||
|
||||
// Mock trpc
|
||||
vi.mock("@calcom/trpc", () => ({
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
useUtils: () => ({
|
||||
viewer: {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
export { default as CheckedTeamSelect } from "./CheckedTeamSelect";
|
||||
export { CreateEventTypeDialog } from "./CreateEventTypeDialog";
|
||||
export { default as EventTypeDescription } from "./EventTypeDescription";
|
||||
export { LearnMoreLink } from "./LearnMoreLink";
|
||||
export { MultiplePrivateLinksController } from "./MultiplePrivateLinksController";
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import { ErrorMessage } from "@hookform/error-message";
|
||||
import { useState } from "react";
|
||||
import { useFormContext, Controller } from "react-hook-form";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import { useHasTeamPlan } from "@calcom/features/billing/hooks/useHasPaidPlan";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import type { CalVideoSettings as CalVideoSettingsType } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { UpgradeTeamsBadge } from "@calcom/ui/components/badge";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import LocationSettingsContainer from "./LocationSettingsContainer";
|
||||
|
||||
const CalVideoSettings = ({ calVideoSettings }: { calVideoSettings?: CalVideoSettingsType }) => {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const isPlatform = useIsPlatform();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [parent] = useAutoAnimate<HTMLDivElement>();
|
||||
const { hasTeamPlan } = useHasTeamPlan();
|
||||
return (
|
||||
<>
|
||||
<Tooltip content="expandable" side="right" className="lg:hidden">
|
||||
<button
|
||||
aria-expanded={isExpanded}
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
className={classNames(
|
||||
"todesktop:py-[7px] text-default group flex w-full items-center rounded-md px-2 py-1.5 text-sm font-medium transition",
|
||||
"[&[aria-current='page']]:!bg-transparent",
|
||||
"[&[aria-current='page']]:text-emphasis mt-0.5 text-sm"
|
||||
)}>
|
||||
<span className="hidden w-full justify-between truncate text-ellipsis lg:flex">
|
||||
{!isExpanded ? t("show_advanced_settings") : t("hide_advanced_settings")}
|
||||
</span>
|
||||
<Icon name={isExpanded ? "chevron-up" : "chevron-down"} className="ml-auto h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<div ref={parent}>
|
||||
{isExpanded && (
|
||||
<LocationSettingsContainer>
|
||||
<Controller
|
||||
name="calVideoSettings.disableRecordingForGuests"
|
||||
defaultValue={!!calVideoSettings?.disableRecordingForGuests}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("disable_recording_for_guests")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal wrap-break-word"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Controller
|
||||
name="calVideoSettings.disableRecordingForOrganizer"
|
||||
defaultValue={!!calVideoSettings?.disableRecordingForOrganizer}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("disable_recording_for_organizer")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal wrap-break-word"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
{!isPlatform && (
|
||||
<Controller
|
||||
name="calVideoSettings.enableAutomaticRecordingForOrganizer"
|
||||
defaultValue={!!calVideoSettings?.enableAutomaticRecordingForOrganizer}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("enable_automatic_recording")}
|
||||
labelClassName="text-sm"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Controller
|
||||
name="calVideoSettings.enableAutomaticTranscription"
|
||||
defaultValue={!!calVideoSettings?.enableAutomaticTranscription}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("enable_automatic_transcription")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal wrap-break-word"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
{!isPlatform && (
|
||||
<Controller
|
||||
name="calVideoSettings.disableTranscriptionForGuests"
|
||||
defaultValue={!!calVideoSettings?.disableTranscriptionForGuests}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("disable_transcription_for_guests")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal wrap-break-word"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{!isPlatform && (
|
||||
<Controller
|
||||
name="calVideoSettings.disableTranscriptionForOrganizer"
|
||||
defaultValue={!!calVideoSettings?.disableTranscriptionForOrganizer}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("disable_transcription_for_organizer")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal wrap-break-word"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Controller
|
||||
name="calVideoSettings.requireEmailForGuests"
|
||||
defaultValue={!!calVideoSettings?.requireEmailForGuests}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("require_email_for_guests")}
|
||||
description={t("require_email_for_guests_description")}
|
||||
labelClassName="text-sm leading-6 whitespace-normal break-words"
|
||||
checked={value}
|
||||
disabled={!hasTeamPlan}
|
||||
onCheckedChange={onChange}
|
||||
Badge={<UpgradeTeamsBadge checkForActiveStatus />}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label={t("enter_redirect_url_on_exit_description")}
|
||||
defaultValue={calVideoSettings?.redirectUrlOnExit || ""}
|
||||
data-testid="calVideoSettings.redirectUrlOnExit"
|
||||
containerClassName="mt-4"
|
||||
className="leading-6"
|
||||
{...formMethods.register("calVideoSettings.redirectUrlOnExit", {
|
||||
setValueAs: (v) => (!v || v.trim() === "" ? null : v),
|
||||
})}
|
||||
/>
|
||||
<ErrorMessage
|
||||
errors={formMethods.formState.errors?.calVideoSettings}
|
||||
name="redirectUrlOnExit"
|
||||
className={classNames("text-error text-sm")}
|
||||
as="div"
|
||||
id="calVideoSettings.redirectUrlOnExit-error"
|
||||
/>
|
||||
</LocationSettingsContainer>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default CalVideoSettings;
|
||||
@@ -1,95 +0,0 @@
|
||||
import { ErrorMessage } from "@hookform/error-message";
|
||||
import { useFieldArray, useFormContext } from "react-hook-form";
|
||||
|
||||
import { getEventLocationType } from "@calcom/app-store/locations";
|
||||
import type { LocationFormValues, FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import CheckboxField from "@calcom/features/form/components/CheckboxField";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
|
||||
import LocationInput from "./LocationInput";
|
||||
import LocationOptionContainer from "./LocationSettingsContainer";
|
||||
import type { LocationCustomClassNames } from "./types";
|
||||
|
||||
const DefaultLocationSettings = ({
|
||||
field,
|
||||
index,
|
||||
disableLocationProp,
|
||||
customClassNames,
|
||||
}: {
|
||||
field: LocationFormValues["locations"][number];
|
||||
index: number;
|
||||
disableLocationProp?: boolean;
|
||||
customClassNames?: LocationCustomClassNames;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { getValues, control, formState } = useFormContext<FormValues>();
|
||||
const { update: updateLocationField } = useFieldArray({
|
||||
control,
|
||||
name: "locations",
|
||||
});
|
||||
const defaultLocation = field;
|
||||
const eventLocationType = getEventLocationType(field.type);
|
||||
|
||||
if (!eventLocationType) return null;
|
||||
|
||||
return (
|
||||
<LocationOptionContainer>
|
||||
<LocationInput
|
||||
label={"organizerInputLabel" in eventLocationType ? eventLocationType?.organizerInputLabel : null}
|
||||
data-testid={`${eventLocationType.type}-location-input`}
|
||||
defaultValue={defaultLocation ? defaultLocation[eventLocationType.defaultValueVariable] : undefined}
|
||||
eventLocationType={eventLocationType}
|
||||
index={index}
|
||||
customClassNames={customClassNames?.organizerContactInput?.locationInput}
|
||||
disableLocationProp={disableLocationProp}
|
||||
/>
|
||||
<ErrorMessage
|
||||
errors={formState.errors?.locations?.[index]}
|
||||
name={eventLocationType.defaultValueVariable}
|
||||
className={classNames(
|
||||
"text-error my-1 ml-6 text-sm",
|
||||
customClassNames?.organizerContactInput?.errorMessage
|
||||
)}
|
||||
as="div"
|
||||
id="location-error"
|
||||
/>
|
||||
{eventLocationType.organizerInputType && (
|
||||
<CheckboxField
|
||||
name={`locations[${index}].displayLocationPublicly`}
|
||||
data-testid="display-location"
|
||||
disabled={disableLocationProp}
|
||||
defaultChecked={defaultLocation?.displayLocationPublicly}
|
||||
description={t("display_location_label")}
|
||||
className={customClassNames?.organizerContactInput?.publicDisplayCheckbox?.checkbox}
|
||||
onChange={(e) => {
|
||||
const fieldValues = getValues("locations")[index];
|
||||
updateLocationField(index, {
|
||||
...fieldValues,
|
||||
displayLocationPublicly: e.target.checked,
|
||||
});
|
||||
}}
|
||||
informationIconText={t("display_location_info_badge")}
|
||||
/>
|
||||
)}
|
||||
{eventLocationType?.supportsCustomLabel && (
|
||||
<TextField
|
||||
label={t("location_custom_label_input_label")}
|
||||
name={`locations[${index}].customLabel`}
|
||||
type="text"
|
||||
defaultValue={defaultLocation?.customLabel}
|
||||
onChange={(e) => {
|
||||
const fieldValues = getValues("locations")[index];
|
||||
updateLocationField(index, {
|
||||
...fieldValues,
|
||||
customLabel: e.target.value,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</LocationOptionContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default DefaultLocationSettings;
|
||||
@@ -1,76 +0,0 @@
|
||||
import { useFormContext, Controller } from "react-hook-form";
|
||||
|
||||
import type { EventLocationType } from "@calcom/app-store/locations";
|
||||
import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
|
||||
import type { LocationInputCustomClassNames } from "./types";
|
||||
|
||||
const LocationInput = (props: {
|
||||
eventLocationType: EventLocationType;
|
||||
defaultValue?: string;
|
||||
index: number;
|
||||
customClassNames?: LocationInputCustomClassNames;
|
||||
disableLocationProp?: boolean;
|
||||
label?: string | null;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { eventLocationType, index, customClassNames, disableLocationProp, label, ...remainingProps } = props;
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
if (eventLocationType?.organizerInputType === "text") {
|
||||
const { defaultValue, ...rest } = remainingProps;
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name={`locations.${index}.${eventLocationType.defaultValueVariable}`}
|
||||
defaultValue={defaultValue}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<TextField
|
||||
label={label ? t(label) : null}
|
||||
name={`locations[${index}].${eventLocationType.defaultValueVariable}`}
|
||||
placeholder={t(eventLocationType.organizerInputPlaceholder || "")}
|
||||
type="text"
|
||||
required
|
||||
onChange={onChange}
|
||||
value={value}
|
||||
{...(disableLocationProp ? { disabled: true } : {})}
|
||||
className={classNames("my-0", customClassNames?.addressInput)}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else if (eventLocationType?.organizerInputType === "phone") {
|
||||
const { defaultValue, ...rest } = remainingProps;
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name={`locations.${index}.${eventLocationType.defaultValueVariable}`}
|
||||
defaultValue={defaultValue}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<PhoneInput
|
||||
required
|
||||
disabled={disableLocationProp}
|
||||
placeholder={t(eventLocationType.organizerInputPlaceholder || "")}
|
||||
name={`locations[${index}].${eventLocationType.defaultValueVariable}`}
|
||||
className={customClassNames?.phoneInput}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export default LocationInput;
|
||||
@@ -1,11 +0,0 @@
|
||||
const LocationSettingsContainer = ({ children }: { children: React.ReactNode }) => {
|
||||
return (
|
||||
<div className="bg-cal-muted mt-2 stack-y-2 rounded-lg p-4">
|
||||
<div className="w-full">
|
||||
<div className="flex flex-col gap-4">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LocationSettingsContainer;
|
||||
@@ -1,439 +0,0 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import { ErrorMessage } from "@hookform/error-message";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useFieldArray } from "react-hook-form";
|
||||
import type { UseFormGetValues, UseFormSetValue, Control, FormState } from "react-hook-form";
|
||||
|
||||
import type { EventLocationType } from "@calcom/app-store/locations";
|
||||
import { getEventLocationType, MeetLocationType } from "@calcom/app-store/locations";
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import type { LocationFormValues, EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
import CheckboxField from "@calcom/features/form/components/CheckboxField";
|
||||
import type { SingleValueLocationOption } from "@calcom/features/form/components/LocationSelect";
|
||||
import LocationSelect from "@calcom/features/form/components/LocationSelect";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
import CalVideoSettings from "./CalVideoSettings";
|
||||
import DefaultLocationSettings from "./DefaultLocationSettings";
|
||||
import LocationInput from "./LocationInput";
|
||||
import type { LocationCustomClassNames } from "./types";
|
||||
|
||||
export type TEventTypeLocation = Pick<EventTypeSetupProps["eventType"], "locations" | "calVideoSettings">;
|
||||
export type TLocationOptions = Pick<EventTypeSetupProps, "locationOptions">["locationOptions"];
|
||||
export type TDestinationCalendar = { integration: string } | null;
|
||||
export type TPrefillLocation = { credentialId?: number; type: string };
|
||||
|
||||
type LocationsProps = {
|
||||
team: { id: number } | null;
|
||||
destinationCalendar: TDestinationCalendar;
|
||||
showAppStoreLink: boolean;
|
||||
isChildrenManagedEventType?: boolean;
|
||||
isManagedEventType?: boolean;
|
||||
disableLocationProp?: boolean;
|
||||
getValues: UseFormGetValues<LocationFormValues>;
|
||||
setValue: UseFormSetValue<LocationFormValues>;
|
||||
control: Control<LocationFormValues>;
|
||||
formState: FormState<LocationFormValues>;
|
||||
eventType: TEventTypeLocation;
|
||||
locationOptions: TLocationOptions;
|
||||
prefillLocation?: SingleValueLocationOption;
|
||||
customClassNames?: LocationCustomClassNames;
|
||||
};
|
||||
|
||||
const getLocationFromType = (type: EventLocationType["type"], locationOptions: TLocationOptions) => {
|
||||
for (const locationOption of locationOptions) {
|
||||
const option = locationOption.options.find((option) => option.value === type);
|
||||
if (option) {
|
||||
return option;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getLocationInfo = ({
|
||||
eventType,
|
||||
locationOptions,
|
||||
}: {
|
||||
eventType: TEventTypeLocation;
|
||||
locationOptions: TLocationOptions;
|
||||
}) => {
|
||||
const locationAvailable =
|
||||
eventType.locations &&
|
||||
eventType.locations.length > 0 &&
|
||||
locationOptions.some((op) => op.options.find((opt) => opt.value === eventType.locations[0].type));
|
||||
const locationDetails = eventType.locations &&
|
||||
eventType.locations.length > 0 &&
|
||||
!locationAvailable && {
|
||||
slug: eventType.locations[0].type.replace("integrations:", "").replace(":", "-").replace("_video", ""),
|
||||
name: eventType.locations[0].type
|
||||
.replace("integrations:", "")
|
||||
.replace(":", " ")
|
||||
.replace("_video", "")
|
||||
.split(" ")
|
||||
.map((word) => word[0].toUpperCase() + word.slice(1))
|
||||
.join(" "),
|
||||
};
|
||||
return { locationAvailable, locationDetails };
|
||||
};
|
||||
|
||||
const Locations: React.FC<LocationsProps> = ({
|
||||
isChildrenManagedEventType,
|
||||
disableLocationProp,
|
||||
isManagedEventType,
|
||||
getValues,
|
||||
setValue: _setValue,
|
||||
control,
|
||||
formState,
|
||||
team,
|
||||
eventType,
|
||||
prefillLocation,
|
||||
customClassNames,
|
||||
...props
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const {
|
||||
fields: locationFields,
|
||||
append,
|
||||
remove,
|
||||
update: updateLocationField,
|
||||
} = useFieldArray({
|
||||
control,
|
||||
name: "locations",
|
||||
});
|
||||
|
||||
const locationOptions = props.locationOptions.map((locationOption) => {
|
||||
const options = locationOption.options.filter((option) => {
|
||||
// Skip "Organizer's Default App" for non-team members
|
||||
return !team?.id ? option.label !== t("organizer_default_conferencing_app") : true;
|
||||
});
|
||||
|
||||
return {
|
||||
...locationOption,
|
||||
options,
|
||||
};
|
||||
});
|
||||
|
||||
const [animationRef] = useAutoAnimate<HTMLUListElement>();
|
||||
const seatsEnabled = !!getValues("seatsPerTimeSlot");
|
||||
|
||||
const validLocations =
|
||||
getValues("locations")?.filter((location) => {
|
||||
const eventLocation = getEventLocationType(location.type);
|
||||
if (!eventLocation) {
|
||||
// It's possible that the location app in use got uninstalled.
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}) || [];
|
||||
|
||||
const defaultValue = isManagedEventType
|
||||
? locationOptions.find((op) => op.label === t("default"))?.options[0]
|
||||
: undefined;
|
||||
|
||||
const { locationDetails, locationAvailable } = getLocationInfo({
|
||||
eventType,
|
||||
locationOptions: props.locationOptions,
|
||||
});
|
||||
|
||||
const [showEmptyLocationSelect, setShowEmptyLocationSelect] = useState(false);
|
||||
const defaultInitialLocation = defaultValue || null;
|
||||
const [selectedNewOption, setSelectedNewOption] = useState<SingleValueLocationOption | null>(
|
||||
defaultInitialLocation
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (prefillLocation) {
|
||||
const newLocationType = prefillLocation.value;
|
||||
|
||||
const canAppendLocation = !validLocations.find((location) => location.type === newLocationType);
|
||||
|
||||
if (canAppendLocation && !seatsEnabled) {
|
||||
append({
|
||||
type: newLocationType,
|
||||
credentialId: prefillLocation?.credentialId,
|
||||
});
|
||||
setSelectedNewOption(prefillLocation);
|
||||
}
|
||||
}
|
||||
}, [prefillLocation, seatsEnabled, validLocations, append]);
|
||||
|
||||
const isPlatform = useIsPlatform();
|
||||
|
||||
return (
|
||||
<div className={classNames("w-full", customClassNames?.container)}>
|
||||
<ul ref={animationRef} className={classNames("stack-y-2")}>
|
||||
{locationFields.map((field, index) => {
|
||||
const eventLocationType = getEventLocationType(field.type);
|
||||
const defaultLocation = field;
|
||||
|
||||
const isCalVideo = field.type === "integrations:daily";
|
||||
|
||||
const option = getLocationFromType(field.type, locationOptions);
|
||||
return (
|
||||
<li key={field.id}>
|
||||
<div className="flex w-full items-center">
|
||||
<LocationSelect
|
||||
name={`locations[${index}].type`}
|
||||
placeholder={t("select")}
|
||||
options={locationOptions}
|
||||
isDisabled={disableLocationProp}
|
||||
defaultValue={option}
|
||||
isSearchable={false}
|
||||
className={classNames(
|
||||
"block min-w-0 flex-1 rounded-sm text-sm",
|
||||
customClassNames?.locationSelect?.selectWrapper
|
||||
)}
|
||||
customClassNames={customClassNames?.locationSelect}
|
||||
menuPlacement="auto"
|
||||
onChange={(e: SingleValueLocationOption) => {
|
||||
setShowEmptyLocationSelect(false);
|
||||
if (e?.value) {
|
||||
const newLocationType = e.value;
|
||||
const eventLocationType = getEventLocationType(newLocationType);
|
||||
if (!eventLocationType) {
|
||||
return;
|
||||
}
|
||||
const canAddLocation =
|
||||
eventLocationType.organizerInputType ||
|
||||
!validLocations?.find((location) => location.type === newLocationType);
|
||||
|
||||
const shouldUpdateLink =
|
||||
eventLocationType?.organizerInputType === "text" &&
|
||||
eventLocationType.defaultValueVariable === "link";
|
||||
|
||||
if (canAddLocation) {
|
||||
updateLocationField(index, {
|
||||
type: newLocationType,
|
||||
...(e.credentialId && {
|
||||
credentialId: e.credentialId,
|
||||
teamName: e.teamName ?? undefined,
|
||||
}),
|
||||
...(shouldUpdateLink && {
|
||||
link: "",
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
updateLocationField(index, {
|
||||
type: field.type,
|
||||
...(field.credentialId && {
|
||||
credentialId: field.credentialId,
|
||||
teamName: field.teamName ?? undefined,
|
||||
}),
|
||||
});
|
||||
showToast(t("location_already_exists"), "warning");
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{!(disableLocationProp && isChildrenManagedEventType) && (
|
||||
<button
|
||||
data-testid={`delete-locations.${index}.type`}
|
||||
className={classNames("min-h-9 block h-9 px-2", customClassNames?.removeLocationButton)}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
remove(index);
|
||||
setSelectedNewOption(null);
|
||||
}}
|
||||
aria-label={t("remove")}>
|
||||
<div className="h-4 w-4">
|
||||
<Icon
|
||||
name="x"
|
||||
className={classNames(
|
||||
"hover:text-emphasis text-subtle h-4 w-4",
|
||||
customClassNames?.removeLocationIcon
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isCalVideo && !isPlatform && <CalVideoSettings />}
|
||||
|
||||
{eventLocationType?.supportsCustomLabel && eventLocationType?.type ? (
|
||||
<DefaultLocationSettings
|
||||
field={field}
|
||||
index={index}
|
||||
disableLocationProp={disableLocationProp}
|
||||
customClassNames={customClassNames}
|
||||
/>
|
||||
) : eventLocationType?.organizerInputType ? (
|
||||
<div className="mt-2 stack-y-2">
|
||||
<div className="w-full">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex items-center justify-center">
|
||||
<Icon name="corner-down-right" className="h-4 w-4" />
|
||||
</div>
|
||||
<LocationInput
|
||||
data-testid={`${eventLocationType.type}-location-input`}
|
||||
defaultValue={
|
||||
defaultLocation
|
||||
? defaultLocation[eventLocationType.defaultValueVariable]
|
||||
: undefined
|
||||
}
|
||||
eventLocationType={eventLocationType}
|
||||
index={index}
|
||||
customClassNames={customClassNames?.organizerContactInput?.locationInput}
|
||||
disableLocationProp={disableLocationProp}
|
||||
/>
|
||||
</div>
|
||||
<ErrorMessage
|
||||
errors={formState.errors?.locations?.[index]}
|
||||
name={eventLocationType.defaultValueVariable}
|
||||
className={classNames(
|
||||
"text-error my-1 ml-6 text-sm",
|
||||
customClassNames?.organizerContactInput?.errorMessage
|
||||
)}
|
||||
as="div"
|
||||
id="location-error"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"ml-6",
|
||||
customClassNames?.organizerContactInput?.publicDisplayCheckbox?.container
|
||||
)}>
|
||||
<CheckboxField
|
||||
name={`locations[${index}].displayLocationPublicly`}
|
||||
data-testid="display-location"
|
||||
disabled={disableLocationProp}
|
||||
defaultChecked={defaultLocation?.displayLocationPublicly}
|
||||
description={t("display_location_label")}
|
||||
className={customClassNames?.organizerContactInput?.publicDisplayCheckbox?.checkbox}
|
||||
onChange={(e) => {
|
||||
const fieldValues = getValues("locations")[index];
|
||||
updateLocationField(index, {
|
||||
...fieldValues,
|
||||
displayLocationPublicly: e.target.checked,
|
||||
});
|
||||
}}
|
||||
informationIconText={t("display_location_info_badge")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{(validLocations.length === 0 || showEmptyLocationSelect) && (
|
||||
<div className="flex">
|
||||
<LocationSelect
|
||||
defaultMenuIsOpen={showEmptyLocationSelect}
|
||||
placeholder={t("select")}
|
||||
options={locationOptions}
|
||||
value={selectedNewOption}
|
||||
isDisabled={disableLocationProp}
|
||||
defaultValue={defaultValue}
|
||||
isSearchable={false}
|
||||
className={classNames(
|
||||
"block w-full min-w-0 flex-1 rounded-sm text-sm",
|
||||
customClassNames?.locationSelect?.selectWrapper
|
||||
)}
|
||||
customClassNames={customClassNames?.locationSelect}
|
||||
menuPlacement="auto"
|
||||
onChange={(e: SingleValueLocationOption) => {
|
||||
setShowEmptyLocationSelect(false);
|
||||
if (e?.value) {
|
||||
const newLocationType = e.value;
|
||||
const eventLocationType = getEventLocationType(newLocationType);
|
||||
if (!eventLocationType) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canAppendLocation =
|
||||
eventLocationType.organizerInputType ||
|
||||
!validLocations.find((location) => location.type === newLocationType);
|
||||
|
||||
if (canAppendLocation) {
|
||||
append({
|
||||
type: newLocationType,
|
||||
...(e.credentialId && {
|
||||
credentialId: e.credentialId,
|
||||
teamName: e.teamName ?? undefined,
|
||||
}),
|
||||
});
|
||||
setSelectedNewOption(e);
|
||||
} else {
|
||||
showToast(t("location_already_exists"), "warning");
|
||||
setSelectedNewOption(null);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{validLocations.some(
|
||||
(location) =>
|
||||
location.type === MeetLocationType && props.destinationCalendar?.integration !== "google_calendar"
|
||||
) && (
|
||||
<div className="text-default flex items-center text-sm">
|
||||
<div className="mr-1.5 h-3 w-3">
|
||||
<Icon name="check" className="h-3 w-3" />
|
||||
</div>
|
||||
<p className="text-default text-sm">
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="event_type_requires_google_calendar"
|
||||
components={[
|
||||
<Link
|
||||
key="event_type_requires_google_calendar"
|
||||
className="cursor-pointer text-blue-500 underline"
|
||||
href="/apps/google-calendar">
|
||||
here
|
||||
</Link>,
|
||||
]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{isChildrenManagedEventType && !locationAvailable && locationDetails && (
|
||||
<p className="pl-1 text-sm leading-none text-red-600">
|
||||
{t("app_not_connected", { appName: locationDetails.name })}{" "}
|
||||
<a className="underline" href={`${WEBAPP_URL}/apps/${locationDetails.slug}`}>
|
||||
{t("connect_now")}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
{validLocations.length > 0 && !disableLocationProp && (
|
||||
// && !isChildrenManagedEventType : Add this to hide add-location button only when location is disabled by Admin
|
||||
<li>
|
||||
<Button
|
||||
data-testid="add-location"
|
||||
StartIcon="plus"
|
||||
color="minimal"
|
||||
disabled={seatsEnabled}
|
||||
className={classNames(customClassNames?.addLocationButton)}
|
||||
tooltip={seatsEnabled ? t("seats_option_doesnt_support_multi_location") : undefined}
|
||||
onClick={() => setShowEmptyLocationSelect(true)}>
|
||||
{t("add_location")}
|
||||
</Button>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
{props.showAppStoreLink && !isPlatform && (
|
||||
<p className="text-default mt-2 text-sm">
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="cant_find_the_right_conferencing_app_visit_our_app_store"
|
||||
components={[
|
||||
<Link
|
||||
key="cant_find_the_right_conferencing_app_visit_our_app_store"
|
||||
className="cursor-pointer text-blue-500 underline"
|
||||
href="/apps/categories/conferencing">
|
||||
App Store
|
||||
</Link>,
|
||||
]}
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Locations;
|
||||
@@ -1,407 +0,0 @@
|
||||
import type { FC } from "react";
|
||||
import type { SubmitHandler } from "react-hook-form";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
import { useForm, useFormContext } from "react-hook-form";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
import { getEventName, validateCustomEventName } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
import type { InputClassNames } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
|
||||
interface FormValues {
|
||||
customEventName: string;
|
||||
}
|
||||
|
||||
export type CustomEventTypeModalClassNames = {
|
||||
eventNameInput?: InputClassNames;
|
||||
availableVariables?: {
|
||||
container?: string;
|
||||
header?: string;
|
||||
scrollArea?: string;
|
||||
variableItem?: {
|
||||
container?: string;
|
||||
variableName?: string;
|
||||
variableDescription?: string;
|
||||
};
|
||||
bookingFieldsHeader?: string;
|
||||
bookingFieldItem?: {
|
||||
container?: string;
|
||||
fieldName?: string;
|
||||
fieldValue?: string;
|
||||
};
|
||||
};
|
||||
previewSection?: {
|
||||
header?: string;
|
||||
previewContainer?: string;
|
||||
previewEventBox?: {
|
||||
container?: string;
|
||||
eventName?: string;
|
||||
eventTime?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
interface CustomEventTypeModalFormProps {
|
||||
placeHolder: string;
|
||||
close: () => void;
|
||||
setValue: (value: string) => void;
|
||||
event: EventNameObjectType;
|
||||
defaultValue: string;
|
||||
isNameFieldSplit: boolean;
|
||||
customClassNames?: CustomEventTypeModalClassNames;
|
||||
}
|
||||
|
||||
const CustomEventTypeModalForm: FC<CustomEventTypeModalFormProps> = (props) => {
|
||||
const { t } = useLocale();
|
||||
const { placeHolder, close, setValue, event, isNameFieldSplit, customClassNames } = props;
|
||||
const { register, handleSubmit, watch, getValues } = useFormContext<FormValues>();
|
||||
const onSubmit: SubmitHandler<FormValues> = (data) => {
|
||||
setValue(data.customEventName);
|
||||
close();
|
||||
};
|
||||
|
||||
const previewText = getEventName({ ...event, eventName: watch("customEventName") });
|
||||
const placeHolder_ = watch("customEventName") === "" ? previewText : placeHolder;
|
||||
|
||||
return (
|
||||
<form
|
||||
id="custom-event-name"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const isEmpty = getValues("customEventName") === "";
|
||||
if (isEmpty) {
|
||||
setValue("");
|
||||
}
|
||||
handleSubmit(onSubmit)(e);
|
||||
}}>
|
||||
<TextField
|
||||
label={t("event_name_in_calendar")}
|
||||
type="text"
|
||||
placeholder={placeHolder_}
|
||||
{...register("customEventName", {
|
||||
validate: (value) => {
|
||||
const validationResult = validateCustomEventName(value, event.bookingFields);
|
||||
return typeof validationResult === "string"
|
||||
? t("invalid_event_name_variables", { item: validationResult })
|
||||
: validationResult;
|
||||
},
|
||||
})}
|
||||
containerClassName={customClassNames?.eventNameInput?.container}
|
||||
labelClassName={customClassNames?.eventNameInput?.label}
|
||||
className={classNames("mb-0", customClassNames?.eventNameInput?.input)}
|
||||
/>
|
||||
<div className="pt-6 text-sm">
|
||||
<div
|
||||
className={classNames(
|
||||
"bg-subtle mb-6 rounded-md p-2",
|
||||
customClassNames?.availableVariables?.container
|
||||
)}>
|
||||
<h1
|
||||
className={classNames(
|
||||
"text-emphasis mb-2 ml-1 font-medium",
|
||||
customClassNames?.availableVariables?.header
|
||||
)}>
|
||||
{t("available_variables")}
|
||||
</h1>
|
||||
<div
|
||||
className={classNames(
|
||||
"scroll-bar h-[216px] overflow-y-auto",
|
||||
customClassNames?.availableVariables?.scrollArea
|
||||
)}>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Event type title}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("event_name_info")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Event duration}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("event_duration_info")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Organiser}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("your_full_name")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Organiser first name}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("organizer_first_name")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Scheduler}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("scheduler_full_name")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Scheduler first name}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("scheduler_first_name")}
|
||||
</p>
|
||||
</div>
|
||||
{isNameFieldSplit && (
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Scheduler last name}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("scheduler_last_name")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.variableItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.variableItem?.variableName
|
||||
)}>
|
||||
{`{Location}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1",
|
||||
customClassNames?.availableVariables?.variableItem?.variableDescription
|
||||
)}>
|
||||
{t("location_info")}
|
||||
</p>
|
||||
</div>
|
||||
{/* Additional variable items here */}
|
||||
{event.bookingFields && (
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle mb-2 ml-1 font-medium",
|
||||
customClassNames?.availableVariables?.bookingFieldsHeader
|
||||
)}>
|
||||
{t("booking_question_response_variables")}
|
||||
</p>
|
||||
)}
|
||||
{event.bookingFields &&
|
||||
Object.keys(event.bookingFields).map((bookingfield, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={classNames(
|
||||
"mb-2.5 flex items-start font-normal",
|
||||
customClassNames?.availableVariables?.bookingFieldItem?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle ml-1 mr-5 w-40 shrink-0",
|
||||
customClassNames?.availableVariables?.bookingFieldItem?.fieldName
|
||||
)}>
|
||||
{`{${bookingfield}}`}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis min-w-0 flex-1 capitalize",
|
||||
customClassNames?.availableVariables?.bookingFieldItem?.fieldValue
|
||||
)}>
|
||||
{event.bookingFields?.[bookingfield]?.toString()}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<h1
|
||||
className={classNames(
|
||||
"mb-2 text-[14px] font-medium leading-4",
|
||||
customClassNames?.previewSection?.header
|
||||
)}>
|
||||
{t("preview")}
|
||||
</h1>
|
||||
<div
|
||||
className={classNames(
|
||||
"flex h-[212px] w-full rounded-md border-y bg-cover bg-center dark:invert",
|
||||
customClassNames?.previewSection?.previewContainer
|
||||
)}
|
||||
style={{
|
||||
backgroundImage: "url(/calendar-preview.svg)",
|
||||
}}>
|
||||
<div className="m-auto flex items-center justify-center self-stretch">
|
||||
<div
|
||||
className={classNames(
|
||||
"bg-subtle ml-11 mt-3 box-border h-[110px] w-[120px] flex-col items-start gap-1 rounded-md border border-solid border-black text-[12px] leading-3",
|
||||
customClassNames?.previewSection?.previewEventBox?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis overflow-hidden text-ellipsis p-1.5 font-medium",
|
||||
customClassNames?.previewSection?.previewEventBox?.eventName
|
||||
)}>
|
||||
{previewText}
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-default ml-1.5 text-[10px] font-normal",
|
||||
customClassNames?.previewSection?.previewEventBox?.eventTime
|
||||
)}>
|
||||
8 - 10 AM
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
interface CustomEventTypeModalProps {
|
||||
placeHolder: string;
|
||||
defaultValue: string;
|
||||
close: () => void;
|
||||
setValue: (value: string) => void;
|
||||
event: EventNameObjectType;
|
||||
isNameFieldSplit: boolean;
|
||||
customClassNames?: CustomEventTypeModalClassNames;
|
||||
}
|
||||
|
||||
const CustomEventTypeModal: FC<CustomEventTypeModalProps> = (props) => {
|
||||
const { t } = useLocale();
|
||||
const { defaultValue, placeHolder, close, setValue, event, isNameFieldSplit, customClassNames } = props;
|
||||
|
||||
const methods = useForm<FormValues>({
|
||||
defaultValues: {
|
||||
customEventName: defaultValue,
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={true} onOpenChange={close}>
|
||||
<DialogContent
|
||||
title={t("custom_event_name")}
|
||||
description={t("custom_event_name_description")}
|
||||
type="creation"
|
||||
enableOverflow>
|
||||
<FormProvider {...methods}>
|
||||
<CustomEventTypeModalForm
|
||||
event={event}
|
||||
close={close}
|
||||
setValue={setValue}
|
||||
placeHolder={placeHolder}
|
||||
defaultValue={defaultValue}
|
||||
isNameFieldSplit={isNameFieldSplit}
|
||||
customClassNames={customClassNames}
|
||||
/>
|
||||
</FormProvider>
|
||||
<DialogFooter>
|
||||
<DialogClose>{t("cancel")}</DialogClose>
|
||||
<Button form="custom-event-name" type="submit" color="primary">
|
||||
{t("create")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomEventTypeModal;
|
||||
@@ -1,102 +0,0 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import type { InputClassNames, SettingsToggleClassNames } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { InputField } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
|
||||
export type EmailNotificationToggleCustomClassNames = SettingsToggleClassNames & {
|
||||
confirmationDialog?: {
|
||||
container?: string;
|
||||
dialogTitle?: string;
|
||||
description?: string;
|
||||
confirmInput?: InputClassNames;
|
||||
dialogFooter?: {
|
||||
container?: string;
|
||||
confirmButton?: string;
|
||||
cancelButton?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
interface DisableEmailsSettingProps {
|
||||
checked: boolean;
|
||||
onCheckedChange: (e: boolean) => void;
|
||||
recipient: "attendees" | "hosts";
|
||||
t: TFunction;
|
||||
customClassNames?: EmailNotificationToggleCustomClassNames;
|
||||
}
|
||||
|
||||
export const DisableAllEmailsSetting = ({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
recipient,
|
||||
t,
|
||||
customClassNames,
|
||||
}: DisableEmailsSettingProps) => {
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [confirmText, setConfirmText] = useState("");
|
||||
const confirmationString = t("confirm", { defaultValue: "confirm" });
|
||||
|
||||
const title =
|
||||
recipient === "attendees" ? t("disable_all_emails_to_attendees") : t("disable_all_emails_to_hosts");
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Dialog open={dialogOpen} onOpenChange={(e) => setDialogOpen(e)}>
|
||||
<DialogContent
|
||||
title={title}
|
||||
Icon="circle-alert"
|
||||
className={customClassNames?.confirmationDialog?.container}>
|
||||
<p
|
||||
className={classNames("text-default text-sm", customClassNames?.confirmationDialog?.description)}>
|
||||
<ServerTrans t={t} i18nKey="disable_attendees_emails_description" values={{ recipient }} />
|
||||
</p>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-default mb-1 mt-2 text-sm",
|
||||
customClassNames?.confirmationDialog?.confirmInput?.label
|
||||
)}>
|
||||
{t("type_confirm_to_continue")}
|
||||
</p>
|
||||
<InputField
|
||||
value={confirmText}
|
||||
onChange={(e) => {
|
||||
setConfirmText(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<DialogFooter className={customClassNames?.confirmationDialog?.dialogFooter?.container}>
|
||||
<DialogClose className={customClassNames?.confirmationDialog?.dialogFooter?.cancelButton} />
|
||||
<Button
|
||||
disabled={confirmText.toLowerCase() !== confirmationString.toLowerCase()}
|
||||
onClick={() => {
|
||||
onCheckedChange(true);
|
||||
setDialogOpen(false);
|
||||
}}
|
||||
className={customClassNames?.confirmationDialog?.dialogFooter?.confirmButton}>
|
||||
{t("disable_email")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<SettingsToggle
|
||||
labelClassName={classNames("text-sm", customClassNames?.label)}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
customClassNames?.container
|
||||
)}
|
||||
descriptionClassName={customClassNames?.description}
|
||||
title={title}
|
||||
description={t("disable_all_emails_description")}
|
||||
checked={!!checked}
|
||||
onCheckedChange={() => (checked ? onCheckedChange(!checked) : setDialogOpen(true))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
-202
@@ -1,202 +0,0 @@
|
||||
import * as RadioGroup from "@radix-ui/react-radio-group";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
|
||||
import type { EventTypeSetup, SettingsToggleClassNames } from "@calcom/features/eventtypes/lib/types";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Input } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { RadioField } from "@calcom/ui/components/radio";
|
||||
|
||||
export type DisableReschedulingCustomClassNames = SettingsToggleClassNames & {
|
||||
radioGroupContainer?: string;
|
||||
alwaysRescheduleRadio?: string;
|
||||
conditionalRescheduleRadio?: {
|
||||
container?: string;
|
||||
timeInput?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type DisableReschedulingControllerProps = {
|
||||
eventType: EventTypeSetup;
|
||||
disableRescheduling: boolean;
|
||||
onDisableRescheduling: (val: boolean) => void;
|
||||
customClassNames?: DisableReschedulingCustomClassNames;
|
||||
};
|
||||
|
||||
export default function DisableReschedulingController({
|
||||
eventType,
|
||||
disableRescheduling,
|
||||
onDisableRescheduling,
|
||||
customClassNames,
|
||||
}: DisableReschedulingControllerProps) {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const currentMinimumRescheduleNotice = formMethods.watch("minimumRescheduleNotice");
|
||||
const [minimumRescheduleNoticeValue, setMinimumRescheduleNoticeValue] = useState<number>(
|
||||
currentMinimumRescheduleNotice && currentMinimumRescheduleNotice > 0 ? currentMinimumRescheduleNotice : 60
|
||||
);
|
||||
const radioGroupOnValueChangeRef = useRef<((val: string) => void) | null>(null);
|
||||
|
||||
const [shouldShowRadioButtons, setShouldShowRadioButtons] = useState(
|
||||
disableRescheduling ||
|
||||
(currentMinimumRescheduleNotice !== null && currentMinimumRescheduleNotice > 0) ||
|
||||
eventType.disableRescheduling === true || false
|
||||
);
|
||||
useEffect(() => {
|
||||
if (currentMinimumRescheduleNotice && currentMinimumRescheduleNotice > 0) {
|
||||
setMinimumRescheduleNoticeValue(currentMinimumRescheduleNotice);
|
||||
}
|
||||
}, [currentMinimumRescheduleNotice]);
|
||||
|
||||
const { shouldLockDisableProps } = useLockedFieldsManager({ eventType, translate: t, formMethods });
|
||||
const disableReschedulingLocked = shouldLockDisableProps("disableRescheduling");
|
||||
const minimumRescheduleNoticeLocked = shouldLockDisableProps("minimumRescheduleNotice");
|
||||
|
||||
return (
|
||||
<div className="block items-start sm:flex">
|
||||
<div className="w-full">
|
||||
<Controller
|
||||
name="disabledRescheduling"
|
||||
control={formMethods.control}
|
||||
render={({ field: { onChange } }) => (
|
||||
<SettingsToggle
|
||||
labelClassName={classNames("text-sm", customClassNames?.label)}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
shouldShowRadioButtons && "rounded-b-none",
|
||||
customClassNames?.container
|
||||
)}
|
||||
childrenClassName={classNames("lg:ml-0", customClassNames?.children)}
|
||||
descriptionClassName={customClassNames?.description}
|
||||
title={t("disable_rescheduling")}
|
||||
data-testid="disable-rescheduling-toggle"
|
||||
disabled={disableReschedulingLocked.disabled}
|
||||
LockedIcon={disableReschedulingLocked.LockedIcon}
|
||||
description={
|
||||
<LearnMoreLink
|
||||
t={t}
|
||||
i18nKey="description_disable_rescheduling"
|
||||
href="https://cal.com/help/event-types/disable-canceling-rescheduling#disable-rescheduling"
|
||||
/>
|
||||
}
|
||||
checked={shouldShowRadioButtons}
|
||||
onCheckedChange={(val) => {
|
||||
if (val) {
|
||||
onChange(true);
|
||||
onDisableRescheduling(true);
|
||||
formMethods.setValue("minimumRescheduleNotice", null, { shouldDirty: true });
|
||||
setShouldShowRadioButtons(true);
|
||||
} else {
|
||||
onChange(false);
|
||||
onDisableRescheduling(false);
|
||||
formMethods.setValue("minimumRescheduleNotice", null, { shouldDirty: true });
|
||||
setShouldShowRadioButtons(false);
|
||||
}
|
||||
}}>
|
||||
{shouldShowRadioButtons && (
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
<RadioGroup.Root
|
||||
value={
|
||||
disableRescheduling
|
||||
? "always"
|
||||
: currentMinimumRescheduleNotice !== null && currentMinimumRescheduleNotice > 0
|
||||
? "notice"
|
||||
: "always"
|
||||
}
|
||||
onValueChange={(val) => {
|
||||
const handler = (val: string) => {
|
||||
if (val === "always") {
|
||||
onChange(true);
|
||||
onDisableRescheduling(true);
|
||||
formMethods.setValue("minimumRescheduleNotice", null, { shouldDirty: true });
|
||||
setMinimumRescheduleNoticeValue(0);
|
||||
} else if (val === "notice") {
|
||||
onChange(false);
|
||||
onDisableRescheduling(false);
|
||||
const valueToSet =
|
||||
minimumRescheduleNoticeValue > 0 ? minimumRescheduleNoticeValue : 60;
|
||||
formMethods.setValue("minimumRescheduleNotice", valueToSet, { shouldDirty: true });
|
||||
setMinimumRescheduleNoticeValue(valueToSet);
|
||||
}
|
||||
};
|
||||
radioGroupOnValueChangeRef.current = handler;
|
||||
handler(val);
|
||||
}}>
|
||||
<div
|
||||
className={classNames(
|
||||
"flex flex-col flex-wrap justify-start gap-y-2",
|
||||
customClassNames?.radioGroupContainer
|
||||
)}>
|
||||
<RadioField
|
||||
label={t("always")}
|
||||
disabled={minimumRescheduleNoticeLocked.disabled}
|
||||
id="always"
|
||||
value="always"
|
||||
className={customClassNames?.alwaysRescheduleRadio}
|
||||
/>
|
||||
<RadioField
|
||||
disabled={minimumRescheduleNoticeLocked.disabled}
|
||||
className={classNames(
|
||||
"items-center",
|
||||
customClassNames?.conditionalRescheduleRadio?.container
|
||||
)}
|
||||
label={
|
||||
<>
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="when_less_than_minutes_before_meeting"
|
||||
components={[
|
||||
<div
|
||||
key="when_less_than_minutes_before_meeting"
|
||||
className="mx-2 inline-flex items-center">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
disabled={minimumRescheduleNoticeLocked.disabled}
|
||||
onChange={(evt) => {
|
||||
const val = Number(evt.target?.value);
|
||||
if (val > 0) {
|
||||
setMinimumRescheduleNoticeValue(val);
|
||||
formMethods.setValue("minimumRescheduleNotice", val, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
radioGroupOnValueChangeRef.current?.("notice");
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
"border-default m-0! block w-20 text-sm [appearance:textfield] focus:z-10",
|
||||
customClassNames?.conditionalRescheduleRadio?.timeInput
|
||||
)}
|
||||
defaultValue={
|
||||
currentMinimumRescheduleNotice && currentMinimumRescheduleNotice > 0
|
||||
? currentMinimumRescheduleNotice
|
||||
: 60
|
||||
}
|
||||
/>
|
||||
</div>,
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
id="notice"
|
||||
value="notice"
|
||||
/>
|
||||
</div>
|
||||
</RadioGroup.Root>
|
||||
</div>
|
||||
)}
|
||||
</SettingsToggle>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
-293
@@ -1,293 +0,0 @@
|
||||
import * as RadioGroup from "@radix-ui/react-radio-group";
|
||||
import type { UnitTypeLongPlural } from "dayjs";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import type z from "zod";
|
||||
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
|
||||
import type { EventTypeSetup, SettingsToggleClassNames } from "@calcom/features/eventtypes/lib/types";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { CheckboxField } from "@calcom/ui/components/form";
|
||||
import { Input } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { RadioField } from "@calcom/ui/components/radio";
|
||||
|
||||
export type RequiresConfirmationCustomClassNames = SettingsToggleClassNames & {
|
||||
radioGroupContainer?: string;
|
||||
alwaysConfirmationRadio?: string;
|
||||
conditionalConfirmationRadio?: {
|
||||
container?: string;
|
||||
timeInput?: string;
|
||||
timeUnitSelect?: string;
|
||||
checkbox?: string;
|
||||
checkboxDescription?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type RequiresConfirmationControllerProps = {
|
||||
metadata: z.infer<typeof EventTypeMetaDataSchema>;
|
||||
requiresConfirmation: boolean;
|
||||
requiresConfirmationWillBlockSlot: boolean;
|
||||
onRequiresConfirmation: Dispatch<SetStateAction<boolean>>;
|
||||
seatsEnabled: boolean;
|
||||
eventType: EventTypeSetup;
|
||||
customClassNames?: RequiresConfirmationCustomClassNames;
|
||||
};
|
||||
|
||||
export default function RequiresConfirmationController({
|
||||
metadata,
|
||||
eventType,
|
||||
requiresConfirmation,
|
||||
onRequiresConfirmation,
|
||||
seatsEnabled,
|
||||
customClassNames,
|
||||
}: RequiresConfirmationControllerProps) {
|
||||
const { t } = useLocale();
|
||||
const [requiresConfirmationSetup, setRequiresConfirmationSetup] = useState(
|
||||
metadata?.requiresConfirmationThreshold
|
||||
);
|
||||
const defaultRequiresConfirmationSetup = { time: 30, unit: "minutes" as UnitTypeLongPlural };
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!requiresConfirmation) {
|
||||
formMethods.setValue("metadata.requiresConfirmationThreshold", undefined, { shouldDirty: true });
|
||||
}
|
||||
}, [requiresConfirmation]);
|
||||
|
||||
const { shouldLockDisableProps } = useLockedFieldsManager({ eventType, translate: t, formMethods });
|
||||
const requiresConfirmationLockedProps = shouldLockDisableProps("requiresConfirmation");
|
||||
|
||||
const options = [
|
||||
{ label: t("minute_timeUnit"), value: "minutes" },
|
||||
{ label: t("hour_timeUnit"), value: "hours" },
|
||||
];
|
||||
|
||||
const defaultValue = options.find(
|
||||
(opt) =>
|
||||
opt.value === (metadata?.requiresConfirmationThreshold?.unit ?? defaultRequiresConfirmationSetup.unit)
|
||||
);
|
||||
|
||||
const requiresConfirmationWillBlockSlot = formMethods.getValues("requiresConfirmationWillBlockSlot");
|
||||
const requiresConfirmationForFreeEmail = formMethods.getValues("requiresConfirmationForFreeEmail");
|
||||
|
||||
return (
|
||||
<div className="block items-start sm:flex">
|
||||
<div className="w-full">
|
||||
<Controller
|
||||
name="requiresConfirmation"
|
||||
control={formMethods.control}
|
||||
render={() => (
|
||||
<SettingsToggle
|
||||
labelClassName={classNames("text-sm", customClassNames?.label)}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
requiresConfirmation && "rounded-b-none",
|
||||
customClassNames?.container
|
||||
)}
|
||||
childrenClassName={classNames("lg:ml-0", customClassNames?.children)}
|
||||
descriptionClassName={customClassNames?.description}
|
||||
title={t("requires_confirmation")}
|
||||
data-testid="requires-confirmation"
|
||||
disabled={seatsEnabled || requiresConfirmationLockedProps.disabled}
|
||||
tooltip={seatsEnabled ? t("seat_options_doesnt_support_confirmation") : undefined}
|
||||
description={
|
||||
<LearnMoreLink
|
||||
t={t}
|
||||
i18nKey="requires_confirmation_description"
|
||||
href="https://cal.com/help/event-types/how-to-requires"
|
||||
/>
|
||||
}
|
||||
checked={requiresConfirmation}
|
||||
LockedIcon={requiresConfirmationLockedProps.LockedIcon}
|
||||
onCheckedChange={(val) => {
|
||||
formMethods.setValue("requiresConfirmation", val, { shouldDirty: true });
|
||||
if (!val) {
|
||||
formMethods.setValue("requiresConfirmationWillBlockSlot", false, { shouldDirty: true });
|
||||
formMethods.setValue("requiresConfirmationForFreeEmail", false, { shouldDirty: true });
|
||||
} else {
|
||||
formMethods.setValue("requiresConfirmationWillBlockSlot", true, { shouldDirty: true });
|
||||
}
|
||||
onRequiresConfirmation(val);
|
||||
}}>
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
<RadioGroup.Root
|
||||
defaultValue={
|
||||
requiresConfirmation
|
||||
? requiresConfirmationSetup === undefined
|
||||
? "always"
|
||||
: "notice"
|
||||
: undefined
|
||||
}
|
||||
onValueChange={(val) => {
|
||||
if (val === "always") {
|
||||
formMethods.setValue("requiresConfirmation", true, { shouldDirty: true });
|
||||
onRequiresConfirmation(true);
|
||||
formMethods.setValue("metadata.requiresConfirmationThreshold", undefined, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
setRequiresConfirmationSetup(undefined);
|
||||
formMethods.setValue("requiresConfirmationWillBlockSlot", true, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
} else if (val === "notice") {
|
||||
formMethods.setValue("requiresConfirmation", true, { shouldDirty: true });
|
||||
onRequiresConfirmation(true);
|
||||
formMethods.setValue(
|
||||
"metadata.requiresConfirmationThreshold",
|
||||
requiresConfirmationSetup || defaultRequiresConfirmationSetup,
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
formMethods.setValue("requiresConfirmationWillBlockSlot", true, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<div
|
||||
className={classNames(
|
||||
"flex flex-col flex-wrap justify-start gap-y-2",
|
||||
customClassNames?.radioGroupContainer
|
||||
)}>
|
||||
{(requiresConfirmationSetup === undefined ||
|
||||
!requiresConfirmationLockedProps.disabled) && (
|
||||
<RadioField
|
||||
label={t("always")}
|
||||
disabled={requiresConfirmationLockedProps.disabled}
|
||||
id="always"
|
||||
value="always"
|
||||
className={customClassNames?.alwaysConfirmationRadio}
|
||||
/>
|
||||
)}
|
||||
{(requiresConfirmationSetup !== undefined ||
|
||||
!requiresConfirmationLockedProps.disabled) && (
|
||||
<>
|
||||
<RadioField
|
||||
disabled={requiresConfirmationLockedProps.disabled}
|
||||
className={classNames(
|
||||
"items-center",
|
||||
customClassNames?.conditionalConfirmationRadio?.container
|
||||
)}
|
||||
label={
|
||||
<>
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="when_booked_with_less_than_notice"
|
||||
components={[
|
||||
<div
|
||||
key="when_booked_with_less_than_notice"
|
||||
className="mx-2 inline-flex items-center">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
disabled={requiresConfirmationLockedProps.disabled}
|
||||
onChange={(evt) => {
|
||||
const val = Number(evt.target?.value);
|
||||
setRequiresConfirmationSetup({
|
||||
unit:
|
||||
requiresConfirmationSetup?.unit ??
|
||||
defaultRequiresConfirmationSetup.unit,
|
||||
time: val,
|
||||
});
|
||||
formMethods.setValue(
|
||||
"metadata.requiresConfirmationThreshold.time",
|
||||
val,
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
}}
|
||||
className={classNames(
|
||||
"border-default m-0! block w-16 rounded-r-none border-r-0 text-sm [appearance:textfield] focus:z-10 focus:border-r",
|
||||
customClassNames?.conditionalConfirmationRadio?.timeInput
|
||||
)}
|
||||
defaultValue={metadata?.requiresConfirmationThreshold?.time || 30}
|
||||
/>
|
||||
<label
|
||||
className={classNames(
|
||||
requiresConfirmationLockedProps.disabled && "cursor-not-allowed"
|
||||
)}>
|
||||
<Select
|
||||
inputId="notice"
|
||||
options={options}
|
||||
isSearchable={false}
|
||||
isDisabled={requiresConfirmationLockedProps.disabled}
|
||||
className={
|
||||
customClassNames?.conditionalConfirmationRadio?.timeUnitSelect
|
||||
}
|
||||
innerClassNames={{
|
||||
control: "rounded-l-none max-h-4 px-3 bg-subtle py-1",
|
||||
}}
|
||||
onChange={(opt) => {
|
||||
setRequiresConfirmationSetup({
|
||||
time:
|
||||
requiresConfirmationSetup?.time ??
|
||||
defaultRequiresConfirmationSetup.time,
|
||||
unit: opt?.value as UnitTypeLongPlural,
|
||||
});
|
||||
formMethods.setValue(
|
||||
"metadata.requiresConfirmationThreshold.unit",
|
||||
opt?.value as UnitTypeLongPlural,
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
}}
|
||||
defaultValue={defaultValue}
|
||||
/>
|
||||
</label>
|
||||
</div>,
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
id="notice"
|
||||
value="notice"
|
||||
/>
|
||||
<div className="-ml-1 stack-y-2">
|
||||
<CheckboxField
|
||||
checked={requiresConfirmationWillBlockSlot}
|
||||
descriptionAsLabel
|
||||
description={t("requires_confirmation_will_block_slot_description")}
|
||||
className={customClassNames?.conditionalConfirmationRadio?.checkbox}
|
||||
descriptionClassName={
|
||||
customClassNames?.conditionalConfirmationRadio?.checkboxDescription
|
||||
}
|
||||
onChange={(e) => {
|
||||
// We set should dirty to properly detect when we can submit the form
|
||||
formMethods.setValue("requiresConfirmationWillBlockSlot", e.target.checked, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<CheckboxField
|
||||
checked={requiresConfirmationForFreeEmail}
|
||||
descriptionAsLabel
|
||||
description={t("require_confirmation_for_free_email")}
|
||||
className={customClassNames?.conditionalConfirmationRadio?.checkbox}
|
||||
descriptionClassName={
|
||||
customClassNames?.conditionalConfirmationRadio?.checkboxDescription
|
||||
}
|
||||
onChange={(e) => {
|
||||
// We set should dirty to properly detect when we can submit the form
|
||||
formMethods.setValue("requiresConfirmationForFreeEmail", e.target.checked, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</RadioGroup.Root>
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,321 +0,0 @@
|
||||
import * as RadioGroup from "@radix-ui/react-radio-group";
|
||||
import { useSession } from "next-auth/react";
|
||||
import React, { useState } from "react";
|
||||
import { useFormContext, Controller } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getTemplateFieldsSchema } from "@calcom/features/calAIPhone/getTemplateFieldsSchema";
|
||||
import { templateFieldsMap } from "@calcom/features/calAIPhone/template-fields-map";
|
||||
import type { TemplateType } from "@calcom/features/calAIPhone/zod-utils";
|
||||
import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import type { EventTypeSetup, FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { ComponentForField } from "@calcom/features/form-builder/FormBuilderField";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Divider } from "@calcom/ui/components/divider";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type AIEventControllerProps = {
|
||||
eventType: EventTypeSetup;
|
||||
isTeamEvent: boolean;
|
||||
};
|
||||
|
||||
export default function AIEventController({ eventType, isTeamEvent }: AIEventControllerProps) {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const [aiEventState, setAIEventState] = useState<boolean>(eventType?.aiPhoneCallConfig?.enabled ?? false);
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const isOrg = !!session.data?.user?.org?.id;
|
||||
|
||||
if (session.status === "loading") return <></>;
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="block items-start sm:flex">
|
||||
{!isOrg || !isTeamEvent ? (
|
||||
<EmptyScreen
|
||||
headline={t("Cal.ai")}
|
||||
Icon="sparkles"
|
||||
description={t("upgrade_to_cal_ai_phone_number_description")}
|
||||
buttonRaw={<Button href="/enterprise">{t("upgrade")}</Button>}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
<SettingsToggle
|
||||
labelClassName="text-sm"
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
aiEventState && "rounded-b-none"
|
||||
)}
|
||||
childrenClassName="lg:ml-0"
|
||||
title={t("Cal.ai")}
|
||||
description={t("use_cal_ai_to_make_call_description")}
|
||||
checked={aiEventState}
|
||||
data-testid="instant-event-check"
|
||||
onCheckedChange={(e) => {
|
||||
if (!e) {
|
||||
formMethods.setValue("aiPhoneCallConfig.enabled", false, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
setAIEventState(false);
|
||||
} else {
|
||||
formMethods.setValue("aiPhoneCallConfig.enabled", true, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
setAIEventState(true);
|
||||
}
|
||||
}}>
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
{aiEventState && <AISettings eventType={eventType} />}
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
}
|
||||
|
||||
const ErrorMessage = ({ fieldName, message }: { fieldName: string; message: string }) => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<div data-testid={`error-message-${fieldName}`} className="mt-2 flex items-center text-sm text-red-700 ">
|
||||
<Icon name="info" className="h-3 w-3 ltr:mr-2 rtl:ml-2" />
|
||||
<p>{t(message || "invalid_input")}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TemplateFields = () => {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { control, watch } = formMethods;
|
||||
|
||||
const templateType = watch("aiPhoneCallConfig.templateType");
|
||||
const fields = templateFieldsMap[templateType as TemplateType];
|
||||
|
||||
return (
|
||||
<div className="stack-y-4">
|
||||
{fields?.map((field) => (
|
||||
<div key={field.name}>
|
||||
<Controller
|
||||
control={control}
|
||||
name={`aiPhoneCallConfig.${field.name}`}
|
||||
render={({ field: { value, onChange }, fieldState: { error } }) => {
|
||||
const { variableName, ...restField } = field;
|
||||
const variableInfo = !!variableName ? `: ${t("variable")} {{${variableName}}}` : "";
|
||||
return (
|
||||
<div>
|
||||
<ComponentForField
|
||||
field={{
|
||||
...restField,
|
||||
label: `${t(field.defaultLabel)}${variableInfo}`,
|
||||
placeholder: t(field.placeholder),
|
||||
}}
|
||||
value={value ?? ""}
|
||||
readOnly={false}
|
||||
setValue={(val: unknown) => {
|
||||
onChange(val);
|
||||
}}
|
||||
/>
|
||||
{error?.message && <ErrorMessage message={error.message} fieldName={field.name} />}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AISettings = ({ eventType }: { eventType: EventTypeSetup }) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const [calApiKey, setCalApiKey] = useState("");
|
||||
|
||||
const createCallMutation = trpc.viewer.organizations.createPhoneCall.useMutation({
|
||||
onSuccess: (data) => {
|
||||
if (!!data?.callId) {
|
||||
showToast("Phone Call Created successfully", "success");
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
const message = err?.message ? err.message : t("something_went_wrong");
|
||||
showToast(message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
const values = formMethods.getValues("aiPhoneCallConfig");
|
||||
const { templateType } = values;
|
||||
|
||||
const schema = getTemplateFieldsSchema({ templateType });
|
||||
|
||||
const data = schema.parse({
|
||||
...values,
|
||||
guestEmail: values.guestEmail && values.guestEmail.trim().length ? values.guestEmail : undefined,
|
||||
guestCompany:
|
||||
values.guestCompany && values.guestCompany.trim().length ? values.guestCompany : undefined,
|
||||
guestName: values.guestName && values.guestName.trim().length ? values.guestName : undefined,
|
||||
eventTypeId: eventType.id,
|
||||
calApiKey,
|
||||
id: eventType.id,
|
||||
});
|
||||
|
||||
createCallMutation.mutate(data);
|
||||
} catch (err) {
|
||||
if (err instanceof z.ZodError) {
|
||||
const fieldName = err.issues?.[0]?.path?.[0];
|
||||
const message = err.issues?.[0]?.message;
|
||||
showToast(`Error on ${fieldName}: ${message} `, "error");
|
||||
|
||||
const issues = err.issues;
|
||||
for (const issue of issues) {
|
||||
const fieldName = `aiPhoneCallConfig.${issue.path[0]}` as unknown as keyof FormValues;
|
||||
formMethods.setError(fieldName, {
|
||||
type: "custom",
|
||||
message: issue.message,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
showToast(t("something_went_wrong"), "error");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="stack-y-4">
|
||||
<>
|
||||
<Label>{t("your_phone_number")}</Label>
|
||||
<Controller
|
||||
name="aiPhoneCallConfig.yourPhoneNumber"
|
||||
render={({ field: { onChange, value, name }, fieldState: { error } }) => {
|
||||
return (
|
||||
<div>
|
||||
<PhoneInput
|
||||
required
|
||||
placeholder={t("your_phone_number")}
|
||||
id="aiPhoneCallConfig.yourPhoneNumber"
|
||||
name="aiPhoneCallConfig.yourPhoneNumber"
|
||||
value={value}
|
||||
onChange={(val) => {
|
||||
onChange(val);
|
||||
}}
|
||||
/>
|
||||
{error?.message && <ErrorMessage message={error.message} fieldName={name} />}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<>
|
||||
<RadioGroup.Root
|
||||
defaultValue={eventType?.aiPhoneCallConfig?.templateType ?? "CUSTOM_TEMPLATE"}
|
||||
onValueChange={(val) => {
|
||||
formMethods.setValue("aiPhoneCallConfig.templateType", val, { shouldDirty: true });
|
||||
}}>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-1 rounded-lg border p-4">
|
||||
<RadioGroup.Item
|
||||
id="CHECK_IN_APPOINTMENT"
|
||||
key="CHECK_IN_APPOINTMENT"
|
||||
value="CHECK_IN_APPOINTMENT"
|
||||
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2 ">
|
||||
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
|
||||
</RadioGroup.Item>
|
||||
<label className="h-full" htmlFor="CHECK_IN_APPOINTMENT">
|
||||
<h2 className="font-semibold leading-tight">{t("check_in_assistant")}</h2>
|
||||
<p className="text-subtle mt-2">{t("check_in_assistant_description")}</p>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-1 rounded-lg border p-4">
|
||||
<RadioGroup.Item
|
||||
id="CUSTOM_TEMPLATE"
|
||||
key="CUSTOM_TEMPLATE"
|
||||
value="CUSTOM_TEMPLATE"
|
||||
className="min-w-4 bg-default border-default flex h-4 w-4 cursor-pointer items-center rounded-full border focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
|
||||
<RadioGroup.Indicator className="after:bg-inverted relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full" />
|
||||
</RadioGroup.Item>
|
||||
<label htmlFor="CUSTOM_TEMPLATE">
|
||||
<h2 className="font-semibold leading-tight">{t("custom_template")}</h2>
|
||||
<p className="text-subtle mt-2">{t("create_your_own_prompt")}</p>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</RadioGroup.Root>
|
||||
</>
|
||||
|
||||
<Label>{t("number_to_call")}</Label>
|
||||
<Controller
|
||||
name="aiPhoneCallConfig.numberToCall"
|
||||
render={({ field: { onChange, value, name }, fieldState: { error } }) => {
|
||||
return (
|
||||
<div>
|
||||
<PhoneInput
|
||||
required
|
||||
placeholder={t("phone_number")}
|
||||
id="aiPhoneCallConfig.numberToCall"
|
||||
name="aiPhoneCallConfig.numberToCall"
|
||||
value={value}
|
||||
onChange={(val) => {
|
||||
onChange(val);
|
||||
}}
|
||||
/>
|
||||
{error?.message && <ErrorMessage message={error.message} fieldName={name} />}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
<TemplateFields />
|
||||
|
||||
<Divider />
|
||||
</>
|
||||
|
||||
<TextField
|
||||
type="text"
|
||||
hint="For eg:- cal_live_0123.."
|
||||
label={t("provide_api_key")}
|
||||
name="calApiKey"
|
||||
placeholder="Cal API Key"
|
||||
value={calApiKey}
|
||||
onChange={(e) => {
|
||||
setCalApiKey(e.target.value);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Button
|
||||
disabled={createCallMutation.isPending}
|
||||
loading={createCallMutation.isPending}
|
||||
onClick={handleSubmit}>
|
||||
{t("make_a_call")}
|
||||
</Button>
|
||||
|
||||
{/* TODO:<small className="block opacity-60">
|
||||
Want to automate outgoing phone calls? Read our{" "}
|
||||
<Link className="underline" href="https://cal.com/docs">
|
||||
API docs
|
||||
</Link>{" "}
|
||||
and learn how to build workflows.
|
||||
</small> */}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
|
||||
import AIEventController from "./AIEventController";
|
||||
|
||||
export const EventAITab = ({
|
||||
eventType,
|
||||
isTeamEvent,
|
||||
}: Pick<EventTypeSetupProps, "eventType"> & { isTeamEvent: boolean }) => {
|
||||
return <AIEventController eventType={eventType} isTeamEvent={isTeamEvent} />;
|
||||
};
|
||||
@@ -1,208 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import { EventTypeAppCard } from "@calcom/app-store/_components/EventTypeAppCardInterface";
|
||||
import type { EventTypeAppCardComponentProps } from "@calcom/app-store/types";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import useAppsData from "@calcom/features/apps/hooks/useAppsData";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type { FormValues, EventTypeSetupProps, EventTypeApps } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Section } from "@calcom/ui/components/section";
|
||||
|
||||
export type EventType = Pick<EventTypeSetupProps, "eventType">["eventType"] &
|
||||
EventTypeAppCardComponentProps["eventType"];
|
||||
|
||||
export const EventAppsTab = ({
|
||||
eventType,
|
||||
eventTypeApps,
|
||||
isPendingApps,
|
||||
}: {
|
||||
eventType: EventType;
|
||||
eventTypeApps?: EventTypeApps;
|
||||
isPendingApps: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const installedApps =
|
||||
eventTypeApps?.items.filter((app) => app.userCredentialIds.length || app.teams.length) || [];
|
||||
const notInstalledApps =
|
||||
eventTypeApps?.items.filter((app) => !app.userCredentialIds.length && !app.teams.length) || [];
|
||||
|
||||
const { getAppDataGetter, getAppDataSetter, eventTypeFormMetadata } = useAppsData();
|
||||
|
||||
const { shouldLockDisableProps, isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager({
|
||||
eventType,
|
||||
translate: t,
|
||||
formMethods,
|
||||
});
|
||||
const appsDisableProps = shouldLockDisableProps("apps", { simple: true });
|
||||
const lockedText = appsDisableProps.isLocked ? "locked" : "unlocked";
|
||||
|
||||
const handleAppInstallSuccess = (appId: string) => () => {
|
||||
utils.viewer.apps.appById.invalidate({ appId });
|
||||
utils.viewer.apps.integrations.invalidate({
|
||||
extendsFeature: "EventType",
|
||||
...(eventType.team?.id && { teamId: eventType.team.id }),
|
||||
});
|
||||
};
|
||||
|
||||
const appsWithTeamCredentials = eventTypeApps?.items.filter((app) => app.teams.length) || [];
|
||||
const cardsForAppsWithTeams = appsWithTeamCredentials.map((app) => {
|
||||
const appCards = [];
|
||||
|
||||
if (app.userCredentialIds.length) {
|
||||
appCards.push(
|
||||
<EventTypeAppCard
|
||||
getAppData={getAppDataGetter(app.slug as EventTypeAppsList)}
|
||||
setAppData={getAppDataSetter(
|
||||
app.slug as EventTypeAppsList,
|
||||
app.categories,
|
||||
app.userCredentialIds[0]
|
||||
)}
|
||||
key={app.slug}
|
||||
app={app}
|
||||
eventType={eventType}
|
||||
eventTypeFormMetadata={eventTypeFormMetadata}
|
||||
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
for (const team of app.teams) {
|
||||
if (team) {
|
||||
appCards.push(
|
||||
<EventTypeAppCard
|
||||
getAppData={getAppDataGetter(app.slug as EventTypeAppsList)}
|
||||
setAppData={getAppDataSetter(app.slug as EventTypeAppsList, app.categories, team.credentialId)}
|
||||
key={app.slug + team?.credentialId}
|
||||
app={{
|
||||
...app,
|
||||
// credentialIds: team?.credentialId ? [team.credentialId] : [],
|
||||
credentialOwner: {
|
||||
name: team.name,
|
||||
avatar: team.logoUrl,
|
||||
teamId: team.teamId,
|
||||
credentialId: team.credentialId,
|
||||
},
|
||||
}}
|
||||
eventType={eventType}
|
||||
eventTypeFormMetadata={eventTypeFormMetadata}
|
||||
disabled={shouldLockDisableProps("apps").disabled}
|
||||
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
return appCards;
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<div className="flex flex-col gap-4 before:border-0">
|
||||
{(isManagedEventType || isChildrenManagedEventType) && (
|
||||
<Alert
|
||||
severity={appsDisableProps.isLocked ? "neutral" : "info"}
|
||||
className="mb-2"
|
||||
title={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`${lockedText}_${isManagedEventType ? "for_members" : "by_team_admins"}`}
|
||||
/>
|
||||
}
|
||||
actions={<div className="flex h-full items-center">{appsDisableProps.LockedIcon}</div>}
|
||||
message={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`apps_${lockedText}_${
|
||||
isManagedEventType ? "for_members" : "by_team_admins"
|
||||
}_description`}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!isPendingApps && !installedApps?.length ? (
|
||||
<EmptyScreen
|
||||
Icon="grid-3x3"
|
||||
headline={t("empty_installed_apps_headline")}
|
||||
description={t("empty_installed_apps_description")}
|
||||
buttonRaw={
|
||||
appsDisableProps.disabled ? (
|
||||
<Button StartIcon="lock" color="secondary" disabled>
|
||||
{t("locked_by_team_admin")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button target="_blank" color="secondary" href="/apps">
|
||||
{t("empty_installed_apps_button")}{" "}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{cardsForAppsWithTeams.map((apps) => apps.map((cards) => cards))}
|
||||
{installedApps.map((app) => {
|
||||
if (!app.teams.length)
|
||||
return (
|
||||
<EventTypeAppCard
|
||||
getAppData={getAppDataGetter(app.slug as EventTypeAppsList)}
|
||||
setAppData={getAppDataSetter(
|
||||
app.slug as EventTypeAppsList,
|
||||
app.categories,
|
||||
app.userCredentialIds[0]
|
||||
)}
|
||||
key={app.slug}
|
||||
app={app}
|
||||
eventType={eventType}
|
||||
eventTypeFormMetadata={eventTypeFormMetadata}
|
||||
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{/* TODO: Add back after salesforce v3 dev */}
|
||||
{!appsDisableProps.disabled && (
|
||||
<div className="bg-cal-muted mt-4 rounded-2xl p-4">
|
||||
{!isPendingApps && notInstalledApps?.length ? (
|
||||
<div className="mb-4 flex flex-col">
|
||||
<Section.Title>{t("available_apps_lower_case")}</Section.Title>
|
||||
<Section.Description>
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="available_apps_desc"
|
||||
components={[
|
||||
<Link key="available_apps_desc" className="cursor-pointer underline" href="/apps">
|
||||
App Store
|
||||
</Link>,
|
||||
]}
|
||||
/>
|
||||
</Section.Description>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="bg-default border-muted flex flex-col gap-4 rounded-xl border p-3">
|
||||
{notInstalledApps?.map((app) => (
|
||||
<EventTypeAppCard
|
||||
getAppData={getAppDataGetter(app.slug as EventTypeAppsList)}
|
||||
setAppData={getAppDataSetter(app.slug as EventTypeAppsList, app.categories)}
|
||||
key={app.slug}
|
||||
app={app}
|
||||
eventType={eventType}
|
||||
eventTypeFormMetadata={eventTypeFormMetadata}
|
||||
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,965 +0,0 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { ComponentProps, Dispatch, SetStateAction } from "react";
|
||||
import { Controller, useFormContext, useWatch } from "react-hook-form";
|
||||
import type { Options } from "react-select";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import type { AddMembersWithSwitchCustomClassNames } from "@calcom/features/eventtypes/components/AddMembersWithSwitch";
|
||||
import AddMembersWithSwitch, {
|
||||
mapUserToValue,
|
||||
} from "@calcom/features/eventtypes/components/AddMembersWithSwitch";
|
||||
import AssignAllTeamMembers from "@calcom/features/eventtypes/components/AssignAllTeamMembers";
|
||||
import type { ChildrenEventTypeSelectCustomClassNames } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
|
||||
import ChildrenEventTypeSelect from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
|
||||
import { sortHosts } from "@calcom/features/eventtypes/components/HostEditDialogs";
|
||||
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
|
||||
import type {
|
||||
FormValues,
|
||||
TeamMember,
|
||||
EventTypeSetupProps,
|
||||
Host,
|
||||
SelectClassNames,
|
||||
SettingsToggleClassNames,
|
||||
} from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { RRTimestampBasis, SchedulingType } from "@calcom/prisma/enums";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { RadioAreaGroup as RadioArea } from "@calcom/ui/components/radio";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
|
||||
import { EditWeightsForAllTeamMembers } from "../../EditWeightsForAllTeamMembers";
|
||||
import WeightDescription from "../../WeightDescription";
|
||||
|
||||
export type EventTeamAssignmentTabCustomClassNames = {
|
||||
assignmentType?: {
|
||||
container?: string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
schedulingTypeSelect?: SelectClassNames;
|
||||
};
|
||||
hosts?: HostsCustomClassNames;
|
||||
childrenEventTypes?: ChildrenEventTypesCustomClassNames;
|
||||
};
|
||||
|
||||
export type EventTeamAssignmentTabBaseProps = Pick<
|
||||
EventTypeSetupProps,
|
||||
"teamMembers" | "team" | "eventType"
|
||||
> & {
|
||||
customClassNames?: EventTeamAssignmentTabCustomClassNames;
|
||||
orgId: number | null;
|
||||
isSegmentApplicable: boolean;
|
||||
};
|
||||
|
||||
export const mapMemberToChildrenOption = (
|
||||
member: EventTypeSetupProps["teamMembers"][number],
|
||||
slug: string,
|
||||
pendingString: string
|
||||
) => {
|
||||
return {
|
||||
slug,
|
||||
hidden: false,
|
||||
created: false,
|
||||
owner: {
|
||||
id: member.id,
|
||||
name: member.name ?? "",
|
||||
email: member.email,
|
||||
username: member.username ?? "",
|
||||
membership: member.membership,
|
||||
eventTypeSlugs: member.eventTypes ?? [],
|
||||
avatar: member.avatar,
|
||||
profile: member.profile,
|
||||
},
|
||||
value: `${member.id ?? ""}`,
|
||||
label: `${member.name || member.email || ""}${!member.username ? ` (${pendingString})` : ""}`,
|
||||
};
|
||||
};
|
||||
|
||||
const ChildrenEventTypesList = ({
|
||||
options = [],
|
||||
value,
|
||||
onChange,
|
||||
customClassNames,
|
||||
...rest
|
||||
}: {
|
||||
value: ReturnType<typeof mapMemberToChildrenOption>[];
|
||||
onChange?: (options: ReturnType<typeof mapMemberToChildrenOption>[]) => void;
|
||||
options?: Options<ReturnType<typeof mapMemberToChildrenOption>>;
|
||||
customClassNames?: ChildrenEventTypeSelectCustomClassNames;
|
||||
} & Omit<Partial<ComponentProps<typeof ChildrenEventTypeSelect>>, "onChange" | "value">) => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<div className={classNames("stack-y-5 flex flex-col", customClassNames?.assignToSelect?.container)}>
|
||||
<div>
|
||||
<Label className={customClassNames?.assignToSelect?.label}>{t("assign_to")}</Label>
|
||||
<ChildrenEventTypeSelect
|
||||
aria-label="assignment-dropdown"
|
||||
data-testid="assignment-dropdown"
|
||||
onChange={(options) => {
|
||||
onChange &&
|
||||
onChange(
|
||||
options.map((option) => ({
|
||||
...option,
|
||||
}))
|
||||
);
|
||||
}}
|
||||
value={value}
|
||||
options={options.filter((opt) => !value.find((val) => val.owner.id.toString() === opt.value))}
|
||||
controlShouldRenderValue={false}
|
||||
customClassNames={customClassNames}
|
||||
{...rest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const FixedHostHelper = ({ t }: { t: TFunction }) => (
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="fixed_host_helper"
|
||||
components={[
|
||||
<Link
|
||||
key="fixed_host_helper"
|
||||
className="underline underline-offset-2"
|
||||
target="_blank"
|
||||
href="https://cal.com/docs/enterprise-features/teams/round-robin-scheduling#fixed-hosts">
|
||||
Learn more
|
||||
</Link>,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
type FixedHostsCustomClassNames = SettingsToggleClassNames & {
|
||||
addMembers?: AddMembersWithSwitchCustomClassNames;
|
||||
};
|
||||
const FixedHosts = ({
|
||||
teamId,
|
||||
teamMembers,
|
||||
value,
|
||||
onChange,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
isRoundRobinEvent = false,
|
||||
customClassNames,
|
||||
}: {
|
||||
teamId: number;
|
||||
value: Host[];
|
||||
onChange: (hosts: Host[]) => void;
|
||||
teamMembers: TeamMember[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
isRoundRobinEvent?: boolean;
|
||||
customClassNames?: FixedHostsCustomClassNames;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { getValues, setValue } = useFormContext<FormValues>();
|
||||
|
||||
const hasActiveFixedHosts = isRoundRobinEvent && getValues("hosts").some((host) => host.isFixed);
|
||||
|
||||
const [isDisabled, setIsDisabled] = useState(hasActiveFixedHosts);
|
||||
|
||||
const handleFixedHostsActivation = useCallback(() => {
|
||||
const currentHosts = getValues("hosts");
|
||||
setValue(
|
||||
"hosts",
|
||||
teamMembers.map((teamMember) => {
|
||||
const host = currentHosts.find((host) => host.userId === parseInt(teamMember.value, 10));
|
||||
return {
|
||||
isFixed: true,
|
||||
userId: parseInt(teamMember.value, 10),
|
||||
priority: host?.priority ?? 2,
|
||||
weight: host?.weight ?? 100,
|
||||
// if host was already added, retain scheduleId and groupId
|
||||
scheduleId: host?.scheduleId || teamMember.defaultScheduleId,
|
||||
groupId: host?.groupId || null,
|
||||
};
|
||||
}),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
}, [getValues, setValue, teamMembers]);
|
||||
|
||||
const handleFixedHostsToggle = useCallback(
|
||||
(checked: boolean) => {
|
||||
if (!checked) {
|
||||
const rrHosts = getValues("hosts")
|
||||
.filter((host) => !host.isFixed)
|
||||
.sort((a, b) => (b.priority ?? 2) - (a.priority ?? 2));
|
||||
setValue("hosts", rrHosts, { shouldDirty: true });
|
||||
}
|
||||
setIsDisabled(checked);
|
||||
},
|
||||
[getValues, setValue]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classNames("mt-5 rounded-lg", customClassNames?.container)}>
|
||||
{!isRoundRobinEvent ? (
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle mt-5 rounded-t-md border p-6 pb-5",
|
||||
customClassNames?.container
|
||||
)}>
|
||||
<Label className={classNames("mb-1 text-sm font-semibold", customClassNames?.label)}>
|
||||
{t("fixed_hosts")}
|
||||
</Label>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle wrap-break-word max-w-full text-sm leading-tight",
|
||||
customClassNames?.description
|
||||
)}>
|
||||
<FixedHostHelper t={t} />
|
||||
</p>
|
||||
</div>
|
||||
<div className="border-subtle rounded-b-md border border-t-0 px-6">
|
||||
<AddMembersWithSwitch
|
||||
teamId={teamId}
|
||||
groupId={null}
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
automaticAddAllEnabled={!isRoundRobinEvent}
|
||||
isFixed={true}
|
||||
customClassNames={customClassNames?.addMembers}
|
||||
onActive={handleFixedHostsActivation}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<SettingsToggle
|
||||
data-testid="fixed-hosts-switch"
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("fixed_hosts")}
|
||||
description={<FixedHostHelper t={t} />}
|
||||
checked={isDisabled && !assignAllTeamMembers}
|
||||
hideSwitch={assignAllTeamMembers}
|
||||
labelClassName={classNames("text-sm", customClassNames?.label)}
|
||||
descriptionClassName={classNames("text-sm text-subtle", customClassNames?.description)}
|
||||
switchContainerClassName={customClassNames?.container}
|
||||
onCheckedChange={handleFixedHostsToggle}
|
||||
childrenClassName={classNames("lg:ml-0", customClassNames?.children)}>
|
||||
<div className="border-subtle flex flex-col gap-6 rounded-bl-md rounded-br-md border border-t-0 px-6">
|
||||
<AddMembersWithSwitch
|
||||
data-testid="fixed-hosts-select"
|
||||
groupId={null}
|
||||
placeholder={t("add_a_member")}
|
||||
teamId={teamId}
|
||||
teamMembers={teamMembers}
|
||||
customClassNames={customClassNames?.addMembers}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
automaticAddAllEnabled={!isRoundRobinEvent}
|
||||
isFixed={true}
|
||||
onActive={handleFixedHostsActivation}
|
||||
/>
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type RoundRobinHostsCustomClassNames = {
|
||||
container?: string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
enableWeights?: SettingsToggleClassNames;
|
||||
addMembers?: AddMembersWithSwitchCustomClassNames;
|
||||
};
|
||||
|
||||
const RoundRobinHosts = ({
|
||||
orgId,
|
||||
teamMembers,
|
||||
value,
|
||||
onChange,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
customClassNames,
|
||||
teamId,
|
||||
isSegmentApplicable,
|
||||
}: {
|
||||
orgId: number | null;
|
||||
value: Host[];
|
||||
onChange: (hosts: Host[]) => void;
|
||||
teamMembers: TeamMember[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
customClassNames?: RoundRobinHostsCustomClassNames;
|
||||
teamId: number;
|
||||
isSegmentApplicable: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const { setValue, getValues, control, formState } = useFormContext<FormValues>();
|
||||
const assignRRMembersUsingSegment = getValues("assignRRMembersUsingSegment");
|
||||
const isRRWeightsEnabled = useWatch({
|
||||
control,
|
||||
name: "isRRWeightsEnabled",
|
||||
});
|
||||
const rrSegmentQueryValue = useWatch({
|
||||
control,
|
||||
name: "rrSegmentQueryValue",
|
||||
});
|
||||
const hostGroups = useWatch({
|
||||
control,
|
||||
name: "hostGroups",
|
||||
});
|
||||
|
||||
const handleWeightsEnabledChange = (active: boolean, onChange: (value: boolean) => void) => {
|
||||
onChange(active);
|
||||
const allHosts = getValues("hosts");
|
||||
const fixedHosts = allHosts.filter((host) => host.isFixed);
|
||||
const rrHosts = allHosts.filter((host) => !host.isFixed);
|
||||
const sortedRRHosts = rrHosts.sort((a, b) => sortHosts(a, b, active));
|
||||
// Preserve fixed hosts when updating
|
||||
setValue("hosts", [...fixedHosts, ...sortedRRHosts]);
|
||||
};
|
||||
|
||||
const handleWeightsChange = (hosts: Host[]) => {
|
||||
const allHosts = getValues("hosts");
|
||||
const fixedHosts = allHosts.filter((host) => host.isFixed);
|
||||
const sortedRRHosts = hosts.sort((a, b) => sortHosts(a, b, true));
|
||||
// Preserve fixed hosts when updating
|
||||
setValue("hosts", [...fixedHosts, ...sortedRRHosts], { shouldDirty: true });
|
||||
};
|
||||
|
||||
const handleAddGroup = useCallback(() => {
|
||||
const allHosts = getValues("hosts");
|
||||
const currentRRHosts = allHosts.filter((host) => !host.isFixed);
|
||||
const fixedHosts = allHosts.filter((host) => host.isFixed);
|
||||
|
||||
// If there are already hosts added and no group exists yet, create two groups
|
||||
if (hostGroups?.length === 0 && currentRRHosts.length > 0) {
|
||||
const firstGroup = { id: uuidv4(), name: "" };
|
||||
const secondGroup = { id: uuidv4(), name: "" };
|
||||
const updatedHostGroups = [firstGroup, secondGroup];
|
||||
setValue("hostGroups", updatedHostGroups, { shouldDirty: true });
|
||||
|
||||
const updatedRRHosts = currentRRHosts.map((host) => {
|
||||
if (!host.groupId && !host.isFixed) {
|
||||
return { ...host, groupId: firstGroup.id };
|
||||
}
|
||||
return host;
|
||||
});
|
||||
setValue("hosts", [...fixedHosts, ...updatedRRHosts], { shouldDirty: true });
|
||||
} else {
|
||||
// If groups already exist, just add one more group
|
||||
const newGroup = { id: uuidv4(), name: "" };
|
||||
const updatedHostGroups = [...hostGroups, newGroup];
|
||||
setValue("hostGroups", updatedHostGroups, { shouldDirty: true });
|
||||
}
|
||||
|
||||
// Disable 'Add all team members' switch if enabled
|
||||
if (assignAllTeamMembers) {
|
||||
setValue("assignAllTeamMembers", false, { shouldDirty: true });
|
||||
setAssignAllTeamMembers(false);
|
||||
}
|
||||
}, [hostGroups, getValues, setValue, assignAllTeamMembers, setAssignAllTeamMembers]);
|
||||
|
||||
const handleGroupNameChange = useCallback(
|
||||
(groupId: string, newName: string) => {
|
||||
const updatedHostGroups =
|
||||
hostGroups?.map((g) => (g.id === groupId ? { ...g, name: newName } : g)) || [];
|
||||
setValue("hostGroups", updatedHostGroups, { shouldDirty: true });
|
||||
},
|
||||
[hostGroups, setValue]
|
||||
);
|
||||
|
||||
const handleRemoveGroup = useCallback(
|
||||
(groupId: string) => {
|
||||
// Remove the group from hostGroups
|
||||
const updatedHostGroups = hostGroups?.filter((g) => g.id !== groupId) || [];
|
||||
setValue("hostGroups", updatedHostGroups, { shouldDirty: true });
|
||||
|
||||
// Remove all hosts that belong to this group
|
||||
const updatedHosts = value.filter((host) => host.groupId !== groupId);
|
||||
onChange(updatedHosts);
|
||||
setValue("hosts", updatedHosts, { shouldDirty: true });
|
||||
},
|
||||
[hostGroups, setValue, value, onChange]
|
||||
);
|
||||
|
||||
const handleMembersActivation = useCallback(
|
||||
(groupId: string | null) => {
|
||||
const currentHosts = getValues("hosts");
|
||||
setValue(
|
||||
"hosts",
|
||||
teamMembers.map((teamMember) => {
|
||||
const host = currentHosts.find((host) => host.userId === parseInt(teamMember.value, 10));
|
||||
return {
|
||||
isFixed: false,
|
||||
userId: parseInt(teamMember.value, 10),
|
||||
priority: host?.priority ?? 2,
|
||||
weight: host?.weight ?? 100,
|
||||
// if host was already added, retain scheduleId and groupId
|
||||
scheduleId: host?.scheduleId || teamMember.defaultScheduleId,
|
||||
groupId: host?.groupId || groupId,
|
||||
};
|
||||
}),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
},
|
||||
[getValues, setValue, teamMembers]
|
||||
);
|
||||
|
||||
const AddMembersWithSwitchComponent = ({
|
||||
groupId,
|
||||
containerClassName,
|
||||
}: {
|
||||
groupId: string | null;
|
||||
containerClassName?: string;
|
||||
}) => {
|
||||
return (
|
||||
<AddMembersWithSwitch
|
||||
placeholder={t("add_a_member")}
|
||||
teamId={teamId}
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
isSegmentApplicable={isSegmentApplicable}
|
||||
automaticAddAllEnabled={true}
|
||||
isRRWeightsEnabled={isRRWeightsEnabled}
|
||||
isFixed={false}
|
||||
groupId={groupId}
|
||||
containerClassName={containerClassName || (assignAllTeamMembers ? "-mt-4" : "")}
|
||||
onActive={() => handleMembersActivation(groupId)}
|
||||
customClassNames={customClassNames?.addMembers}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const UnassignedHostsGroup = () => {
|
||||
const unassignedHosts = value.filter((host) => !host.isFixed && !host.groupId);
|
||||
|
||||
if (unassignedHosts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-subtle my-4 rounded-md border p-4 pb-0">
|
||||
<div className="-mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-default text-sm font-medium">{`Group ${hostGroups.length + 1}`}</span>
|
||||
</div>
|
||||
</div>
|
||||
<AddMembersWithSwitchComponent groupId={null} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames("rounded-lg")}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle mt-5 rounded-t-md border p-6 pb-5",
|
||||
customClassNames?.container
|
||||
)}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label className={classNames("mb-1 text-sm font-semibold", customClassNames?.label)}>
|
||||
{t("round_robin_hosts")}
|
||||
</Label>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle wrap-break-word max-w-full text-sm leading-tight",
|
||||
customClassNames?.description
|
||||
)}>
|
||||
<LearnMoreLink
|
||||
t={t}
|
||||
i18nKey={hostGroups?.length > 0 ? "round_robin_groups_helper" : "round_robin_helper"}
|
||||
href="https://cal.com/help/event-types/round-robin"
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
<Button color="secondary" size="sm" StartIcon="plus" onClick={handleAddGroup}>
|
||||
{t("add_group")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-subtle rounded-b-md border border-t-0 px-6 pt-4">
|
||||
<>
|
||||
<Controller<FormValues>
|
||||
name="isRRWeightsEnabled"
|
||||
render={({ field: { value: isRRWeightsEnabled, onChange } }) => (
|
||||
<SettingsToggle
|
||||
title={t("enable_weights")}
|
||||
description={<WeightDescription t={t} />}
|
||||
checked={isRRWeightsEnabled}
|
||||
switchContainerClassName={customClassNames?.enableWeights?.container}
|
||||
labelClassName={customClassNames?.enableWeights?.label}
|
||||
descriptionClassName={customClassNames?.enableWeights?.description}
|
||||
onCheckedChange={(active) => handleWeightsEnabledChange(active, onChange)}>
|
||||
<EditWeightsForAllTeamMembers
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={handleWeightsChange}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
assignRRMembersUsingSegment={assignRRMembersUsingSegment}
|
||||
teamId={teamId}
|
||||
queryValue={rrSegmentQueryValue}
|
||||
/>
|
||||
</SettingsToggle>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
{!hostGroups.length ? (
|
||||
<AddMembersWithSwitchComponent groupId={hostGroups[0]?.id ?? null} />
|
||||
) : (
|
||||
<>
|
||||
{/* Show unassigned hosts first */}
|
||||
<UnassignedHostsGroup />
|
||||
|
||||
{/* Show all defined groups */}
|
||||
{hostGroups.map((group, index) => {
|
||||
const groupNumber = index + 1;
|
||||
|
||||
return (
|
||||
<div key={index} className="border-subtle my-4 rounded-md border p-4 pb-0">
|
||||
<div className="-mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={group.name ?? ""}
|
||||
onChange={(e) => handleGroupNameChange(group.id, e.target.value)}
|
||||
className="border-none bg-transparent p-0 text-sm font-medium focus:outline-none focus:ring-0"
|
||||
placeholder={`Group ${groupNumber}`}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveGroup(group.id)}
|
||||
className="text-subtle hover:text-default rounded p-1">
|
||||
<Icon name="x" className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<AddMembersWithSwitchComponent groupId={group.id} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type ChildrenEventTypesCustomClassNames = {
|
||||
container?: string;
|
||||
assignAllTeamMembers?: SettingsToggleClassNames;
|
||||
childrenEventTypesList?: ChildrenEventTypeSelectCustomClassNames;
|
||||
};
|
||||
|
||||
const ChildrenEventTypes = ({
|
||||
childrenEventTypeOptions,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
customClassNames,
|
||||
}: {
|
||||
childrenEventTypeOptions: ReturnType<typeof mapMemberToChildrenOption>[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
customClassNames?: ChildrenEventTypesCustomClassNames;
|
||||
}) => {
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle stack-y-5 mt-6 rounded-lg border px-4 py-6 sm:px-6",
|
||||
customClassNames?.container
|
||||
)}>
|
||||
<div className="flex flex-col gap-4">
|
||||
<AssignAllTeamMembers
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
customClassNames={customClassNames?.assignAllTeamMembers}
|
||||
onActive={() => setValue("children", childrenEventTypeOptions, { shouldDirty: true })}
|
||||
/>
|
||||
{!assignAllTeamMembers ? (
|
||||
<Controller<FormValues>
|
||||
name="children"
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<ChildrenEventTypesList
|
||||
value={value}
|
||||
options={childrenEventTypeOptions}
|
||||
onChange={onChange}
|
||||
customClassNames={customClassNames?.childrenEventTypesList}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type HostsCustomClassNames = {
|
||||
fixedHosts?: FixedHostsCustomClassNames;
|
||||
roundRobinHosts?: RoundRobinHostsCustomClassNames;
|
||||
};
|
||||
const Hosts = ({
|
||||
orgId,
|
||||
teamId,
|
||||
teamMembers,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
customClassNames,
|
||||
isSegmentApplicable,
|
||||
}: {
|
||||
orgId: number | null;
|
||||
teamId: number;
|
||||
teamMembers: TeamMember[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
customClassNames?: HostsCustomClassNames;
|
||||
isSegmentApplicable: boolean;
|
||||
}) => {
|
||||
const {
|
||||
control,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { submitCount },
|
||||
} = useFormContext<FormValues>();
|
||||
const schedulingType = useWatch({
|
||||
control,
|
||||
name: "schedulingType",
|
||||
});
|
||||
const initialValue = useRef<{
|
||||
hosts: FormValues["hosts"];
|
||||
schedulingType: SchedulingType | null;
|
||||
submitCount: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Handles init & out of date initial value after submission.
|
||||
if (!initialValue.current || initialValue.current?.submitCount !== submitCount) {
|
||||
initialValue.current = { hosts: getValues("hosts"), schedulingType, submitCount };
|
||||
return;
|
||||
}
|
||||
setValue(
|
||||
"hosts",
|
||||
initialValue.current.schedulingType === schedulingType ? initialValue.current.hosts : [],
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
}, [schedulingType, setValue, getValues, submitCount]);
|
||||
|
||||
// To ensure existing host do not loose its scheduleId and groupId properties, whenever a new host of same type is added.
|
||||
// This is because the host is created from list option in CheckedHostField component.
|
||||
const updatedHosts = (changedHosts: Host[]) => {
|
||||
const existingHosts = getValues("hosts");
|
||||
return changedHosts.map((newValue) => {
|
||||
const existingHost = existingHosts.find((host: Host) => host.userId === newValue.userId);
|
||||
|
||||
return existingHost
|
||||
? {
|
||||
...newValue,
|
||||
scheduleId: existingHost.scheduleId,
|
||||
groupId: existingHost.groupId,
|
||||
}
|
||||
: newValue;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Controller<FormValues>
|
||||
name="hosts"
|
||||
render={({ field: { onChange, value } }) => {
|
||||
const schedulingTypeRender = {
|
||||
COLLECTIVE: (
|
||||
<FixedHosts
|
||||
teamId={teamId}
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={(changeValue) => {
|
||||
onChange([...updatedHosts(changeValue)]);
|
||||
}}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
customClassNames={customClassNames?.fixedHosts}
|
||||
/>
|
||||
),
|
||||
ROUND_ROBIN: (
|
||||
<>
|
||||
<FixedHosts
|
||||
teamId={teamId}
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={(changeValue) => {
|
||||
onChange([...value.filter((host: Host) => !host.isFixed), ...updatedHosts(changeValue)]);
|
||||
}}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
isRoundRobinEvent={true}
|
||||
customClassNames={customClassNames?.fixedHosts}
|
||||
/>
|
||||
<RoundRobinHosts
|
||||
orgId={orgId}
|
||||
teamId={teamId}
|
||||
teamMembers={teamMembers}
|
||||
value={value}
|
||||
onChange={(changeValue) => {
|
||||
const hosts = [...value.filter((host: Host) => host.isFixed), ...updatedHosts(changeValue)];
|
||||
onChange(hosts);
|
||||
}}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
customClassNames={customClassNames?.roundRobinHosts}
|
||||
isSegmentApplicable={isSegmentApplicable}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
MANAGED: <></>,
|
||||
};
|
||||
return !!schedulingType ? schedulingTypeRender[schedulingType] : <></>;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export const EventTeamAssignmentTab = ({
|
||||
team,
|
||||
teamMembers,
|
||||
eventType,
|
||||
customClassNames,
|
||||
orgId,
|
||||
isSegmentApplicable,
|
||||
}: EventTeamAssignmentTabBaseProps) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const schedulingTypeOptions: {
|
||||
value: SchedulingType;
|
||||
label: string;
|
||||
// description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "COLLECTIVE",
|
||||
label: t("collective"),
|
||||
// description: t("collective_description"),
|
||||
},
|
||||
{
|
||||
value: "ROUND_ROBIN",
|
||||
label: t("round_robin"),
|
||||
// description: t("round_robin_description"),
|
||||
},
|
||||
];
|
||||
const pendingMembers = (member: (typeof teamMembers)[number]) =>
|
||||
!!eventType.team?.parentId || !!member.username;
|
||||
const teamMembersOptions = teamMembers
|
||||
.filter(pendingMembers)
|
||||
.map((member) => mapUserToValue(member, t("pending")));
|
||||
const childrenEventTypeOptions = teamMembers.filter(pendingMembers).map((member) => {
|
||||
return mapMemberToChildrenOption(
|
||||
{
|
||||
...member,
|
||||
eventTypes: member.eventTypes.filter(
|
||||
(et) => et !== eventType.slug || !eventType.children.some((c) => c.owner.id === member.id)
|
||||
),
|
||||
},
|
||||
eventType.slug,
|
||||
t("pending")
|
||||
);
|
||||
});
|
||||
const isManagedEventType = eventType.schedulingType === SchedulingType.MANAGED;
|
||||
const { getValues, setValue, control } = useFormContext<FormValues>();
|
||||
const [assignAllTeamMembers, setAssignAllTeamMembers] = useState<boolean>(
|
||||
getValues("assignAllTeamMembers") ?? false
|
||||
);
|
||||
|
||||
const resetRROptions = () => {
|
||||
setValue("assignRRMembersUsingSegment", false, { shouldDirty: true });
|
||||
setValue("assignAllTeamMembers", false, { shouldDirty: true });
|
||||
setAssignAllTeamMembers(false);
|
||||
};
|
||||
|
||||
const handleSchedulingTypeChange = useCallback(
|
||||
(schedulingType: SchedulingType | undefined, onChange: (value: SchedulingType | undefined) => void) => {
|
||||
if (schedulingType) {
|
||||
onChange(schedulingType);
|
||||
resetRROptions();
|
||||
}
|
||||
},
|
||||
[setValue, setAssignAllTeamMembers]
|
||||
);
|
||||
|
||||
const handleMaxLeadThresholdChange = (val: string, onChange: (value: number | null) => void) => {
|
||||
if (val === "loadBalancing") {
|
||||
onChange(3);
|
||||
} else {
|
||||
onChange(null);
|
||||
}
|
||||
};
|
||||
|
||||
const schedulingType = useWatch({
|
||||
control,
|
||||
name: "schedulingType",
|
||||
});
|
||||
|
||||
const hostGroups = useWatch({
|
||||
control,
|
||||
name: "hostGroups",
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
{team && !isManagedEventType && (
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle flex flex-col rounded-md",
|
||||
customClassNames?.assignmentType?.container
|
||||
)}>
|
||||
<div className="border-subtle rounded-t-md border p-6 pb-5">
|
||||
<Label
|
||||
className={classNames("mb-1 text-sm font-semibold", customClassNames?.assignmentType?.label)}>
|
||||
{t("assignment")}
|
||||
</Label>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle wrap-break-word max-w-full text-sm leading-tight",
|
||||
customClassNames?.assignmentType?.description
|
||||
)}>
|
||||
{t("assignment_description")}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle rounded-b-md border border-t-0 p-6",
|
||||
customClassNames?.assignmentType?.schedulingTypeSelect?.container
|
||||
)}>
|
||||
<Label className={customClassNames?.assignmentType?.schedulingTypeSelect?.label}>
|
||||
{t("scheduling_type")}
|
||||
</Label>
|
||||
<Controller<FormValues>
|
||||
name="schedulingType"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<Select
|
||||
options={schedulingTypeOptions}
|
||||
value={schedulingTypeOptions.find((opt) => opt.value === value)}
|
||||
className={classNames(
|
||||
"w-full",
|
||||
customClassNames?.assignmentType?.schedulingTypeSelect?.select
|
||||
)}
|
||||
innerClassNames={customClassNames?.assignmentType?.schedulingTypeSelect?.innerClassNames}
|
||||
onChange={(val) => handleSchedulingTypeChange(val?.value, onChange)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{schedulingType === "ROUND_ROBIN" && (
|
||||
<div className="border-subtle mt-4 flex flex-col rounded-md">
|
||||
<div className="border-subtle rounded-t-md border p-6 pb-5">
|
||||
<Label className="mb-1 text-sm font-semibold">{t("rr_distribution_method")}</Label>
|
||||
<p className="text-subtle wrap-break-word max-w-full text-sm leading-tight">
|
||||
{t("rr_distribution_method_description")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="border-subtle rounded-b-md border border-t-0 p-6">
|
||||
<Controller
|
||||
name="maxLeadThreshold"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<RadioArea.Group
|
||||
onValueChange={(val) => handleMaxLeadThresholdChange(val, onChange)}
|
||||
className="mt-1 flex flex-col gap-4">
|
||||
<RadioArea.Item
|
||||
value="maximizeAvailability"
|
||||
checked={value === null}
|
||||
className="w-full text-sm"
|
||||
classNames={{ container: "w-full" }}>
|
||||
<strong className="mb-1 block">
|
||||
{t("rr_distribution_method_availability_title")}
|
||||
</strong>
|
||||
<p>{t("rr_distribution_method_availability_description")}</p>
|
||||
</RadioArea.Item>
|
||||
{(eventType.team?.rrTimestampBasis &&
|
||||
eventType.team?.rrTimestampBasis !== RRTimestampBasis.CREATED_AT) ||
|
||||
hostGroups?.length > 1 ? (
|
||||
<Tooltip
|
||||
content={
|
||||
!!(
|
||||
eventType.team?.rrTimestampBasis &&
|
||||
eventType.team?.rrTimestampBasis !== RRTimestampBasis.CREATED_AT
|
||||
)
|
||||
? t("rr_load_balancing_disabled")
|
||||
: t("rr_load_balancing_disabled_with_groups")
|
||||
}>
|
||||
<div className="w-full">
|
||||
<RadioArea.Item
|
||||
value="loadBalancing"
|
||||
checked={value !== null}
|
||||
className="text-sm"
|
||||
disabled={true}
|
||||
classNames={{ container: "w-full" }}>
|
||||
<strong className="mb-1">{t("rr_distribution_method_balanced_title")}</strong>
|
||||
<p>{t("rr_distribution_method_balanced_description")}</p>
|
||||
</RadioArea.Item>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
<RadioArea.Item
|
||||
value="loadBalancing"
|
||||
checked={value !== null}
|
||||
className="text-sm"
|
||||
classNames={{ container: "w-full" }}>
|
||||
<strong className="mb-1">{t("rr_distribution_method_balanced_title")}</strong>
|
||||
<p>{t("rr_distribution_method_balanced_description")}</p>
|
||||
</RadioArea.Item>
|
||||
</div>
|
||||
)}
|
||||
</RadioArea.Group>
|
||||
)}
|
||||
/>
|
||||
<div className="mt-4">
|
||||
<Controller
|
||||
name="includeNoShowInRRCalculation"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SettingsToggle
|
||||
title={t("include_no_show_in_rr_calculation")}
|
||||
labelClassName="mt-1.5"
|
||||
checked={value}
|
||||
onCheckedChange={(val) => onChange(val)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Hosts
|
||||
orgId={orgId}
|
||||
isSegmentApplicable={isSegmentApplicable}
|
||||
teamId={team.id}
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
teamMembers={teamMembersOptions}
|
||||
customClassNames={customClassNames?.hosts}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{team && isManagedEventType && (
|
||||
<ChildrenEventTypes
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
childrenEventTypeOptions={childrenEventTypeOptions}
|
||||
customClassNames={customClassNames?.childrenEventTypes}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,880 +0,0 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import type { UseQueryResult } from "@tanstack/react-query";
|
||||
import { useState, memo, useEffect } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import type { OptionProps, SingleValueProps } from "react-select";
|
||||
import { components } from "react-select";
|
||||
|
||||
import type { GetAllSchedulesByUserIdQueryType } from "@calcom/atoms/event-types/wrappers/EventAvailabilityTabWebWrapper";
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { SelectSkeletonLoader } from "@calcom/features/availability/components/SkeletonLoader";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type { TeamMembers } from "@calcom/features/eventtypes/components/EventType";
|
||||
import type {
|
||||
AvailabilityOption,
|
||||
FormValues,
|
||||
EventTypeSetup,
|
||||
Host,
|
||||
SelectClassNames,
|
||||
} from "@calcom/features/eventtypes/lib/types";
|
||||
import CheckboxField from "@calcom/features/form/components/CheckboxField";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { weekdayNames } from "@calcom/lib/weekday";
|
||||
import { weekStartNum } from "@calcom/lib/weekstart";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { Spinner } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
|
||||
export type ScheduleQueryData = RouterOutputs["viewer"]["availability"]["schedule"]["get"];
|
||||
|
||||
type AvailabilityTableCustomClassNames = {
|
||||
tableContainer?: string;
|
||||
table?: string;
|
||||
tableRow?: string;
|
||||
day?: string;
|
||||
dayUnavailable?: string;
|
||||
dayAvailabilityContainer?: string;
|
||||
dayAvailabilityFrom?: string;
|
||||
dayAvailabilityTo?: string;
|
||||
dayAvailabilitySeperator?: string;
|
||||
};
|
||||
|
||||
type TeamMemmberScheduelCustomClassNames = SelectClassNames & {
|
||||
labelAvatar?: string;
|
||||
labelContainer?: string;
|
||||
};
|
||||
|
||||
type UserAvailabilityCustomClassNames = {
|
||||
availabilitySectionContainer?: string;
|
||||
availabilitySelect?: SelectClassNames;
|
||||
availabilityTable?: AvailabilityTableCustomClassNames;
|
||||
};
|
||||
|
||||
type TeamAvailabilityCustomClassNames = {
|
||||
chooseHostSchedulesLabelContainer?: string;
|
||||
chooseHostSchedulesLabel?: string;
|
||||
chooseHostSchedulesLabelDescription?: string;
|
||||
teamAvailibilityContainer?: string;
|
||||
teamMemberSchedule: TeamMemmberScheduelCustomClassNames;
|
||||
};
|
||||
|
||||
export type EventAvailabilityTabCustomClassNames = {
|
||||
teamAvailability: TeamAvailabilityCustomClassNames;
|
||||
userAvailability: UserAvailabilityCustomClassNames;
|
||||
};
|
||||
|
||||
type EventTypeScheduleDetailsProps = {
|
||||
scheduleQueryData?: Pick<ScheduleQueryData, "timeZone" | "id" | "isManaged" | "readOnly"> & {
|
||||
schedule: Array<Pick<ScheduleQueryData["schedule"][number], "days" | "startTime" | "endTime">>;
|
||||
};
|
||||
isSchedulePending?: boolean;
|
||||
user?: Pick<RouterOutputs["viewer"]["me"]["get"], "timeFormat" | "weekStart">;
|
||||
editAvailabilityRedirectUrl?: string;
|
||||
customClassNames?: AvailabilityTableCustomClassNames;
|
||||
};
|
||||
|
||||
type HostSchedulesQueryType =
|
||||
| GetAllSchedulesByUserIdQueryType
|
||||
| (({ userId }: { userId: number }) => UseQueryResult<
|
||||
{
|
||||
schedules: {
|
||||
id: number;
|
||||
name: string;
|
||||
isDefault: boolean;
|
||||
userId: number;
|
||||
readOnly: boolean;
|
||||
}[];
|
||||
},
|
||||
Error
|
||||
>);
|
||||
|
||||
type EventTypeTeamScheduleProps = {
|
||||
hostSchedulesQuery: HostSchedulesQueryType;
|
||||
hosts?: Host[];
|
||||
customClassNames?: TeamAvailabilityCustomClassNames;
|
||||
};
|
||||
|
||||
type TeamMember = Pick<TeamMembers[number], "avatar" | "name" | "id">;
|
||||
|
||||
type EventTypeScheduleProps = {
|
||||
schedulesQueryData?: Array<
|
||||
Omit<RouterOutputs["viewer"]["availability"]["list"]["schedules"][number], "availability">
|
||||
>;
|
||||
isSchedulesPending?: boolean;
|
||||
eventType: EventTypeSetup;
|
||||
teamMembers: TeamMember[];
|
||||
customClassNames?: UserAvailabilityCustomClassNames;
|
||||
fieldName?: "schedule" | "restrictionSchedule";
|
||||
scheduleQueryData?: ScheduleQueryData;
|
||||
restrictionScheduleQueryData?: ScheduleQueryData;
|
||||
isSchedulePending?: boolean;
|
||||
isRestrictionSchedulePending?: boolean;
|
||||
restrictionScheduleRedirectUrl?: string;
|
||||
isRestrictionScheduleEnabled?: boolean;
|
||||
} & Omit<EventTypeScheduleDetailsProps, "customClassNames"> &
|
||||
Omit<EventTypeTeamScheduleProps, "customClassNames">;
|
||||
|
||||
export type EventAvailabilityTabBaserProps = {
|
||||
isTeamEvent: boolean;
|
||||
};
|
||||
|
||||
type UseTeamEventScheduleSettingsToggle = Omit<EventTypeScheduleProps, "customClassNames"> & {
|
||||
customClassNames?: EventAvailabilityTabCustomClassNames;
|
||||
};
|
||||
|
||||
type EventAvailabilityTabProps = EventAvailabilityTabBaserProps &
|
||||
Omit<EventTypeScheduleProps, "customClassNames"> & {
|
||||
customClassNames?: EventAvailabilityTabCustomClassNames;
|
||||
};
|
||||
|
||||
const Option = ({ ...props }: OptionProps<AvailabilityOption>) => {
|
||||
const { label, isDefault, isManaged = false } = props.data;
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<components.Option {...props}>
|
||||
<span>{label}</span>
|
||||
{isDefault && (
|
||||
<Badge variant="blue" className="ml-2">
|
||||
{t("default")}
|
||||
</Badge>
|
||||
)}
|
||||
{isManaged && (
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{t("managed")}
|
||||
</Badge>
|
||||
)}
|
||||
</components.Option>
|
||||
);
|
||||
};
|
||||
|
||||
const SingleValue = ({ ...props }: SingleValueProps<AvailabilityOption>) => {
|
||||
const { label, isDefault, isManaged = false } = props.data;
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<components.SingleValue {...props}>
|
||||
<span>{label}</span>
|
||||
{isDefault && (
|
||||
<Badge variant="blue" className="ml-2">
|
||||
{t("default")}
|
||||
</Badge>
|
||||
)}
|
||||
{isManaged && (
|
||||
<Badge variant="gray" className="ml-2">
|
||||
{t("managed")}
|
||||
</Badge>
|
||||
)}
|
||||
</components.SingleValue>
|
||||
);
|
||||
};
|
||||
|
||||
const format = (date: Date, hour12: boolean) =>
|
||||
Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
hourCycle: hour12 ? "h12" : "h24",
|
||||
}).format(new Date(dayjs.utc(date).format("YYYY-MM-DDTHH:mm:ss")));
|
||||
|
||||
const EventTypeScheduleDetails = memo(
|
||||
({
|
||||
scheduleQueryData,
|
||||
isSchedulePending,
|
||||
user,
|
||||
editAvailabilityRedirectUrl,
|
||||
customClassNames,
|
||||
}: EventTypeScheduleDetailsProps) => {
|
||||
const timeFormat = user?.timeFormat;
|
||||
const { t, i18n } = useLocale();
|
||||
|
||||
const weekStart = weekStartNum(user?.weekStart);
|
||||
|
||||
const filterDays = (dayNum: number) =>
|
||||
scheduleQueryData?.schedule?.filter((item) => item.days.includes((dayNum + weekStart) % 7)) || [];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={classNames("border-subtle stack-y-4 border-x p-6", customClassNames?.tableContainer)}>
|
||||
<ol className={classNames("table border-collapse text-sm", customClassNames?.table)}>
|
||||
{weekdayNames(i18n.language, weekStart, "long").map((day, index) => {
|
||||
const isAvailable = !!filterDays(index).length;
|
||||
return (
|
||||
<li
|
||||
key={day}
|
||||
className={classNames(
|
||||
"my-6 flex border-transparent last:mb-2",
|
||||
customClassNames?.tableRow
|
||||
)}>
|
||||
<span
|
||||
className={classNames(
|
||||
"w-20 font-medium sm:w-32 ",
|
||||
!isAvailable ? "text-subtle line-through" : "text-default",
|
||||
customClassNames?.day
|
||||
)}>
|
||||
{day}
|
||||
</span>
|
||||
{isSchedulePending ? (
|
||||
<SkeletonText className="block h-5 w-60" />
|
||||
) : isAvailable ? (
|
||||
<div className="stack-y-3 text-right">
|
||||
{filterDays(index).map((dayRange, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={classNames(
|
||||
"text-default flex items-center leading-4",
|
||||
customClassNames?.dayAvailabilityContainer
|
||||
)}>
|
||||
<span
|
||||
className={classNames(
|
||||
"w-16 sm:w-28 sm:text-left",
|
||||
customClassNames?.dayAvailabilityFrom
|
||||
)}>
|
||||
{format(dayRange.startTime, timeFormat === 12)}
|
||||
</span>
|
||||
<span className={classNames("ms-4", customClassNames?.dayAvailabilitySeperator)}>
|
||||
-
|
||||
</span>
|
||||
<div className={classNames("ml-6 sm:w-28", customClassNames?.dayAvailabilityTo)}>
|
||||
{format(dayRange.endTime, timeFormat === 12)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span
|
||||
className={classNames("text-subtle ml-6 sm:ml-0", customClassNames?.dayUnavailable)}>
|
||||
{t("unavailable")}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
<div className="bg-cal-muted border-subtle flex flex-col items-center gap-2 rounded-b-md border p-6 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-default flex items-center justify-center text-center text-sm sm:justify-start">
|
||||
<Icon name="globe" className="h-3.5 w-3.5 ltr:mr-2 rtl:ml-2" />
|
||||
{scheduleQueryData?.timeZone || <SkeletonText className="block h-5 w-32" />}
|
||||
</span>
|
||||
</div>
|
||||
{!!scheduleQueryData?.id &&
|
||||
!scheduleQueryData.isManaged &&
|
||||
!scheduleQueryData.readOnly &&
|
||||
!!editAvailabilityRedirectUrl && (
|
||||
<Button
|
||||
href={editAvailabilityRedirectUrl}
|
||||
disabled={isSchedulePending}
|
||||
color="minimal"
|
||||
EndIcon="external-link"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">
|
||||
{t("edit_availability")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
EventTypeScheduleDetails.displayName = "EventTypeScheduleDetails";
|
||||
|
||||
type EventTypeRestrictionScheduleDetailsProps = {
|
||||
scheduleQueryData?: Pick<ScheduleQueryData, "timeZone" | "id" | "isManaged" | "readOnly"> & {
|
||||
schedule: Array<Pick<ScheduleQueryData["schedule"][number], "days" | "startTime" | "endTime">>;
|
||||
};
|
||||
isSchedulePending?: boolean;
|
||||
user?: Pick<RouterOutputs["viewer"]["me"]["get"], "timeFormat" | "weekStart">;
|
||||
restrictionScheduleRedirectUrl?: string;
|
||||
customClassNames?: AvailabilityTableCustomClassNames;
|
||||
useBookerTimezone?: boolean;
|
||||
};
|
||||
|
||||
const EventTypeRestrictionScheduleDetails = memo(
|
||||
({
|
||||
scheduleQueryData,
|
||||
isSchedulePending,
|
||||
user,
|
||||
restrictionScheduleRedirectUrl,
|
||||
customClassNames,
|
||||
useBookerTimezone: initialUseBookerTimezone,
|
||||
}: EventTypeRestrictionScheduleDetailsProps) => {
|
||||
const timeFormat = user?.timeFormat;
|
||||
const { t, i18n } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { setValue, watch } = formMethods;
|
||||
|
||||
const weekStart = weekStartNum(user?.weekStart);
|
||||
|
||||
const filterDays = (dayNum: number) =>
|
||||
scheduleQueryData?.schedule?.filter((item) => item.days.includes((dayNum + weekStart) % 7)) || [];
|
||||
|
||||
const useBookerTimezone = watch("useBookerTimezone");
|
||||
|
||||
useEffect(() => {
|
||||
if (useBookerTimezone === undefined) {
|
||||
setValue("useBookerTimezone", initialUseBookerTimezone || false, { shouldDirty: false });
|
||||
}
|
||||
}, [useBookerTimezone, setValue, initialUseBookerTimezone]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={classNames("border-subtle stack-y-4 border-x p-6", customClassNames?.tableContainer)}>
|
||||
<ol className={classNames("table border-collapse text-sm", customClassNames?.table)}>
|
||||
{weekdayNames(i18n.language, weekStart, "long").map((day, index) => {
|
||||
const isAvailable = !!filterDays(index).length;
|
||||
return (
|
||||
<li
|
||||
key={day}
|
||||
className={classNames(
|
||||
"my-6 flex border-transparent last:mb-2",
|
||||
customClassNames?.tableRow
|
||||
)}>
|
||||
<span
|
||||
className={classNames(
|
||||
"w-20 font-medium sm:w-32 ",
|
||||
!isAvailable ? "text-subtle line-through" : "text-default",
|
||||
customClassNames?.day
|
||||
)}>
|
||||
{day}
|
||||
</span>
|
||||
{isSchedulePending ? (
|
||||
<SkeletonText className="block h-5 w-60" />
|
||||
) : isAvailable ? (
|
||||
<div className="stack-y-3 text-right">
|
||||
{filterDays(index).map((dayRange, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={classNames(
|
||||
"text-default flex items-center leading-4",
|
||||
customClassNames?.dayAvailabilityContainer
|
||||
)}>
|
||||
<span
|
||||
className={classNames(
|
||||
"w-16 sm:w-28 sm:text-left",
|
||||
customClassNames?.dayAvailabilityFrom
|
||||
)}>
|
||||
{format(dayRange.startTime, timeFormat === 12)}
|
||||
</span>
|
||||
<span className={classNames("ms-4", customClassNames?.dayAvailabilitySeperator)}>
|
||||
-
|
||||
</span>
|
||||
<div className={classNames("ml-6 sm:w-28", customClassNames?.dayAvailabilityTo)}>
|
||||
{format(dayRange.endTime, timeFormat === 12)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span
|
||||
className={classNames("text-subtle ml-6 sm:ml-0", customClassNames?.dayUnavailable)}>
|
||||
{t("unavailable")}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
<div className="bg-cal-muted border-subtle flex flex-col justify-center gap-2 rounded-b-md border p-6 sm:flex-row sm:justify-between">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span
|
||||
className={classNames(
|
||||
"text-default flex items-center justify-center text-sm sm:justify-start",
|
||||
useBookerTimezone && "text-muted line-through"
|
||||
)}>
|
||||
<Icon
|
||||
name="globe"
|
||||
className={classNames("h-3.5 w-3.5 ltr:mr-2 rtl:ml-2", useBookerTimezone && "text-muted")}
|
||||
/>
|
||||
{scheduleQueryData?.timeZone || <SkeletonText className="block h-5 w-32" />}
|
||||
</span>
|
||||
<div className="ltr:mr-2 rtl:ml-2">
|
||||
<CheckboxField
|
||||
checked={useBookerTimezone}
|
||||
disabled={isSchedulePending}
|
||||
description={t("use_booker_timezone")}
|
||||
informationIconText={t("use_booker_timezone_info")}
|
||||
onChange={(e) => {
|
||||
setValue("useBookerTimezone", e.target.checked, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!!scheduleQueryData?.id &&
|
||||
!scheduleQueryData.isManaged &&
|
||||
!scheduleQueryData.readOnly &&
|
||||
!!restrictionScheduleRedirectUrl && (
|
||||
<Button
|
||||
href={restrictionScheduleRedirectUrl}
|
||||
disabled={isSchedulePending}
|
||||
color="minimal"
|
||||
EndIcon="external-link"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">
|
||||
{t("edit_availability")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
EventTypeRestrictionScheduleDetails.displayName = "EventTypeRestrictionScheduleDetails";
|
||||
|
||||
const EventTypeSchedule = ({
|
||||
eventType,
|
||||
schedulesQueryData,
|
||||
isSchedulesPending,
|
||||
customClassNames,
|
||||
fieldName = "schedule",
|
||||
scheduleQueryData,
|
||||
restrictionScheduleQueryData,
|
||||
isSchedulePending,
|
||||
isRestrictionSchedulePending,
|
||||
restrictionScheduleRedirectUrl,
|
||||
...rest
|
||||
}: EventTypeScheduleProps) => {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { shouldLockIndicator, shouldLockDisableProps, isManagedEventType, isChildrenManagedEventType } =
|
||||
useLockedFieldsManager({ eventType, translate: t, formMethods });
|
||||
const { watch, setValue } = formMethods;
|
||||
|
||||
// Map the fieldName to the actual form field name
|
||||
const formFieldName = fieldName === "restrictionSchedule" ? "restrictionScheduleId" : fieldName;
|
||||
const scheduleId = watch(formFieldName);
|
||||
|
||||
useEffect(() => {
|
||||
if (schedulesQueryData && scheduleId !== 0 && !scheduleId) {
|
||||
let newValue;
|
||||
if (fieldName === "restrictionSchedule") {
|
||||
newValue =
|
||||
eventType.restrictionScheduleId || schedulesQueryData.find((schedule) => schedule.isDefault)?.id;
|
||||
} else {
|
||||
newValue = isManagedEventType ? 0 : schedulesQueryData.find((schedule) => schedule.isDefault)?.id;
|
||||
}
|
||||
if (!newValue && newValue !== 0) return;
|
||||
setValue(formFieldName, newValue, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [scheduleId, schedulesQueryData]);
|
||||
|
||||
if (isSchedulesPending || !schedulesQueryData) {
|
||||
return <SelectSkeletonLoader />;
|
||||
}
|
||||
|
||||
const options = schedulesQueryData.map((schedule) => ({
|
||||
value: schedule.id,
|
||||
label: schedule.name,
|
||||
isDefault: schedule.isDefault,
|
||||
isManaged: false,
|
||||
}));
|
||||
|
||||
// We are showing a managed event for a team admin, so adding the option to let members choose their schedule
|
||||
if (isManagedEventType) {
|
||||
options.push({
|
||||
value: 0,
|
||||
label: t("members_default_schedule"),
|
||||
isDefault: false,
|
||||
isManaged: false,
|
||||
});
|
||||
}
|
||||
// We are showing a managed event for a member and team owner selected their own schedule, so adding
|
||||
// the managed schedule option
|
||||
if (
|
||||
isChildrenManagedEventType &&
|
||||
scheduleId &&
|
||||
!schedulesQueryData.find((schedule) => schedule.id === scheduleId)
|
||||
) {
|
||||
options.push({
|
||||
value: scheduleId,
|
||||
label: eventType.scheduleName ?? t("default_schedule_name"),
|
||||
isDefault: false,
|
||||
isManaged: false,
|
||||
});
|
||||
}
|
||||
// We push the selected schedule from the event type if it's not part of the list response. This happens if the user is an admin but not the schedule owner.
|
||||
else if (eventType.schedule && !schedulesQueryData.find((schedule) => schedule.id === eventType.schedule)) {
|
||||
options.push({
|
||||
value: eventType.schedule,
|
||||
label: eventType.scheduleName ?? t("default_schedule_name"),
|
||||
isDefault: false,
|
||||
isManaged: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
fieldName === "restrictionSchedule" &&
|
||||
eventType.restrictionScheduleId &&
|
||||
!schedulesQueryData.find((schedule) => schedule.id === eventType.restrictionScheduleId)
|
||||
) {
|
||||
options.push({
|
||||
value: eventType.restrictionScheduleId,
|
||||
label: eventType.restrictionScheduleName ?? t("default_schedule_name"),
|
||||
isDefault: false,
|
||||
isManaged: false,
|
||||
});
|
||||
}
|
||||
|
||||
const filteredOptions =
|
||||
fieldName === "restrictionSchedule"
|
||||
? options.filter((option) => option.value !== eventType.schedule)
|
||||
: options;
|
||||
|
||||
const currentScheduleQueryData =
|
||||
fieldName === "schedule" ? scheduleQueryData : restrictionScheduleQueryData;
|
||||
const isCurrentSchedulePending =
|
||||
fieldName === "schedule" ? isSchedulePending : isRestrictionSchedulePending;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle rounded-t-md border p-6",
|
||||
customClassNames?.availabilitySectionContainer
|
||||
)}>
|
||||
<label
|
||||
htmlFor="availability"
|
||||
className={classNames(
|
||||
"text-default mb-2 block text-sm font-medium leading-none",
|
||||
customClassNames?.availabilitySelect?.label
|
||||
)}>
|
||||
{t("availability")}
|
||||
{(isManagedEventType || isChildrenManagedEventType) && shouldLockIndicator(formFieldName)}
|
||||
</label>
|
||||
<Controller
|
||||
name={formFieldName}
|
||||
render={({ field: { onChange, value } }) => {
|
||||
const optionValue: AvailabilityOption | undefined = filteredOptions.find(
|
||||
(option) => option.value === value
|
||||
);
|
||||
return (
|
||||
<Select
|
||||
placeholder={t("select")}
|
||||
options={filteredOptions}
|
||||
isDisabled={shouldLockDisableProps(formFieldName).disabled}
|
||||
isSearchable={false}
|
||||
onChange={(selected) => {
|
||||
if (selected) {
|
||||
onChange(selected.value);
|
||||
if (fieldName === "restrictionSchedule" && selected.value) {
|
||||
setValue("restrictionScheduleId", selected.value, { shouldDirty: true });
|
||||
}
|
||||
}
|
||||
}}
|
||||
className={classNames(
|
||||
"block w-full min-w-0 flex-1 rounded-sm text-sm",
|
||||
customClassNames?.availabilitySelect?.select
|
||||
)}
|
||||
value={optionValue}
|
||||
components={{ Option, SingleValue }}
|
||||
isMulti={false}
|
||||
innerClassNames={customClassNames?.availabilitySelect?.innerClassNames}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{scheduleId !== 0 && (fieldName === "schedule" || fieldName === "restrictionSchedule") ? (
|
||||
fieldName === "restrictionSchedule" ? (
|
||||
<EventTypeRestrictionScheduleDetails
|
||||
{...rest}
|
||||
scheduleQueryData={currentScheduleQueryData}
|
||||
isSchedulePending={isCurrentSchedulePending}
|
||||
customClassNames={customClassNames?.availabilityTable}
|
||||
useBookerTimezone={eventType.useBookerTimezone}
|
||||
restrictionScheduleRedirectUrl={restrictionScheduleRedirectUrl}
|
||||
/>
|
||||
) : (
|
||||
<EventTypeScheduleDetails
|
||||
{...rest}
|
||||
scheduleQueryData={currentScheduleQueryData}
|
||||
isSchedulePending={isCurrentSchedulePending}
|
||||
customClassNames={customClassNames?.availabilityTable}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
isManagedEventType &&
|
||||
fieldName === "schedule" && (
|
||||
<p className="mt-2! ml-1 text-sm text-gray-600">{t("members_default_schedule_description")}</p>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TeamMemberSchedule = ({
|
||||
host,
|
||||
index,
|
||||
teamMembers,
|
||||
hostScheduleQuery,
|
||||
customClassNames,
|
||||
}: {
|
||||
host: Host;
|
||||
index: number;
|
||||
teamMembers: TeamMember[];
|
||||
hostScheduleQuery: HostSchedulesQueryType;
|
||||
customClassNames?: TeamMemmberScheduelCustomClassNames;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const isPlatform = useIsPlatform();
|
||||
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { getValues } = formMethods;
|
||||
|
||||
const { data, isPending } = hostScheduleQuery({
|
||||
userId: host.userId,
|
||||
});
|
||||
|
||||
const schedules = data?.schedules;
|
||||
const options = schedules?.map((schedule) => ({
|
||||
value: schedule.id,
|
||||
label: schedule.name,
|
||||
isDefault: schedule.isDefault,
|
||||
isManaged: false,
|
||||
}));
|
||||
|
||||
//Set to defaultSchedule if Host Schedule is not previously selected
|
||||
const scheduleId = getValues(`hosts.${index}.scheduleId`);
|
||||
const value = options?.find((option) =>
|
||||
scheduleId
|
||||
? option.value === scheduleId
|
||||
: option.value === schedules?.find((schedule) => schedule.isDefault)?.id
|
||||
);
|
||||
|
||||
const member = teamMembers.find((mem) => mem.id === host.userId);
|
||||
const avatar = member?.avatar;
|
||||
const label = member?.name;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={classNames("flex w-full items-center", customClassNames?.labelContainer)}>
|
||||
{!isPlatform && <Avatar size="sm" imageSrc={avatar} alt={label || ""} />}
|
||||
{isPlatform && <Icon name="user" className={classNames("h-4 w-4", customClassNames?.labelAvatar)} />}
|
||||
<p className={classNames("text-emphasis my-auto ms-3 text-sm", customClassNames?.label)}>{label}</p>
|
||||
</div>
|
||||
<div className="flex w-full flex-col pt-2">
|
||||
{isPending ? (
|
||||
<Spinner className="mt-2 h-6 w-6" />
|
||||
) : (
|
||||
<Controller
|
||||
name={`hosts.${index}.scheduleId`}
|
||||
render={({ field }) => {
|
||||
return (
|
||||
<Select
|
||||
placeholder={t("select")}
|
||||
options={options}
|
||||
isSearchable={false}
|
||||
onChange={(selected) => {
|
||||
field.onChange(selected?.value || null);
|
||||
}}
|
||||
className={classNames(
|
||||
"block w-full min-w-0 flex-1 rounded-sm text-sm",
|
||||
customClassNames?.select
|
||||
)}
|
||||
innerClassNames={customClassNames?.innerClassNames}
|
||||
value={value as AvailabilityOption}
|
||||
components={{ Option, SingleValue }}
|
||||
isMulti={false}
|
||||
isDisabled={isPending}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const TeamAvailability = ({
|
||||
teamMembers,
|
||||
hostSchedulesQuery,
|
||||
customClassNames,
|
||||
}: EventTypeTeamScheduleProps & {
|
||||
teamMembers: TeamMember[];
|
||||
customClassNames?: TeamAvailabilityCustomClassNames;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { watch } = useFormContext<FormValues>();
|
||||
const [animationRef] = useAutoAnimate<HTMLUListElement>();
|
||||
const hosts = watch("hosts");
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle flex flex-col rounded-md",
|
||||
customClassNames?.teamAvailibilityContainer
|
||||
)}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle mt-5 rounded-t-md border p-6 pb-5",
|
||||
customClassNames?.chooseHostSchedulesLabelContainer
|
||||
)}>
|
||||
<Label
|
||||
className={classNames("mb-1 text-sm font-semibold", customClassNames?.chooseHostSchedulesLabel)}>
|
||||
{t("choose_hosts_schedule")}
|
||||
</Label>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-subtle max-w-full wrap-break-word text-sm leading-tight",
|
||||
customClassNames?.chooseHostSchedulesLabelDescription
|
||||
)}>
|
||||
{t("hosts_schedule_description")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="border-subtle rounded-b-md border border-t-0 p-6">
|
||||
{hosts && hosts.length > 0 ? (
|
||||
<ul
|
||||
className={classNames("mb-4 mt-3 rounded-md", hosts.length >= 1 && "border-subtle border")}
|
||||
ref={animationRef}>
|
||||
{hosts?.map((host, index) => (
|
||||
<li
|
||||
key={host.userId}
|
||||
className={classNames(
|
||||
`flex flex-col px-3 py-2 ${index === hosts.length - 1 ? "" : "border-subtle border-b"}`,
|
||||
customClassNames?.teamMemberSchedule?.container
|
||||
)}>
|
||||
<TeamMemberSchedule
|
||||
host={host}
|
||||
index={index}
|
||||
teamMembers={teamMembers}
|
||||
hostScheduleQuery={hostSchedulesQuery}
|
||||
customClassNames={customClassNames?.teamMemberSchedule}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-subtle max-w-full wrap-break-word text-sm leading-tight">
|
||||
{t("no_hosts_description")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const useCommonScheduleState = (initialScheduleId: number | null) => {
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
const [useHostSchedulesForTeamEvent, setUseHostSchedulesForTeamEvent] = useState(!initialScheduleId);
|
||||
// Reset the main schedule
|
||||
const clearMainSchedule = () => {
|
||||
setValue("schedule", null, { shouldDirty: Boolean(initialScheduleId) });
|
||||
};
|
||||
// Toggle function
|
||||
const toggleScheduleState = (checked: boolean) => {
|
||||
const useHostSchedulesForTeamEvent = !checked;
|
||||
setUseHostSchedulesForTeamEvent(useHostSchedulesForTeamEvent);
|
||||
if (useHostSchedulesForTeamEvent) clearMainSchedule();
|
||||
};
|
||||
return {
|
||||
useHostSchedulesForTeamEvent,
|
||||
toggleScheduleState,
|
||||
};
|
||||
};
|
||||
|
||||
const useRestrictionScheduleState = (initialRestrictionScheduleId: number | null) => {
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
const [restrictScheduleForHosts, setRestrictScheduleForHosts] = useState(!!initialRestrictionScheduleId);
|
||||
|
||||
// Toggle function for restriction schedule
|
||||
const toggleRestrictScheduleState = (checked: boolean) => {
|
||||
setRestrictScheduleForHosts(checked);
|
||||
if (!checked) {
|
||||
setValue("restrictionScheduleId", null, { shouldDirty: true });
|
||||
setValue("useBookerTimezone", false, { shouldDirty: true });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
restrictScheduleForHosts,
|
||||
toggleRestrictScheduleState,
|
||||
};
|
||||
};
|
||||
|
||||
const UseTeamEventScheduleSettingsToggle = ({
|
||||
eventType,
|
||||
customClassNames,
|
||||
isRestrictionScheduleEnabled,
|
||||
...rest
|
||||
}: UseTeamEventScheduleSettingsToggle) => {
|
||||
const { t } = useLocale();
|
||||
const isPlatform = useIsPlatform();
|
||||
const { useHostSchedulesForTeamEvent, toggleScheduleState } = useCommonScheduleState(eventType.schedule);
|
||||
const { restrictScheduleForHosts, toggleRestrictScheduleState } = useRestrictionScheduleState(
|
||||
eventType.restrictionScheduleId
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="stack-y-4">
|
||||
<div className="border-subtle stack-y-6 rounded-lg border p-6">
|
||||
<SettingsToggle
|
||||
checked={!useHostSchedulesForTeamEvent}
|
||||
onCheckedChange={toggleScheduleState}
|
||||
title={t("choose_common_schedule_team_event")}
|
||||
description={t("choose_common_schedule_team_event_description")}>
|
||||
<EventTypeSchedule
|
||||
customClassNames={customClassNames?.userAvailability}
|
||||
eventType={eventType}
|
||||
fieldName="schedule"
|
||||
{...rest}
|
||||
/>
|
||||
</SettingsToggle>
|
||||
{useHostSchedulesForTeamEvent && (
|
||||
<div className="lg:ml-14">
|
||||
<TeamAvailability
|
||||
teamMembers={rest.teamMembers}
|
||||
hostSchedulesQuery={rest.hostSchedulesQuery}
|
||||
customClassNames={customClassNames?.teamAvailability}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!isPlatform && isRestrictionScheduleEnabled ? (
|
||||
<div className="border-subtle stack-y-6 rounded-lg border p-6">
|
||||
<SettingsToggle
|
||||
checked={restrictScheduleForHosts}
|
||||
onCheckedChange={toggleRestrictScheduleState}
|
||||
title={t("choose_restriction_schedule")}
|
||||
description={t("restriction_schedule_description")}>
|
||||
<EventTypeSchedule
|
||||
customClassNames={customClassNames?.userAvailability}
|
||||
eventType={eventType}
|
||||
fieldName="restrictionSchedule"
|
||||
{...rest}
|
||||
/>
|
||||
</SettingsToggle>
|
||||
</div>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const EventAvailabilityTab = ({ eventType, isTeamEvent, ...rest }: EventAvailabilityTabProps) => {
|
||||
return isTeamEvent && eventType.schedulingType !== SchedulingType.MANAGED ? (
|
||||
<UseTeamEventScheduleSettingsToggle eventType={eventType} {...rest} />
|
||||
) : (
|
||||
<EventTypeSchedule
|
||||
eventType={eventType}
|
||||
{...rest}
|
||||
customClassNames={rest?.customClassNames?.userAvailability}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
|
||||
import InstantEventController from "./InstantEventController";
|
||||
|
||||
export const EventInstantTab = ({
|
||||
eventType,
|
||||
isTeamEvent,
|
||||
}: Pick<EventTypeSetupProps, "eventType"> & { isTeamEvent: boolean }) => {
|
||||
const paymentAppData = getPaymentAppData({
|
||||
...eventType,
|
||||
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
|
||||
});
|
||||
|
||||
const requirePayment = paymentAppData.price > 0;
|
||||
|
||||
return (
|
||||
<InstantEventController paymentEnabled={requirePayment} eventType={eventType} isTeamEvent={isTeamEvent} />
|
||||
);
|
||||
};
|
||||
@@ -1,476 +0,0 @@
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useState } from "react";
|
||||
import { useFormContext, Controller } from "react-hook-form";
|
||||
import { components } from "react-select";
|
||||
import type { OptionProps, SingleValueProps } from "react-select";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type { EventTypeSetup, FormValues, AvailabilityOption } from "@calcom/features/eventtypes/lib/types";
|
||||
import { WebhookForm } from "@calcom/features/webhooks/components";
|
||||
import type { TWebhook, WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";
|
||||
import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";
|
||||
import { subscriberUrlReserved } from "@calcom/features/webhooks/lib/subscriberUrlReserved";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent } from "@calcom/ui/components/dialog";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
|
||||
type InstantEventControllerProps = {
|
||||
eventType: EventTypeSetup;
|
||||
paymentEnabled: boolean;
|
||||
isTeamEvent: boolean;
|
||||
};
|
||||
|
||||
const Option = ({ ...props }: OptionProps<AvailabilityOption>) => {
|
||||
const { label, isDefault } = props.data;
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<components.Option {...props}>
|
||||
<span>{label}</span>
|
||||
{isDefault && (
|
||||
<Badge variant="blue" className="ml-2">
|
||||
{t("default")}
|
||||
</Badge>
|
||||
)}
|
||||
</components.Option>
|
||||
);
|
||||
};
|
||||
|
||||
const SingleValue = ({ ...props }: SingleValueProps<AvailabilityOption>) => {
|
||||
const { label, isDefault } = props.data;
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<components.SingleValue {...props}>
|
||||
<span>{label}</span>
|
||||
{isDefault && (
|
||||
<Badge variant="blue" className="ml-2">
|
||||
{t("default")}
|
||||
</Badge>
|
||||
)}
|
||||
</components.SingleValue>
|
||||
);
|
||||
};
|
||||
|
||||
export default function InstantEventController({
|
||||
eventType,
|
||||
paymentEnabled,
|
||||
isTeamEvent,
|
||||
}: InstantEventControllerProps) {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
const [instantEventState, setInstantEventState] = useState<boolean>(eventType?.isInstantEvent ?? false);
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const [parameters, setParameters] = useState<string[]>(
|
||||
formMethods.getValues("instantMeetingParameters") || []
|
||||
);
|
||||
|
||||
const { shouldLockDisableProps } = useLockedFieldsManager({
|
||||
eventType,
|
||||
translate: t,
|
||||
formMethods,
|
||||
});
|
||||
|
||||
const instantLocked = shouldLockDisableProps("isInstantEvent");
|
||||
|
||||
const isOrg = !!session.data?.user?.org?.id;
|
||||
|
||||
const { data, isPending } = trpc.viewer.availability.list.useQuery(undefined);
|
||||
|
||||
if (session.status === "loading" || isPending || !data) return <></>;
|
||||
|
||||
const schedules = data.schedules;
|
||||
|
||||
const options = schedules.map((schedule) => ({
|
||||
value: schedule.id,
|
||||
label: schedule.name,
|
||||
isDefault: schedule.isDefault,
|
||||
isManaged: false,
|
||||
}));
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
<div className="block items-start sm:flex">
|
||||
{!isOrg || !isTeamEvent ? (
|
||||
<EmptyScreen
|
||||
headline={t("instant_tab_title")}
|
||||
Icon="phone-call"
|
||||
description={t("uprade_to_create_instant_bookings")}
|
||||
buttonRaw={<Button href="/enterprise">{t("upgrade")}</Button>}
|
||||
/>
|
||||
) : (
|
||||
<div className={!paymentEnabled ? "w-full" : ""}>
|
||||
{paymentEnabled ? (
|
||||
<Alert severity="warning" title={t("warning_payment_instant_meeting_event")} />
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
className="mb-4"
|
||||
severity="warning"
|
||||
title={t("warning_instant_meeting_experimental")}
|
||||
/>
|
||||
<SettingsToggle
|
||||
labelClassName="text-sm"
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
instantEventState && "rounded-b-none"
|
||||
)}
|
||||
childrenClassName="lg:ml-0"
|
||||
title={t("instant_tab_title")}
|
||||
{...instantLocked}
|
||||
description={t("instant_event_tab_description")}
|
||||
checked={instantEventState}
|
||||
data-testid="instant-event-check"
|
||||
onCheckedChange={(e) => {
|
||||
if (!e) {
|
||||
formMethods.setValue("isInstantEvent", false, { shouldDirty: true });
|
||||
setInstantEventState(false);
|
||||
} else {
|
||||
formMethods.setValue("isInstantEvent", true, { shouldDirty: true });
|
||||
setInstantEventState(true);
|
||||
}
|
||||
}}>
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
{instantEventState && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Controller
|
||||
name="instantMeetingSchedule"
|
||||
render={({ field: { onChange, value } }) => {
|
||||
const optionValue: AvailabilityOption | undefined = options.find(
|
||||
(option) => option.value === value
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Label>{t("instant_meeting_availability")}</Label>
|
||||
<Select
|
||||
placeholder={t("select")}
|
||||
options={options}
|
||||
isDisabled={shouldLockDisableProps("instantMeetingSchedule").disabled}
|
||||
isSearchable={false}
|
||||
onChange={(selected) => {
|
||||
if (selected) onChange(selected.value);
|
||||
}}
|
||||
className="mb-4 block w-full min-w-0 flex-1 rounded-sm text-sm"
|
||||
value={optionValue}
|
||||
components={{ Option, SingleValue }}
|
||||
isMulti={false}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<Label>{t("only_show_if_parameter_set")}</Label>
|
||||
<div className="stack-y-2">
|
||||
{parameters.map((parameter, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<TextField
|
||||
required
|
||||
name={`parameter-${index}`}
|
||||
labelSrOnly
|
||||
type="text"
|
||||
value={parameter}
|
||||
containerClassName="flex-1 max-w-80"
|
||||
onChange={(e) => {
|
||||
const newParameters = [...parameters];
|
||||
newParameters[index] = e.target.value;
|
||||
setParameters(newParameters);
|
||||
formMethods.setValue("instantMeetingParameters", newParameters, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
color="destructive"
|
||||
variant="icon"
|
||||
StartIcon="trash"
|
||||
onClick={() => {
|
||||
const newParameters = parameters.filter((_, i) => i !== index);
|
||||
setParameters(newParameters);
|
||||
formMethods.setValue("instantMeetingParameters", newParameters, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
color="minimal"
|
||||
StartIcon="plus"
|
||||
onClick={() => {
|
||||
const newParameters = [...parameters, ""];
|
||||
setParameters(newParameters);
|
||||
formMethods.setValue("instantMeetingParameters", newParameters, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}>
|
||||
{t("add_parameter")}
|
||||
</Button>
|
||||
</div>
|
||||
<Controller
|
||||
name="instantMeetingExpiryTimeOffsetInSeconds"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<>
|
||||
<Label>{t("set_instant_meeting_expiry_time_offset_description")}</Label>
|
||||
<TextField
|
||||
required
|
||||
name="instantMeetingExpiryTimeOffsetInSeconds"
|
||||
labelSrOnly
|
||||
type="number"
|
||||
defaultValue={value}
|
||||
min={10}
|
||||
containerClassName="max-w-80"
|
||||
addOnSuffix={<>{t("seconds")}</>}
|
||||
onChange={(e) => {
|
||||
onChange(Math.abs(Number(e.target.value)));
|
||||
}}
|
||||
data-testid="instant-meeting-expiry-time-offset"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="autoTranslateInstantMeetingTitleEnabled"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<SettingsToggle
|
||||
labelClassName="text-sm"
|
||||
title={t("auto_translate_instant_meeting_title")}
|
||||
checked={value}
|
||||
onCheckedChange={(e) => onChange(e)}
|
||||
data-testid="auto-translate-instant-meeting-title-toggle"
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName="border-subtle rounded-lg border py-6 px-4 sm:px-6 mt-4"
|
||||
description={t("auto_translate_instant_meeting_title_description")}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<InstantMeetingWebhooks eventType={eventType} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</LicenseRequired>
|
||||
);
|
||||
}
|
||||
|
||||
const InstantMeetingWebhooks = ({ eventType }: { eventType: EventTypeSetup }) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useUtils();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery({
|
||||
eventTypeId: eventType.id,
|
||||
eventTriggers: [WebhookTriggerEvents.INSTANT_MEETING],
|
||||
});
|
||||
const { data: installedApps, isPending } = trpc.viewer.apps.integrations.useQuery({
|
||||
variant: "other",
|
||||
onlyInstalled: true,
|
||||
});
|
||||
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [editModalOpen, setEditModalOpen] = useState(false);
|
||||
const [webhookToEdit, setWebhookToEdit] = useState<TWebhook>();
|
||||
|
||||
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess() {
|
||||
setEditModalOpen(false);
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
showToast(t("webhook_updated_successfully"), "success");
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const createWebhookMutation = trpc.viewer.webhook.create.useMutation({
|
||||
async onSuccess() {
|
||||
showToast(t("webhook_created_successfully"), "success");
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
setCreateModalOpen(false);
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onCreateWebhook = async (values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
id: values.id,
|
||||
webhooks,
|
||||
eventTypeId: eventType.id,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
createWebhookMutation.mutate({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
eventTypeId: eventType.id,
|
||||
});
|
||||
};
|
||||
|
||||
const NewWebhookButton = () => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<Button
|
||||
color="secondary"
|
||||
data-testid="new_webhook"
|
||||
StartIcon="plus"
|
||||
onClick={() => setCreateModalOpen(true)}>
|
||||
{t("new_webhook")}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
const { shouldLockDisableProps, isChildrenManagedEventType, isManagedEventType } = useLockedFieldsManager({
|
||||
eventType,
|
||||
formMethods,
|
||||
translate: t,
|
||||
});
|
||||
const webhookLockedStatus = shouldLockDisableProps("webhooks");
|
||||
|
||||
return (
|
||||
<div>
|
||||
{webhooks && !isPending && (
|
||||
<>
|
||||
<div>
|
||||
{webhooks.length ? (
|
||||
<>
|
||||
<div className="border-subtle my-2 rounded-md border">
|
||||
{webhooks.map((webhook, index) => {
|
||||
return (
|
||||
<WebhookListItem
|
||||
key={webhook.id}
|
||||
webhook={webhook}
|
||||
lastItem={webhooks.length === index + 1}
|
||||
canEditWebhook={!webhookLockedStatus.disabled}
|
||||
onEditWebhook={() => {
|
||||
setEditModalOpen(true);
|
||||
setWebhookToEdit(webhook);
|
||||
}}
|
||||
// TODO (SEAN): Implement Permissions here when we have event-types PR merged
|
||||
permissions={{
|
||||
canEditWebhook: !webhookLockedStatus.disabled,
|
||||
canDeleteWebhook: !webhookLockedStatus.disabled,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-default text-sm font-normal">
|
||||
{t("warning_payment_instant_meeting_event")}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EmptyScreen
|
||||
Icon="webhook"
|
||||
headline={t("create_your_first_webhook")}
|
||||
description={t("create_instant_meeting_webhook_description")}
|
||||
buttonRaw={
|
||||
isChildrenManagedEventType && !isManagedEventType ? (
|
||||
<Button StartIcon="lock" color="secondary" disabled>
|
||||
{t("locked_by_admin")}
|
||||
</Button>
|
||||
) : (
|
||||
<NewWebhookButton />
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* New webhook dialog */}
|
||||
<Dialog open={createModalOpen} onOpenChange={(isOpen) => !isOpen && setCreateModalOpen(false)}>
|
||||
<DialogContent
|
||||
enableOverflow
|
||||
title={t("create_webhook")}
|
||||
description={t("create_webhook_team_event_type")}>
|
||||
<WebhookForm
|
||||
noRoutingFormTriggers={true}
|
||||
onSubmit={onCreateWebhook}
|
||||
onCancel={() => setCreateModalOpen(false)}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
selectOnlyInstantMeetingOption={true}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{/* Edit webhook dialog */}
|
||||
<Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
|
||||
<DialogContent enableOverflow title={t("edit_webhook")}>
|
||||
<WebhookForm
|
||||
noRoutingFormTriggers={true}
|
||||
webhook={webhookToEdit}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
onCancel={() => setEditModalOpen(false)}
|
||||
onSubmit={(values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
id: webhookToEdit?.id,
|
||||
webhooks,
|
||||
eventTypeId: eventType.id,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (values.changeSecret) {
|
||||
values.secret = values.newSecret.length ? values.newSecret : null;
|
||||
}
|
||||
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
editWebhookMutation.mutate({
|
||||
id: webhookToEdit?.id || "",
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
eventTypeId: webhookToEdit?.eventTypeId || undefined,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
-100
@@ -1,100 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { TextField, CheckboxField } from "@calcom/ui/components/form";
|
||||
|
||||
type maxActiveBookingsPerBookerLockedProps = {
|
||||
disabled: boolean;
|
||||
LockedIcon: false | JSX.Element;
|
||||
isLocked: boolean;
|
||||
};
|
||||
|
||||
export default function MaxActiveBookingsPerBookerController({
|
||||
maxActiveBookingsPerBookerLocked,
|
||||
}: {
|
||||
maxActiveBookingsPerBookerLocked: maxActiveBookingsPerBookerLockedProps;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const [maxActiveBookingsPerBookerToggle, setMaxActiveBookingsPerBookerToggle] = useState(
|
||||
(formMethods.getValues("maxActiveBookingsPerBooker") ?? 0) > 0
|
||||
);
|
||||
|
||||
const isRecurringEvent = !!formMethods.getValues("recurringEvent");
|
||||
const maxActiveBookingPerBookerOfferReschedule = formMethods.watch(
|
||||
"maxActiveBookingPerBookerOfferReschedule"
|
||||
);
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name="maxActiveBookingsPerBooker"
|
||||
render={({ field: { onChange, value } }) => {
|
||||
const isChecked = maxActiveBookingsPerBookerToggle;
|
||||
return (
|
||||
<SettingsToggle
|
||||
labelClassName={classNames("text-sm")}
|
||||
{...maxActiveBookingsPerBookerLocked}
|
||||
disabled={isRecurringEvent || maxActiveBookingsPerBookerLocked.disabled}
|
||||
tooltip={isRecurringEvent ? t("recurring_event_doesnt_support_booker_booking_limit") : ""}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle mt-6 rounded-lg border py-6 px-4 sm:px-6",
|
||||
isChecked && "rounded-b-none"
|
||||
)}
|
||||
childrenClassName={classNames("lg:ml-0")}
|
||||
title={t("booker_upcoming_limit")}
|
||||
description={
|
||||
<LearnMoreLink
|
||||
t={t}
|
||||
i18nKey="booker_booking_limit_description"
|
||||
href="https://cal.com/help/event-types/booker-active-booking-limit"
|
||||
/>
|
||||
}
|
||||
checked={isChecked}
|
||||
onCheckedChange={(active) => {
|
||||
if (active) {
|
||||
onChange(1);
|
||||
} else {
|
||||
onChange(null);
|
||||
}
|
||||
setMaxActiveBookingsPerBookerToggle((state) => !state);
|
||||
}}>
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
<TextField
|
||||
required
|
||||
type="number"
|
||||
value={value ?? ""}
|
||||
disabled={maxActiveBookingsPerBookerLocked.disabled}
|
||||
onChange={(e) => {
|
||||
onChange(e.target.value === "" ? null : parseInt(e.target.value, 10));
|
||||
}}
|
||||
min={1}
|
||||
step={1}
|
||||
containerClassName={classNames("max-w-80")}
|
||||
addOnSuffix="bookings"
|
||||
data-testid="booker-booking-limit-input"
|
||||
/>
|
||||
<CheckboxField
|
||||
checked={!!maxActiveBookingPerBookerOfferReschedule}
|
||||
descriptionAsLabel
|
||||
description={t("reschedule_last_booking_offer")}
|
||||
disabled={maxActiveBookingsPerBookerLocked.disabled}
|
||||
onChange={(e) => {
|
||||
formMethods.setValue("maxActiveBookingPerBookerOfferReschedule", e.target.checked, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
|
||||
import type { RecurringEventControllerProps } from "./RecurringEventController";
|
||||
import RecurringEventController from "./RecurringEventController";
|
||||
|
||||
export type EventRecurringTabProps = Omit<RecurringEventControllerProps, "paymentEnabled">;
|
||||
|
||||
export const EventRecurringTab = ({ eventType, customClassNames }: EventRecurringTabProps) => {
|
||||
const paymentAppData = getPaymentAppData({
|
||||
...eventType,
|
||||
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata),
|
||||
});
|
||||
|
||||
const requirePayment = paymentAppData.price > 0;
|
||||
|
||||
return (
|
||||
<RecurringEventController
|
||||
paymentEnabled={requirePayment}
|
||||
eventType={eventType}
|
||||
customClassNames={customClassNames}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,220 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
|
||||
import type {
|
||||
EventTypeSetup,
|
||||
InputClassNames,
|
||||
SelectClassNames,
|
||||
SettingsToggleClassNames,
|
||||
} from "@calcom/features/eventtypes/lib/types";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Frequency } from "@calcom/prisma/zod-utils";
|
||||
import type { RecurringEvent } from "@calcom/types/Calendar";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
|
||||
export type RecurringEventControllerProps = {
|
||||
eventType: EventTypeSetup;
|
||||
paymentEnabled: boolean;
|
||||
customClassNames?: EventRecurringTabCustomClassNames;
|
||||
};
|
||||
|
||||
export type EventRecurringTabCustomClassNames = {
|
||||
container?: string;
|
||||
recurringToggle?: SettingsToggleClassNames;
|
||||
frequencyInput?: InputClassNames;
|
||||
frequencyUnitSelect?: SelectClassNames;
|
||||
maxEventsInput?: {
|
||||
countInput?: string;
|
||||
labelText?: string;
|
||||
suffixText?: string;
|
||||
container?: string;
|
||||
};
|
||||
experimentalAlert?: string;
|
||||
paymentAlert?: string;
|
||||
};
|
||||
|
||||
export default function RecurringEventController({
|
||||
eventType,
|
||||
paymentEnabled,
|
||||
customClassNames,
|
||||
}: RecurringEventControllerProps) {
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const [recurringEventState, setRecurringEventState] = useState<RecurringEvent | null>(
|
||||
formMethods.getValues("recurringEvent")
|
||||
);
|
||||
const isSeatsOffered = !!formMethods.getValues("seatsPerTimeSlot");
|
||||
const hasBookingLimitPerBooker = !!formMethods.getValues("maxActiveBookingsPerBooker");
|
||||
/* Just yearly-0, monthly-1 and weekly-2 */
|
||||
const recurringEventFreqOptions = Object.entries(Frequency)
|
||||
.filter(([key, value]) => isNaN(Number(key)) && Number(value) < 3)
|
||||
.map(([key, value]) => ({
|
||||
label: t(`${key.toString().toLowerCase()}`, { count: recurringEventState?.interval }),
|
||||
value: value.toString(),
|
||||
}));
|
||||
|
||||
const { shouldLockDisableProps } = useLockedFieldsManager({ eventType, translate: t, formMethods });
|
||||
|
||||
const recurringLocked = shouldLockDisableProps("recurringEvent");
|
||||
|
||||
return (
|
||||
<div className={classNames("block items-start sm:flex", customClassNames?.container)}>
|
||||
<div className={!paymentEnabled ? "w-full" : ""}>
|
||||
{paymentEnabled ? (
|
||||
<Alert
|
||||
severity="warning"
|
||||
className={customClassNames?.paymentAlert}
|
||||
title={t("warning_payment_recurring_event")}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
className={classNames("mb-4", customClassNames?.experimentalAlert)}
|
||||
severity="warning"
|
||||
title="Experimental: Recurring Events are currently experimental and causes some issues sometimes when checking for availability. We are working on fixing this."
|
||||
/>
|
||||
<SettingsToggle
|
||||
labelClassName={classNames("text-sm", customClassNames?.recurringToggle?.label)}
|
||||
toggleSwitchAtTheEnd={true}
|
||||
switchContainerClassName={classNames(
|
||||
"border-subtle rounded-lg border py-6 px-4 sm:px-6",
|
||||
recurringEventState !== null && "rounded-b-none",
|
||||
customClassNames?.recurringToggle?.container
|
||||
)}
|
||||
childrenClassName={classNames("lg:ml-0", customClassNames?.recurringToggle?.children)}
|
||||
descriptionClassName={customClassNames?.recurringToggle?.description}
|
||||
title={t("recurring_event")}
|
||||
{...recurringLocked}
|
||||
description={
|
||||
<LearnMoreLink
|
||||
t={t}
|
||||
i18nKey="recurring_event_description"
|
||||
href="https://cal.com/help/event-types/recurring-events"
|
||||
/>
|
||||
}
|
||||
checked={!!recurringEventState}
|
||||
data-testid="recurring-event-check"
|
||||
disabled={(!recurringEventState && isSeatsOffered) || hasBookingLimitPerBooker}
|
||||
tooltip={
|
||||
isSeatsOffered
|
||||
? t("seats_doesnt_support_recurring")
|
||||
: hasBookingLimitPerBooker
|
||||
? t("booking_limit_per_booker_doesnt_support_recurring")
|
||||
: undefined
|
||||
}
|
||||
onCheckedChange={(e) => {
|
||||
if (!e) {
|
||||
formMethods.setValue("recurringEvent", null, { shouldDirty: true });
|
||||
setRecurringEventState(null);
|
||||
} else {
|
||||
const newVal = eventType.recurringEvent || {
|
||||
interval: 1,
|
||||
count: 12,
|
||||
freq: Frequency.WEEKLY,
|
||||
};
|
||||
formMethods.setValue("recurringEvent", newVal, { shouldDirty: true });
|
||||
setRecurringEventState(newVal);
|
||||
}
|
||||
}}>
|
||||
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
|
||||
{recurringEventState && (
|
||||
<div data-testid="recurring-event-collapsible" className="text-sm">
|
||||
<div className="flex items-center">
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis ltr:mr-2 rtl:ml-2",
|
||||
customClassNames?.frequencyInput?.label
|
||||
)}>
|
||||
{t("repeats_every")}
|
||||
</p>
|
||||
<TextField
|
||||
disabled={recurringLocked.disabled}
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
className={classNames("mb-0", customClassNames?.frequencyInput?.input)}
|
||||
defaultValue={recurringEventState.interval}
|
||||
onChange={(event) => {
|
||||
const newVal = {
|
||||
...recurringEventState,
|
||||
interval: parseInt(event?.target.value),
|
||||
};
|
||||
formMethods.setValue("recurringEvent", newVal, { shouldDirty: true });
|
||||
setRecurringEventState(newVal);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
options={recurringEventFreqOptions}
|
||||
value={recurringEventFreqOptions[recurringEventState.freq]}
|
||||
isSearchable={false}
|
||||
className={classNames(
|
||||
"w-18 ml-2 block min-w-0 rounded-md text-sm",
|
||||
customClassNames?.frequencyUnitSelect?.select
|
||||
)}
|
||||
innerClassNames={customClassNames?.frequencyUnitSelect?.innerClassNames}
|
||||
isDisabled={recurringLocked.disabled}
|
||||
onChange={(event) => {
|
||||
const newVal = {
|
||||
...recurringEventState,
|
||||
freq: parseInt(event?.value || `${Frequency.WEEKLY}`),
|
||||
};
|
||||
formMethods.setValue("recurringEvent", newVal, { shouldDirty: true });
|
||||
setRecurringEventState(newVal);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"mt-4 flex items-center",
|
||||
customClassNames?.maxEventsInput?.container
|
||||
)}>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis ltr:mr-2 rtl:ml-2",
|
||||
customClassNames?.maxEventsInput?.labelText
|
||||
)}>
|
||||
{t("for_a_maximum_of")}
|
||||
</p>
|
||||
<TextField
|
||||
disabled={recurringLocked.disabled}
|
||||
type="number"
|
||||
min="1"
|
||||
max="24"
|
||||
defaultValue={recurringEventState.count}
|
||||
className={classNames("mb-0", customClassNames?.maxEventsInput?.countInput)}
|
||||
onChange={(event) => {
|
||||
const newVal = {
|
||||
...recurringEventState,
|
||||
count: parseInt(event?.target.value),
|
||||
};
|
||||
formMethods.setValue("recurringEvent", newVal, { shouldDirty: true });
|
||||
setRecurringEventState(newVal);
|
||||
}}
|
||||
/>
|
||||
<p
|
||||
className={classNames(
|
||||
"text-emphasis ltr:ml-2 rtl:mr-2",
|
||||
customClassNames?.maxEventsInput?.suffixText
|
||||
)}>
|
||||
{t("events", {
|
||||
count: recurringEventState.count,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SettingsToggle>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import type { UseFormGetValues, UseFormSetValue, Control, FormState } from "react-hook-form";
|
||||
import type { MultiValue } from "react-select";
|
||||
|
||||
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type {
|
||||
EventTypeSetupProps,
|
||||
InputClassNames,
|
||||
SelectClassNames,
|
||||
SettingsToggleClassNames,
|
||||
} from "@calcom/features/eventtypes/lib/types";
|
||||
import type { FormValues, LocationFormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { MAX_EVENT_DURATION_MINUTES, MIN_EVENT_DURATION_MINUTES } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { md } from "@calcom/lib/markdownIt";
|
||||
import { slugify } from "@calcom/lib/slugify";
|
||||
import turndown from "@calcom/lib/turndownService";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Editor } from "@calcom/ui/components/editor";
|
||||
import { TextAreaField } from "@calcom/ui/components/form";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { TextField } from "@calcom/ui/components/form";
|
||||
import { Select } from "@calcom/ui/components/form";
|
||||
import { SettingsToggle } from "@calcom/ui/components/form";
|
||||
import { Skeleton } from "@calcom/ui/components/skeleton";
|
||||
|
||||
import Locations from "../../locations/Locations";
|
||||
import type { LocationCustomClassNames } from "../../locations/types";
|
||||
|
||||
export type EventSetupTabCustomClassNames = {
|
||||
wrapper?: string;
|
||||
titleSection?: {
|
||||
container?: string;
|
||||
titleInput?: InputClassNames;
|
||||
urlInput?: InputClassNames;
|
||||
descriptionInput?: Pick<InputClassNames, "input" | "label">;
|
||||
};
|
||||
durationSection?: {
|
||||
container?: string;
|
||||
singleDurationInput?: InputClassNames;
|
||||
multipleDuration?: {
|
||||
container?: string;
|
||||
availableDurationsSelect?: SelectClassNames;
|
||||
defaultDurationSelect?: SelectClassNames;
|
||||
};
|
||||
selectDurationToggle?: SettingsToggleClassNames;
|
||||
};
|
||||
locationSection?: LocationCustomClassNames & {
|
||||
container?: string;
|
||||
label?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type EventSetupTabProps = Pick<
|
||||
EventTypeSetupProps,
|
||||
"eventType" | "locationOptions" | "team" | "teamMembers" | "destinationCalendar"
|
||||
> & {
|
||||
customClassNames?: EventSetupTabCustomClassNames;
|
||||
};
|
||||
export const EventSetupTab = (
|
||||
props: EventSetupTabProps & {
|
||||
urlPrefix: string;
|
||||
hasOrgBranding: boolean;
|
||||
orgId?: number;
|
||||
localeOptions?: { value: string; label: string }[];
|
||||
}
|
||||
) => {
|
||||
const { t } = useLocale();
|
||||
const isPlatform = useIsPlatform();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { eventType, team, urlPrefix, hasOrgBranding, customClassNames, orgId } = props;
|
||||
|
||||
const [multipleDuration, setMultipleDuration] = useState(
|
||||
formMethods.getValues("metadata")?.multipleDuration
|
||||
);
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
const seatsEnabled = formMethods.watch("seatsPerTimeSlotEnabled");
|
||||
|
||||
const multipleDurationOptions = [
|
||||
5, 10, 15, 20, 25, 30, 45, 50, 60, 75, 80, 90, 120, 150, 180, 240, 300, 360, 420, 480,
|
||||
].map((mins) => ({
|
||||
value: mins,
|
||||
label: t("multiple_duration_mins", { count: mins }),
|
||||
}));
|
||||
|
||||
const [selectedMultipleDuration, setSelectedMultipleDuration] = useState<
|
||||
MultiValue<{
|
||||
value: number;
|
||||
label: string;
|
||||
}>
|
||||
>(multipleDurationOptions.filter((mdOpt) => multipleDuration?.includes(mdOpt.value)));
|
||||
const [defaultDuration, setDefaultDuration] = useState(
|
||||
selectedMultipleDuration.find((opt) => opt.value === formMethods.getValues("length")) ?? null
|
||||
);
|
||||
|
||||
const { isChildrenManagedEventType, isManagedEventType, shouldLockIndicator, shouldLockDisableProps } =
|
||||
useLockedFieldsManager({ eventType, translate: t, formMethods });
|
||||
|
||||
const lengthLockedProps = shouldLockDisableProps("length");
|
||||
const descriptionLockedProps = shouldLockDisableProps("description");
|
||||
const urlLockedProps = shouldLockDisableProps("slug");
|
||||
const titleLockedProps = shouldLockDisableProps("title");
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={classNames("stack-y-4", customClassNames?.wrapper)}>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle stack-y-6 rounded-lg border p-6",
|
||||
customClassNames?.titleSection?.container
|
||||
)}>
|
||||
<TextField
|
||||
required
|
||||
containerClassName={classNames(customClassNames?.titleSection?.titleInput?.container)}
|
||||
labelClassName={classNames(customClassNames?.titleSection?.titleInput?.label)}
|
||||
className={classNames(customClassNames?.titleSection?.titleInput?.input)}
|
||||
label={t("title")}
|
||||
{...(isManagedEventType || isChildrenManagedEventType ? titleLockedProps : {})}
|
||||
defaultValue={eventType.title}
|
||||
data-testid="event-title"
|
||||
{...formMethods.register("title")}
|
||||
/>
|
||||
<div>
|
||||
{isPlatform ? (
|
||||
<TextAreaField
|
||||
{...formMethods.register("description", {
|
||||
disabled: descriptionLockedProps.disabled,
|
||||
})}
|
||||
placeholder={t("quick_video_meeting")}
|
||||
className={customClassNames?.titleSection?.descriptionInput?.input}
|
||||
labelProps={{
|
||||
className: customClassNames?.titleSection?.descriptionInput?.label,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Label htmlFor="editor">
|
||||
{t("description")}
|
||||
{(isManagedEventType || isChildrenManagedEventType) && shouldLockIndicator("description")}
|
||||
</Label>
|
||||
<Editor
|
||||
getText={() => md.render(formMethods.getValues("description") || "")}
|
||||
setText={(value: string) =>
|
||||
formMethods.setValue("description", turndown(value), { shouldDirty: true })
|
||||
}
|
||||
excludedToolbarItems={["blockType"]}
|
||||
placeholder={t("quick_video_meeting")}
|
||||
editable={!descriptionLockedProps.disabled}
|
||||
firstRender={firstRender}
|
||||
setFirstRender={setFirstRender}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<TextField
|
||||
required
|
||||
label={isPlatform ? "Slug" : t("URL")}
|
||||
{...(isManagedEventType || isChildrenManagedEventType ? urlLockedProps : {})}
|
||||
defaultValue={eventType.slug}
|
||||
data-testid="event-slug"
|
||||
containerClassName={classNames(
|
||||
"[&>div]:gap-0",
|
||||
customClassNames?.titleSection?.urlInput?.container
|
||||
)}
|
||||
labelClassName={classNames(customClassNames?.titleSection?.urlInput?.label)}
|
||||
className={classNames("pl-0", customClassNames?.titleSection?.urlInput?.input)}
|
||||
addOnLeading={
|
||||
isPlatform ? undefined : (
|
||||
<span className="max-w-24 md:max-w-56 inline-block overflow-hidden text-ellipsis whitespace-nowrap min-w-0">
|
||||
{urlPrefix}/
|
||||
{!isManagedEventType
|
||||
? team
|
||||
? (hasOrgBranding ? "" : "team/") + team.slug
|
||||
: formMethods.getValues("users")[0].username
|
||||
: t("username_placeholder")}
|
||||
/
|
||||
</span>
|
||||
)
|
||||
}
|
||||
{...formMethods.register("slug", {
|
||||
setValueAs: (v) => slugify(v),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle rounded-lg border p-6",
|
||||
customClassNames?.durationSection?.container
|
||||
)}>
|
||||
{multipleDuration ? (
|
||||
<div
|
||||
className={classNames(
|
||||
"stack-y-6",
|
||||
customClassNames?.durationSection?.multipleDuration?.availableDurationsSelect?.container
|
||||
)}>
|
||||
<div>
|
||||
<Skeleton
|
||||
as={Label}
|
||||
loadingClassName="w-16"
|
||||
className={
|
||||
customClassNames?.durationSection?.multipleDuration?.availableDurationsSelect?.label
|
||||
}>
|
||||
{t("available_durations")}
|
||||
</Skeleton>
|
||||
<Select
|
||||
isMulti
|
||||
defaultValue={selectedMultipleDuration}
|
||||
name="metadata.multipleDuration"
|
||||
isSearchable={false}
|
||||
isDisabled={lengthLockedProps.disabled}
|
||||
className={classNames(
|
||||
"h-auto min-h-[36px]! text-sm",
|
||||
customClassNames?.durationSection?.multipleDuration?.availableDurationsSelect?.select
|
||||
)}
|
||||
innerClassNames={
|
||||
customClassNames?.durationSection?.multipleDuration?.availableDurationsSelect
|
||||
?.innerClassNames
|
||||
}
|
||||
options={multipleDurationOptions}
|
||||
value={selectedMultipleDuration}
|
||||
onChange={(options) => {
|
||||
let newOptions = [...options];
|
||||
newOptions = newOptions.sort((a, b) => {
|
||||
return a?.value - b?.value;
|
||||
});
|
||||
const values = newOptions.map((opt) => opt.value);
|
||||
setMultipleDuration(values);
|
||||
setSelectedMultipleDuration(newOptions);
|
||||
if (!newOptions.find((opt) => opt.value === defaultDuration?.value)) {
|
||||
if (newOptions.length > 0) {
|
||||
setDefaultDuration(newOptions[0]);
|
||||
formMethods.setValue("length", newOptions[0].value, { shouldDirty: true });
|
||||
} else {
|
||||
setDefaultDuration(null);
|
||||
}
|
||||
}
|
||||
if (newOptions.length === 1 && defaultDuration === null) {
|
||||
setDefaultDuration(newOptions[0]);
|
||||
formMethods.setValue("length", newOptions[0].value, { shouldDirty: true });
|
||||
}
|
||||
formMethods.setValue("metadata.multipleDuration", values, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
customClassNames?.durationSection?.multipleDuration?.defaultDurationSelect?.container
|
||||
}>
|
||||
<Skeleton
|
||||
as={Label}
|
||||
loadingClassName="w-16"
|
||||
className={
|
||||
customClassNames?.durationSection?.multipleDuration?.defaultDurationSelect?.label
|
||||
}>
|
||||
{t("default_duration")}
|
||||
{shouldLockIndicator("length")}
|
||||
</Skeleton>
|
||||
<Select
|
||||
value={defaultDuration}
|
||||
isSearchable={false}
|
||||
name="length"
|
||||
className={classNames(
|
||||
"text-sm",
|
||||
customClassNames?.durationSection?.multipleDuration?.defaultDurationSelect?.select
|
||||
)}
|
||||
innerClassNames={
|
||||
customClassNames?.durationSection?.multipleDuration?.defaultDurationSelect
|
||||
?.innerClassNames
|
||||
}
|
||||
isDisabled={lengthLockedProps.disabled}
|
||||
noOptionsMessage={() => t("default_duration_no_options")}
|
||||
options={selectedMultipleDuration}
|
||||
onChange={(option) => {
|
||||
setDefaultDuration(
|
||||
selectedMultipleDuration.find((opt) => opt.value === option?.value) ?? null
|
||||
);
|
||||
if (option) formMethods.setValue("length", option.value, { shouldDirty: true });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<TextField
|
||||
required
|
||||
type="number"
|
||||
containerClassName={classNames(
|
||||
customClassNames?.durationSection?.singleDurationInput?.container
|
||||
)}
|
||||
labelClassName={classNames(customClassNames?.durationSection?.singleDurationInput?.label)}
|
||||
className={classNames(customClassNames?.durationSection?.singleDurationInput?.input)}
|
||||
data-testid="duration"
|
||||
{...(isManagedEventType || isChildrenManagedEventType ? lengthLockedProps : {})}
|
||||
label={t("duration")}
|
||||
defaultValue={formMethods.getValues("length") ?? 15}
|
||||
{...formMethods.register("length", {
|
||||
valueAsNumber: true,
|
||||
min: {
|
||||
value: MIN_EVENT_DURATION_MINUTES,
|
||||
message: t("duration_min_error", { min: MIN_EVENT_DURATION_MINUTES }),
|
||||
},
|
||||
max: {
|
||||
value: MAX_EVENT_DURATION_MINUTES,
|
||||
message: t("duration_max_error", { max: MAX_EVENT_DURATION_MINUTES }),
|
||||
},
|
||||
})}
|
||||
addOnSuffix={<>{t("minutes")}</>}
|
||||
min={MIN_EVENT_DURATION_MINUTES}
|
||||
max={MAX_EVENT_DURATION_MINUTES}
|
||||
/>
|
||||
)}
|
||||
{!lengthLockedProps.disabled && (
|
||||
<div className="mt-4! [&_label]:my-1 [&_label]:font-normal">
|
||||
<SettingsToggle
|
||||
title={t("allow_multiple_durations")}
|
||||
checked={multipleDuration !== undefined}
|
||||
disabled={seatsEnabled}
|
||||
tooltip={seatsEnabled ? t("seat_options_doesnt_multiple_durations") : undefined}
|
||||
labelClassName={customClassNames?.durationSection?.selectDurationToggle?.label}
|
||||
descriptionClassName={customClassNames?.durationSection?.selectDurationToggle?.description}
|
||||
switchContainerClassName={customClassNames?.durationSection?.selectDurationToggle?.container}
|
||||
childrenClassName={customClassNames?.durationSection?.selectDurationToggle?.children}
|
||||
onCheckedChange={() => {
|
||||
if (multipleDuration !== undefined) {
|
||||
setMultipleDuration(undefined);
|
||||
setSelectedMultipleDuration([]);
|
||||
setDefaultDuration(null);
|
||||
formMethods.setValue("metadata.multipleDuration", undefined, { shouldDirty: true });
|
||||
formMethods.setValue("length", eventType.length, { shouldDirty: true });
|
||||
} else {
|
||||
setMultipleDuration([]);
|
||||
formMethods.setValue("metadata.multipleDuration", [], { shouldDirty: true });
|
||||
formMethods.setValue("length", 0, { shouldDirty: true });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"border-subtle rounded-lg border p-6",
|
||||
customClassNames?.locationSection?.container
|
||||
)}>
|
||||
<div>
|
||||
<Skeleton
|
||||
as={Label}
|
||||
loadingClassName="w-16"
|
||||
htmlFor="locations"
|
||||
className={customClassNames?.locationSection?.label}>
|
||||
{t("location")}
|
||||
{/*improve shouldLockIndicator function to also accept eventType and then conditionally render
|
||||
based on Managed Event type or not.*/}
|
||||
{shouldLockIndicator("locations")}
|
||||
</Skeleton>
|
||||
<Controller
|
||||
name="locations"
|
||||
control={formMethods.control}
|
||||
defaultValue={eventType.locations || []}
|
||||
render={() => (
|
||||
<Locations
|
||||
showAppStoreLink={true}
|
||||
isChildrenManagedEventType={isChildrenManagedEventType}
|
||||
isManagedEventType={isManagedEventType}
|
||||
disableLocationProp={shouldLockDisableProps("locations").disabled}
|
||||
getValues={formMethods.getValues as unknown as UseFormGetValues<LocationFormValues>}
|
||||
setValue={formMethods.setValue as unknown as UseFormSetValue<LocationFormValues>}
|
||||
control={formMethods.control as unknown as Control<LocationFormValues>}
|
||||
formState={formMethods.formState as unknown as FormState<LocationFormValues>}
|
||||
{...props}
|
||||
customClassNames={customClassNames?.locationSection}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,280 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import { Dialog } from "@calcom/features/components/controlled-dialog";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import type { FormValues, EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
import { WebhookForm } from "@calcom/features/webhooks/components";
|
||||
import EventTypeWebhookListItem from "@calcom/features/webhooks/components/EventTypeWebhookListItem";
|
||||
import type { TWebhook, WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";
|
||||
import { subscriberUrlReserved } from "@calcom/features/webhooks/lib/subscriberUrlReserved";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent } from "@calcom/ui/components/dialog";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateEventTypeEditPage } from "@calcom/web/app/(use-page-wrapper)/event-types/[type]/actions";
|
||||
|
||||
export const EventWebhooksTab = ({ eventType }: Pick<EventTypeSetupProps, "eventType">) => {
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery({ eventTypeId: eventType.id });
|
||||
|
||||
const { data: installedApps, isLoading } = trpc.viewer.apps.integrations.useQuery({
|
||||
variant: "other",
|
||||
onlyInstalled: true,
|
||||
});
|
||||
|
||||
const [createModalOpen, setCreateModalOpen] = useState(false);
|
||||
const [editModalOpen, setEditModalOpen] = useState(false);
|
||||
const [webhookToEdit, setWebhookToEdit] = useState<TWebhook>();
|
||||
|
||||
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess() {
|
||||
setEditModalOpen(false);
|
||||
revalidateEventTypeEditPage(eventType.id);
|
||||
showToast(t("webhook_updated_successfully"), "success");
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
await utils.viewer.eventTypes.get.invalidate();
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const createWebhookMutation = trpc.viewer.webhook.create.useMutation({
|
||||
async onSuccess() {
|
||||
setCreateModalOpen(false);
|
||||
revalidateEventTypeEditPage(eventType.id);
|
||||
showToast(t("webhook_created_successfully"), "success");
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
await utils.viewer.eventTypes.get.invalidate();
|
||||
},
|
||||
onError(error) {
|
||||
showToast(`${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const onCreateWebhook = async (values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
id: values.id,
|
||||
webhooks,
|
||||
eventTypeId: eventType.id,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
createWebhookMutation.mutate({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
eventTypeId: eventType.id,
|
||||
time: values.time,
|
||||
timeUnit: values.timeUnit,
|
||||
});
|
||||
};
|
||||
|
||||
const NewWebhookButton = () => {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<Button
|
||||
color="secondary"
|
||||
data-testid="new_webhook"
|
||||
StartIcon="plus"
|
||||
onClick={() => setCreateModalOpen(true)}>
|
||||
{t("new_webhook")}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
const { shouldLockDisableProps, isChildrenManagedEventType, isManagedEventType } = useLockedFieldsManager({
|
||||
eventType,
|
||||
translate: t,
|
||||
formMethods,
|
||||
});
|
||||
const webhooksDisableProps = shouldLockDisableProps("webhooks", { simple: true });
|
||||
const lockedText = webhooksDisableProps.isLocked ? "locked" : "unlocked";
|
||||
const cannotEditWebhooks = isChildrenManagedEventType ? webhooksDisableProps.isLocked : false;
|
||||
return (
|
||||
<div>
|
||||
{webhooks && !isLoading && (
|
||||
<>
|
||||
<div>
|
||||
<div>
|
||||
<>
|
||||
{(isManagedEventType || isChildrenManagedEventType) && (
|
||||
<Alert
|
||||
severity={webhooksDisableProps.isLocked ? "neutral" : "info"}
|
||||
className="mb-2"
|
||||
title={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`${lockedText}_${isManagedEventType ? "for_members" : "by_team_admins"}`}
|
||||
/>
|
||||
}
|
||||
actions={
|
||||
<div className="flex h-full items-center">{webhooksDisableProps.LockedIcon}</div>
|
||||
}
|
||||
message={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`webhooks_${lockedText}_${
|
||||
isManagedEventType ? "for_members" : "by_team_admins"
|
||||
}_description`}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{webhooks.length ? (
|
||||
<>
|
||||
<div className="border-subtle mb-2 rounded-md border p-8">
|
||||
<div className="flex justify-between">
|
||||
<div>
|
||||
<div className="text-default text-sm font-semibold">{t("webhooks")}</div>
|
||||
<p className="text-subtle max-w-[280px] wrap-break-word text-sm sm:max-w-[500px]">
|
||||
{t("add_webhook_description", { appName: APP_NAME })}
|
||||
</p>
|
||||
</div>
|
||||
{cannotEditWebhooks ? (
|
||||
<Button StartIcon="lock" color="secondary" disabled>
|
||||
{t("locked_by_team_admin")}
|
||||
</Button>
|
||||
) : (
|
||||
<NewWebhookButton />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-subtle my-8 rounded-md border">
|
||||
{webhooks.map((webhook, index) => {
|
||||
return (
|
||||
<EventTypeWebhookListItem
|
||||
key={webhook.id}
|
||||
webhook={webhook}
|
||||
lastItem={webhooks.length === index + 1}
|
||||
onEditWebhook={() => {
|
||||
setEditModalOpen(true);
|
||||
setWebhookToEdit(webhook);
|
||||
}}
|
||||
readOnly={isChildrenManagedEventType && webhook.eventTypeId !== eventType.id}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="text-default text-sm font-normal">
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="edit_or_manage_webhooks"
|
||||
components={[
|
||||
<Link
|
||||
key="edit_or_manage_webhooks"
|
||||
className="cursor-pointer font-semibold underline"
|
||||
href="/settings/developer/webhooks">
|
||||
webhooks settings
|
||||
</Link>,
|
||||
]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<EmptyScreen
|
||||
Icon="webhook"
|
||||
headline={t("create_your_first_webhook")}
|
||||
description={t("first_event_type_webhook_description")}
|
||||
buttonRaw={
|
||||
cannotEditWebhooks ? (
|
||||
<Button StartIcon="lock" color="secondary" disabled>
|
||||
{t("locked_by_team_admin")}
|
||||
</Button>
|
||||
) : (
|
||||
<NewWebhookButton />
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* New webhook dialog */}
|
||||
<Dialog open={createModalOpen} onOpenChange={(isOpen) => !isOpen && setCreateModalOpen(false)}>
|
||||
<DialogContent
|
||||
enableOverflow
|
||||
title={t("create_webhook")}
|
||||
description={t("create_webhook_team_event_type")}>
|
||||
<WebhookForm
|
||||
noRoutingFormTriggers={true}
|
||||
onSubmit={onCreateWebhook}
|
||||
onCancel={() => setCreateModalOpen(false)}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{/* Edit webhook dialog */}
|
||||
<Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
|
||||
<DialogContent enableOverflow title={t("edit_webhook")}>
|
||||
<WebhookForm
|
||||
noRoutingFormTriggers={true}
|
||||
webhook={webhookToEdit}
|
||||
apps={installedApps?.items.map((app) => app.slug)}
|
||||
onCancel={() => setEditModalOpen(false)}
|
||||
onSubmit={(values: WebhookFormSubmitData) => {
|
||||
if (
|
||||
subscriberUrlReserved({
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
id: webhookToEdit?.id,
|
||||
webhooks,
|
||||
eventTypeId: eventType.id,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (values.changeSecret) {
|
||||
values.secret = values.newSecret.length ? values.newSecret : null;
|
||||
}
|
||||
|
||||
if (!values.payloadTemplate) {
|
||||
values.payloadTemplate = null;
|
||||
}
|
||||
|
||||
editWebhookMutation.mutate({
|
||||
id: webhookToEdit?.id || "",
|
||||
subscriberUrl: values.subscriberUrl,
|
||||
eventTriggers: values.eventTriggers,
|
||||
active: values.active,
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
eventTypeId: webhookToEdit?.eventTypeId || undefined,
|
||||
timeUnit: values.timeUnit,
|
||||
time: values.time,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,312 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
|
||||
import SkeletonLoader from "@calcom/features/ee/workflows/components/SkeletonLoaderEventWorkflowsTab";
|
||||
import type { WorkflowType } from "@calcom/features/ee/workflows/components/WorkflowListPage";
|
||||
import { getActionIcon } from "@calcom/features/ee/workflows/lib/getActionIcon";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
import { Switch } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import { revalidateEventTypeEditPage } from "@calcom/web/app/(use-page-wrapper)/event-types/[type]/actions";
|
||||
|
||||
type PartialWorkflowType = Pick<
|
||||
WorkflowType,
|
||||
"name" | "activeOn" | "isOrg" | "steps" | "id" | "readOnly" | "permissions"
|
||||
>;
|
||||
|
||||
type ItemProps = {
|
||||
workflow: PartialWorkflowType;
|
||||
eventType: {
|
||||
id: number;
|
||||
title: string;
|
||||
requiresConfirmation: boolean;
|
||||
};
|
||||
isChildrenManagedEventType: boolean;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
const WorkflowListItem = (props: ItemProps) => {
|
||||
const { workflow, eventType, isActive } = props;
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const activateEventTypeMutation = trpc.viewer.workflows.activateEventType.useMutation({
|
||||
onSuccess: async () => {
|
||||
const offOn = isActive ? "off" : "on";
|
||||
revalidateEventTypeEditPage(eventType.id);
|
||||
await utils.viewer.workflows.getAllActiveWorkflows.invalidate();
|
||||
|
||||
await utils.viewer.eventTypes.get.invalidate({ id: eventType.id });
|
||||
showToast(
|
||||
t("workflow_turned_on_successfully", {
|
||||
workflowName: workflow.name,
|
||||
offOn,
|
||||
}),
|
||||
"success"
|
||||
);
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof HttpError) {
|
||||
const message = `${err.statusCode}: ${err.message}`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
if (err.data?.code === "UNAUTHORIZED") {
|
||||
showToast(
|
||||
t("unauthorized_workflow_error_message", {
|
||||
errorCode: err.data.code,
|
||||
}),
|
||||
"error"
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const sendTo: Set<string> = new Set();
|
||||
|
||||
workflow.steps.forEach((step) => {
|
||||
switch (step.action) {
|
||||
case WorkflowActions.EMAIL_HOST:
|
||||
sendTo.add(t("organizer"));
|
||||
break;
|
||||
case WorkflowActions.EMAIL_ATTENDEE:
|
||||
case WorkflowActions.SMS_ATTENDEE:
|
||||
case WorkflowActions.WHATSAPP_ATTENDEE:
|
||||
sendTo.add(t("attendee_name_variable"));
|
||||
break;
|
||||
case WorkflowActions.SMS_NUMBER:
|
||||
case WorkflowActions.WHATSAPP_NUMBER:
|
||||
case WorkflowActions.EMAIL_ADDRESS:
|
||||
sendTo.add(step.sendTo || "");
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="border-subtle w-full overflow-hidden rounded-md border p-6 px-3 md:p-6">
|
||||
<div className="flex items-center">
|
||||
<div className="bg-subtle mr-4 flex h-10 w-10 items-center justify-center rounded-full text-xs font-medium">
|
||||
{getActionIcon(
|
||||
workflow.steps,
|
||||
isActive ? "h-6 w-6 stroke-[1.5px] text-default" : "h-6 w-6 stroke-[1.5px] text-muted"
|
||||
)}
|
||||
</div>
|
||||
<div className="grow">
|
||||
<div
|
||||
className={classNames(
|
||||
"text-emphasis mb-1 w-full truncate text-base font-medium leading-4 md:max-w-max",
|
||||
workflow.name && isActive ? "text-emphasis" : "text-subtle"
|
||||
)}>
|
||||
{workflow.name
|
||||
? workflow.name
|
||||
: `Untitled (${`${t(`${workflow.steps[0].action.toLowerCase()}_action`)}`
|
||||
.charAt(0)
|
||||
.toUpperCase()}${`${t(`${workflow.steps[0].action.toLowerCase()}_action`)}`.slice(1)})`}
|
||||
</div>
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"flex w-fit items-center whitespace-nowrap rounded-sm text-sm leading-4",
|
||||
isActive ? "text-default" : "text-muted"
|
||||
)}>
|
||||
<span className="mr-1">{t("to")}:</span>
|
||||
{Array.from(sendTo).map((sendToPerson, index) => {
|
||||
return <span key={index}>{`${index ? ", " : ""}${sendToPerson}`}</span>;
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
{workflow.permissions?.canUpdate && (
|
||||
<div className="flex-none">
|
||||
<Link href={`/workflows/${workflow.id}`} passHref={true} target="_blank">
|
||||
<Button type="button" color="minimal" className="mr-4" EndIcon="external-link">
|
||||
<div className="hidden ltr:mr-2 rtl:ml-2 sm:block">{t("edit")}</div>
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
<Tooltip
|
||||
content={
|
||||
t(
|
||||
workflow.readOnly && props.isChildrenManagedEventType
|
||||
? "locked_by_team_admin"
|
||||
: isActive
|
||||
? "turn_off"
|
||||
: "turn_on"
|
||||
) as string
|
||||
}>
|
||||
<div className="flex items-center ltr:mr-2 rtl:ml-2">
|
||||
{workflow.readOnly && props.isChildrenManagedEventType && (
|
||||
<Icon name="lock" className="text-subtle h-4 w-4 ltr:mr-2 rtl:ml-2" />
|
||||
)}
|
||||
<Switch
|
||||
checked={isActive}
|
||||
disabled={!workflow.permissions?.canUpdate}
|
||||
onCheckedChange={() => {
|
||||
activateEventTypeMutation.mutate({ workflowId: workflow.id, eventTypeId: eventType.id });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type EventTypeSetup = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"];
|
||||
|
||||
type Props = {
|
||||
eventType: EventTypeSetup;
|
||||
workflows: PartialWorkflowType[];
|
||||
};
|
||||
|
||||
function EventWorkflowsTab(props: Props) {
|
||||
const { workflows, eventType } = props;
|
||||
const { t } = useLocale();
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const { shouldLockDisableProps, isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager({
|
||||
eventType,
|
||||
translate: t,
|
||||
formMethods,
|
||||
});
|
||||
|
||||
const workflowsDisableProps = shouldLockDisableProps("workflows", { simple: true });
|
||||
const lockedText = workflowsDisableProps.isLocked ? "locked" : "unlocked";
|
||||
const { data, isPending } = trpc.viewer.workflows.list.useQuery({
|
||||
teamId: eventType.team?.id,
|
||||
userId: !isChildrenManagedEventType ? eventType.userId || undefined : undefined,
|
||||
includeOnlyEventTypeWorkflows: true,
|
||||
});
|
||||
const router = useRouter();
|
||||
const [sortedWorkflows, setSortedWorkflows] = useState<Array<WorkflowType>>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.workflows) {
|
||||
const allActiveWorkflows = workflows.map((workflowOnEventType) => {
|
||||
const dataWf = data.workflows.find((wf) => wf.id === workflowOnEventType.id);
|
||||
return {
|
||||
...workflowOnEventType,
|
||||
readOnly: isChildrenManagedEventType && dataWf?.teamId ? true : dataWf?.readOnly ?? false,
|
||||
} as WorkflowType;
|
||||
});
|
||||
|
||||
const disabledWorkflows = data.workflows.filter(
|
||||
(workflow) =>
|
||||
(!workflow.teamId || eventType.teamId === workflow.teamId) &&
|
||||
!workflows
|
||||
.map((workflow) => {
|
||||
return workflow.id;
|
||||
})
|
||||
.includes(workflow.id)
|
||||
);
|
||||
const allSortedWorkflows =
|
||||
workflowsDisableProps.isLocked && !isManagedEventType
|
||||
? allActiveWorkflows
|
||||
: allActiveWorkflows.concat(disabledWorkflows);
|
||||
setSortedWorkflows(allSortedWorkflows);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isPending]);
|
||||
|
||||
const createMutation = trpc.viewer.workflows.create.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
router.replace(`/workflows/${workflow.id}?eventTypeId=${eventType.id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof HttpError) {
|
||||
const message = `${err.statusCode}: ${err.message}`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
|
||||
if (err.data?.code === "UNAUTHORIZED") {
|
||||
const message = `${err.data.code}: ${t("error_workflow_unauthorized_create")}`;
|
||||
showToast(message, "error");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<LicenseRequired>
|
||||
{!isPending ? (
|
||||
<>
|
||||
{(isManagedEventType || isChildrenManagedEventType) && (
|
||||
<Alert
|
||||
severity={workflowsDisableProps.isLocked ? "neutral" : "info"}
|
||||
className="mb-2"
|
||||
title={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`${lockedText}_${isManagedEventType ? "for_members" : "by_team_admins"}`}
|
||||
/>
|
||||
}
|
||||
actions={<div className="flex h-full items-center">{workflowsDisableProps.LockedIcon}</div>}
|
||||
message={
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={`workflows_${lockedText}_${
|
||||
isManagedEventType ? "for_members" : "by_team_admins"
|
||||
}_description`}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{data?.workflows && sortedWorkflows.length > 0 ? (
|
||||
<div>
|
||||
<div className="stack-y-4">
|
||||
{sortedWorkflows.map((workflow) => {
|
||||
return (
|
||||
<WorkflowListItem
|
||||
key={workflow.id}
|
||||
workflow={workflow}
|
||||
eventType={props.eventType}
|
||||
isChildrenManagedEventType
|
||||
isActive={!!workflows.find((activeWorkflow) => activeWorkflow.id === workflow.id)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pt-2 before:border-0">
|
||||
<EmptyScreen
|
||||
Icon="zap"
|
||||
headline={t("workflows")}
|
||||
description={t("no_workflows_description")}
|
||||
buttonRaw={
|
||||
<Button
|
||||
disabled={workflowsDisableProps.isLocked && !isManagedEventType}
|
||||
target="_blank"
|
||||
color="secondary"
|
||||
onClick={() => createMutation.mutate({ teamId: eventType.team?.id })}
|
||||
loading={createMutation.isPending}>
|
||||
{t("create_workflow")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<SkeletonLoader />
|
||||
)}
|
||||
</LicenseRequired>
|
||||
);
|
||||
}
|
||||
|
||||
export default EventWorkflowsTab;
|
||||
Reference in new issue
Block a user