refactor: Cal.diy (#28903)

* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com

This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main:

- Rebrand Cal.com to Cal.diy across the entire codebase
- Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions
- Switch license from AGPL-3.0 to MIT
- Remove docs/ directory (migrated to Nextra at cal.diy)
- Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc.
- Clean up .env.example for self-hosted Cal.diy
- Update Docker image references to calcom/cal.diy
- Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork
- Add PR welcome bot for Cal.diy contributors
- Fix API v2 breaking changes oasdiff ignore entries
- Replace Blacksmith CI runners with default GitHub Actions

3893 files changed, 20789 insertions(+), 411020 deletions(-)

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rip out org related comments in api v2

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-04-15 09:52:36 -03:00
1 parent a17f28e9ab
commit ab21c7f805
4080 files changed
+14403 -404922

No files matched your search

@@ -3,8 +3,7 @@ import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import type { TApiKeys } from "~/ee/api-keys/components/ApiKeyListItem";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import type { TApiKeys } from "~/api-keys/api-keys/components/ApiKeyListItem";
import { API_NAME_LENGTH_MAX_LIMIT } from "@calcom/lib/constants";
import { IS_CALCOM } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -93,7 +92,7 @@ export default function ApiKeyDialogForm({
];
return (
<LicenseRequired>
<>
{successfulNewApiKeyModal ? (
<>
<div className="mb-6">
@@ -260,6 +259,6 @@ export default function ApiKeyDialogForm({
</DialogFooter>
</Form>
)}
</LicenseRequired>
</>
);
}
@@ -56,7 +56,6 @@ function SingleAppPage(props: AppDataProps) {
website={data.url}
email={data.email}
licenseRequired={data.licenseRequired}
teamsPlanRequired={data.teamsPlanRequired}
descriptionItems={source.data?.items as string[] | undefined}
isTemplate={data.isTemplate}
dependencies={data.dependencies}
@@ -148,7 +148,6 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
? !app.isGlobal && (
<InstallAppButton
type={app.type}
teamsPlanRequired={app.teamsPlanRequired}
disableInstall={!!app.dependencies && !app.dependencyData?.some((data) => !data.installed)}
wrapperClassName="[@media(max-width:260px)]:w-full"
render={({ useDefaultComponent, ...props }) => {
@@ -187,7 +186,6 @@ export function AppCard({ app, credentials, searchText, userAdminTeams }: AppCar
type={app.type}
wrapperClassName="[@media(max-width:260px)]:w-full"
disableInstall={!!app.dependencies && app.dependencyData?.some((data) => !data.installed)}
teamsPlanRequired={app.teamsPlanRequired}
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
props = {
@@ -11,7 +11,7 @@ export const _SBApps: App[] = [
category: "calendar",
categories: ["calendar"],
logo: "/api/app-store/googlecalendar/icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
slug: "google-calendar",
url: "https://cal.com/",
email: "[email protected]",
@@ -24,7 +24,7 @@ export const _SBApps: App[] = [
categories: ["video"],
variant: "conferencing",
logo: "/api/app-store/zoomvideo/icon.svg",
publisher: "Cal.com",
publisher: "Cal.diy",
url: "https://zoom.us/",
category: "video",
slug: "zoom",
@@ -22,7 +22,6 @@ describe("Tests for AppCard component", () => {
description: "Test description for the app.",
categories: ["calendar"],
concurrentMeetings: true,
teamsPlanRequired: { upgradeUrl: "test" },
type: "test_calendar",
variant: "calendar",
publisher: "test",
@@ -1,80 +0,0 @@
import { signIn } from "next-auth/react";
import type { Dispatch, SetStateAction } from "react";
import { useFormContext } from "react-hook-form";
import z from "zod";
import { LastUsed, useLastUsed } from "../hooks/useLastUsed";
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
import { emailRegex } from "@calcom/lib/emailSchema";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui/components/button";
import { Button } from "@calcom/ui/components/button";
interface Props {
samlTenantID: string;
samlProductID: string;
setErrorMessage: Dispatch<SetStateAction<string | null>>;
}
const schema = z.object({
email: z.string().regex(emailRegex, { message: "Please enter a valid email" }),
});
export function SAMLLogin({
samlTenantID,
samlProductID,
setErrorMessage,
...buttonProps
}: Props & ButtonProps) {
const { t } = useLocale();
const methods = useFormContext();
const [lastUsed, setLastUsed] = useLastUsed();
const mutation = trpc.viewer.public.samlTenantProduct.useMutation({
onSuccess: async (data) => {
setLastUsed("saml");
await signIn("saml", {}, { tenant: data.tenant, product: data.product });
},
onError: (err) => {
setErrorMessage(t(err.message));
},
});
return (
<Button
StartIcon="lock"
color="secondary"
data-testid="samlAndOidc"
className="flex w-full justify-center"
onClick={async (event) => {
event.preventDefault();
if (!HOSTED_CAL_FEATURES) {
await signIn("saml", {}, { tenant: samlTenantID, product: samlProductID });
return;
}
// Hosted solution, fetch tenant and product from the backend
const email = methods.getValues("email");
const parsed = schema.safeParse({ email });
if (!parsed.success) {
const {
fieldErrors: { email },
} = parsed.error.flatten();
setErrorMessage(email ? email[0] : null);
return;
}
mutation.mutate({
email,
});
}}
{...buttonProps}>
<span>{t("signin_with_saml_oidc")}</span>
{lastUsed === "saml" && <LastUsed />}
</Button>
);
}
+1 -34
View File
@@ -6,10 +6,8 @@ import { emailRegex } from "@calcom/lib/emailSchema";
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Icon } from "@calcom/ui/components/icon";
import { SAMLLogin } from "@calcom/web/modules/auth/components/SAMLLogin";
import { LastUsed, useLastUsed } from "@calcom/web/modules/auth/hooks/useLastUsed";
import AddToHomescreen from "@components/AddToHomescreen";
import BackupCode from "@components/auth/BackupCode";
@@ -107,9 +105,6 @@ export default function Login({
csrfToken,
isGoogleLoginEnabled,
isOutlookLoginEnabled,
isSAMLLoginEnabled,
samlTenantID,
samlProductID,
totpEmail,
}: PageProps) {
const searchParams = useCompatSearchParams();
@@ -155,21 +150,6 @@ export default function Login({
callbackUrl = safeCallbackUrl || "";
const { data, isPending, error } = trpc.viewer.public.ssoConnections.useQuery();
useEffect(
function refactorMeWithoutEffect() {
if (error) {
setErrorMessage(error.message);
}
},
[error]
);
const displaySSOLogin = HOSTED_CAL_FEATURES
? true
: isSAMLLoginEnabled && !isPending && data?.connectionExists;
const onSubmit = async (values: LoginValues) => {
setErrorMessage(null);
// telemetry.event(telemetryEventTypes.login, collectPageParameters());
@@ -203,7 +183,7 @@ export default function Login({
<div className="w-full rounded-xl border border-subtle bg-default p-10 shadow-sm">
{/* Logo */}
<div className="mb-2 text-center">
<h1 className="font-cal text-xl font-bold text-emphasis">Cal.com</h1>
<h1 className="font-cal text-xl font-bold text-emphasis">Cal.diy</h1>
</div>
{/* Heading */}
@@ -399,19 +379,6 @@ export default function Login({
{t("create_account")}
</Link>
)}
{displaySSOLogin && (
<>
{showSignupLink && <span className="text-subtle">·</span>}
<SAMLLogin
samlTenantID={samlTenantID}
samlProductID={samlProductID}
setErrorMessage={setErrorMessage}
color="minimal"
StartIcon={undefined}
className="text-sm font-medium text-emphasis hover:underline p-0 h-auto"
/>
</>
)}
</div>
)}
</div>
@@ -1,17 +0,0 @@
"use client";
import { signIn } from "next-auth/react";
import { useEffect } from "react";
// To handle the IdP initiated login flow callback
export default function SamlIdp({ code }: { code: string }) {
useEffect(() => {
signIn("saml-idp", {
callbackUrl: "/",
code,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}
+4 -47
View File
@@ -1,7 +1,7 @@
"use client";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import AdminAppsList from "~/apps/components/AdminAppsList";
import { APP_NAME } from "@calcom/lib/constants";
@@ -11,38 +11,25 @@ import { WizardForm } from "@calcom/ui/components/form";
import type { WizardStep } from "@calcom/ui/components/form/wizard/WizardForm";
import { AdminUserContainer as AdminUser } from "@components/setup/AdminUser";
import LicenseSelection from "@components/setup/LicenseSelection";
import type { getServerSideProps } from "@server/lib/setup/getServerSideProps";
const SETUP_VIEW_SETPS = {
ADMIN_USER: 1,
LICENSE: 2,
APPS: 3,
APPS: 2,
} as const;
export type PageProps = inferSSRProps<typeof getServerSideProps>;
export function Setup(props: PageProps) {
const [hasPickedAGPLv3, setHasPickedAGPLv3] = useState(false);
const { t } = useLocale();
const router = useRouter();
const [licenseOption, setLicenseOption] = useState<"FREE" | "EXISTING">(
props.hasValidLicense ? "EXISTING" : "FREE"
);
const hasLicenseStep = !props.hasValidLicense && !hasPickedAGPLv3;
const defaultStep = useMemo(() => {
if (props.userCount > 0) {
if (hasLicenseStep) {
return SETUP_VIEW_SETPS.LICENSE;
} else {
// License step is not shown, so apps step is at position 2 instead of 3
return SETUP_VIEW_SETPS.APPS - 1;
}
return SETUP_VIEW_SETPS.APPS;
}
return SETUP_VIEW_SETPS.ADMIN_USER;
}, [props.userCount, hasLicenseStep]);
}, [props.userCount]);
const steps: WizardStep[] = [
{
@@ -67,36 +54,6 @@ export function Setup(props: PageProps) {
},
];
// Only show license selection step if there's no valid license already and AGPLv3 wasn't picked
if (hasLicenseStep) {
steps.push({
title: t("choose_a_license"),
description: t("choose_license_description"),
customActions: true,
content: (setIsPending, nav) => {
return (
<LicenseSelection
id="wizard-step-2"
name="wizard-step-2"
value={licenseOption}
onChange={setLicenseOption}
onSubmit={(values) => {
setIsPending(true);
if (licenseOption === "FREE") {
setHasPickedAGPLv3(true);
nav.onNext();
} else if (licenseOption === "EXISTING" && values.licenseKey) {
nav.onNext();
}
}}
onPrevStep={nav.onPrev}
onNextStep={nav.onNext}
/>
);
},
});
}
steps.push({
title: t("enable_apps"),
description: t("enable_apps_description", { appName: APP_NAME }),
-40
View File
@@ -1,40 +0,0 @@
"use client";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import type { getServerSideProps } from "@server/lib/auth/sso/direct/getServerSideProps";
// This page is used to initiate the SAML authentication flow by redirecting to the SAML provider.
// Accessible only on self-hosted Cal.com instances.
export type SSODirectPageProps = inferSSRProps<typeof getServerSideProps>;
export default function Page({ samlTenantID, samlProductID }: SSODirectPageProps) {
const router = useRouter();
useEffect(() => {
if (HOSTED_CAL_FEATURES) {
router.push("/auth/login");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
// Initiate SAML authentication flow
signIn(
"saml",
{
callbackUrl: "/",
},
{ tenant: samlTenantID, product: samlProductID }
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}
@@ -1,43 +0,0 @@
"use client";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import type { getServerSideProps } from "@server/lib/auth/sso/[provider]/getServerSideProps";
export type SSOProviderPageProps = inferSSRProps<typeof getServerSideProps>;
export default function Provider(props: SSOProviderPageProps) {
const searchParams = useCompatSearchParams();
const router = useRouter();
useEffect(() => {
const email = searchParams?.get("email");
if (props.provider === "saml") {
if (!email) {
router.push(`/auth/error?error=Email not provided`);
return;
}
if (!props.isSAMLLoginEnabled) {
router.push(`/auth/error?error=SAML login not enabled`);
return;
}
signIn("saml", {}, { tenant: props.tenant, product: props.product });
} else if (props.provider === "google" && email) {
signIn("google", {}, { login_hint: email });
} else if (props.provider === "microsoft") {
signIn("azure-ad");
} else {
signIn(props.provider);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}
+1 -1
View File
@@ -28,7 +28,7 @@ const EMAIL_CLIENTS = [
{
name: "Yahoo",
icon: "/email-clients/yahoo.svg",
href: "https://mail.yahoo.com/d/search?p=Cal.com",
href: "https://mail.yahoo.com/d/search?p=Cal.diy",
},
{
name: "Proton",
@@ -1,25 +1,21 @@
"use client";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { revalidateAvailabilityList } from "app/(use-page-wrapper)/(main-nav)/availability/actions";
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import { useCallback, useState } from "react";
import posthog from "posthog-js";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import type { BulkUpdatParams } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { NewScheduleButton } from "@calcom/web/modules/schedules/components/NewScheduleButton";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { ScheduleListItem } from "@calcom/features/schedules/components/ScheduleListItem";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { ToggleGroup } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { NewScheduleButton } from "@calcom/web/modules/schedules/components/NewScheduleButton";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { revalidateAvailabilityList } from "app/(use-page-wrapper)/(main-nav)/availability/actions";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
type AvailabilityListProps = {
availabilities: RouterOutputs["viewer"]["availability"]["list"];
@@ -182,53 +178,9 @@ export function AvailabilityList({ availabilities }: AvailabilityListProps) {
);
}
type AvailabilityCTAProps = {
canViewTeamAvailability: boolean;
};
export const AvailabilityCTA = ({ canViewTeamAvailability }: AvailabilityCTAProps) => {
const searchParams = useCompatSearchParams();
const router = useRouter();
const pathname = usePathname();
const { t } = useLocale();
const toggleGroupOptions = [
{ value: "mine", label: t("my_availability") },
...(canViewTeamAvailability
? [
{
value: "team",
label: t("team_availability"),
onClick: () => {
posthog.capture("team_availability_toggle_clicked");
},
},
]
: []),
];
// Get a new searchParams string by merging the current
// searchParams with a provided key/value pair
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams ?? undefined);
params.set(name, value);
return params.toString();
},
[searchParams]
);
export const AvailabilityCTA = () => {
return (
<div className="flex items-center gap-2">
<ToggleGroup
className="hidden h-fit md:block"
defaultValue={searchParams?.get("type") ?? "mine"}
onValueChange={(value) => {
if (!value) return;
router.push(`${pathname}?${createQueryString("type", value)}`);
}}
options={toggleGroupOptions}
/>
<NewScheduleButton />
</div>
);
@@ -1,318 +0,0 @@
"use client";
import { useFillRemainingHeight } from "@calcom/lib/hooks/useFillRemainingHeight";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { Icon } from "@calcom/ui/components/icon";
import { OrgBadge, TeamBadge } from "@calcom/web/modules/billing/components/PlanBadge";
import { UpgradePlanDialog } from "@calcom/web/modules/billing/components/UpgradePlanDialog";
import { Badge } from "@coss/ui/components/badge";
import { Button } from "@coss/ui/components/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPopup,
DialogTitle,
} from "@coss/ui/components/dialog";
import Image from "next/image";
import Link from "next/link";
import posthog from "posthog-js";
import { useState } from "react";
import type { UpgradeTarget } from "./types";
export type { UpgradeTarget };
export type FullScreenUpgradeBannerProps = {
tracking: string;
name: string;
title: string;
subtitle: string;
features?: string[];
target: UpgradeTarget;
learnMoreButton?: {
text: string;
href?: string;
onClick?: () => void;
};
extraOffset?:
| number
| {
mobile?: number;
tablet?: number;
desktop?: number;
};
image: {
src: string;
width: number;
height: number;
};
youtubeId?: string;
};
function useResponsiveOffset(
extraOffset?:
| number
| {
mobile?: number;
tablet?: number;
desktop?: number;
}
) {
const isMobile = useMediaQuery("(max-width: 639px)");
const isTablet = useMediaQuery("(max-width: 767px)");
if (isMobile) {
return typeof extraOffset === "number" ? extraOffset : (extraOffset?.mobile ?? 74);
} else if (isTablet) {
return typeof extraOffset === "number" ? extraOffset : (extraOffset?.tablet ?? 85);
} else {
return typeof extraOffset === "number" ? extraOffset : (extraOffset?.desktop ?? 24);
}
}
function BannerImage({
image,
name,
youtubeId,
tracking,
target,
onPlayVideo,
}: {
image: { src: string; width: number; height: number };
name: string;
youtubeId?: string;
tracking: string;
target: UpgradeTarget;
onPlayVideo: () => void;
}): JSX.Element {
const { t } = useLocale();
return (
<>
<Image
src={image.src}
alt={name}
width={image.width}
height={image.height}
className="h-full w-full object-cover object-top"
/>
{youtubeId && (
<button
type="button"
className="absolute inset-0 flex items-center justify-center cursor-pointer"
onClick={() => {
posthog.capture("fullscreen_upgrade_banner_video_played", { source: tracking, target });
onPlayVideo();
}}>
<Image src="/play_button.svg" alt={t("play_video")} width={48} height={48} />
</button>
)}
</>
);
}
export function FullScreenUpgradeBanner({
tracking,
name,
title,
subtitle,
features,
target,
learnMoreButton,
extraOffset,
image,
youtubeId,
}: FullScreenUpgradeBannerProps): JSX.Element {
const [videoOpen, setVideoOpen] = useState(false);
const [showFeatures, setShowFeatures] = useState(false);
const deviceSpecificOffset = useResponsiveOffset(extraOffset);
const { t } = useLocale();
const ref = useFillRemainingHeight(deviceSpecificOffset);
const bannerImageProps = {
image,
name,
youtubeId,
tracking,
target,
onPlayVideo: () => setVideoOpen(true),
};
return (
<div ref={ref} className="flex w-full shrink-0 items-center justify-center rounded-xl bg-subtle p-8">
<div className="flex w-full h-full md:h-auto max-w-3xl gap-2 overflow-hidden rounded-3xl bg-default p-5 md:py-8 md:pl-8 md:pr-0 shadow-sm">
{/* Left Content */}
<div className="flex flex-1 flex-col justify-between overflow-hidden">
<div className={`${showFeatures ? "overflow-y-auto" : ""} md:overflow-visible`}>
<div>
<Badge
variant="outline"
className="text-sm text-default font-medium bg-subtle px-2 py-1 h-fit! border-0">
{name}
</Badge>
</div>
<h2 className="mt-3 font-cal font-semibold text-emphasis text-xl leading-none">{title}</h2>
<p className="mt-2 text-subtle text-sm">{subtitle}</p>
{/* Features List */}
{features && (
<>
<ul className="mt-4 space-y-2 hidden md:block">
{features.map((feature) => (
<li key={feature} className="flex items-center gap-2 text-sm text-subtle">
<span className="text-subtle">•</span>
{feature}
</li>
))}
</ul>
<div className="md:hidden mt-4">
{showFeatures ? (
<>
<ul className="space-y-2">
{features.map((feature) => (
<li key={feature} className="flex items-center gap-2 text-sm text-subtle">
<span className="text-subtle">•</span>
{feature}
</li>
))}
</ul>
<button
type="button"
className="mt-2 text-sm text-emphasis font-medium cursor-pointer underline"
onClick={() => setShowFeatures(false)}>
{t("hide")}
</button>
</>
) : (
<button
type="button"
className="text-sm text-emphasis font-medium cursor-pointer underline"
onClick={() => setShowFeatures(true)}>
{t("show_more")}
</button>
)}
</div>
</>
)}
</div>
{/* Image - mobile only, hidden when features are expanded */}
<div className={`${showFeatures ? "hidden" : ""} md:hidden my-4 flex items-center justify-center rounded-xl bg-subtle aspect-[3/4] overflow-hidden relative`}>
<BannerImage {...bannerImageProps} />
</div>
<div>
<div className="hidden md:flex items-center gap-2 mt-4">
<p className="text-sm font-medium text-subtle">{t("available_on")}</p>
{target === "team" && <TeamBadge />}
{(target === "team" || target === "organization") && <OrgBadge />}
</div>
<div className="mt-4 h-px w-full border border-t-subtle border-dashed" />
{/* Buttons */}
<div className="mt-6 flex items-center justify-between md:justify-start gap-2">
<UpgradePlanDialog
tracking={tracking}
info={{
title,
description: subtitle,
}}
target={target}>
<Button
onClick={() =>
posthog.capture("fullscreen_upgrade_banner_cta_clicked", { source: tracking, target })
}>
{t("try_for_free")}
<Icon name="arrow-right" />
</Button>
</UpgradePlanDialog>
{learnMoreButton &&
(learnMoreButton.href ? (
<Button
variant="ghost"
className="text-subtle"
onClick={() =>
posthog.capture("fullscreen_upgrade_banner_learn_more_clicked", {
source: tracking,
target,
})
}
render={<Link href={learnMoreButton.href} target="_blank" rel="noopener noreferrer" />}>
{learnMoreButton.text}
</Button>
) : (
<Button
variant="ghost"
className="text-subtle"
onClick={() => {
posthog.capture("fullscreen_upgrade_banner_learn_more_clicked", {
source: tracking,
target,
});
learnMoreButton.onClick?.();
}}>
{learnMoreButton.text}
</Button>
))}
</div>
</div>
</div>
{/* Right Content - Image */}
<div className="-my-2 hidden md:flex flex-1 items-center justify-center rounded-l-xl bg-subtle aspect-[3/4] overflow-hidden border border-muted border-r-0 relative">
<BannerImage {...bannerImageProps} />
</div>
</div>
{youtubeId && (
<Dialog open={videoOpen} onOpenChange={setVideoOpen}>
<DialogPopup className="max-w-3xl overflow-hidden">
<DialogHeader>
<DialogTitle>{name}</DialogTitle>
<DialogDescription>
{t("available_on_plan", { plan: target === "organization" ? t("organization") : t("team") })}
</DialogDescription>
</DialogHeader>
<div className="aspect-video w-full px-6 pb-6">
<iframe
src={`https://www.youtube.com/embed/${youtubeId}`}
title={title}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className="h-full w-full rounded-lg border border-muted"
/>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
posthog.capture("fullscreen_upgrade_banner_video_dismissed", { source: tracking, target });
setVideoOpen(false);
}}>
{t("dismiss")}
</Button>
<UpgradePlanDialog
tracking={tracking}
info={{
title,
description: subtitle,
}}
target={target}>
<Button
onClick={() =>
posthog.capture("fullscreen_upgrade_banner_video_cta_clicked", {
source: tracking,
target,
})
}>
{t("get_started")}
<Icon name="arrow-right" />
</Button>
</UpgradePlanDialog>
</DialogFooter>
</DialogPopup>
</Dialog>
)}
</div>
);
}
@@ -1,16 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@coss/ui/components/badge";
export function TeamBadge() {
const { t } = useLocale();
return <Badge variant="warning" className="bg-orange-200! text-orange-900">{t("teams")}</Badge>;
}
export function OrgBadge() {
const { t } = useLocale();
return (
<Badge variant="warning" className="bg-purple-200! text-purple-900">
{t("orgs")}
</Badge>
);
}
@@ -1,303 +0,0 @@
"use client";
import { BILLING_PLANS, BILLING_PRICING } from "@calcom/features/ee/billing/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Icon } from "@calcom/ui/components/icon";
import { Alert, AlertDescription, AlertTitle } from "@coss/ui/components/alert";
import { Badge } from "@coss/ui/components/badge";
import { Button } from "@coss/ui/components/button";
import { Card, CardPanel } from "@coss/ui/components/card";
import {
Dialog,
DialogClose,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
DialogTrigger,
} from "@coss/ui/components/dialog";
import { Toggle, ToggleGroup } from "@coss/ui/components/toggle-group";
import Link from "next/link";
import posthog from "posthog-js";
import { useState } from "react";
type BillingPeriodToggle = "annual" | "monthly";
interface PlanFeature {
text: string;
}
interface PlanColumnProps {
name: string;
badge?: string;
price: string;
priceSubtext: string;
description: string;
features: PlanFeature[];
buttonText: string;
buttonHref: string;
buttonTarget?: string;
primaryButton?: boolean;
onCtaClick?: () => void;
}
function PlanColumn({
name,
badge,
price,
priceSubtext,
description,
features,
buttonText,
buttonHref,
buttonTarget,
primaryButton,
onCtaClick,
}: PlanColumnProps): JSX.Element {
return (
<Card className="flex-1 gap-0 rounded-xl border-subtle p-4 py-0">
<CardPanel className="px-0">
<div className="flex items-center gap-2">
<h3 className="font-medium text-sm text-emphasis">{name}</h3>
{badge && (
<Badge variant="outline" className="rounded-lg py-0.5 px-2 h-fit!">
{badge}
</Badge>
)}
</div>
<p className="font-cal mt-2 leading-none font-semibold text-2xl text-emphasis">{price}</p>
<p className="mt-2 leading-none font-medium text-sm text-subtle h-4">{priceSubtext}</p>
<Button
className="mt-4 w-full"
variant={primaryButton ? "default" : "outline"}
onClick={onCtaClick}
render={
<Link
href={buttonHref}
target={buttonTarget}
rel={buttonTarget === "_blank" ? "noopener noreferrer" : undefined}
/>
}>
<Icon name="circle-arrow-up" />
<span>{buttonText}</span>
</Button>
<p className="mt-4 text-sm text-subtle">{description}</p>
<ul className="mt-3 space-y-2">
{features.map((feature) => (
<li key={feature.text} className="flex items-start gap-2 text-sm">
<Icon name="dot" className="relative top-0.5 h-4 w-4 shrink-0 text-default" />
<span className="text-default">{feature.text}</span>
</li>
))}
</ul>
</CardPanel>
</Card>
);
}
export type UpgradePlanDialogProps = {
tracking: string;
target: "team" | "organization";
info?: {
title: string;
description: string;
};
children: React.ReactNode;
};
export function UpgradePlanDialog({ tracking, target, info, children }: UpgradePlanDialogProps): JSX.Element {
const { t } = useLocale();
const [billingPeriod, setBillingPeriod] = useState<"annual" | "monthly">("annual");
const { data: activeTeamPlan } = trpc.viewer.teams.hasActiveTeamPlan.useQuery();
const formatCents = (cents: number) => {
const dollars = cents / 100;
return `$${cents % 100 === 0 ? dollars : dollars.toFixed(2)}`;
};
const teamPrice = formatCents(BILLING_PRICING[BILLING_PLANS.TEAMS][billingPeriod]);
const orgPrice = formatCents(BILLING_PRICING[BILLING_PLANS.ORGANIZATIONS][billingPeriod]);
const currentPlanPricingKey = activeTeamPlan?.billingPeriod === "ANNUALLY" ? "annual" : "monthly";
const currentTeamPrice = formatCents(BILLING_PRICING[BILLING_PLANS.TEAMS][currentPlanPricingKey]);
const bpParam = billingPeriod === "annual" ? "a" : "m";
const teamHref = `/settings/teams/new?bp=${bpParam}`;
const organizationHref = `/onboarding/organization/details?migrate=true&bp=${bpParam}`;
const teamFeatures: PlanFeature[] = [
{ text: t("upgrade_feature_round_robin") },
{ text: t("upgrade_feature_collective_events") },
{ text: t("routing_forms") },
{ text: t("upgrade_feature_workflows") },
{ text: t("upgrade_feature_insights") },
{ text: t("upgrade_feature_remove_branding") },
];
const orgFeatures: PlanFeature[] = [
{ text: t("upgrade_feature_everything_in_team") },
{ text: t("unlimited_teams") },
{ text: t("upgrade_feature_verified_domain") },
{ text: t("upgrade_feature_directory_sync") },
{ text: t("upgrade_feature_sso") },
{ text: t("upgrade_feature_admin_panel") },
];
const enterpriseFeatures: PlanFeature[] = [
{ text: t("upgrade_feature_everything_in_org") },
{ text: t("upgrade_feature_dedicated_support") },
{ text: t("upgrade_feature_custom_sla") },
{ text: t("upgrade_feature_custom_integrations") },
{ text: t("upgrade_feature_compliance") },
];
return (
<Dialog>
<DialogTrigger render={children as React.ReactElement} />
<DialogPopup className="max-w-3xl" showCloseButton={false} bottomStickOnMobile={false}>
<DialogHeader>
<div className="flex flex-wrap items-center justify-between gap-2">
<DialogTitle>{t("upgrade_dialog_title")}</DialogTitle>
<div className="flex items-center gap-1 max-sm:order-last">
<ToggleGroup
value={[billingPeriod]}
onValueChange={(value): void => {
if (value.length > 0) {
const newPeriod = value[0] as BillingPeriodToggle;
setBillingPeriod(newPeriod);
posthog.capture("upgrade_plan_dialog_billing_period_changed", {
source: tracking,
target,
billingPeriod: newPeriod,
});
}
}}
className="rounded-lg bg-muted p-1"
size="sm">
<Toggle
value="annual"
className="gap-1 rounded-md data-pressed:bg-default data-pressed:shadow-sm">
{t("upgrade_billing_annual")}
<Badge variant="info" size="sm">
{t("discount_25")}
</Badge>
</Toggle>
<Toggle
value="monthly"
className="ml-1 rounded-md data-pressed:bg-default data-pressed:shadow-sm">
{t("monthly")}
</Toggle>
</ToggleGroup>
<DialogClose render={<Button size="icon" variant="ghost" />}>
<Icon name="x" />
</DialogClose>
</div>
{info && (
<Alert variant="info" className="w-full">
<AlertTitle>{info.title}</AlertTitle>
<AlertDescription>{info.description}</AlertDescription>
</Alert>
)}
</div>
</DialogHeader>
<DialogPanel>
<div className="mt-3 overflow-x-auto">
<div className="flex gap-2 sm:gap-4 max-sm:grid max-sm:grid-flow-col max-sm:auto-cols-fr max-sm:w-max">
{target === "team" && (
<PlanColumn
name={t("team")}
badge={t("upgrade_badge_free_trial")}
price={teamPrice}
priceSubtext={t("upgrade_price_per_month_user")}
description={t("upgrade_plan_team_tagline")}
features={teamFeatures}
buttonText={t("upgrade_cta_teams")}
buttonHref={teamHref}
primaryButton={target === "team"}
onCtaClick={() =>
posthog.capture("upgrade_plan_dialog_cta_clicked", {
source: tracking,
plan: "team",
target,
billingPeriod,
})
}
/>
)}
<PlanColumn
name={t("organization")}
badge={t("upgrade_badge_free_trial")}
price={orgPrice}
priceSubtext={t("upgrade_price_per_month_user")}
description={t("upgrade_plan_org_tagline")}
features={orgFeatures}
buttonText={t("upgrade_cta_orgs")}
buttonHref={organizationHref}
primaryButton={target === "organization"}
onCtaClick={() =>
posthog.capture("upgrade_plan_dialog_cta_clicked", {
source: tracking,
plan: "organization",
target,
billingPeriod,
})
}
/>
<PlanColumn
name={t("enterprise")}
price={t("custom")}
priceSubtext=""
description={t("upgrade_plan_enterprise_tagline")}
features={enterpriseFeatures}
buttonText={t("upgrade_cta_enterprise")}
buttonHref="https://cal.com/sales"
buttonTarget="_blank"
onCtaClick={() =>
posthog.capture("upgrade_plan_dialog_cta_clicked", {
source: tracking,
plan: "enterprise",
target,
billingPeriod,
})
}
/>
</div>
</div>
<Card className="bg-muted mt-4 py-3 px-4 flex-row justify-between items-center">
{target === "team" && (
<div>
<p className="font-medium text-sm text-emphasis">{t("individual")}</p>
<p className="font-cal mt-1 font-semibold text-emphasis text-2xl leading-none">{t("free")}</p>
</div>
)}
{target === "organization" && (
<div>
<p className="font-medium text-sm text-emphasis">{t("team")}</p>
<p className="mt-1">
<span className="font-cal font-semibold text-emphasis text-2xl leading-none">
{currentTeamPrice}
</span>
<span className="ml-1 leading-none font-medium text-sm text-subtle">
{t("upgrade_price_per_month_user")}
</span>
</p>
</div>
)}
<Badge variant="outline" size="lg" className="rounded-lg py-1.5 px-2.5 h-fit!">
<span className="text-emphasis opacity-50 leading-none">{t("upgrade_badge_current_plan")}</span>
</Badge>
</Card>
</DialogPanel>
</DialogPopup>
</Dialog>
);
}
@@ -1,18 +0,0 @@
"use client";
import { UpgradeTeamsBadge as UpgradeTeamsBadgeBase } from "@calcom/ui/components/badge";
import { useHasPaidPlan, useHasActiveTeamPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
export function UpgradeTeamsBadgeWebWrapper({ checkForActiveStatus }: { checkForActiveStatus?: boolean }) {
const { hasPaidPlan } = useHasPaidPlan();
const { hasActiveTeamPlan, isTrial } = useHasActiveTeamPlan();
return (
<UpgradeTeamsBadgeBase
checkForActiveStatus={checkForActiveStatus}
hasPaidPlan={hasPaidPlan}
hasActiveTeamPlan={hasActiveTeamPlan}
isTrial={isTrial}
/>
);
}
@@ -1,149 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import { Icon } from "@calcom/ui/components/icon";
import { OrgBadge, TeamBadge } from "@calcom/web/modules/billing/components/PlanBadge";
import { Button } from "@coss/ui/components/button";
import Image from "next/image";
import Link from "next/link";
import posthog from "posthog-js";
import { useClientOnly } from "@calcom/lib/hooks/useClientOnly";
import { useState } from "react";
import type { UpgradeTarget } from "./types";
const STORAGE_KEY = "dismissed-large-upgrade-banners";
function isDismissed(tracking: string): boolean {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return false;
try {
const dismissed = JSON.parse(raw) as Record<string, boolean>;
return dismissed[tracking] === true;
} catch {
return false;
}
}
function dismiss(tracking: string): void {
const raw = localStorage.getItem(STORAGE_KEY);
let dismissed: Record<string, boolean> = {};
if (raw) {
try {
dismissed = JSON.parse(raw) as Record<string, boolean>;
} catch {
// corrupted data, start fresh
}
}
dismissed[tracking] = true;
localStorage.setItem(STORAGE_KEY, JSON.stringify(dismissed));
}
export type WideUpgradeBannerProps = {
tracking: string;
title: string;
subtitle: string;
target: UpgradeTarget;
size?: "md" | "sm";
image: {
src: string;
width: number;
height: number;
};
learnMoreButton?: {
text: string;
href?: string;
onClick?: () => void;
};
children: React.ReactNode;
};
export function WideUpgradeBanner({
tracking,
title,
subtitle,
target,
size = "md",
image,
learnMoreButton,
children,
}: WideUpgradeBannerProps) {
const { t } = useLocale();
const [visible, setVisible] = useState(false);
useClientOnly(() => {
setVisible(!isDismissed(tracking));
});
if (!visible) return null;
return (
<div className="relative flex w-full overflow-hidden rounded-xl bg-muted border-muted border">
<Button
variant="ghost"
className="absolute right-2 top-2 z-10"
onClick={() => {
dismiss(tracking);
setVisible(false);
posthog.capture("large_upgrade_banner_dismissed", { source: tracking, target });
}}>
{/* This button goes on top of the image, so it's better to force this color */}
<Icon name="x" className="h-4 w-4 text-gray-700" />
</Button>
{/* Left Content */}
<div className="flex flex-1 flex-col p-6">
{size === "sm" ? (
<div className="flex items-start gap-1.5">
<h2 className="font-cal text-base font-semibold leading-none text-default">{title}</h2>
<div className="relative -top-1">
{target === "team" ? <TeamBadge /> : <OrgBadge />}
</div>
</div>
) : (
<div>
{target === "team" ? <TeamBadge /> : <OrgBadge />}
<h2 className="mt-1 font-cal text-lg font-semibold leading-none text-default">{title}</h2>
</div>
)}
<p className="mt-2 text-sm font-normal text-subtle">{subtitle}</p>
{/* Buttons */}
<div className={`${size === "sm" ? "mt-4" : "mt-9"} flex items-center gap-2`}>
{children}
{learnMoreButton &&
(learnMoreButton.href ? (
<Button
variant="ghost"
className="text-subtle"
onClick={() =>
posthog.capture("large_upgrade_banner_learn_more_clicked", { source: tracking, target })
}
render={<Link href={learnMoreButton.href} target="_blank" rel="noopener noreferrer" />}>
{learnMoreButton.text}
</Button>
) : (
<Button
variant="ghost"
className="text-subtle"
onClick={() => {
posthog.capture("large_upgrade_banner_learn_more_clicked", { source: tracking, target });
learnMoreButton.onClick?.();
}}>
{learnMoreButton.text}
</Button>
))}
</div>
</div>
{/* Right Content - Image */}
<div
className={`relative hidden w-1/2 overflow-hidden md:block${size === "sm" ? " max-w-64" : " max-w-[520px]"}`}>
<Image
src={image.src}
alt={title}
fill
className="object-cover object-left"
/>
</div>
</div>
);
}
@@ -1 +0,0 @@
export type UpgradeTarget = "team" | "organization";
@@ -1,62 +0,0 @@
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { trpc } from "@calcom/trpc/react";
export function useHasPaidPlan() {
if (IS_SELF_HOSTED) return { isPending: false, hasPaidPlan: true };
const { data, isPending: isPendingTeamQuery } = trpc.viewer.teams.hasTeamPlan.useQuery();
const { data: user, isPending: isPendingUserQuery } = trpc.viewer.me.get.useQuery();
const isPending = isPendingTeamQuery || isPendingUserQuery;
const isCurrentUsernamePremium =
user && hasKeyInMetadata(user, "isPremium") ? !!user.metadata.isPremium : false;
const hasPaidPlan = data?.hasTeamPlan || isCurrentUsernamePremium;
return { isPending, hasPaidPlan, plan: data?.plan };
}
export function useTeamInvites() {
const listInvites = trpc.viewer.teams.listInvites.useQuery();
return { isPending: listInvites.isPending, listInvites: listInvites.data };
}
export function useHasTeamMembership() {
const { data, isPending } = trpc.viewer.teams.hasTeamMembership.useQuery();
return { isPending, hasTeamMembership: data?.hasTeamMembership ?? false };
}
export function useHasTeamPlan() {
const { data: hasTeamPlan, isPending } = trpc.viewer.teams.hasTeamPlan.useQuery();
return { isPending, hasTeamPlan: hasTeamPlan?.hasTeamPlan };
}
export function useHasEnterprisePlan() {
// TODO: figure out how to get "has Enterprise / has Org" from the backend
const { data: hasTeamPlan, isPending } = trpc.viewer.teams.hasTeamPlan.useQuery();
return { isPending, hasTeamPlan: hasTeamPlan?.hasTeamPlan };
}
export function useHasActiveTeamPlan() {
if (IS_SELF_HOSTED) return { isPending: false, hasActiveTeamPlan: true, isTrial: false };
const { data, isPending } = trpc.viewer.teams.hasActiveTeamPlan.useQuery();
return { isPending, hasActiveTeamPlan: !!data?.isActive, isTrial: !!data?.isTrial };
}
export function useHasActiveTeamPlanAsOwner() {
if (IS_SELF_HOSTED) return { isPending: false, hasActiveTeamPlan: true, isTrial: false };
const { data, isPending } = trpc.viewer.teams.hasActiveTeamPlan.useQuery({ ownerOnly: true });
return { isPending, hasActiveTeamPlan: !!data?.isActive, isTrial: !!data?.isTrial };
}
export default useHasPaidPlan;
@@ -1,34 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { FullScreenUpgradeBanner } from "@calcom/web/modules/billing/components/FullScreenUpgradeBanner";
export function FullscreenUpgradeBannerForInsightsPage() {
const { t } = useLocale();
const features = [
t("upgrade_banner_insights_feature1"),
t("upgrade_banner_insights_feature2"),
t("upgrade_banner_insights_feature3"),
];
return (
<FullScreenUpgradeBanner
tracking="fullscreen-upgrade-banner-for-insights-page"
name={t("upgrade_banner_insights_name")}
title={t("upgrade_banner_insights_title")}
subtitle={t("upgrade_banner_insights_subtitle")}
features={features}
target="team"
image={{
src: "/upgrade/full_insights.png",
width: 572,
height: 744,
}}
learnMoreButton={{
text: t("learn_more"),
href: "https://cal.com/blog/insight-2-0-calcom-scheduling",
}}
/>
);
}
@@ -1,29 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { FullScreenUpgradeBanner } from "@calcom/web/modules/billing/components/FullScreenUpgradeBanner";
export function FullscreenUpgradeBannerForRolesAndPermissions() {
const { t } = useLocale();
return (
<FullScreenUpgradeBanner
tracking="fullscreen-upgrade-banner-for-roles-and-permissions"
name={t("upgrade_banner_roles_name")}
title={t("upgrade_banner_roles_title")}
subtitle={t("upgrade_banner_roles_subtitle")}
target="organization"
extraOffset={20}
image={{
src: "/upgrade/full_roles.png",
width: 572,
height: 744,
}}
youtubeId="J8HsK-8W39U"
learnMoreButton={{
text: t("learn_more"),
href: "https://cal.com/blog/role-based-access-control",
}}
/>
);
}
@@ -1,28 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { FullScreenUpgradeBanner } from "@calcom/web/modules/billing/components/FullScreenUpgradeBanner";
export function FullscreenUpgradeBannerForRoutingFormPage() {
const { t } = useLocale();
return (
<FullScreenUpgradeBanner
tracking="fullscreen-upgrade-banner-for-routing-form-page"
name={t("upgrade_banner_routing_form_name")}
title={t("upgrade_banner_routing_form_title")}
subtitle={t("upgrade_banner_routing_form_subtitle")}
target="team"
image={{
src: "/upgrade/full_insights_routing.png",
width: 572,
height: 744,
}}
youtubeId="omM89sE7Jpg"
learnMoreButton={{
text: t("learn_more"),
href: "https://cal.com/routing",
}}
/>
);
}
@@ -1,36 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { FullScreenUpgradeBanner } from "@calcom/web/modules/billing/components/FullScreenUpgradeBanner";
export function FullscreenUpgradeBannerForTeamsPage() {
const { t } = useLocale();
const features = [
t("upgrade_banner_teams_feature1"),
t("upgrade_banner_teams_feature2"),
t("upgrade_banner_teams_feature3"),
t("upgrade_banner_teams_feature4"),
];
return (
<FullScreenUpgradeBanner
tracking="fullscreen-upgrade-banner-for-teams-page"
name={t("upgrade_banner_teams_name")}
title={t("upgrade_banner_teams_title")}
subtitle={t("upgrade_banner_teams_subtitle")}
features={features}
target="team"
image={{
src: "/upgrade/full_teams.png",
width: 572,
height: 744,
}}
youtubeId="hp-l5oRVD-U"
learnMoreButton={{
text: t("learn_more"),
href: "https://cal.com/teams",
}}
/>
);
}
@@ -1,35 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
import { UpgradePlanDialog } from "@calcom/web/modules/billing/components/UpgradePlanDialog";
import { WideUpgradeBanner } from "@calcom/web/modules/billing/components/WideUpgradeBanner";
import { Button } from "@coss/ui/components/button";
export function WideUpgradeBannerForMembers() {
const { t } = useLocale();
return (
<WideUpgradeBanner
tracking="large-upgrade-banner-for-members"
title={t("upgrade_banner_team_attributes_title")}
subtitle={t("upgrade_banner_team_attributes_subtitle")}
target="organization"
image={{
src: "/upgrade/large_members.png",
width: 1010,
height: 340,
}}
learnMoreButton={{
text: t("learn_more"),
href: "https://cal.com/help/routing/routing-with-attributes",
}}>
<UpgradePlanDialog tracking="members" target="organization">
<Button variant="outline">
{t("try_for_free")}
<Icon name="arrow-right" />
</Button>
</UpgradePlanDialog>
</WideUpgradeBanner>
);
}
@@ -1,28 +1,26 @@
// We do not need to worry about importing framer-motion here as it is lazy imported in Booker.
import * as HoverCard from "@radix-ui/react-hover-card";
import { AnimatePresence, m } from "framer-motion";
import { useMemo } from "react";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import dayjs from "@calcom/dayjs";
import type { IOutOfOfficeData } from "@calcom/features/availability/lib/getUserAvailability";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { OutOfOfficeInSlots } from "./OutOfOfficeInSlots";
import type { IUseBookingLoadingStates } from "../hooks/useBookings";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { Slot } from "~/schedules/lib/types";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useCheckOverlapWithOverlay } from "@calcom/features/bookings/lib/useCheckOverlapWithOverlay";
import type { BookerEvent, Slots } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { CalendarX2Icon } from "@coss/ui/icons";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useCheckOverlapWithOverlay } from "@calcom/features/bookings/lib/useCheckOverlapWithOverlay";
import type { Slots } from "@calcom/features/bookings/types";
import * as HoverCard from "@radix-ui/react-hover-card";
import { AnimatePresence, m } from "framer-motion";
import { useMemo } from "react";
import type { Slot } from "~/schedules/lib/types";
import type { IUseBookingLoadingStates } from "../hooks/useBookings";
import { OutOfOfficeInSlots } from "./OutOfOfficeInSlots";
import { SeatsAvailabilityText } from "./SeatsAvailabilityText";
type TOnTimeSelect = (
@@ -160,7 +158,6 @@ const SlotItem = ({
loadingStates?.creatingBooking ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking ||
(skipConfirmStep && !!shouldRenderCaptcha && !watchedCfToken) ||
isTimeslotUnavailable
}
@@ -220,15 +217,13 @@ const SlotItem = ({
loadingStates?.creatingBooking ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking ||
confirmButtonDisabled
}
color="primary"
loading={
(selectedTimeslot === slot.time && loadingStates?.creatingBooking) ||
loadingStates?.creatingRecurringBooking ||
isVerificationCodeSending ||
loadingStates?.creatingInstantBooking
isVerificationCodeSending
}>
{(() => {
if (layout === "column_view") return "";
@@ -1,11 +1,9 @@
import type { TFunction } from "i18next";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { FieldError } from "react-hook-form";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useIsPlatformBookerEmbed } from "@calcom/atoms/hooks/useIsPlatformBookerEmbed";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { formatEventFromTime } from "@calcom/features/bookings/Booker/utils/dates";
import type { BookerEvent } from "@calcom/features/bookings/types";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { APP_NAME, WEBSITE_PRIVACY_POLICY_URL, WEBSITE_TERMS_URL } from "@calcom/lib/constants";
@@ -16,10 +14,10 @@ import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { Form } from "@calcom/ui/components/form";
import { formatEventFromTime } from "@calcom/features/bookings/Booker/utils/dates";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import type { TFunction } from "i18next";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { FieldError } from "react-hook-form";
import type { IUseBookingErrors, IUseBookingLoadingStates } from "../../hooks/useBookings";
import { BookingFields } from "./BookingFields";
import { FormSkeleton } from "./Skeleton";
@@ -30,7 +28,6 @@ type BookEventFormProps = {
errorRef: React.RefObject<HTMLDivElement>;
errors: UseBookingFormReturnType["errors"] & IUseBookingErrors;
loadingStates: IUseBookingLoadingStates;
children?: React.ReactNode;
bookingForm: UseBookingFormReturnType["bookingForm"];
renderConfirmNotVerifyEmailButtonCond: boolean;
extraOptions: Record<string, string | string[]>;
@@ -55,7 +52,6 @@ export const BookEventForm = ({
loadingStates,
renderConfirmNotVerifyEmailButtonCond,
bookingForm,
children,
extraOptions,
isVerificationCodeSending,
isPlatform = false,
@@ -76,7 +72,6 @@ export const BookEventForm = ({
const bookingData = useBookerStoreContext((state) => state.bookingData);
const rescheduleUid = useBookerStoreContext((state) => state.rescheduleUid);
const username = useBookerStoreContext((state) => state.username);
const isInstantMeeting = useBookerStoreContext((state) => state.isInstantMeeting);
const isPlatformBookerEmbed = useIsPlatformBookerEmbed();
const { timeFormat, timezone } = useBookerTime();
@@ -227,51 +222,40 @@ export const BookEventForm = ({
</div>
)}
<div className="flex justify-end mt-auto space-x-2 modalsticky rtl:space-x-reverse">
{isInstantMeeting ? (
<Button type="submit" color="primary" loading={loadingStates.creatingInstantBooking}>
{isPaidEvent ? t("pay_and_book") : t("confirm")}
{!!onCancel && (
<Button
color="minimal"
type="button"
onClick={onCancel}
data-testid="back"
className={classNames?.backButton}>
{t("back")}
</Button>
) : (
<>
{!!onCancel && (
<Button
color="minimal"
type="button"
onClick={onCancel}
data-testid="back"
className={classNames?.backButton}>
{t("back")}
</Button>
)}
<Button
type="submit"
color="primary"
disabled={
(!!shouldRenderCaptcha && !watchedCfToken) || isTimeslotUnavailable || confirmButtonDisabled
}
loading={
loadingStates.creatingBooking ||
loadingStates.creatingRecurringBooking ||
isVerificationCodeSending
}
className={classNames?.confirmButton}
data-testid={
rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"
}>
{rescheduleUid && bookingData
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? isPaidEvent
? t("pay_and_book")
: t("confirm")
: t("verify_email_button")}
</Button>
</>
)}
<Button
type="submit"
color="primary"
disabled={
(!!shouldRenderCaptcha && !watchedCfToken) || isTimeslotUnavailable || confirmButtonDisabled
}
loading={
loadingStates.creatingBooking ||
loadingStates.creatingRecurringBooking ||
isVerificationCodeSending
}
className={classNames?.confirmButton}
data-testid={rescheduleUid && bookingData ? "confirm-reschedule-button" : "confirm-book-button"}>
{rescheduleUid && bookingData
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? isPaidEvent
? t("pay_and_book")
: t("confirm")
: t("verify_email_button")}
</Button>
</div>
</Form>
{children}
</div>
);
};
@@ -1,20 +1,17 @@
import { useMemo, useRef } from "react";
import { useFormContext } from "react-hook-form";
import { z } from "zod";
import type { LocationObject } from "@calcom/app-store/locations";
import { getOrganizerInputLocationTypes } from "@calcom/app-store/locations";
import { DefaultEventLocationTypeEnum } from "@calcom/app-store/locations";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { DefaultEventLocationTypeEnum, getOrganizerInputLocationTypes } from "@calcom/app-store/locations";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import getLocationOptionsForSelect from "@calcom/features/bookings/lib/getLocationOptionsForSelect";
import { FormBuilderField } from "@calcom/web/modules/form-builder/components/FormBuilderField";
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
import { SystemField } from "@calcom/lib/bookings/SystemField";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { RouterOutputs } from "@calcom/trpc/react";
import { FormBuilderField } from "@calcom/web/modules/form-builder/components/FormBuilderField";
import { useMemo, useRef } from "react";
import { useFormContext } from "react-hook-form";
import { z } from "zod";
type TouchedFields = {
responses?: Record<string, boolean>;
@@ -46,8 +43,6 @@ export const BookingFields = ({
const { watch, setValue, formState } = useFormContext();
const locationResponse = watch("responses.location");
const currentView = rescheduleUid ? "reschedule" : "";
const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
// Identify all phone fields (except location field)
const otherPhoneFieldNames = useMemo(
() => fields.filter((f) => f.type === "phone" && f.name !== SystemField.Enum.location).map((f) => f.name),
@@ -130,9 +125,6 @@ export const BookingFields = ({
// The logic here intends to make modifications to booking fields based on the way we want to specifically show Booking Form
<div>
{fields.map((field, index) => {
// Don't Display Location field in case of instant meeting as only Cal Video is supported
if (isInstantMeeting && field.name === "location") return null;
// During reschedule by default all system fields are readOnly. Make them editable on case by case basis.
// Allowing a system field to be edited might require sending emails to attendees, so we need to be careful
const rescheduleReadOnly =
@@ -134,8 +134,6 @@ const defaultProps = {
handleBookEvent: vi.fn(),
errors: {},
loadingStates: {},
expiryTime: 0,
instantVideoMeetingUrl: "",
},
verifyEmail: {
isEmailVerificationModalVisible: false,
@@ -166,13 +164,10 @@ const defaultProps = {
isPlatform: false,
orgBannerUrl: null,
customClassNames: {},
areInstantMeetingParametersSet: false,
userLocale: "en",
hasValidLicense: true,
isBookingDryRun: false,
renderCaptcha: false,
onConnectNowInstantMeeting: vi.fn(),
onGoBackInstantMeeting: vi.fn(),
onOverlayClickNoCalendar: vi.fn(),
onClickOverlayContinue: vi.fn(),
onOverlaySwitchStateChange: vi.fn(),
@@ -180,7 +175,6 @@ const defaultProps = {
sessionUsername: null,
rescheduleUid: null,
hasSession: false,
isInstantMeeting: false,
};
describe("Booker", () => {
@@ -188,7 +182,7 @@ describe("Booker", () => {
constantsScenarios.set({
PUBLIC_QUICK_AVAILABILITY_ROLLOUT: "100",
POWERED_BY_URL: "https://go.cal.com/booking",
APP_NAME: "Cal.com",
APP_NAME: "Cal.diy",
});
vi.clearAllMocks();
});
+51 -109
View File
@@ -4,10 +4,7 @@ import { useIsPlatformBookerEmbed } from "@calcom/atoms/hooks/useIsPlatformBooke
import dayjs from "@calcom/dayjs";
import { useEmbedUiConfig } from "@calcom/embed-core/embed-iframe";
import { updateEmbedBookerState } from "@calcom/embed-core/src/embed-iframe";
import TurnstileCaptcha from "@calcom/web/modules/auth/components/Turnstile";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useIsQuickAvailabilityCheckFeatureEnabled } from "../hooks/useIsQuickAvailabilityCheckFeatureEnabled";
import { useSkipConfirmStep } from "@calcom/web/modules/bookings/hooks/useSkipConfirmStep";
import {
fadeInLeft,
getBookerSizeClassNames,
@@ -15,12 +12,12 @@ import {
} from "@calcom/features/bookings/Booker/config";
import framerFeatures from "@calcom/features/bookings/Booker/framer-features";
import type { BookerProps } from "@calcom/features/bookings/Booker/types";
import type { WrappedBookerProps } from "../types";
import { isBookingDryRun } from "@calcom/features/bookings/Booker/utils/isBookingDryRun";
import { isTimeSlotAvailable } from "@calcom/features/bookings/Booker/utils/isTimeslotAvailable";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { Header } from "@calcom/features/bookings/components/Header";
import { BookerSection } from "@calcom/features/bookings/components/Section";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useNonEmptyScheduleDays } from "@calcom/web/modules/schedules/hooks/useNonEmptyScheduleDays";
import { scrollIntoViewSmooth } from "@calcom/lib/browser/browser.utils";
import {
CLOUDFLARE_SITE_ID,
@@ -32,12 +29,16 @@ import { BookerLayouts } from "@calcom/prisma/zod-utils";
import classNames from "@calcom/ui/classNames";
import { DialogContent } from "@calcom/ui/components/dialog";
import { UnpublishedEntity } from "@calcom/ui/components/unpublished-entity";
import PoweredBy from "@calcom/web/modules/ee/common/components/PoweredBy";
import TurnstileCaptcha from "@calcom/web/modules/auth/components/Turnstile";
import { useSkipConfirmStep } from "@calcom/web/modules/bookings/hooks/useSkipConfirmStep";
import { useNonEmptyScheduleDays } from "@calcom/web/modules/schedules/hooks/useNonEmptyScheduleDays";
import { AnimatePresence, LazyMotion, m } from "framer-motion";
import { useEffect, useMemo, useRef } from "react";
import StickyBox from "react-sticky-box";
import { Toaster } from "sonner";
import { shallow } from "zustand/shallow";
import { useIsQuickAvailabilityCheckFeatureEnabled } from "../hooks/useIsQuickAvailabilityCheckFeatureEnabled";
import type { WrappedBookerProps } from "../types";
import { AvailableTimeSlots } from "./AvailableTimeSlots";
import { BookEventForm } from "./BookEventForm";
import { BookFormAsModal } from "./BookEventForm/BookFormAsModal";
@@ -45,12 +46,8 @@ import { DatePicker } from "./DatePicker";
import { DryRunMessage } from "./DryRunMessage";
import { EventMeta } from "./EventMeta";
import { HavingTroubleFindingTime } from "./HavingTroubleFindingTime";
import { Header } from "@calcom/features/bookings/components/Header";
import { InstantBooking } from "./InstantBooking";
import { LargeCalendar } from "./LargeCalendar";
import { OverlayCalendar } from "./OverlayCalendar/OverlayCalendar";
import { RedirectToInstantMeetingModal } from "./RedirectToInstantMeetingModal";
import { BookerSection } from "@calcom/features/bookings/components/Section";
import { SlotSelectionModalHeader } from "./SlotSelectionModalHeader";
import { NotFound } from "./Unavailable";
import { VerifyCodeDialog } from "./VerifyCodeDialog";
@@ -60,9 +57,6 @@ const BookerComponent = ({
eventSlug,
hideBranding = false,
entity,
isInstantMeeting = false,
onGoBackInstantMeeting,
onConnectNowInstantMeeting,
onOverlayClickNoCalendar,
onClickOverlayContinue,
onOverlaySwitchStateChange,
@@ -82,7 +76,6 @@ const BookerComponent = ({
isPlatform,
orgBannerUrl,
customClassNames,
areInstantMeetingParametersSet = false,
userLocale,
hasValidLicense,
isBookingDryRun: isBookingDryRunProp,
@@ -162,14 +155,7 @@ const BookerComponent = ({
const { bookerFormErrorRef, key, formEmail, bookingForm, errors: formErrors } = bookerForm;
const {
handleBookEvent,
errors,
loadingStates,
expiryTime,
instantVideoMeetingUrl,
instantConnectCooldownMs,
} = bookings;
const { handleBookEvent, errors, loadingStates } = bookings;
const watchedCfToken = bookingForm.watch("cfToken");
@@ -206,7 +192,6 @@ const BookerComponent = ({
const skipConfirmStep = useSkipConfirmStep(
bookingForm,
bookerState,
isInstantMeeting,
layout == BookerLayouts.WEEK_VIEW,
event?.data?.bookingFields,
event?.data?.locations
@@ -237,19 +222,11 @@ const BookerComponent = ({
if (event.isPending) return setBookerState("loading");
if (!selectedDate) return setBookerState("selecting_date");
if (!selectedTimeslot) return setBookerState("selecting_time");
const isSkipConfirmStepSupported = !isInstantMeeting && layout !== BookerLayouts.WEEK_VIEW;
const isSkipConfirmStepSupported = layout !== BookerLayouts.WEEK_VIEW;
if (selectedTimeslot && skipConfirmStep && isSkipConfirmStepSupported)
return setBookerState("selecting_time");
return setBookerState("booking");
}, [
event.isPending,
selectedDate,
selectedTimeslot,
setBookerState,
skipConfirmStep,
layout,
isInstantMeeting,
]);
}, [event.isPending, selectedDate, selectedTimeslot, setBookerState, skipConfirmStep, layout]);
const unavailableTimeSlots = isQuickAvailabilityCheckFeatureEnabled
? allSelectedTimeslots.filter((slot) => {
@@ -298,7 +275,7 @@ const BookerComponent = ({
onSubmit={() => (renderConfirmNotVerifyEmailButtonCond ? handleBookEvent() : handleVerifyEmail())}
errorRef={bookerFormErrorRef}
errors={{ ...formErrors, ...errors }}
isTimeslotUnavailable={!isInstantMeeting && unavailableTimeSlots.includes(selectedTimeslot || "")}
isTimeslotUnavailable={unavailableTimeSlots.includes(selectedTimeslot || "")}
loadingStates={loadingStates}
renderConfirmNotVerifyEmailButtonCond={renderConfirmNotVerifyEmailButtonCond}
bookingForm={bookingForm}
@@ -310,35 +287,21 @@ const BookerComponent = ({
confirmButton: customClassNames?.confirmStep?.confirmButton,
backButton: customClassNames?.confirmStep?.backButton,
}}
isPlatform={isPlatform}>
{!isPlatform && (
<RedirectToInstantMeetingModal
expiryTime={expiryTime}
bookingId={parseInt(getQueryParam("bookingId") || "0")}
instantVideoMeetingUrl={instantVideoMeetingUrl}
onGoBack={() => {
onGoBackInstantMeeting();
}}
orgName={event.data?.entity?.name}
/>
)}
</BookEventForm>
isPlatform={isPlatform}
/>
);
}, [
bookerFormErrorRef,
instantVideoMeetingUrl,
bookerState,
bookingForm,
errors,
event,
expiryTime,
extraOptions,
formErrors,
handleBookEvent,
handleVerifyEmail,
key,
loadingStates,
onGoBackInstantMeeting,
renderConfirmNotVerifyEmailButtonCond,
seatedEventData,
setSeatedEventData,
@@ -395,45 +358,43 @@ const BookerComponent = ({
`${customClassNames?.bookerContainer}`
)}>
<AnimatePresence>
{!isInstantMeeting && (
<BookerSection
area="header"
className={classNames(
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
"bg-default dark:bg-cal-muted sticky top-0 z-10"
)}>
{isPlatform && layout === BookerLayouts.MONTH_VIEW ? (
<></>
) : (
<Header
isMyLink={Boolean(username === sessionUsername)}
eventSlug={eventSlug}
enabledLayouts={bookerLayouts.enabledLayouts}
extraDays={layout === BookerLayouts.COLUMN_VIEW ? columnViewExtraDays.current : extraDays}
isMobile={isMobile}
nextSlots={nextSlots}
renderOverlay={() => {
if (isEmbed) return null;
return (
<OverlayCalendar
isOverlayCalendarEnabled={isOverlayCalendarEnabled}
connectedCalendars={connectedCalendars}
overlayBusyDates={overlayBusyDates}
onToggleCalendar={onToggleCalendar}
hasSession={hasSession}
handleClickContinue={onClickOverlayContinue}
handleSwitchStateChange={onOverlaySwitchStateChange}
handleClickNoCalendar={() => {
onOverlayClickNoCalendar();
}}
/>
);
}}
/>
)}
</BookerSection>
)}
<BookerSection
area="header"
className={classNames(
layout === BookerLayouts.MONTH_VIEW && "fixed top-4 z-10 ltr:right-4 rtl:left-4",
(layout === BookerLayouts.COLUMN_VIEW || layout === BookerLayouts.WEEK_VIEW) &&
"bg-default dark:bg-cal-muted sticky top-0 z-10"
)}>
{isPlatform && layout === BookerLayouts.MONTH_VIEW ? (
<></>
) : (
<Header
isMyLink={Boolean(username === sessionUsername)}
eventSlug={eventSlug}
enabledLayouts={bookerLayouts.enabledLayouts}
extraDays={layout === BookerLayouts.COLUMN_VIEW ? columnViewExtraDays.current : extraDays}
isMobile={isMobile}
nextSlots={nextSlots}
renderOverlay={() => {
if (isEmbed) return null;
return (
<OverlayCalendar
isOverlayCalendarEnabled={isOverlayCalendarEnabled}
connectedCalendars={connectedCalendars}
overlayBusyDates={overlayBusyDates}
onToggleCalendar={onToggleCalendar}
hasSession={hasSession}
handleClickContinue={onClickOverlayContinue}
handleSwitchStateChange={onOverlaySwitchStateChange}
handleClickNoCalendar={() => {
onOverlayClickNoCalendar();
}}
/>
);
}}
/>
)}
</BookerSection>
<StickyOnDesktop key="meta" className={classNames("relative z-10 flex [grid-area:meta]")}>
<BookerSection
area="meta"
@@ -580,25 +541,6 @@ const BookerComponent = ({
}}
/>
{bookerState !== "booking" &&
event.data?.showInstantEventConnectNowModal &&
areInstantMeetingParametersSet && (
<div
className={classNames(
"animate-fade-in-up z-40 my-2 opacity-0",
layout === BookerLayouts.MONTH_VIEW && isEmbed ? "" : "fixed bottom-2"
)}
style={{ animationDelay: "1s" }}>
<InstantBooking
event={event.data}
cooldownMs={instantConnectCooldownMs}
onConnectNow={() => {
onConnectNowInstantMeeting();
}}
/>
</div>
)}
{shouldRenderCaptcha && (
<div className="mb-6 mt-auto pt-6">
<TurnstileCaptcha
@@ -618,7 +560,7 @@ const BookerComponent = ({
hasDarkBackground ? "dark" : "",
layout === BookerLayouts.MONTH_VIEW ? "block" : "hidden"
)}>
<PoweredBy logoOnly hasValidLicense={hasValidLicense} />
{null}
</m.span>
)}
</div>
@@ -10,22 +10,22 @@ import {
} from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import { useBookingForm } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useInitializeBookerStore } from "@calcom/features/bookings/Booker/store";
import { useBrandColors } from "@calcom/features/bookings/Booker/utils/use-brand-colors";
import type { getPublicEvent } from "@calcom/features/eventtypes/lib/getPublicEvent";
import { DEFAULT_DARK_BRAND_COLOR, DEFAULT_LIGHT_BRAND_COLOR, WEBAPP_URL } from "@calcom/lib/constants";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { localStorage } from "@calcom/lib/webstorage";
import { useEvent, useScheduleForEvent } from "@calcom/web/modules/schedules/hooks/useEvent";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { useCallback, useEffect, useMemo } from "react";
import { shallow } from "zustand/shallow";
import { useBookings } from "../hooks/useBookings";
import { useCalendars } from "../hooks/useCalendars";
import { useSlots } from "../hooks/useSlots";
import { useVerifyCode } from "../hooks/useVerifyCode";
import { useVerifyEmail } from "../hooks/useVerifyEmail";
import { useInitializeBookerStore } from "@calcom/features/bookings/Booker/store";
import { useEvent, useScheduleForEvent } from "@calcom/web/modules/schedules/hooks/useEvent";
import { useBrandColors } from "@calcom/features/bookings/Booker/utils/use-brand-colors";
import type { getPublicEvent } from "@calcom/features/eventtypes/lib/getPublicEvent";
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR, WEBAPP_URL } from "@calcom/lib/constants";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { localStorage } from "@calcom/lib/webstorage";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { useCallback, useEffect, useMemo } from "react";
import { shallow } from "zustand/shallow";
import { Booker as BookerComponent } from "./Booker";
export type BookerWebWrapperAtomProps = BookerProps & {
@@ -42,11 +42,11 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
});
const event = props.eventData
? {
data: props.eventData,
isSuccess: true,
isError: false,
isPending: false,
}
data: props.eventData,
isSuccess: true,
isError: false,
isPending: false,
}
: clientFetchedEvent;
const bookerLayout = useBookerLayout(event.data?.profile?.bookerLayouts);
@@ -150,9 +150,6 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
useApiV2: props.useApiV2,
bookerLayout,
...(props.entity.orgSlug ? { orgSlug: props.entity.orgSlug } : {}),
restrictionSchedule: event.data?.restrictionScheduleId
? { id: event.data.restrictionScheduleId, useBookerTimezone: event.data.useBookerTimezone }
: undefined,
});
const bookings = useBookings({
event,
@@ -199,14 +196,6 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
theme: event.data?.profile.theme,
});
const areInstantMeetingParametersSet = Boolean(
event.data?.instantMeetingParameters &&
searchParams &&
event.data.instantMeetingParameters?.every?.((param) =>
Array.from(searchParams.values()).includes(param)
)
);
useEffect(() => {
if (hasSession) onOverlaySwitchStateChange(true);
}, [hasSession]);
@@ -214,19 +203,6 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
return (
<BookerComponent
{...props}
onGoBackInstantMeeting={() => {
if (pathname) window.location.href = pathname;
}}
onConnectNowInstantMeeting={() => {
const newPath = `${pathname}?isInstantMeeting=true`;
if (isEmbed) {
const fullUrl = `${new URL(document.URL).origin}/${newPath}`;
window.open(fullUrl, "_blank", "noopener,noreferrer");
} else {
router.push(newPath);
}
}}
onOverlayClickNoCalendar={() => {
router.push("/apps/categories/calendar");
}}
@@ -256,7 +232,6 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
schedule={schedule}
verifyCode={verifyCode}
isPlatform={false}
areInstantMeetingParametersSet={areInstantMeetingParametersSet}
userLocale={session?.user.locale}
renderCaptcha
/>
@@ -4,7 +4,7 @@ import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
import { Calendar } from "@calcom/features/calendars/weeklyview/components/Calendar";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import { useBanners } from "@calcom/web/modules/shell/banners/useBanners";
import { useEffect, useMemo } from "react";
import { useBookingDetailsSheetStore } from "../store/bookingDetailsSheetStore";
@@ -32,7 +32,6 @@ import {
} from "@calcom/ui/components/sheet";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { ExternalLinkIcon, RepeatIcon } from "@coss/ui/icons";
import { BookingHistory } from "@calcom/web/modules/booking-audit/components/BookingHistory";
import assignmentReasonBadgeTitleMap from "@lib/booking/assignmentReasonBadgeTitleMap";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef } from "react";
@@ -428,9 +427,7 @@ function BookingDetailsSheetInner({
</>
)}
{bookingAuditEnabled && activeSegment === "history" && (
<BookingHistory bookingUid={booking.uid} />
)}
{/* Booking history removed (enterprise) */}
</div>
</SheetBody>
@@ -13,14 +13,13 @@ import { ToggleGroup } from "@calcom/ui/components/form";
import { WipeMyCalActionButton } from "@calcom/web/components/apps/wipemycalother/wipeMyCalActionButton";
import { getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useBookingFilters } from "~/bookings/hooks/useBookingFilters";
import { useBookingListColumns } from "~/bookings/hooks/useBookingListColumns";
import { useBookingListData } from "~/bookings/hooks/useBookingListData";
import { useBookingStatusTab } from "~/bookings/hooks/useBookingStatusTab";
import { useFacetedUniqueValues } from "~/bookings/hooks/useFacetedUniqueValues";
import { useListAutoSelector } from "~/bookings/hooks/useListAutoSelector";
import { useSwitchToCorrectStatusTab } from "~/bookings/hooks/useSwitchToCorrectStatusTab";
import { DataTableFilters, DataTableSegment } from "~/data-table/components";
import {
BookingDetailsSheetStoreProvider,
@@ -232,21 +231,17 @@ function BookingListInner({
}
export function BookingListContainer(props: BookingListContainerProps) {
const { limit, offset, isValidatorPending } = useDataTable();
const { limit, offset, setPageIndex, isValidatorPending } = useDataTable();
const { eventTypeIds, teamIds, userIds, dateRange, attendeeName, attendeeEmail, bookingUid } =
useBookingFilters();
const { resolvedTabStatus, isResolvingTabStatus, preSelectedBooking } = useSwitchToCorrectStatusTab({
defaultStatus: props.status,
});
// Build query input once - shared between query and prefetching
const queryInput = useMemo(
() => ({
limit,
offset,
filters: {
statuses: [resolvedTabStatus],
statuses: [props.status],
eventTypeIds,
teamIds,
userIds,
@@ -262,7 +257,7 @@ export function BookingListContainer(props: BookingListContainerProps) {
[
limit,
offset,
resolvedTabStatus,
props.status,
eventTypeIds,
teamIds,
userIds,
@@ -276,19 +271,10 @@ export function BookingListContainer(props: BookingListContainerProps) {
const query = trpc.viewer.bookings.get.useQuery(queryInput, {
staleTime: 5 * 60 * 1000, // 5 minutes - data is considered fresh
gcTime: 30 * 60 * 1000, // 30 minutes - cache retention time
// We wait for tab status to be resolved before fetching, so that we can fetch the correct bookings as per resolved tab status
enabled: !isValidatorPending && !isResolvingTabStatus, // Wait for validator to be ready before fetching
enabled: !isValidatorPending, // Wait for validator to be ready before fetching
});
const bookings = useMemo(() => {
const queryBookings = query.data?.bookings ?? [];
if (!preSelectedBooking) return queryBookings;
if (queryBookings.some((b) => b.uid === preSelectedBooking.uid)) return queryBookings;
// It ensures that the drawer opens for a booking that isn't even in the bookings list
// Note that, bookings list doesn't use this so, it won't be visible in the list view but drawer will open for it
// We don't want to show this booking in the list view, as it might not match the filters/pagination applied
return [...queryBookings, preSelectedBooking];
}, [query.data?.bookings, preSelectedBooking]);
const bookings = useMemo(() => query.data?.bookings ?? [], [query.data?.bookings]);
// Always call the hook and provide navigation capabilities
// The BookingDetailsSheet is only rendered when bookingsV3Enabled is true (see line 212)
@@ -304,7 +290,6 @@ export function BookingListContainer(props: BookingListContainerProps) {
<BookingDetailsSheetStoreProvider bookings={bookings}>
<BookingListInner
{...props}
status={resolvedTabStatus}
data={query.data}
isPending={query.isPending}
hasError={!!query.error}
@@ -1,69 +0,0 @@
import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { User } from "@calcom/prisma/client";
import { UserAvatarGroupWithOrg } from "@calcom/ui/components/avatar";
import { Button } from "@calcom/ui/components/button";
import { Tooltip } from "@calcom/ui/components/tooltip";
interface IInstantBookingProps {
onConnectNow: () => void;
event: Pick<BookerEvent, "entity" | "schedulingType"> & {
subsetOfUsers: (Pick<User, "name" | "username" | "avatarUrl"> & { bookerUrl: string })[];
};
cooldownMs?: number;
}
export const InstantBooking = ({ onConnectNow, event, cooldownMs = 0 }: IInstantBookingProps) => {
const { t } = useLocale();
const disabled = cooldownMs > 0;
return (
<div className=" bg-default border-subtle mx-2 block items-center gap-3 rounded-xl border p-[6px] text-sm shadow-sm delay-1000 sm:flex">
<div className="flex items-center gap-3 ps-1">
<div className="relative">
<UserAvatarGroupWithOrg
size="sm"
className="border-muted"
organization={{
slug: event.entity.orgSlug,
name: event.entity.name || "",
logoUrl: event.entity.logoUrl ?? null,
}}
users={event.subsetOfUsers.slice(0, 2)}
disableHref
/>
<div className="border-muted absolute -bottom-0.5 -right-1 h-2 w-2 rounded-full border bg-green-500" />
</div>
<div>{t("dont_want_to_wait")}</div>
</div>
<div className="mt-2 flex items-center gap-3 sm:mt-0">
{disabled ? (
<Tooltip content={t("just_connected_description")}>
<span className="inline-flex">
<Button
disabled={disabled}
color="primary"
onClick={() => {
onConnectNow();
}}
size="sm"
className="w-full justify-center rounded-lg sm:w-auto">
{t("connect_now")}
</Button>
</span>
</Tooltip>
) : (
<Button
color="primary"
onClick={() => {
onConnectNow();
}}
size="sm"
className="w-full justify-center rounded-lg sm:w-auto">
{t("connect_now")}
</Button>
)}
</div>
</div>
);
};
@@ -1,19 +1,17 @@
import { useEffect, useMemo } from "react";
import { useMemo, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/hooks/useAvailableTimeSlots";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/features/calendars/weeklyview/components/Calendar";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import { localStorage } from "@calcom/lib/webstorage";
import type { useScheduleForEventReturnType } from "@calcom/web/modules/schedules/hooks/useEvent";
import { OutOfOfficeInSlots } from "./OutOfOfficeInSlots";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
export const LargeCalendar = ({
extraDays,
@@ -80,7 +78,6 @@ export const LargeCalendar = ({
hoverEventDuration={eventDuration}
hideHeader
timezone={timezone}
renderOutOfOffice={(props) => <OutOfOfficeInSlots {...props} />}
/>
</div>
);
@@ -1,116 +0,0 @@
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent } from "@calcom/ui/components/dialog";
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const message = "/o";
event.returnValue = message; // Standard for most browsers
return message; // For some older browsers
};
export const RedirectToInstantMeetingModal = ({
bookingId,
onGoBack,
expiryTime,
instantVideoMeetingUrl,
orgName,
}: {
bookingId: number;
onGoBack: () => void;
expiryTime?: Date;
instantVideoMeetingUrl?: string;
orgName?: string | null;
}) => {
const { t } = useLocale();
const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining());
const [hasInstantMeetingTokenExpired, setHasInstantMeetingTokenExpired] = useState(false);
const router = useRouter();
function calculateTimeRemaining() {
const now = dayjs();
const expiration = dayjs(expiryTime);
const duration = expiration.diff(now);
return Math.max(duration, 0);
}
useEffect(() => {
if (!expiryTime) return;
const timer = setInterval(() => {
setTimeRemaining(calculateTimeRemaining());
setHasInstantMeetingTokenExpired(expiryTime && new Date(expiryTime) < new Date());
}, 1000);
return () => {
clearInterval(timer);
};
}, [expiryTime]);
const formatTime = (milliseconds: number) => {
const duration = dayjs.duration(milliseconds);
const seconds = duration.seconds();
const minutes = duration.minutes();
return `${minutes}m ${seconds}s`;
};
useEffect(() => {
if (!expiryTime || hasInstantMeetingTokenExpired || !!instantVideoMeetingUrl) {
window.removeEventListener("beforeunload", handleBeforeUnload);
return;
}
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, [expiryTime, hasInstantMeetingTokenExpired, instantVideoMeetingUrl]);
useEffect(() => {
if (!!instantVideoMeetingUrl) {
window.removeEventListener("beforeunload", handleBeforeUnload);
router.push(instantVideoMeetingUrl);
}
}, [instantVideoMeetingUrl]);
return (
<Dialog open={!!bookingId && !!expiryTime}>
<DialogContent enableOverflow className="py-8">
<div>
{hasInstantMeetingTokenExpired ? (
<div>
<p className="font-medium">{t("please_book_a_time_sometime_later")}</p>
<Button
className="mt-4"
onClick={() => {
onGoBack();
}}
color="primary">
{t("schedule_instead")}
</Button>
</div>
) : (
<div className="text-center">
<p className="font-medium">{t("connecting_you_to_someone", { orgName })}</p>
<p className="font-bold">{t("please_do_not_close_this_tab")}</p>
<p className="mt-2 font-medium">
{t("please_schedule_future_call", {
seconds: formatTime(timeRemaining),
})}
</p>
<div className="mt-4 h-[414px]">
<iframe className="mx-auto h-full w-[276px] rounded-lg" src="https://cal.games/" />
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
@@ -1,19 +1,16 @@
import React, { Fragment } from "react";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { PriceIcon } from "@calcom/web/modules/bookings/components/event-meta/PriceIcon";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { EventDetailBlocks } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Icon } from "@calcom/ui/components/icon";
import { type IconName } from "@calcom/ui/components/icon";
import { EventDetailBlocks } from "@calcom/features/bookings/types";
import { Icon, type IconName } from "@calcom/ui/components/icon";
import { PriceIcon } from "@calcom/web/modules/bookings/components/event-meta/PriceIcon";
import React, { Fragment } from "react";
import { AvailableEventLocations } from "./AvailableEventLocations";
import { EventDuration } from "./Duration";
import { EventOccurences } from "./Occurences";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
type EventDetailsPropsBase = {
event: Pick<
@@ -134,7 +131,6 @@ export const EventMetaBlock = ({
export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: EventDetailsProps) => {
const { t } = useLocale();
const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
const isInstantMeeting = useBookerStore((store) => store.isInstantMeeting);
return (
<>
@@ -152,7 +148,7 @@ export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: Even
);
case EventDetailBlocks.LOCATION:
if (!event?.locations?.length || isInstantMeeting || event.enablePerHostLocations) return null;
if (!event?.locations?.length || event.enablePerHostLocations) return null;
return (
<EventMetaBlock key={block}>
<AvailableEventLocations locations={event.locations} />
@@ -177,7 +173,7 @@ export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: Even
</EventMetaBlock>
);
case EventDetailBlocks.PRICE:
case EventDetailBlocks.PRICE: {
const paymentAppData = getPaymentAppData(event);
if (event.price <= 0 || paymentAppData.price <= 0) return null;
@@ -197,6 +193,7 @@ export const EventDetails = ({ event, blocks = defaultEventDetailsBlocks }: Even
/>
</EventMetaBlock>
);
}
}
})}
</>
@@ -2,8 +2,7 @@ import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { SchedulingType } from "@calcom/prisma/enums";
import { AvatarGroup } from "@calcom/ui/components/avatar";
@@ -49,7 +48,7 @@ export const EventMembers = ({
}
if (schedulingType === SchedulingType.ROUND_ROBIN && hideOrgTeamAvatar) {
return <p className="text-subtle pt-6 text-sm font-semibold">{profile.name}</p>;
return <p className="pt-6 font-semibold text-sm text-subtle">{profile.name}</p>;
}
const orgOrTeamAvatarItem =
@@ -62,8 +61,8 @@ export const EventMembers = ({
isEmbed || isPlatform || isPrivateLink || entity.hideProfileLink
? null
: entity.teamSlug
? getTeamUrlSync({ orgSlug: entity.orgSlug, teamSlug: entity.teamSlug })
: getBookerBaseUrlSync(entity.orgSlug),
? `${WEBAPP_URL}/team/${entity.teamSlug}`
: WEBAPP_URL,
image: entity.logoUrl ?? profile.image ?? "",
alt: entity.name ?? profile.name ?? "",
title: entity.name ?? profile.name ?? "",
@@ -81,9 +80,7 @@ export const EventMembers = ({
href:
isPlatform || isPrivateLink || entity.hideProfileLink
? null
: `${getBookerBaseUrlSync(user.profile?.organization?.slug ?? null)}/${
user.profile?.username
}?redirect=false`,
: `${WEBAPP_URL}/${user.profile?.username}?redirect=false`,
alt: user.name || "",
title: user.name || "",
image: getUserAvatarUrl(user),
@@ -91,7 +88,7 @@ export const EventMembers = ({
]}
/>
<p className="text-subtle mt-2 text-sm font-semibold">
<p className="mt-2 font-semibold text-sm text-subtle">
{showOnlyProfileName
? profile.name
: shownUsers
@@ -1,10 +1,9 @@
import type { ActiveFilter, ActiveFilters } from "@calcom/features/data-table";
import { ColumnFilterType } from "@calcom/features/data-table";
import type { ActiveFiltersValidator } from "~/data-table/DataTableProvider";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { useCallback, useMemo } from "react";
import type { ActiveFiltersValidator } from "~/data-table/DataTableProvider";
import { useEventTypes } from "./useEventTypes";
interface UseActiveFiltersValidatorOptions {
@@ -59,10 +58,8 @@ export function useActiveFiltersValidator({
canReadOthersBookings,
}: UseActiveFiltersValidatorOptions): ActiveFiltersValidatorState {
const eventTypes = useEventTypes();
const { data: teams } = trpc.viewer.teams.list.useQuery();
const { data: members } = trpc.viewer.teams.listSimpleMembers.useQuery(undefined, {
enabled: canReadOthersBookings,
});
const teams = undefined as { id: number; name: string }[] | undefined;
const members = undefined as { id: number; name: string | null }[] | undefined;
const { data: currentUser } = useMeQuery();
const accessibleUserIds = useMemo(() => {
@@ -1,314 +0,0 @@
import React from "react";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { BookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { useBookings } from "./useBookings";
const mockBookingMetadataSchema = vi.mocked(bookingMetadataSchema);
// Mock dependencies
vi.mock("@calcom/features/bookings/Booker/utils/query-param", () => ({
getQueryParam: vi.fn(),
updateQueryParam: vi.fn(),
}));
vi.mock("@calcom/features/bookings/lib/create-booking", () => ({
createBooking: vi.fn(),
}));
vi.mock("@calcom/features/bookings/lib/create-instant-booking", () => ({
createInstantBooking: vi.fn(),
}));
vi.mock("@calcom/features/bookings/lib/create-recurring-booking", () => ({
createRecurringBooking: vi.fn(),
}));
vi.mock("@calcom/features/bookings/lib/bookingSuccessRedirect", () => ({
useBookingSuccessRedirect: () => vi.fn(),
}));
vi.mock("@calcom/lib/hooks/useLocale", () => ({
useLocale: () => ({
t: (text: string) => text,
}),
}));
vi.mock("@calcom/ui/components/toast", () => ({
showToast: vi.fn(),
}));
vi.mock("@calcom/atoms/hooks/bookings/useHandleBookEvent", () => ({
useHandleBookEvent: () => ({
handleBookEvent: vi.fn(),
}),
}));
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: vi.fn(),
replace: vi.fn(),
back: vi.fn(),
}),
}));
vi.mock("@calcom/features/bookings/Booker/hooks/useBookingForm", () => ({
useBookingForm: () => ({
bookingForm: {
watch: vi.fn(),
setValue: vi.fn(),
getValues: vi.fn().mockReturnValue({ responses: {} }),
},
formEmail: "",
bookerFormErrorRef: { current: null },
key: "test-key",
}),
}));
vi.mock("@calcom/lib/webstorage", () => ({
localStorage: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
},
}));
vi.mock("@calcom/embed-core/embed-iframe", () => ({
sdkActionManager: {
fire: vi.fn(),
},
useIsEmbed: () => false,
}));
vi.mock("@calcom/lib/hooks/useCompatSearchParams", () => ({
useCompatSearchParams: () => new URLSearchParams(),
}));
vi.mock("@calcom/features/bookings/lib/client/decoyBookingStore", () => ({
storeDecoyBooking: vi.fn(),
}));
vi.mock("@calcom/app-store/stripepayment/lib/client", () => ({
createPaymentLink: vi.fn(),
}));
// Create mock function that can be accessed after vi.mock hoisting
const mockUseQuery = vi.fn();
vi.mock("@calcom/trpc/react", () => {
const mockUseQueryFn = vi.fn();
// Store reference globally so we can access it in tests
(globalThis as any).__mockUseQuery = mockUseQueryFn;
return {
trpc: {
viewer: {
bookings: {
getInstantBookingLocation: {
useQuery: mockUseQueryFn,
},
},
},
},
};
});
// Get the mock function reference after module is loaded
const getMockUseQuery = () => (globalThis as any).__mockUseQuery as ReturnType<typeof vi.fn>;
// Mock bookingMetadataSchema.parse
vi.mock("@calcom/prisma/zod-utils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@calcom/prisma/zod-utils")>();
return {
...actual,
bookingMetadataSchema: {
...actual.bookingMetadataSchema,
parse: vi.fn(),
},
};
});
const createMockStore = (isInstantMeeting: boolean) => {
const state = {
eventSlug: "test-event",
eventId: 1,
isInstantMeeting,
rescheduleUid: null,
rescheduledBy: null,
bookingData: null,
selectedTimeslot: null,
selectedDuration: null,
setRescheduleUid: vi.fn(),
setBookingData: vi.fn(),
};
return {
getState: () => state,
setState: vi.fn(),
subscribe: vi.fn(),
destroy: vi.fn(),
};
};
const mockEvent = {
data: {
id: 1,
slug: "test-event",
length: 30,
requiresConfirmation: false,
recurringEvent: null,
schedulingType: null,
metadata: {},
successRedirectUrl: null,
forwardParamsSuccessRedirect: false,
subsetOfHosts: [],
isDynamic: false,
subsetOfUsers: [],
},
isSuccess: true,
isPending: false,
};
const createTestWrapper = (mockStore: ReturnType<typeof createMockStore>) => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
<BookerStoreContext.Provider value={mockStore as any}>{children}</BookerStoreContext.Provider>
</QueryClientProvider>
);
};
describe("useBookings - Instant Booking Query", () => {
beforeEach(() => {
vi.clearAllMocks();
const mockUseQueryFn = getMockUseQuery();
mockUseQueryFn.mockReturnValue({
data: undefined,
isPending: false,
});
});
it("should NOT enable instant booking query when bookingUid exists but isInstantMeeting is false (seated event scenario - THE BUG)", () => {
vi.mocked(getQueryParam).mockReturnValue("test-booking-uid");
const mockStore = createMockStore(false);
renderHook(() => useBookings({ event: mockEvent, bookingForm: {} as any, metadata: {} }), {
wrapper: createTestWrapper(mockStore),
});
const mockUseQueryFn = getMockUseQuery();
expect(mockUseQueryFn).toHaveBeenCalledWith(
{
bookingUid: "test-booking-uid",
},
expect.objectContaining({
enabled: false, // FIX: Should be false when isInstantMeeting is false
})
);
});
it("should enable instant booking query when bookingUid exists AND isInstantMeeting is true", () => {
vi.mocked(getQueryParam).mockReturnValue("test-booking-uid");
const mockStore = createMockStore(true);
renderHook(() => useBookings({ event: mockEvent, bookingForm: {} as any, metadata: {} }), {
wrapper: createTestWrapper(mockStore),
});
const mockUseQueryFn = getMockUseQuery();
expect(mockUseQueryFn).toHaveBeenCalledWith(
{
bookingUid: "test-booking-uid",
},
expect.objectContaining({
enabled: true, // Should be true when isInstantMeeting is true
})
);
});
it("should NOT set instantVideoMeetingUrl when query returns data but isInstantMeeting is false (prevents redirect bug)", async () => {
vi.mocked(getQueryParam).mockReturnValue("test-booking-uid");
const mockBookingData = {
booking: {
uid: "test-booking-uid",
metadata: {
videoCallUrl: "http://localhost:3000/video/test-booking-uid",
},
},
};
const mockUseQueryFn = getMockUseQuery();
mockUseQueryFn.mockReturnValue({
data: mockBookingData,
isPending: false,
});
mockBookingMetadataSchema.parse.mockReturnValue({
videoCallUrl: "http://localhost:3000/video/test-booking-uid",
});
const mockStore = createMockStore(false);
const { result } = renderHook(
() => useBookings({ event: mockEvent, bookingForm: {} as any, metadata: {} }),
{
wrapper: createTestWrapper(mockStore),
}
);
await waitFor(() => {
// FIX: instantVideoMeetingUrl should remain undefined when isInstantMeeting is false
// This prevents the redirect to /video/[uid] for seated events
expect(result.current.instantVideoMeetingUrl).toBeUndefined();
});
});
it("should set instantVideoMeetingUrl when query returns data AND isInstantMeeting is true", async () => {
vi.mocked(getQueryParam).mockReturnValue("test-booking-uid");
const mockBookingData = {
booking: {
uid: "test-booking-uid",
metadata: {
videoCallUrl: "http://localhost:3000/video/test-booking-uid",
},
},
};
const mockUseQueryFn = getMockUseQuery();
mockUseQueryFn.mockReturnValue({
data: mockBookingData,
isPending: false,
});
mockBookingMetadataSchema.parse.mockReturnValue({
videoCallUrl: "http://localhost:3000/video/test-booking-uid",
});
const mockStore = createMockStore(true);
const { result } = renderHook(
() => useBookings({ event: mockEvent, bookingForm: {} as any, metadata: {} }),
{
wrapper: createTestWrapper(mockStore),
}
);
await waitFor(() => {
// instantVideoMeetingUrl should be set when isInstantMeeting is true
expect(result.current.instantVideoMeetingUrl).toBe("http://localhost:3000/video/test-booking-uid");
});
});
});
+34 -176
View File
@@ -1,33 +1,26 @@
"use client";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useRef, useState, useEffect } from "react";
import { shallow } from "zustand/shallow";
import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
import { useHandleBookEvent } from "@calcom/atoms/hooks/bookings/useHandleBookEvent";
import dayjs from "@calcom/dayjs";
import { sdkActionManager } from "@calcom/embed-core/embed-iframe";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import { storeDecoyBooking } from "@calcom/features/bookings/lib/client/decoyBookingStore";
import { createBooking } from "@calcom/features/bookings/lib/create-booking";
import { createInstantBooking } from "@calcom/features/bookings/lib/create-instant-booking";
import { createRecurringBooking } from "@calcom/features/bookings/lib/create-recurring-booking";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { BookerEvent, BookingResponse } from "@calcom/features/bookings/types";
import { getFullName } from "@calcom/features/form-builder/utils";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import { BookingStatus } from "@calcom/prisma/enums";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useRef } from "react";
import { shallow } from "zustand/shallow";
export interface IUseBookings {
event: {
@@ -107,7 +100,6 @@ export const getDryRunRescheduleBookingSuccessfulEventPayload = getDryRunBooking
export interface IUseBookingLoadingStates {
creatingBooking: boolean;
creatingRecurringBooking: boolean;
creatingInstantBooking: boolean;
}
export interface IUseBookingErrors {
@@ -116,63 +108,10 @@ export interface IUseBookingErrors {
}
export type UseBookingsReturnType = ReturnType<typeof useBookings>;
const STORAGE_KEY = "instantBookingData";
const COOLDOWN_STORAGE_KEY = "instantBookingCooldownByEvent";
const COOLDOWN_WINDOW_MS = 10 * 60 * 1000; // 10 minutes
type InstantBookingCooldownMap = Record<string, number>;
const readInstantCooldownMap = (): InstantBookingCooldownMap => {
try {
const raw = localStorage.getItem(COOLDOWN_STORAGE_KEY);
return raw ? (JSON.parse(raw) as InstantBookingCooldownMap) : {};
} catch {
return {};
}
};
const writeInstantCooldownMap = (map: InstantBookingCooldownMap) => {
try {
localStorage.setItem(COOLDOWN_STORAGE_KEY, JSON.stringify(map));
} catch {
// don't do anything
}
};
const getInstantCooldownRemainingMs = (eventTypeId?: number | null): number => {
if (!eventTypeId) return 0;
const map = readInstantCooldownMap();
const lastTs = map[String(eventTypeId)];
if (!lastTs) return 0;
const remaining = lastTs + COOLDOWN_WINDOW_MS - Date.now();
return remaining > 0 ? remaining : 0;
};
const setInstantCooldownNow = (eventTypeId?: number | null) => {
if (!eventTypeId) return;
const map = readInstantCooldownMap();
map[String(eventTypeId)] = Date.now();
writeInstantCooldownMap(map);
};
const storeInLocalStorage = ({
eventTypeId,
expiryTime,
bookingUid,
}: {
eventTypeId: number;
expiryTime: Date;
bookingUid: string;
}) => {
const value = JSON.stringify({ eventTypeId, expiryTime, bookingUid });
localStorage.setItem(STORAGE_KEY, value);
};
export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookingDryRun }: IUseBookings) => {
const router = useRouter();
const eventSlug = useBookerStoreContext((state) => state.eventSlug);
const eventTypeId = useBookerStoreContext((state) => state.eventId);
const isInstantMeeting = useBookerStoreContext((state) => state.isInstantMeeting);
const [rescheduleUid, setRescheduleUid] = useBookerStoreContext(
(state) => [state.rescheduleUid, state.setRescheduleUid],
@@ -188,70 +127,12 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
const bookingSuccessRedirect = useBookingSuccessRedirect();
const bookerFormErrorRef = useRef<HTMLDivElement>(null);
const [instantMeetingTokenExpiryTime, setExpiryTime] = useState<Date | undefined>();
const [instantVideoMeetingUrl, setInstantVideoMeetingUrl] = useState<string | undefined>();
const duration = useBookerStoreContext((state) => state.selectedDuration);
const isRescheduling = !!rescheduleUid && !!bookingData;
const bookingUid = getQueryParam("bookingUid") ?? "";
useEffect(() => {
if (!isInstantMeeting) return;
const storedInfo = localStorage.getItem(STORAGE_KEY);
if (storedInfo) {
const parsedInfo = JSON.parse(storedInfo);
const parsedInstantBookingInfo =
parsedInfo.eventTypeId === eventTypeId &&
isInstantMeeting &&
new Date(parsedInfo.expiryTime) > new Date()
? parsedInfo
: null;
if (parsedInstantBookingInfo) {
setExpiryTime(parsedInstantBookingInfo.expiryTime);
updateQueryParam("bookingUid", parsedInstantBookingInfo.bookingUid);
}
}
}, [eventTypeId, isInstantMeeting]);
const instantConnectCooldownMs = getInstantCooldownRemainingMs(eventTypeId);
const _instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery(
{
bookingUid: bookingUid,
},
{
enabled: !!bookingUid && isInstantMeeting,
refetchInterval: 2000,
refetchIntervalInBackground: true,
}
);
useEffect(
function refactorMeWithoutEffect() {
const data = _instantBooking.data;
if (!data || !data.booking || !isInstantMeeting) return;
try {
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
data.booking?.metadata || {}
)?.videoCallUrl;
if (locationVideoCallUrl) {
setInstantVideoMeetingUrl(locationVideoCallUrl);
} else {
showToast(t("something_went_wrong_on_our_end"), "error");
}
} catch {
showToast(t("something_went_wrong_on_our_end"), "error");
}
},
[_instantBooking.data, isInstantMeeting]
);
const createBookingMutation = useMutation({
mutationFn: createBooking,
onSuccess: (booking) => {
@@ -386,7 +267,18 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
bookingSuccessRedirect({
successRedirectUrl: event?.data?.successRedirectUrl || "",
query,
booking: booking,
booking: booking as unknown as Pick<
BookingResponse,
| "uid"
| "title"
| "description"
| "startTime"
| "endTime"
| "location"
| "attendees"
| "user"
| "responses"
>,
forwardParamsSuccessRedirect:
event?.data?.forwardParamsSuccessRedirect === undefined
? true
@@ -414,29 +306,6 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
},
});
const createInstantBookingMutation = useMutation({
mutationFn: createInstantBooking,
onSuccess: (responseData) => {
if (eventTypeId) {
storeInLocalStorage({
eventTypeId,
expiryTime: responseData.expires,
bookingUid: responseData.bookingUid,
});
setInstantCooldownNow(eventTypeId);
}
updateQueryParam("bookingUid", responseData.bookingUid);
setExpiryTime(responseData.expires);
},
onError: (err) => {
console.error("Error creating instant booking", err);
if (bookerFormErrorRef?.current) {
bookerFormErrorRef.current.scrollIntoView({ behavior: "smooth" });
}
},
});
const createRecurringBookingMutation = useMutation({
mutationFn: createRecurringBooking,
onSuccess: async (bookings) => {
@@ -515,7 +384,18 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
bookingSuccessRedirect({
successRedirectUrl: event?.data?.successRedirectUrl || "",
query,
booking,
booking: booking as unknown as Pick<
BookingResponse,
| "uid"
| "title"
| "description"
| "startTime"
| "endTime"
| "location"
| "attendees"
| "user"
| "responses"
>,
forwardParamsSuccessRedirect:
event?.data?.forwardParamsSuccessRedirect === undefined
? true
@@ -534,32 +414,14 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
bookingForm,
hashedLink,
metadata,
handleInstantBooking: (variables: Parameters<typeof createInstantBookingMutation.mutate>[0]) => {
const remaining = getInstantCooldownRemainingMs(eventTypeId);
if (remaining > 0) {
showToast(
t("please_try_again_later_or_book_another_slot", { remaining: Math.ceil(remaining / 60000) }),
"error"
);
return;
}
createInstantBookingMutation.mutate(variables);
},
handleRecBooking: createRecurringBookingMutation.mutate,
handleBooking: createBookingMutation.mutate,
isBookingDryRun,
});
const errors = {
hasDataErrors: Boolean(
createBookingMutation.isError ||
createRecurringBookingMutation.isError ||
createInstantBookingMutation.isError
),
dataErrors:
createBookingMutation.error ||
createRecurringBookingMutation.error ||
createInstantBookingMutation.error,
hasDataErrors: Boolean(createBookingMutation.isError || createRecurringBookingMutation.isError),
dataErrors: createBookingMutation.error || createRecurringBookingMutation.error,
};
// A redirect is triggered on mutation success, so keep the loading state while it is happening.
@@ -567,17 +429,13 @@ export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookin
creatingBooking: createBookingMutation.isPending || createBookingMutation.isSuccess,
creatingRecurringBooking:
createRecurringBookingMutation.isPending || createRecurringBookingMutation.isSuccess,
creatingInstantBooking: createInstantBookingMutation.isPending,
};
return {
handleBookEvent,
expiryTime: instantMeetingTokenExpiryTime,
bookingForm,
bookerFormErrorRef,
errors,
loadingStates,
instantVideoMeetingUrl,
instantConnectCooldownMs,
};
};
@@ -3,7 +3,6 @@ import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import type { RowData, Table } from "@tanstack/react-table";
import { useCallback } from "react";
import { useEventTypes } from "./useEventTypes";
interface UseFacetedUniqueValuesOptions {
@@ -17,10 +16,8 @@ export function useFacetedUniqueValues({
columnId: string
) => () => Map<FacetedValue, number> {
const eventTypes = useEventTypes();
const { data: teams } = trpc.viewer.teams.list.useQuery();
const { data: members } = trpc.viewer.teams.listSimpleMembers.useQuery(undefined, {
enabled: canReadOthersBookings,
});
const teams = undefined as { id: number; name: string }[] | undefined;
const members = undefined as { id: number; name: string | null }[] | undefined;
const { data: currentUser } = useMeQuery();
return useCallback(
@@ -1,16 +1,13 @@
import { useEffect, useState } from "react";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { BookerState } from "@calcom/features/bookings/Booker/types";
import { getBookingResponsesSchemaWithOptionalChecks } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useEffect, useState } from "react";
export const useSkipConfirmStep = (
bookingForm: UseBookingFormReturnType["bookingForm"],
bookerState: BookerState,
isInstantMeeting: boolean,
isWeekView: boolean,
bookingFields?: BookerEvent["bookingFields"],
locations?: BookerEvent["locations"]
@@ -39,11 +36,11 @@ export const useSkipConfirmStep = (
setCanSkip(false);
}
};
const isSkipConfirmStepSupported = !isInstantMeeting && !isWeekView;
const isSkipConfirmStepSupported = !isWeekView;
if (bookerState === "selecting_time" && isSkipConfirmStepSupported) {
checkSkipStep();
}
}, [bookingFormValues, bookingFields, rescheduleUid, bookerState, isWeekView, isInstantMeeting]);
}, [bookingFormValues, bookingFields, rescheduleUid, bookerState, isWeekView]);
return canSkip;
};
@@ -1,60 +0,0 @@
import { describe, it, expect } from "vitest";
import { getTabForBooking } from "./useSwitchToCorrectStatusTab";
function makeBooking(overrides: {
status: string;
endTime: Date;
recurringEventId?: string | null;
}){
return {
status: overrides.status,
endTime: overrides.endTime,
recurringEventId: overrides.recurringEventId ?? null,
};
}
const future = new Date(Date.now() + 24 * 60 * 60 * 1000);
const past = new Date(Date.now() - 24 * 60 * 60 * 1000);
describe("getTabForBooking", () => {
it("returns 'cancelled' for CANCELLED bookings", () => {
expect(getTabForBooking(makeBooking({ status: "CANCELLED", endTime: future }))).toBe("cancelled");
});
it("returns 'cancelled' for REJECTED bookings", () => {
expect(getTabForBooking(makeBooking({ status: "REJECTED", endTime: future }))).toBe("cancelled");
});
it("returns 'cancelled' for CANCELLED bookings even if past", () => {
expect(getTabForBooking(makeBooking({ status: "CANCELLED", endTime: past }))).toBe("cancelled");
});
it("returns 'unconfirmed' for PENDING bookings in the future", () => {
expect(getTabForBooking(makeBooking({ status: "PENDING", endTime: future }))).toBe("unconfirmed");
});
it("returns 'past' for PENDING bookings that have ended", () => {
expect(getTabForBooking(makeBooking({ status: "PENDING", endTime: past }))).toBe("past");
});
it("returns 'past' for ACCEPTED bookings that have ended", () => {
expect(getTabForBooking(makeBooking({ status: "ACCEPTED", endTime: past }))).toBe("past");
});
it("returns 'recurring' for future ACCEPTED bookings with recurringEventId", () => {
expect(
getTabForBooking(makeBooking({ status: "ACCEPTED", endTime: future, recurringEventId: "rec-123" }))
).toBe("recurring");
});
it("returns 'upcoming' for future ACCEPTED bookings without recurringEventId", () => {
expect(getTabForBooking(makeBooking({ status: "ACCEPTED", endTime: future }))).toBe("upcoming");
});
it("returns 'past' for recurring bookings that have ended", () => {
expect(
getTabForBooking(makeBooking({ status: "ACCEPTED", endTime: past, recurringEventId: "rec-123" }))
).toBe("past");
});
});
@@ -17,19 +17,8 @@ export const useVerifyCode = ({ onSuccess }: UseVerifyCodeProps) => {
const [value, setValue] = useState("");
const [hasVerified, setHasVerified] = useState(false);
const verifyCodeMutationUserSessionRequired = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsPending(false);
onSuccess(data);
},
onError: (err) => {
setIsPending(false);
setHasVerified(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const verifyCodeMutationUserSessionRequired = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
const verifyCodeMutationUserSessionNotRequired = trpc.viewer.auth.verifyCodeUnAuthenticated.useMutation({
onSuccess: (data) => {
+7 -10
View File
@@ -1,17 +1,16 @@
import type { DataTableRow } from "@calcom/features/data-table/lib/separator";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { BookerEventQuery } from "@calcom/features/bookings/types";
import type { useScheduleForEventReturnType } from "@calcom/web/modules/schedules/hooks/useEvent";
import type { ToggledConnectedCalendars, CustomClassNames } from "@calcom/features/bookings/Booker/types";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { validStatuses } from "./lib/validStatuses";
import type { UseBookerLayoutType } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import type { CustomClassNames, ToggledConnectedCalendars } from "@calcom/features/bookings/Booker/types";
import type { BookerEventQuery } from "@calcom/features/bookings/types";
import type { DataTableRow } from "@calcom/features/data-table/lib/separator";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { useScheduleForEventReturnType } from "@calcom/web/modules/schedules/hooks/useEvent";
import type { UseBookingsReturnType } from "./hooks/useBookings";
import type { UseSlotsReturnType } from "./hooks/useSlots";
import type { UseVerifyCodeReturnType } from "./hooks/useVerifyCode";
import type { UseVerifyEmailReturnType } from "./hooks/useVerifyEmail";
import type { validStatuses } from "./lib/validStatuses";
export type BookingsGetOutput = RouterOutputs["viewer"]["bookings"]["get"];
@@ -52,8 +51,6 @@ export type WrappedBookerPropsMain = {
isRedirect: boolean;
fromUserNameRedirected: string;
hasSession: boolean;
onGoBackInstantMeeting: () => void;
onConnectNowInstantMeeting: () => void;
onOverlayClickNoCalendar: () => void;
onClickOverlayContinue: () => void;
onOverlaySwitchStateChange: (state: boolean) => void;
@@ -1,13 +1,7 @@
import { createRouterCaller } from "app/_trpc/context";
import type { GetServerSidePropsContext } from "next";
import { z } from "zod";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
import { orgDomainConfig } from "@calcom/ee/organizations/lib/orgDomains";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import getBookingInfo from "@calcom/features/bookings/lib/getBookingInfo";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { isTeamMember } from "@calcom/features/ee/teams/lib/queries";
import { getDefaultEvent } from "@calcom/features/eventtypes/lib/defaultEvents";
import { getBrandingForEventType } from "@calcom/features/profile/lib/getBranding";
import { shouldHideBrandingForEvent } from "@calcom/features/profile/lib/hideBranding";
@@ -17,8 +11,10 @@ import { maybeGetBookingUidFromSeat } from "@calcom/lib/server/maybeGetBookingUi
import prisma from "@calcom/prisma";
import { customInputSchema } from "@calcom/prisma/zod-utils";
import { meRouter } from "@calcom/trpc/server/routers/viewer/me/_router";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import { createRouterCaller } from "app/_trpc/context";
import type { GetServerSidePropsContext } from "next";
import { z } from "zod";
const stringToBoolean = z
.string()
@@ -114,8 +110,8 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
// @NOTE: had to do this because Server side cant return [Object objects]
// probably fixable with json.stringify -> json.parse
bookingInfo["startTime"] = (bookingInfo?.startTime as Date)?.toISOString() as unknown as Date;
bookingInfo["endTime"] = (bookingInfo?.endTime as Date)?.toISOString() as unknown as Date;
bookingInfo.startTime = (bookingInfo?.startTime as Date)?.toISOString() as unknown as Date;
bookingInfo.endTime = (bookingInfo?.endTime as Date)?.toISOString() as unknown as Date;
eventTypeRaw.users = eventTypeRaw.hosts?.length
? eventTypeRaw.hosts.map((host) => host.user)
@@ -185,7 +181,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
const isLoggedInUserHost = checkIfUserIsHost(userId);
const eventTeamId = eventType.team?.id ?? eventType.parent?.teamId;
const isLoggedInUserTeamMember = !!(userId && eventTeamId && (await isTeamMember(userId, eventTeamId)));
const isLoggedInUserTeamMember = false;
const canViewHiddenData = isLoggedInUserHost || isLoggedInUserTeamMember;
@@ -216,7 +212,8 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
}
}
const { currentOrgDomain } = orgDomainConfig(context.req);
const currentOrgDomain = null;
const isValidOrgDomain = false;
async function getInternalNotePresets(teamId: number | null) {
if (!teamId || !canViewHiddenData) return [];
@@ -64,7 +64,6 @@ import {
import { showToast } from "@calcom/ui/components/toast";
import { useCalcomTheme } from "@calcom/ui/styles";
import CancelBooking from "@calcom/web/components/booking/CancelBooking";
import { RoutingTraceSheet } from "@calcom/web/components/booking/RoutingTraceSheet";
import EventReservationSchema from "@calcom/web/components/schemas/EventReservationSchema";
import { timeZone } from "@calcom/web/lib/clock";
@@ -211,7 +210,6 @@ export default function Success(props: PageProps) {
const defaultRating = validateRating(rating);
const [rateValue, setRateValue] = useState<number>(defaultRating);
const [isFeedbackSubmitted, setIsFeedbackSubmitted] = useState(false);
const [isRoutingTraceSheetOpen, setIsRoutingTraceSheetOpen] = useState(false);
const mutation = trpc.viewer.public.submitRating.useMutation({
onSuccess: async () => {
@@ -785,7 +783,7 @@ export default function Success(props: PageProps) {
<Badge
variant="gray"
className="mb-2 cursor-pointer hover:opacity-80"
onClick={() => setIsRoutingTraceSheetOpen(true)}>
>
{t(
assignmentReasonBadgeTitleMap(
bookingInfo.assignmentReason[0].reasonEnum as AssignmentReasonEnum
@@ -797,11 +795,6 @@ export default function Success(props: PageProps) {
{bookingInfo.assignmentReason[0].reasonString}
</p>
)}
<RoutingTraceSheet
isOpen={isRoutingTraceSheetOpen}
setIsOpen={setIsRoutingTraceSheetOpen}
bookingUid={bookingInfo.uid}
/>
</div>
</>
)}
@@ -3,13 +3,11 @@
import { ColumnFilterType, type SystemFilterSegment } from "@calcom/features/data-table";
import { DataTableProvider } from "~/data-table/DataTableProvider";
import { useSegments } from "~/data-table/hooks/useSegments";
import FeatureOptInBannerWrapper from "~/feature-opt-in/components/FeatureOptInBannerWrapper";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import dynamic from "next/dynamic";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useMemo } from "react";
import { useFeatureOptInBanner } from "../../feature-opt-in/hooks/useFeatureOptInBanner";
import { BookingListContainer } from "../components/BookingListContainer";
import { useActiveFiltersValidator } from "../hooks/useActiveFiltersValidator";
import { useBookingsView } from "../hooks/useBookingsView";
@@ -83,7 +81,7 @@ function BookingsContent({ status, permissions, bookingsV3Enabled, bookingAuditE
const handleOptInSuccess = useCallback(() => {
router.refresh();
}, [router]);
const optInBanner = useFeatureOptInBanner("bookings-v3", { onOptInSuccess: handleOptInSuccess });
const optInBanner = null;
return (
<div className={classNames(view === "calendar" && "-mb-8")}>
@@ -102,7 +100,6 @@ function BookingsContent({ status, permissions, bookingsV3Enabled, bookingAuditE
bookingsV3Enabled={bookingsV3Enabled}
/>
)}
<FeatureOptInBannerWrapper state={optInBanner} />
</div>
</div>
);
}
@@ -0,0 +1,160 @@
import { useEffect, useMemo } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/weeklyview/types/state";
import { localStorage } from "@calcom/lib/webstorage";
import type { BookingStatus } from "@calcom/prisma/enums";
import { useBookings } from "@calcom/atoms/hooks/bookings/useBookings";
import { useCalendarsBusyTimes } from "@calcom/atoms/hooks/useCalendarsBusyTimes";
import { useConnectedCalendars } from "@calcom/atoms/hooks/useConnectedCalendars";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
export const LargeCalendar = ({
extraDays,
availableTimeslots,
isLoading,
event,
}: {
extraDays: number;
availableTimeslots?: CalendarAvailableTimeslots | undefined;
isLoading: boolean;
event?: {
data?: Pick<BookerEvent, "length" | "id"> | null;
};
}) => {
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const selectedEventDuration = useBookerStoreContext((state) => state.selectedDuration);
const displayOverlay =
getQueryParam("overlayCalendar") === "true" || localStorage?.getItem("overlayCalendarSwitchDefault");
const { timezone } = useBookerTime();
const eventDuration = selectedEventDuration || event?.data?.length || 30;
const availableSlots = availableTimeslots !== undefined ? availableTimeslots : undefined;
const startDate = selectedDate ? dayjs(selectedDate).toDate() : dayjs().toDate();
const endDate = dayjs(startDate)
.add(extraDays - 1, "day")
.toDate();
const { data: bookings, isPending: _isFetchingBookings } = useBookings({
take: 150,
skip: 0,
eventTypeId: event?.data?.id,
afterStart: startDate.toISOString(),
beforeEnd: endDate.toISOString(),
status: ["upcoming", "past", "recurring"],
});
const { data: connectedCalendars, isPending: isFetchingConnectedCalendars } = useConnectedCalendars({
enabled: true,
});
const calendarsToLoad = connectedCalendars?.connectedCalendars.flatMap((connectedCalendar) => {
return (
connectedCalendar.calendars
?.filter((calendar) => calendar.isSelected === true)
.map((cal) => ({
credentialId: cal.credentialId,
externalId: cal.externalId,
})) ?? []
);
});
const { data: overlayBusyDates } = useCalendarsBusyTimes({
loggedInUsersTz: timezone,
dateFrom: startDate.toISOString(),
dateTo: endDate.toISOString(),
calendarsToLoad: calendarsToLoad ?? [],
enabled: Boolean(!isFetchingConnectedCalendars && !!calendarsToLoad?.length),
});
// HACK: force rerender when overlay events change
// Sine we dont use react router here we need to force rerender (ATOM SUPPORT)
useEffect(() => {}, [displayOverlay]);
const sortedBookingRanges = useMemo(
() =>
(bookings ?? [])
.map((booking) => ({
booking,
startTime: dayjs(booking.start).valueOf(),
endTime: dayjs(booking.end).valueOf(),
}))
.sort((a, b) => a.startTime - b.startTime),
[bookings]
);
const filteredBusyDates = useMemo(() => {
const overlay = overlayBusyDates?.data ?? [];
if (!sortedBookingRanges.length) return overlay;
return overlay.filter((busy) => {
const busyStart = dayjs(busy.start).valueOf();
const busyEnd = dayjs(busy.end).valueOf();
for (const { startTime, endTime } of sortedBookingRanges) {
if (startTime >= busyEnd) break;
if (endTime <= busyStart) continue;
return false;
}
return true;
});
}, [overlayBusyDates?.data, sortedBookingRanges]);
const overlayEventsForDate = useMemo(() => {
const allBookings = bookings ?? [];
// since busy dates comes straight from the calendar, it contains slots have bookings and also slots that are marked as busy by user but are not bookings
// hence we filter overlayBusyDates to exclude anything that overlaps with bookings
const busyEvents = filteredBusyDates.map((busyData, index) => ({
id: index,
title: `Busy`,
start: new Date(busyData.start),
end: new Date(busyData.end),
options: {
status: "ACCEPTED" as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
const bookingEvents = allBookings.map((booking) => ({
id: booking.id,
title: booking.title ?? `Busy`,
start: new Date(booking.start),
end: new Date(booking.end),
options: {
status: booking.status.toUpperCase() as BookingStatus,
"data-test-id": "troubleshooter-busy-event",
className: "border-[1.5px]",
},
}));
return [...bookingEvents, ...busyEvents];
}, [bookings, filteredBusyDates]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
<Calendar
isPending={isLoading}
availableTimeslots={availableSlots}
startHour={0}
endHour={23}
events={overlayEventsForDate}
startDate={startDate}
endDate={endDate}
gridCellsPerHour={60 / eventDuration}
hoverEventDuration={eventDuration}
hideHeader
timezone={timezone}
/>
</div>
);
};
@@ -0,0 +1,215 @@
import {
CalendarStoreContext,
createCalendarStore,
useCalendarStore,
} from "@calcom/features/calendars/weeklyview/state/store";
import classNames from "@calcom/ui/classNames";
import type React from "react";
import { useEffect, useMemo, useRef } from "react";
import "@calcom/features/calendars/weeklyview/styles/styles.css";
import type { CalendarComponentProps } from "@calcom/features/calendars/weeklyview/types/state";
import { getDaysBetweenDates, getHoursToDisplay } from "@calcom/features/calendars/weeklyview/utils";
import { CurrentTime } from "./currentTime";
import { DateValues } from "./DateValues";
import { AvailableCellsForDay, EmptyCell } from "./event/Empty";
import { EventList } from "./event/EventList";
import { SchedulerColumns } from "./grid";
import { SchedulerHeading } from "./heading/SchedulerHeading";
import { HorizontalLines } from "./horizontalLines";
import { Spinner } from "./spinner/Spinner";
import { VerticalLines } from "./verticalLines";
function CalendarInner(props: CalendarComponentProps) {
const container = useRef<HTMLDivElement | null>(null);
const containerNav = useRef<HTMLDivElement | null>(null);
const containerOffset = useRef<HTMLDivElement | null>(null);
const schedulerGrid = useRef<HTMLOListElement | null>(null);
const initialState = useCalendarStore((state) => state.initState);
const startDate = useCalendarStore((state) => state.startDate);
const endDate = useCalendarStore((state) => state.endDate);
const startHour = useCalendarStore((state) => state.startHour || 0);
const endHour = useCalendarStore((state) => state.endHour || 23);
const usersCellsStopsPerHour = useCalendarStore((state) => state.gridCellsPerHour || 4);
const availableTimeslots = useCalendarStore((state) => state.availableTimeslots);
const hideHeader = useCalendarStore((state) => state.hideHeader);
const timezone = useCalendarStore((state) => state.timezone);
const showBackgroundPattern = useCalendarStore((state) => state.showBackgroundPattern);
const showBorder = useCalendarStore((state) => state.showBorder ?? true);
const borderColor = useCalendarStore((state) => state.borderColor ?? "default");
const scrollToCurrentTime = useCalendarStore((state) => state.scrollToCurrentTime ?? true);
const updateCurrentTimeOnFocus = useCalendarStore((state) => state.updateCurrentTimeOnFocus ?? false);
const days = useMemo(() => getDaysBetweenDates(startDate, endDate), [startDate, endDate]);
const hours = useMemo(
() => getHoursToDisplay(startHour || 0, endHour || 23, timezone),
[startHour, endHour, timezone]
);
const numberOfGridStopsPerDay = hours.length * usersCellsStopsPerHour;
const hourSize = 58;
// Initalise State on initial mount and when props change
useEffect(() => {
initialState(props);
}, [props, initialState]);
return (
<MobileNotSupported>
<div
className={classNames("scheduler-wrapper flex h-full w-full flex-col")}
style={
{
"--one-minute-height": `calc(${hourSize}px/60)`,
"--gridDefaultSize": `${hourSize}px`,
} as React.CSSProperties // This can't live in the css file because it's a dynamic value and css variable gets super
}>
{hideHeader !== true && <SchedulerHeading />}
{props.isPending && <Spinner />}
<div
ref={container}
className="bg-default dark:bg-cal-muted relative isolate flex h-full flex-auto flex-col">
<div
style={{ width: "165%" }}
className="flex max-w-full flex-none flex-col sm:max-w-none md:max-w-full">
<DateValues
containerNavRef={containerNav}
days={days}
showBorder={showBorder}
borderColor={borderColor}
/>
<div className="relative flex flex-auto">
<CurrentTime
timezone={timezone}
scrollToCurrentTime={scrollToCurrentTime}
updateOnFocus={updateCurrentTimeOnFocus}
/>
<div
className={classNames(
"bg-default dark:bg-cal-muted ring-muted sticky left-0 z-10 w-16 flex-none ring-1",
showBorder &&
(borderColor === "subtle"
? "border-subtle border-l border-r"
: "border-default border-l border-r")
)}
/>
<div
className="grid flex-auto grid-cols-1 grid-rows-1 [--disabled-gradient-background:#F8F9FB] [--disabled-gradient-foreground:#E6E7EB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
style={
showBackgroundPattern === false
? undefined
: {
backgroundColor: "var(--disabled-gradient-background)",
background:
"repeating-linear-gradient(-45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 5px)",
}
}>
<HorizontalLines
hours={hours}
numberOfGridStopsPerCell={usersCellsStopsPerHour}
containerOffsetRef={containerOffset}
borderColor={borderColor}
/>
<VerticalLines days={days} borderColor={borderColor} />
<SchedulerColumns
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
{/*Loop over events per day */}
{days.map((day, i) => {
return (
<li key={day.toISOString()} className="relative" style={{ gridColumnStart: i + 1 }}>
<EventList day={day} />
{/* <BlockedList day={day} containerRef={container} /> */}
</li>
);
})}
</SchedulerColumns>
{/* Empty Cells */}
<SchedulerColumns
ref={schedulerGrid}
offsetHeight={containerOffset.current?.offsetHeight}
gridStopsPerDay={numberOfGridStopsPerDay}>
<>
{[...Array(days.length)].map((_, i) => (
<li
className="relative"
key={i}
style={{
gridColumnStart: i + 1,
gridRow: `1 / span ${numberOfGridStopsPerDay}`,
}}>
{/* While startDate < endDate: */}
{availableTimeslots ? (
<AvailableCellsForDay
key={days[i].toISOString()}
timezone={timezone}
day={days[i]}
startHour={startHour}
availableSlots={availableTimeslots}
/>
) : (
<>
{[...Array(numberOfGridStopsPerDay)].map((_, j) => {
const key = `${i}-${j}`;
return (
<EmptyCell
key={key}
day={days[i]}
gridCellIdx={j}
totalGridCells={numberOfGridStopsPerDay}
selectionLength={endHour - startHour}
startHour={startHour}
timezone={timezone}
/>
);
})}
</>
)}
</li>
))}
</>
</SchedulerColumns>
</div>
</div>
</div>
</div>
</div>
</MobileNotSupported>
);
}
export function Calendar(props: CalendarComponentProps) {
const storeRef = useRef<ReturnType<typeof createCalendarStore> | null>(null);
if (!storeRef.current) {
storeRef.current = createCalendarStore();
storeRef.current.getState().initState(props);
}
useEffect(() => {
if (storeRef.current) {
storeRef.current.getState().initState(props);
}
}, [props]);
return (
<CalendarStoreContext.Provider value={storeRef.current}>
<CalendarInner {...props} />
</CalendarStoreContext.Provider>
);
}
/** @todo Will be removed once we have mobile support */
const MobileNotSupported = ({ children }: { children: React.ReactNode }) => {
return (
<>
<div className="flex h-full flex-col items-center justify-center sm:hidden">
<h1 className="text-2xl font-bold">Mobile not supported yet </h1>
<p className="text-subtle">Please use a desktop browser to view this page</p>
</div>
<div className="hidden h-full sm:block">{children}</div>
</>
);
};
@@ -0,0 +1,115 @@
import React from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
type Props = {
showBorder: boolean;
borderColor: BorderColor;
days: dayjs.Dayjs[];
containerNavRef: React.RefObject<HTMLDivElement>;
};
export function DateValues({ showBorder, borderColor, days, containerNavRef }: Props) {
const { i18n } = useLocale();
const timezone = useCalendarStore((state) => state.timezone);
const showTimezone = useCalendarStore((state) => state.showTimezone ?? false);
const formatDate = (date: dayjs.Dayjs): string => {
return new Intl.DateTimeFormat(i18n.language, { weekday: "short" }).format(date.toDate());
};
const getTimezoneDisplay = () => {
if (!showTimezone || !timezone) return null;
try {
const timeRaw = dayjs().tz(timezone);
const utcOffsetInMinutes = timeRaw.utcOffset();
// Convert offset to decimal hours
const offsetInHours = Math.abs(utcOffsetInMinutes / 60);
const sign = utcOffsetInMinutes < 0 ? "-" : "+";
// If offset is 0, just return "GMT"
if (utcOffsetInMinutes === 0) {
return "GMT";
}
// Format as decimal (e.g., 1.5 for 1:30, 1 for 1:00)
const offsetFormatted = `${sign}${offsetInHours}`;
return `GMT ${offsetFormatted}`;
} catch {
// Fallback to showing the timezone name if formatting fails
return timezone.split("/").pop()?.replace(/_/g, " ") || timezone;
}
};
return (
<div
ref={containerNavRef}
className={classNames(
"bg-default dark:bg-cal-muted top-(--calendar-dates-sticky-offset,0px) z-80 sticky flex-none border-b",
borderColor === "subtle" ? "border-b-subtle" : "border-b-default",
showBorder && (borderColor === "subtle" ? "border-r-subtle border-r" : "border-r-default border-r")
)}>
<div className="text-subtle flex leading-6 sm:hidden" data-dayslength={days.length}>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<button
key={day.toString()}
type="button"
className="flex flex-1 flex-col items-center pb-3 pt-2">
{day.format("dd")}{" "}
<span
className={classNames(
"text-emphasis mt-1 flex h-8 w-8 items-center justify-center font-medium",
isToday && "bg-inverted text-inverted rounded-sm"
)}>
{day.format("D")}
</span>
</button>
);
})}
</div>
<div className="text-subtle -mr-px hidden auto-cols-fr leading-6 sm:flex">
<div
className={classNames(
"col-end-1 flex w-16 items-center justify-center",
showBorder &&
(borderColor === "subtle" ? "border-l-subtle border-l" : "border-l-default border-l")
)}>
{showTimezone && timezone && (
<span className="text-muted text-xs font-medium">{getTimezoneDisplay()}</span>
)}
</div>
{days.map((day) => {
const isToday = dayjs().isSame(day, "day");
return (
<div
key={day.toString()}
className={classNames(
"flex flex-1 items-center justify-center py-3 text-xs font-medium uppercase",
isToday && "text-default"
)}>
<span>
{formatDate(day)}{" "}
<span
className={classNames(
"items-center justify-center p-1",
isToday && "bg-brand-default text-brand ml-1 rounded-md"
)}>
{day.format("DD")}
</span>
</span>
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,129 @@
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { BlockedTimeCell } from "./BlockedTimeCell";
type Props = {
day: dayjs.Dayjs;
containerRef: React.RefObject<HTMLDivElement>;
};
function roundX(x: number, roundBy: number) {
return Math.round(x / roundBy) * roundBy;
}
type BlockedDayProps = {
startHour: number;
endHour: number;
day: dayjs.Dayjs;
};
function BlockedBeforeToday({ day, startHour, endHour }: BlockedDayProps) {
return (
<>
{day.isBefore(dayjs(), "day") && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`,
zIndex: 60,
height: `calc(${(endHour + 1 - startHour) * 60} * var(--one-minute-height))`, // Add 1 to endHour to include the last hour that we add to display the last vertical line
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
function BlockedToday({
day,
startHour,
gridCellsPerHour,
endHour,
}: BlockedDayProps & { gridCellsPerHour: number }) {
const dayStart = useMemo(() => day.startOf("day").hour(startHour), [day, startHour]);
const dayEnd = useMemo(() => day.startOf("day").hour(endHour), [day, endHour]);
const dayEndInMinutes = useMemo(() => dayEnd.diff(dayStart, "minutes"), [dayEnd, dayStart]);
let nowComparedToDayStart = useMemo(() => dayjs().diff(dayStart, "minutes"), [dayStart]);
if (nowComparedToDayStart > dayEndInMinutes) nowComparedToDayStart = dayEndInMinutes;
return (
<>
{day.isToday() && (
<div
key={day.format("YYYY-MM-DD")}
className="absolute z-40 w-full"
style={{
top: `var(--one-minute-height)`, // Still need this as this var takes into consideration the offset of the "AllDayEvents" bar
zIndex: 60,
height: `calc(${roundX(
nowComparedToDayStart,
60 / gridCellsPerHour
)} * var(--one-minute-height) - 2px)`, // We minus the border width to make it 🧹
}}>
<BlockedTimeCell />
</div>
)}
</>
);
}
export function BlockedList({ day }: Props) {
const { startHour, blockingDates, endHour, gridCellsPerHour } = useCalendarStore(
(state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
blockingDates: state.blockingDates,
gridCellsPerHour: state.gridCellsPerHour || 4,
}),
shallow
);
return (
<>
<BlockedBeforeToday day={day} startHour={startHour} endHour={endHour} />
<BlockedToday gridCellsPerHour={gridCellsPerHour} day={day} startHour={startHour} endHour={endHour} />
{blockingDates &&
blockingDates.map((event, i) => {
const dayStart = day.startOf("day").hour(startHour);
const blockingStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventStart = dayStart.isAfter(blockingStart) ? dayStart : blockingStart;
if (!eventStart.isSame(day, "day")) {
return null;
}
if (eventStart.isBefore(dayjs())) {
if (eventEnd.isBefore(dayjs())) {
return null;
}
}
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60;
return (
<div
key={`${eventStart.toISOString()}-${i}`}
className="absolute w-full"
style={{
zIndex: 60,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `calc(${eventDuration}*var(--one-minute-height))`,
}}>
<BlockedTimeCell />
</div>
);
})}
</>
);
}
@@ -0,0 +1,17 @@
import classNames from "@calcom/ui/classNames";
export function BlockedTimeCell() {
return (
<div
className={classNames(
"group absolute inset-0 flex h-full flex-col hover:cursor-not-allowed",
"[--disabled-gradient-background:#E5E7EB] [--disabled-gradient-foreground:#D1D5DB] dark:[--disabled-gradient-background:#262626] dark:[--disabled-gradient-foreground:#393939]"
)}
style={{
backgroundColor: "#D1D5DB",
background:
"repeating-linear-gradient( -45deg, var(--disabled-gradient-background), var(--disabled-gradient-background) 2.5px, var(--disabled-gradient-foreground) 2.5px, var(--disabled-gradient-foreground) 6.5px )",
}}
/>
);
}
@@ -0,0 +1,83 @@
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { useCallback, useEffect, useRef, useState } from "react";
function calculateMinutesFromStart(startHour: number, currentHour: number, currentMinute: number) {
const startMinute = startHour * 60;
const currentMinuteOfDay = currentHour * 60 + currentMinute;
return currentMinuteOfDay - startMinute;
}
export function CurrentTime({
timezone,
scrollToCurrentTime = true,
updateOnFocus = false,
}: {
timezone: string;
scrollToCurrentTime?: boolean;
updateOnFocus?: boolean;
}) {
const { timeFormat } = useTimePreferences();
const currentTimeRef = useRef<HTMLDivElement>(null);
const [scrolledIntoView, setScrolledIntoView] = useState(false);
const [currentTimePos, setCurrentTimePos] = useState<number | null>(null);
const { startHour, endHour } = useCalendarStore((state) => ({
startHour: state.startHour || 0,
endHour: state.endHour || 23,
}));
const updateCurrentTimePosition = useCallback(() => {
const currentDateTime = dayjs().tz(timezone);
const currentHour = currentDateTime.hour();
const currentMinute = currentDateTime.minute();
if (currentHour > endHour || currentHour < startHour) {
setCurrentTimePos(null);
return;
}
const minutesFromStart = calculateMinutesFromStart(startHour, currentHour, currentMinute);
setCurrentTimePos(minutesFromStart);
}, [timezone, startHour, endHour]);
useEffect(() => {
updateCurrentTimePosition();
if (!scrollToCurrentTime || !currentTimeRef.current || scrolledIntoView) return;
setTimeout(() => {
currentTimeRef?.current?.scrollIntoView({ block: "center" });
setScrolledIntoView(true);
}, 100);
}, [updateCurrentTimePosition, scrolledIntoView, scrollToCurrentTime]);
useEffect(() => {
if (!updateOnFocus) return;
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
updateCurrentTimePosition();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [updateOnFocus, updateCurrentTimePosition]);
return (
<div
ref={currentTimeRef}
className="absolute top-0 z-40 flex h-px items-center justify-center text-xs"
aria-hidden="true"
style={{
top: `calc(${currentTimePos}*var(--one-minute-height) + var(--calendar-offset-top))`,
zIndex: 70,
}}>
<div className="w-16 pr-2 text-right">{dayjs().tz(timezone).format(timeFormat)}</div>
<div className="bg-inverted h-3 w-px" />
<div className="bg-inverted h-px w-screen" />
</div>
);
}
@@ -0,0 +1,219 @@
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import classNames from "@calcom/ui/classNames";
import { OutOfOfficeInSlots } from "@calcom/web/modules/bookings/components/OutOfOfficeInSlots";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import type { CalendarAvailableTimeslots } from "@calcom/features/calendars/weeklyview/types/state";
import type { GridCellToDateProps } from "@calcom/features/calendars/weeklyview/utils";
import { gridCellToDateTime } from "@calcom/features/calendars/weeklyview/utils";
type EmptyCellProps = GridCellToDateProps & {
isDisabled?: boolean;
topOffsetMinutes?: number;
};
export function EmptyCell(props: EmptyCellProps) {
const cellToDate = gridCellToDateTime({
day: props.day,
gridCellIdx: props.gridCellIdx,
totalGridCells: props.totalGridCells,
selectionLength: props.selectionLength,
startHour: props.startHour,
timezone: props.timezone,
});
const minutesFromStart = (cellToDate.hour() - props.startHour) * 60 + cellToDate.minute();
return <Cell topOffsetMinutes={minutesFromStart} timeSlot={dayjs(cellToDate).tz(props.timezone)} />;
}
type AvailableCellProps = {
timezone: string;
availableSlots: CalendarAvailableTimeslots;
day: GridCellToDateProps["day"];
startHour: GridCellToDateProps["startHour"];
};
export function AvailableCellsForDay({ timezone, availableSlots, day, startHour }: AvailableCellProps) {
const date = dayjs(day);
const dateFormatted = date.format("YYYY-MM-DD");
const slotsForToday = availableSlots && availableSlots[dateFormatted];
const slots = useMemo(() => {
const calculatedSlots: {
slot: CalendarAvailableTimeslots[string][number];
topOffsetMinutes: number;
firstSlot?: CalendarAvailableTimeslots[string][number];
timezone?: string;
}[] = [];
// first and last slot for ooo to display range correctly in week view
let firstSlotIndex = -1;
let lastSlotIndex = -1;
let areAllSlotsAway = true;
let startEndTimeDuration = 0;
slotsForToday?.forEach((slot, index) => {
const startTime = dayjs(slot.start).tz(timezone);
const topOffsetMinutes = (startTime.hour() - startHour) * 60 + startTime.minute();
calculatedSlots.push({ slot, topOffsetMinutes });
if (!slot.away) {
areAllSlotsAway = false;
} else {
if (firstSlotIndex === -1) {
firstSlotIndex = index;
}
lastSlotIndex = index;
}
});
if (areAllSlotsAway && firstSlotIndex !== -1) {
const firstSlot = slotsForToday[firstSlotIndex];
const lastSlot = slotsForToday[lastSlotIndex];
startEndTimeDuration = dayjs(lastSlot.end).diff(dayjs(firstSlot.start), "minutes");
if (firstSlot.toUser == null && !firstSlot.showNotePublicly) {
return null;
}
// This will return null if all slots are away and the first slot has no user
return {
slots: calculatedSlots,
startEndTimeDuration,
firstSlot,
timezone,
};
}
return { slots: calculatedSlots, startEndTimeDuration };
}, [slotsForToday, startHour, timezone]);
if (slots === null) return null;
if (slots.startEndTimeDuration) {
const { firstSlot, startEndTimeDuration } = slots;
return (
<CustomCell
timeSlot={dayjs(firstSlot?.start).tz(slots.timezone)}
topOffsetMinutes={slots.slots[0]?.topOffsetMinutes}
startEndTimeDuration={startEndTimeDuration}>
<OutOfOfficeInSlots
fromUser={firstSlot?.fromUser}
toUser={firstSlot?.toUser}
reason={firstSlot?.reason}
emoji={firstSlot?.emoji}
notes={firstSlot?.notes}
showNotePublicly={firstSlot?.showNotePublicly}
borderDashed={false}
date={dateFormatted}
className="pb-0"
/>
</CustomCell>
);
}
return (
<>
{slots.slots.map((slot, index) => (
<Cell
key={index}
timeSlot={dayjs(slot.slot.start).tz(timezone)}
topOffsetMinutes={slot.topOffsetMinutes}
/>
))}
</>
);
}
type CellProps = {
isDisabled?: boolean;
topOffsetMinutes?: number;
timeSlot: Dayjs;
};
function Cell({ isDisabled, topOffsetMinutes, timeSlot }: CellProps) {
const { timeFormat } = useTimePreferences();
const { onEmptyCellClick, hoverEventDuration } = useCalendarStore(
(state) => ({
onEmptyCellClick: state.onEmptyCellClick,
hoverEventDuration: state.hoverEventDuration,
}),
shallow
);
return (
<div
className={classNames(
"group flex w-[calc(100%-1px)] items-center justify-center",
isDisabled && "pointer-events-none",
!isDisabled && "bg-default dark:bg-cal-muted",
topOffsetMinutes && "absolute"
)}
data-disabled={isDisabled}
data-slot={timeSlot.toISOString()}
data-testid="calendar-empty-cell"
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height))`,
overflow: "visible",
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
}}
onClick={() => {
onEmptyCellClick?.(timeSlot.toDate());
}}>
{!isDisabled && hoverEventDuration !== 0 && (
<div
className={classNames(
"bg-brand-default hover:bg-brand-default text-brand dark:border-emphasis absolute hidden rounded-[4px] p-[6px] text-xs font-semibold leading-5 group-hover:flex group-hover:cursor-pointer",
hoverEventDuration && hoverEventDuration > 15 && "items-start pt-3",
hoverEventDuration && hoverEventDuration < 15 && "items-center"
)}
style={{
height: `calc(${hoverEventDuration}*var(--one-minute-height) - 2px)`,
zIndex: 80,
// @TODO: This used to be 90% as per Sean's work. I think this was needed when
// multiple events are stacked next to each other. We might need to add this back later.
width: "calc(100% - 2px)",
}}>
<div className="text-ellipsis leading-0">{timeSlot.format(timeFormat)}</div>
</div>
)}
</div>
);
}
function CustomCell({
timeSlot,
children,
topOffsetMinutes,
startEndTimeDuration,
}: CellProps & { children: React.ReactNode; startEndTimeDuration?: number }) {
return (
<div
className={classNames(
"bg-default dark:bg-cal-muted group absolute z-65 flex w-[calc(100%-1px)] items-center justify-center"
)}
data-slot={timeSlot.toISOString()}
style={{
top: topOffsetMinutes ? `calc(${topOffsetMinutes}*var(--one-minute-height))` : undefined,
overflow: "visible",
}}>
<div
className={classNames(
"dark:border-emphasis bg-default dark:bg-cal-muted cursor-pointer rounded-[4px] p-[6px] text-xs font-semibold dark:text-white"
)}
style={{
height: `calc(${startEndTimeDuration}*var(--one-minute-height) - 2px)`,
width: "calc(100% - 2px)",
}}>
{children}
</div>
</div>
);
}
@@ -0,0 +1,163 @@
import dayjs from "@calcom/dayjs";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import type { BookingStatus } from "@calcom/prisma/enums";
import classNames from "@calcom/ui/classNames";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { cva } from "class-variance-authority";
type EventProps = {
event: CalendarEvent;
currentlySelectedEventId?: number;
eventDuration: number;
onEventClick?: (event: CalendarEvent) => void;
disabled?: boolean;
isHovered?: boolean;
};
const eventClasses = cva(
"group flex h-full w-full overflow-hidden rounded-[6px] px-[6px] text-xs leading-5 border-default font-medium",
{
variants: {
status: {
ACCEPTED: "bg-subtle hover:bg-emphasis text-emphasis border-[1px] border-default",
PENDING: "bg-subtle text-subtle border-[1px] border-dashed border-default",
REJECTED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
CANCELLED: "bg-subtle border-[1px] border-dashed text-subtle line-through",
AWAITING_HOST: "bg-subtle text-emphasis border-[1px] border-dashed border-default",
},
disabled: {
true: "hover:cursor-default",
false: "hover:cursor-pointer",
},
selected: {
true: "",
false: "",
},
borderOnly: {
true: "bg-transparent border-[1.5px] border-subtle border-dashed opacity-60",
false: "",
},
},
}
);
const STATUS_COLOR_MAP: Record<BookingStatus, string> = {
ACCEPTED: "bg-green-500",
PENDING: "bg-orange-500",
REJECTED: "bg-red-500",
CANCELLED: "bg-red-500",
AWAITING_HOST: "bg-blue-500",
};
// Maps booking status to color classes for the color bar
// Follows the same pattern as BookingDetailsSheet badge variants
const getStatusColorClass = (status?: BookingStatus): string | undefined => {
if (!status) return undefined;
return STATUS_COLOR_MAP[status];
};
export function Event({
event,
currentlySelectedEventId,
eventDuration,
disabled,
onEventClick,
isHovered = false,
}: EventProps) {
const selected = currentlySelectedEventId === event.id;
const { options } = event;
// Use custom color if provided, otherwise derive from status
const colorClass = !options?.color ? getStatusColorClass(options?.status) : undefined;
const Component = onEventClick ? "button" : "div";
const dayOfWeek = dayjs(event.start).day();
const tooltipSide = dayOfWeek >= 1 && dayOfWeek <= 4 ? "right" : "left";
const tooltipContent = (
<div className="flex min-w-[200px] max-w-[300px] flex-col gap-1 py-1">
<div className="flex items-start gap-2">
{(options?.color || colorClass) && (
<div
className={classNames("mt-1 h-3 w-1 shrink-0 rounded-sm", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className="flex-1">
<div className="font-semibold leading-tight">{event.title}</div>
{!event.options?.hideTime && (
<div className="text-inverted-muted mt-1 text-xs">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</div>
)}
{event.description && (
<div className="text-inverted-muted mt-1 text-xs leading-snug">{event.description}</div>
)}
{options?.status && options.status !== "ACCEPTED" && (
<div className="text-inverted-muted mt-1 text-xs capitalize">
{options.status.toLowerCase().replace("_", " ")}
</div>
)}
</div>
</div>
</div>
);
const displayType = eventDuration < 40 ? "single-line" : eventDuration < 45 ? "multi-line" : "full";
return (
<Tooltip content={tooltipContent} className="max-w-none" side={tooltipSide}>
<Component
data-booking-calendar-event="true"
onClick={() => onEventClick?.(event)}
{...(options?.bookingUid ? { "data-booking-uid": options.bookingUid } : {})}
className={classNames(
eventClasses({
status: options?.status,
disabled,
selected,
borderOnly: options?.borderOnly ?? false,
}),
options?.className,
(isHovered || selected) && "ring-brand-default shadow-lg ring-2 ring-offset-0"
)}
style={{
transition: "all 100ms ease-out",
}}>
{(options?.color || colorClass) && (
<div
className={classNames("-ml-1.5 mr-1.5 h-full w-[3px] shrink-0", colorClass)}
style={options?.color ? { backgroundColor: options.color } : undefined}></div>
)}
<div className={classNames("flex w-full", displayType !== "single-line" && "flex-col py-1")}>
{displayType === "single-line" && (
<div
className={classNames(
"flex w-full shrink-0 gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-left leading-4",
"items-center"
)}>
<span>{event.title}</span>
{!event.options?.hideTime && (
<p className="text-subtle mt-1 w-full whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
</div>
)}
{displayType !== "single-line" && (
<p className={classNames("shrink-0 whitespace-nowrap text-left leading-4")}>{event.title}</p>
)}
{displayType !== "single-line" && !event.options?.hideTime && (
<p className="text-subtle mt-1 whitespace-nowrap text-left text-[10px] leading-none">
{dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
</p>
)}
{displayType === "full" && event.description && (
<p className="text-subtle mt-1 text-left text-[10px] leading-none">{event.description}</p>
)}
</div>
</Component>
</Tooltip>
);
}
@@ -0,0 +1,136 @@
import { useEffect, useMemo, useState } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import classNames from "@calcom/ui/classNames";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
import { calculateEventLayouts, createLayoutMap } from "@calcom/features/calendars/weeklyview/utils/overlap";
import { Event } from "./Event";
type Props = {
day: dayjs.Dayjs;
};
export function EventList({ day }: Props) {
const { startHour, events, eventOnClick, selectedBookingUid } = useCalendarStore(
(state) => ({
startHour: state.startHour,
events: state.events,
eventOnClick: state.onEventClick,
selectedBookingUid: state.selectedBookingUid,
}),
shallow
);
const [hoveredEventId, setHoveredEventId] = useState<number | null>(null);
const dayEvents = useMemo(() => {
return events.filter((event) => {
return dayjs(event.start).isSame(day, "day") && !event.options?.allDay;
});
}, [events, day]);
const layoutMap = useMemo(() => {
const layouts = calculateEventLayouts(dayEvents);
return createLayoutMap(layouts);
}, [dayEvents]);
const eventCalculations = useMemo(() => {
return new Map(
dayEvents.map((event) => {
const eventStart = dayjs(event.start);
const eventEnd = dayjs(event.end);
const eventDuration = eventEnd.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60 + eventStart.minute();
return [
event.id,
{
eventStart,
eventDuration,
eventStartDiff,
},
];
})
);
}, [dayEvents, startHour]);
// Find which overlap group the hovered event belongs to
const hoveredEventLayout = hoveredEventId ? layoutMap.get(hoveredEventId) : null;
const hoveredGroupIndex = hoveredEventLayout?.groupIndex ?? null;
// Find the event ID that matches the selected booking UID (only for events on this day)
const selectedEventId = useMemo(() => {
if (!selectedBookingUid) return undefined;
const matchingEvent = dayEvents.find((event) => event.options?.bookingUid === selectedBookingUid);
return matchingEvent?.id;
}, [dayEvents, selectedBookingUid]);
// Scroll to the selected event when it changes
useEffect(() => {
if (selectedEventId === undefined) return;
// Use requestAnimationFrame to ensure the DOM has updated
requestAnimationFrame(() => {
const eventElement = document.querySelector(`[data-calendar-event-id="${selectedEventId}"]`);
if (eventElement) {
eventElement.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
});
}, [selectedEventId]);
return (
<>
{dayEvents.map((event) => {
const layout = layoutMap.get(event.id);
if (!layout) return null;
const calc = eventCalculations.get(event.id);
if (!calc) return null;
const { eventStart, eventDuration, eventStartDiff } = calc;
const isHovered = hoveredEventId === event.id;
const isSelected = selectedEventId === event.id;
const isInHoveredGroup = hoveredGroupIndex !== null && layout.groupIndex === hoveredGroupIndex;
const zIndex = isHovered || isSelected ? 79 : layout.baseZIndex;
return (
<div
key={`${event.id}-${eventStart.toISOString()}`}
className={classNames(
"absolute transition-all duration-100 ease-out",
event.options?.borderOnly && "pointer-events-none"
)}
data-testid={event.options?.["data-test-id"]}
data-calendar-event-id={event.id}
data-calendar-event-source={event.source}
onMouseEnter={() => setHoveredEventId(event.id)}
onMouseLeave={() => setHoveredEventId(null)}
style={{
left: `${layout.leftOffsetPercent}%`,
width: `${layout.widthPercent}%`,
zIndex,
top: `calc(${eventStartDiff}*var(--one-minute-height))`,
height: `max(15px, calc(${eventDuration}*var(--one-minute-height)))`,
transform: isHovered || isSelected ? "scale(1.02)" : "scale(1)",
opacity: hoveredGroupIndex !== null && !isHovered && isInHoveredGroup ? 0.6 : 1,
}}>
<Event
event={event}
eventDuration={eventDuration}
onEventClick={eventOnClick}
isHovered={isHovered}
currentlySelectedEventId={selectedEventId}
/>
</div>
);
})}
</>
);
}
@@ -0,0 +1 @@
export { Event } from "./Event";
@@ -0,0 +1,23 @@
import React from "react";
type Props = {
offsetHeight: number | undefined;
gridStopsPerDay: number;
children: React.ReactNode;
zIndex?: number;
};
export const SchedulerColumns = React.forwardRef<HTMLOListElement, Props>(function SchedulerColumns(
{ offsetHeight, gridStopsPerDay, children, zIndex },
ref
) {
return (
<ol
ref={ref}
className="scheduler-grid-row-template col-start-1 col-end-2 row-start-1 grid auto-cols-auto text-[0px] scheduler-wrapper"
style={{ marginTop: offsetHeight || "var(--gridDefaultSize)", zIndex }}
data-gridstopsperday={gridStopsPerDay}>
{children}
</ol>
);
});
@@ -0,0 +1,54 @@
import dayjs from "@calcom/dayjs";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
export function SchedulerHeading() {
const { startDate, endDate, handleDateChange } = useCalendarStore((state) => ({
startDate: dayjs(state.startDate),
endDate: dayjs(state.endDate),
handleDateChange: state.handleDateChange,
}));
return (
<header className="flex flex-none flex-col justify-between py-4 sm:flex-row sm:items-center">
<h1 className="text-emphasis text-xl font-semibold">
{startDate.format("MMM DD")}-{endDate.format("DD")}
<span className="text-subtle">,{startDate.format("YYYY")}</span>
</h1>
<div className="flex items-center space-x-2 rtl:space-x-reverse">
{/* TODO: Renable when we have daily/mobile support */}
{/* <ToggleGroup
options={[
{ label: "Daily", value: "day", disabled: false },
{ label: "Weekly", value: "week", disabled: isSm },
]}
defaultValue={view === "day" ? "day" : "week"}
/> */}
<ButtonGroup combined>
{/* TODO: i18n label with correct view */}
<Button
StartIcon="chevron-left"
variant="icon"
color="secondary"
aria-label="Previous Week"
onClick={() => {
handleDateChange("DECREMENT");
}}
/>
<Button
StartIcon="chevron-right"
variant="icon"
color="secondary"
aria-label="Next Week"
onClick={() => {
handleDateChange("INCREMENT");
}}
/>
</ButtonGroup>
</div>
</header>
);
}
@@ -0,0 +1 @@
export { SchedulerHeading } from "./SchedulerHeading";
@@ -0,0 +1,49 @@
import { useId } from "react";
import type dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import classNames from "@calcom/ui/classNames";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
export const HorizontalLines = ({
hours,
containerOffsetRef,
borderColor,
}: {
hours: dayjs.Dayjs[];
numberOfGridStopsPerCell: number;
containerOffsetRef: React.RefObject<HTMLDivElement>;
borderColor: BorderColor;
}) => {
const { timeFormat } = useTimePreferences();
// We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00)
const finalHour = hours[hours.length - 1].add(1, "hour").minute(0).format(timeFormat);
const id = useId();
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid divide-y",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
style={{
gridTemplateRows: `repeat(${hours.length}, minmax(var(--gridDefaultSize),1fr)`,
}}>
<div className="row-end-1 h-(--calendar-offset-top) " ref={containerOffsetRef} />
{hours.map((hour) => (
<div key={`${id}-${hour.get("hour")}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{/* We need to force the minute to zero, because otherwise in ex GMT+5.5, it would show :30 minute times (but at the positino of :00) */}
{hour.minute(0).format(timeFormat)}
</div>
</div>
))}
<div key={`${id}-${finalHour}`}>
<div className="text-muted sticky left-0 z-20 -ml-14 -mt-2.5 w-14 pr-2 text-right text-xs leading-5 rtl:-mr-14">
{finalHour}
</div>
</div>
</div>
);
};
@@ -0,0 +1 @@
export { Calendar } from "./Calendar";
@@ -0,0 +1,21 @@
import classNames from "@calcom/ui/classNames";
export const Spinner = ({ className }: { className?: string }) => (
<div
className={classNames(
"fixed left-[calc(50%+calc(var(--booker-meta-width,0px)/2))] top-1/2 z-80 h-10 w-10 -translate-x-1/2 -translate-y-1/2",
className
)}>
<svg className="h-10 w-10" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
className="fill-default"
d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
opacity=".25"
/>
<path
className="animate-spinning fill-emphasis origin-center"
d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
/>
</svg>
</div>
);
@@ -0,0 +1,40 @@
import type dayjs from "@calcom/dayjs";
import classNames from "@calcom/ui/classNames";
import type { BorderColor } from "@calcom/features/calendars/weeklyview/types/common";
export const VerticalLines = ({ days, borderColor }: { days: dayjs.Dayjs[]; borderColor: BorderColor }) => {
const isRTL = () => {
let userLanguage = "en"; // Default to 'en' if navigator is not defined
if (typeof window !== "undefined" && typeof navigator !== "undefined") {
const userLocale = navigator.language;
userLanguage = new Intl.Locale(userLocale).language;
}
return ["ar", "he", "fa", "ur"].includes(userLanguage);
};
const direction = isRTL() ? "rtl" : "ltr";
return (
<div
className={classNames(
"pointer-events-none relative z-60 col-start-1 col-end-2 row-start-1 grid auto-cols-auto grid-rows-1 divide-x",
borderColor === "subtle" ? "divide-subtle" : "divide-default"
)}
dir={direction}
style={{
direction: direction,
}}>
{days.map((_, i) => (
<div
key={`Key_vertical_${i}`}
className="row-span-full"
style={{
gridColumnStart: isRTL() ? days.length - i : i + 1,
}}
/>
))}
</div>
);
};
@@ -1,26 +1,25 @@
"use client";
import type { SortingState, OnChangeFn, VisibilityState, ColumnSizingState } from "@tanstack/react-table";
import { createContext, useMemo } from "react";
import {
DataTableStateProvider,
DataTableSegmentProvider,
DataTableFiltersProvider,
useDataTableState,
useDataTableSegment,
useDataTableFilters,
} from "./contexts";
import type { ActiveFiltersValidatorState } from "./contexts";
import type {
FilterValue,
FilterSegmentOutput,
SystemFilterSegment,
CombinedFilterSegment,
SegmentIdentifier,
ActiveFilters,
CombinedFilterSegment,
FilterSegmentOutput,
FilterValue,
SegmentIdentifier,
SystemFilterSegment,
UseSegments,
} from "@calcom/features/data-table/lib/types";
import type { ColumnSizingState, OnChangeFn, SortingState, VisibilityState } from "@tanstack/react-table";
import { createContext, useMemo } from "react";
import type { ActiveFiltersValidatorState } from "./contexts";
import {
DataTableFiltersProvider,
DataTableSegmentProvider,
DataTableStateProvider,
useDataTableFilters,
useDataTableSegment,
useDataTableState,
} from "./contexts";
export type { ActiveFiltersValidatorState };
export type { ActiveFiltersValidator } from "./contexts";
@@ -1,30 +1,27 @@
"use client";
import type { Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import type { Table as ReactTableType, Header, HeaderGroup } from "@tanstack/react-table";
import { useVirtualizer, type Virtualizer, type VirtualItem } from "@tanstack/react-virtual";
import kebabCase from "lodash/kebabCase";
import { useEffect, useState, memo, useMemo } from "react";
import type { SeparatorRow } from "@calcom/features/data-table/lib/separator";
import { isSeparatorRow } from "@calcom/features/data-table/lib/separator";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Command, CommandList, CommandItem } from "@calcom/ui/components/command";
import { ArrowDownIcon, ArrowUpIcon, CheckIcon, ChevronsUpDownIcon, EyeOffIcon } from "@coss/ui/icons";
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
import { Command, CommandItem, CommandList } from "@calcom/ui/components/command";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import {
TableNew,
TableBody,
TableCell,
TableHead,
TableHeader,
TableNew,
TableRow,
} from "@calcom/ui/components/table";
import { useColumnSizingVars } from "~/data-table/hooks/useColumnSizingVars";
import { ArrowDownIcon, ArrowUpIcon, CheckIcon, ChevronsUpDownIcon, EyeOffIcon } from "@coss/ui/icons";
import type { Header, HeaderGroup, Table as ReactTableType, Row } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import { useVirtualizer, type VirtualItem, type Virtualizer } from "@tanstack/react-virtual";
import kebabCase from "lodash/kebabCase";
import { memo, useEffect, useMemo, useState } from "react";
import { useColumnResizing } from "~/data-table/hooks/useColumnResizing";
import type { SeparatorRow } from "@calcom/features/data-table/lib/separator";
import { isSeparatorRow } from "@calcom/features/data-table/lib/separator";
import { useColumnSizingVars } from "~/data-table/hooks/useColumnSizingVars";
export type DataTablePropsFromWrapper<TData> = {
table: ReactTableType<TData>;
@@ -1,9 +1,7 @@
"use client";
import { type Table } from "@tanstack/react-table";
import { Pagination } from "@calcom/ui/components/pagination";
import type { Table } from "@tanstack/react-table";
import { useDataTable } from "~/data-table/hooks";
interface DataTablePaginationProps<TData> {
@@ -1,15 +1,12 @@
"use client";
import type { Table } from "@tanstack/react-table";
import { forwardRef, useEffect } from "react";
import type { ComponentPropsWithoutRef } from "react";
import { useState, type Ref, type ChangeEvent } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button, type ButtonProps } from "@calcom/ui/components/button";
import { FilterSearchField } from "@calcom/ui/components/form";
import type { Table } from "@tanstack/react-table";
import type { ComponentPropsWithoutRef } from "react";
import { type ChangeEvent, forwardRef, type Ref, useEffect, useState } from "react";
import { useColumnFilters, useDataTable } from "~/data-table/hooks";
interface DataTableToolbarProps extends ComponentPropsWithoutRef<"div"> {
@@ -1,9 +1,8 @@
"use client";
import { type Table } from "@tanstack/react-table";
import { useDataTable, useFilterableColumns } from "~/data-table/hooks";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import type { Table } from "@tanstack/react-table";
import { useDataTable, useFilterableColumns } from "~/data-table/hooks";
import { DateRangeFilter } from "./DateRangeFilter";
import { FilterPopover } from "./FilterPopover";
@@ -1,16 +1,14 @@
"use client";
import { type Table } from "@tanstack/react-table";
import startCase from "lodash/startCase";
import { forwardRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Command, CommandInput, CommandList, CommandEmpty, CommandItem } from "@calcom/ui/components/command";
import { EyeOffIcon, PlusIcon } from "@coss/ui/icons";
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@calcom/ui/components/command";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { EyeOffIcon, PlusIcon } from "@coss/ui/icons";
import type { Table } from "@tanstack/react-table";
import startCase from "lodash/startCase";
import { forwardRef, useState } from "react";
import { useDataTable, useFilterableColumns } from "~/data-table/hooks";
export interface AddFilterButtonProps<TData> {
@@ -1,28 +1,26 @@
"use client";
import { useMemo } from "react";
import type {
FilterableColumn as _FilterableColumn,
FacetedValue,
FilterValueSchema,
} from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { FilterType } from "@calcom/types/data-table";
import classNames from "@calcom/ui/classNames";
import { buttonClasses } from "@calcom/ui/components/button";
import {
Command,
CommandInput,
CommandList,
CommandEmpty,
CommandItem,
CommandSeparator,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@calcom/ui/components/command";
import { CheckIcon } from "@coss/ui/icons";
import { useMemo } from "react";
import { useDataTable, useFilterValue } from "~/data-table/hooks";
import type {
FacetedValue,
FilterableColumn as _FilterableColumn,
FilterValueSchema,
} from "@calcom/features/data-table/lib/types";
import type { FilterType } from "@calcom/types/data-table";
type FilterableColumn = Extract<_FilterableColumn, { type: Extract<FilterType, "ms" | "ss"> }>;
@@ -1,8 +1,7 @@
import { type Column, getCoreRowModel, type Table, useReactTable } from "@tanstack/react-table";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useEffect, useMemo } from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { vi } from "vitest";
import { useReactTable, getCoreRowModel, type Table, type Column } from "@tanstack/react-table";
import { ColumnVisibilityButton } from "./ColumnVisibilityButton";
let tableRef: Table<{ a: number; b: number; c: number }> | null = null;
@@ -1,23 +1,21 @@
"use client";
import { type Table } from "@tanstack/react-table";
import { forwardRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { type ButtonProps, Button, buttonClasses } from "@calcom/ui/components/button";
import { Button, type ButtonProps, buttonClasses } from "@calcom/ui/components/button";
import {
Command,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@calcom/ui/components/command";
import { Popover, PopoverTrigger, PopoverContent } from "@calcom/ui/components/popover";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import { CheckIcon } from "@coss/ui/icons";
import type { Table } from "@tanstack/react-table";
import { forwardRef, useState } from "react";
export interface ColumnVisiblityProps<TData> {
table: Table<TData>;
@@ -1,39 +1,37 @@
import { format } from "date-fns";
import type { Dayjs } from "dayjs";
import { useState, useEffect, useCallback } from "react";
import dayjs from "@calcom/dayjs";
import {
CUSTOM_PRESET,
CUSTOM_PRESET_VALUE,
DEFAULT_PRESET,
getCompatiblePresets,
getDateRangeFromPreset,
getDefaultEndDate,
getDefaultStartDate,
type PresetOption,
} from "@calcom/features/data-table/lib/dateRange";
import { preserveLocalTime } from "@calcom/features/data-table/lib/preserveLocalTime";
import type { DateRangeFilterOptions, FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType, ZDateRangeFilterValue } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
import type { FilterType } from "@calcom/types/data-table";
import classNames from "@calcom/ui/classNames";
import { Badge } from "@calcom/ui/components/badge";
import { Button, buttonClasses } from "@calcom/ui/components/button";
import {
Command,
CommandList,
CommandItem,
CommandGroup,
CommandItem,
CommandList,
CommandSeparator,
} from "@calcom/ui/components/command";
import { DateRangePicker } from "@calcom/ui/components/form";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import { CheckIcon } from "@coss/ui/icons";
import { format } from "date-fns";
import type { Dayjs } from "dayjs";
import { useCallback, useEffect, useState } from "react";
import { useDataTable, useFilterValue } from "~/data-table/hooks";
import {
CUSTOM_PRESET,
CUSTOM_PRESET_VALUE,
DEFAULT_PRESET,
getDefaultStartDate,
getDefaultEndDate,
getDateRangeFromPreset,
getCompatiblePresets,
type PresetOption,
} from "@calcom/features/data-table/lib/dateRange";
import { preserveLocalTime } from "@calcom/features/data-table/lib/preserveLocalTime";
import type { FilterableColumn, DateRangeFilterOptions } from "@calcom/features/data-table/lib/types";
import { ZDateRangeFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import type { FilterType } from "@calcom/types/data-table";
import { useFilterPopoverOpen } from "./useFilterPopoverOpen";
type DateRangeFilterProps = {
@@ -1,7 +1,6 @@
"use client";
import { type Table } from "@tanstack/react-table";
import type { Table } from "@tanstack/react-table";
import { useDisplayedFilterCount } from "~/data-table/hooks";
import { ActiveFilters } from "./ActiveFilters";
import { AddFilterButton } from "./AddFilterButton";
@@ -1,24 +1,22 @@
import startCase from "lodash/startCase";
import {
ColumnFilterType,
type FilterableColumn,
type FilterValue,
ZFilterValue,
} from "@calcom/features/data-table/lib/types";
import {
isMultiSelectFilterValue,
isNumberFilterValue,
isSingleSelectFilterValue,
isTextFilterValue,
} from "@calcom/features/data-table/lib/utils";
import type { FilterType } from "@calcom/types/data-table";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import type { IconName } from "@calcom/ui/components/icon";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import startCase from "lodash/startCase";
import { useFilterValue } from "~/data-table/hooks";
import {
type FilterableColumn,
type FilterValue,
ZFilterValue,
ColumnFilterType,
} from "@calcom/features/data-table/lib/types";
import {
isSingleSelectFilterValue,
isMultiSelectFilterValue,
isTextFilterValue,
isNumberFilterValue,
} from "@calcom/features/data-table/lib/utils";
import { FilterOptions } from "./FilterOptions";
import { useFilterPopoverOpen } from "./useFilterPopoverOpen";
import { numberFilterOperatorOptions, useTextFilterOperatorOptions } from "./utils";
@@ -1,9 +1,9 @@
"use client";
import { useDataTable } from "~/data-table/hooks";
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ZMultiSelectFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType, ZMultiSelectFilterValue } from "@calcom/features/data-table/lib/types";
import type { FilterType } from "@calcom/types/data-table";
import { useDataTable } from "~/data-table/hooks";
import { BaseSelectFilterOptions } from "./BaseSelectFilterOptions";
export type MultiSelectFilterOptionsProps = {
@@ -1,15 +1,13 @@
"use client";
import { useForm, Controller } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Form, Select, NumberInput } from "@calcom/ui/components/form";
import { useFilterValue, useDataTable } from "~/data-table/hooks";
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ZNumberFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType, ZNumberFilterValue } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { FilterType } from "@calcom/types/data-table";
import { Button } from "@calcom/ui/components/button";
import { Form, NumberInput, Select } from "@calcom/ui/components/form";
import { Controller, useForm } from "react-hook-form";
import { useDataTable, useFilterValue } from "~/data-table/hooks";
import { numberFilterOperatorOptions } from "./utils";
export type NumberFilterOptionsProps = {
@@ -1,10 +1,9 @@
"use client";
import type { FilterType } from "@calcom/types/data-table";
import { useDataTable } from "~/data-table/hooks";
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ZSingleSelectFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType, ZSingleSelectFilterValue } from "@calcom/features/data-table/lib/types";
import type { FilterType } from "@calcom/types/data-table";
import { useDataTable } from "~/data-table/hooks";
import { BaseSelectFilterOptions } from "./BaseSelectFilterOptions";
export type SingleSelectFilterOptionsProps = {
@@ -1,15 +1,13 @@
"use client";
import { useForm, Controller } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Form, Select, Input } from "@calcom/ui/components/form";
import { useFilterValue, useDataTable } from "~/data-table/hooks";
import type { FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ZTextFilterValue, ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType, ZTextFilterValue } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { FilterType } from "@calcom/types/data-table";
import { Button } from "@calcom/ui/components/button";
import { Form, Input, Select } from "@calcom/ui/components/form";
import { Controller, useForm } from "react-hook-form";
import { useDataTable, useFilterValue } from "~/data-table/hooks";
import { useTextFilterOperatorOptions } from "./utils";
export type TextFilterOptionsProps = {
@@ -1,5 +1,4 @@
import { useState, useEffect, useCallback } from "react";
import { useCallback, useEffect, useState } from "react";
import { useDataTable } from "~/data-table/hooks";
export function useFilterPopoverOpen(columnId: string) {
@@ -1,7 +1,6 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { type TextFilterOperator, textFilterOperators } from "@calcom/features/data-table/lib/types";
import type { TextFilterOperatorOption, NumberFilterOperatorOption } from "./types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { NumberFilterOperatorOption, TextFilterOperatorOption } from "./types";
export const numberFilterOperatorOptions: NumberFilterOperatorOption[] = [
{ value: "eq", label: "=" },
@@ -1,9 +1,9 @@
export { DataTableToolbar } from "./DataTableToolbar";
export { DataTableSelectionBar } from "./DataTableSelectionBar";
export { DataTablePagination } from "./DataTablePagination";
export * from "./filters";
export { DataTable } from "./DataTable";
export { DataTableSkeleton } from "./DataTableSkeleton";
export { DataTableWrapper } from "./DataTableWrapper";
export type { DataTableProps } from "./DataTable";
export { DataTable } from "./DataTable";
export { DataTablePagination } from "./DataTablePagination";
export { DataTableSelectionBar } from "./DataTableSelectionBar";
export { DataTableSkeleton } from "./DataTableSkeleton";
export { DataTableToolbar } from "./DataTableToolbar";
export { DataTableWrapper } from "./DataTableWrapper";
export * from "./filters";
export { DataTableSegment } from "./segment";
@@ -1,10 +1,9 @@
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Dialog, ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { ConfirmationDialogContent, Dialog } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import { useDataTable } from "~/data-table/hooks";
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
export function DeleteSegmentDialog({
segment,
@@ -17,23 +16,12 @@ export function DeleteSegmentDialog({
const utils = trpc.useUtils();
const { segmentId, setSegmentId } = useDataTable();
const { mutate: deleteSegment, isPending } = trpc.viewer.filterSegments.delete.useMutation({
onSuccess: ({ id }) => {
utils.viewer.filterSegments.list.invalidate();
showToast(t("filter_segment_deleted"), "success");
if (segmentId && segmentId.type === "user" && segmentId.id === id) {
setSegmentId(null);
}
onClose();
},
onError: () => {
showToast(t("error_deleting_filter_segment"), "error");
},
});
const deleteSegment = { mutate: (_args: Record<string, unknown>) => {}, isPending: false };
const isPending = deleteSegment.isPending;
const handleDelete = () => {
if (!segment) return;
deleteSegment({ id: segment.id });
deleteSegment.mutate({ id: segment.id });
};
return (
@@ -1,16 +1,14 @@
import { useSession } from "next-auth/react";
import { useForm } from "react-hook-form";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import type { CombinedFilterSegment } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { Form, TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import { useSession } from "next-auth/react";
import { useForm } from "react-hook-form";
import { useDataTable } from "~/data-table/hooks";
import type { CombinedFilterSegment } from "@calcom/features/data-table/lib/types";
type FormValues = {
name: string;
@@ -34,17 +32,8 @@ export function DuplicateSegmentDialog({
const session = useSession();
const isAdminOrOwner = checkAdminOrOwner(session.data?.user?.org?.role);
const { mutate: createSegment, isPending } = trpc.viewer.filterSegments.create.useMutation({
onSuccess: ({ id }) => {
utils.viewer.filterSegments.list.invalidate();
showToast(t("filter_segment_duplicated"), "success");
setSegmentId({ id, type: "user" });
onClose();
},
onError: () => {
showToast(t("error_duplicating_filter_segment"), "error");
},
});
const createSegment = { mutate: (_args: Record<string, unknown>) => {}, isPending: false };
const isPending = createSegment.isPending;
const handleSubmit = (data: FormValues) => {
if (!segment) {
@@ -53,14 +42,14 @@ export function DuplicateSegmentDialog({
if (segment.type === "user") {
const { type: _type, id: _id, name: _name, team: _team, teamId, ...rest } = segment;
if (segment.scope === "TEAM" && isAdminOrOwner) {
createSegment({
createSegment.mutate({
...rest,
teamId: teamId ?? 0,
scope: "TEAM",
name: data.name,
});
} else {
createSegment({
createSegment.mutate({
...rest,
scope: "USER",
name: data.name,
@@ -68,7 +57,7 @@ export function DuplicateSegmentDialog({
}
} else if (segment.type === "system") {
const { type: _type, ...rest } = segment;
createSegment({
createSegment.mutate({
...rest,
scope: "USER",
name: data.name,
@@ -1,13 +1,11 @@
import { useForm } from "react-hook-form";
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { Form, TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import type { FilterSegmentOutput } from "@calcom/features/data-table/lib/types";
import { useForm } from "react-hook-form";
type FormValues = {
name: string;
@@ -28,23 +26,15 @@ export function RenameSegmentDialog({
});
const utils = trpc.useUtils();
const { mutate: updateSegment, isPending } = trpc.viewer.filterSegments.update.useMutation({
onSuccess: () => {
utils.viewer.filterSegments.list.invalidate();
showToast(t("filter_segment_updated"), "success");
onClose();
},
onError: () => {
showToast(t("error_updating_filter_segment"), "error");
},
});
const updateSegment = { mutate: (_args: Record<string, unknown>) => {}, isPending: false };
const isPending = updateSegment.isPending;
const handleSubmit = (data: FormValues) => {
if (!segment) {
return;
}
if (segment.scope === "TEAM") {
updateSegment({
updateSegment.mutate({
...segment,
scope: "TEAM",
teamId: segment.teamId ?? 0,
@@ -52,7 +42,7 @@ export function RenameSegmentDialog({
});
return;
}
updateSegment({
updateSegment.mutate({
...segment,
scope: "USER",
name: data.name,
@@ -1,11 +1,6 @@
import { useSession } from "next-auth/react";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import posthog from "posthog-js";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { type FilterSegmentScope } from "@calcom/prisma/enums";
import type { FilterSegmentScope } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import {
@@ -16,9 +11,12 @@ import {
DialogTrigger,
} from "@calcom/ui/components/dialog";
import { Form, Input, Label, Select, Switch } from "@calcom/ui/components/form";
import { RadioGroup, RadioField } from "@calcom/ui/components/radio";
import { RadioField, RadioGroup } from "@calcom/ui/components/radio";
import { showToast } from "@calcom/ui/components/toast";
import { useSession } from "next-auth/react";
import posthog from "posthog-js";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useDataTable } from "~/data-table/hooks";
interface FormValues {
@@ -28,6 +26,16 @@ interface FormValues {
}
export function SaveFilterSegmentButton() {
const createSegmentMutation = {
mutate: (_args: Record<string, unknown>) => {},
mutateAsync: async (_args: Record<string, unknown>) => ({ id: "" }),
};
const updateSegmentMutation = {
mutate: (_args: Record<string, unknown>) => {},
mutateAsync: async (_args: Record<string, unknown>) => ({}),
};
const createSegment = (args: Record<string, unknown>) => createSegmentMutation.mutate(args);
const updateSegment = (args: Record<string, unknown>) => updateSegmentMutation.mutate(args);
const { t } = useLocale();
const utils = trpc.useUtils();
const [isOpen, setIsOpen] = useState(false);
@@ -70,30 +78,7 @@ export function SaveFilterSegmentButton() {
setSaveMode(selectedSegment && selectedSegment.type === "user" ? "update" : "create");
}, [selectedSegment, isOpen]);
const { data: teams } = trpc.viewer.teams.list.useQuery();
const { mutate: createSegment } = trpc.viewer.filterSegments.create.useMutation({
onSuccess: (segment) => {
utils.viewer.filterSegments.list.invalidate();
showToast(t("filter_segment_saved"), "success");
setSegmentId({ id: segment.id, type: "user" }, { type: "user", ...segment });
setIsOpen(false);
},
onError: () => {
showToast(t("error_saving_filter_segment"), "error");
},
});
const { mutate: updateSegment } = trpc.viewer.filterSegments.update.useMutation({
onSuccess: () => {
utils.viewer.filterSegments.list.invalidate();
showToast(t("filter_segment_updated"), "success");
setIsOpen(false);
},
onError: () => {
showToast(t("error_updating_filter_segment"), "error");
},
});
const teams = null as { id: number; name: string; slug: string | null }[] | null;
const onSubmit = (values: FormValues) => {
if (isTeamSegment && !selectedTeamId) {
@@ -1,9 +1,8 @@
"use client";
import type { ActiveFilters, FilterValue } from "@calcom/features/data-table/lib/types";
import debounce from "lodash/debounce";
import { createContext, useContext, useCallback, useMemo, useEffect } from "react";
import type { FilterValue, ActiveFilters } from "@calcom/features/data-table/lib/types";
import { createContext, useCallback, useContext, useEffect, useMemo } from "react";
import { useDataTableSegment } from "./DataTableSegmentContext";
import { useDataTableState } from "./DataTableStateContext";
@@ -1,16 +1,15 @@
"use client";
import { createContext, useContext, useState, useCallback, useEffect, useRef, useMemo } from "react";
import { useSegmentsNoop } from "../hooks/useSegmentsNoop";
import type {
FilterSegmentOutput,
SystemFilterSegment,
CombinedFilterSegment,
FilterSegmentOutput,
SegmentIdentifier,
SystemFilterSegment,
UseSegments,
} from "@calcom/features/data-table/lib/types";
import { SYSTEM_SEGMENT_PREFIX } from "@calcom/features/data-table/lib/types";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useSegmentsNoop } from "../hooks/useSegmentsNoop";
import { useDataTableState } from "./DataTableStateContext";
export type DataTableSegmentContextType = {
@@ -1,24 +1,22 @@
"use client";
import type { SortingState, OnChangeFn, VisibilityState, ColumnSizingState } from "@tanstack/react-table";
import { useQueryState } from "nuqs";
import { createContext, useContext, useRef, useMemo } from "react";
import { useElementByClassName } from "@calcom/lib/hooks/useElementByClassName";
import {
activeFiltersParser,
sortingParser,
columnVisibilityParser,
columnSizingParser,
segmentIdParser,
columnVisibilityParser,
DEFAULT_PAGE_SIZE,
pageIndexParser,
pageSizeParser,
searchTermParser,
DEFAULT_PAGE_SIZE,
segmentIdParser,
sortingParser,
} from "@calcom/features/data-table/lib/parsers";
import type { ActiveFilters, SegmentIdentifier } from "@calcom/features/data-table/lib/types";
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { useElementByClassName } from "@calcom/lib/hooks/useElementByClassName";
import type { ColumnSizingState, OnChangeFn, SortingState, VisibilityState } from "@tanstack/react-table";
import { useQueryState } from "nuqs";
import { createContext, useContext, useMemo, useRef } from "react";
export type ActiveFiltersValidator = (filters: ActiveFilters) => ActiveFilters;
+15 -17
View File
@@ -1,22 +1,20 @@
export {
DataTableStateContext,
DataTableStateProvider,
useDataTableState,
type DataTableStateContextType,
type ActiveFiltersValidator,
type ActiveFiltersValidatorState,
} from "./DataTableStateContext";
export {
DataTableSegmentContext,
DataTableSegmentProvider,
useDataTableSegment,
type DataTableSegmentContextType,
} from "./DataTableSegmentContext";
export {
DataTableFiltersContext,
type DataTableFiltersContextType,
DataTableFiltersProvider,
useDataTableFilters,
type DataTableFiltersContextType,
} from "./DataTableFiltersContext";
export {
DataTableSegmentContext,
type DataTableSegmentContextType,
DataTableSegmentProvider,
useDataTableSegment,
} from "./DataTableSegmentContext";
export {
type ActiveFiltersValidator,
type ActiveFiltersValidatorState,
DataTableStateContext,
type DataTableStateContextType,
DataTableStateProvider,
useDataTableState,
} from "./DataTableStateContext";
+5 -5
View File
@@ -1,8 +1,8 @@
export * from "./useDebouncedWidth";
export * from "./useFetchMoreOnBottomReached";
export * from "./useColumnSizingVars";
export * from "./useFilterValue";
export * from "./useColumnFilters";
export * from "./useColumnSizingVars";
export * from "./useDataTable";
export * from "./useFilterableColumns";
export * from "./useDebouncedWidth";
export * from "./useDisplayedFilterCount";
export * from "./useFetchMoreOnBottomReached";
export * from "./useFilterableColumns";
export * from "./useFilterValue";
@@ -1,11 +1,10 @@
"use client";
import type { Header, Table, ColumnSizingState } from "@tanstack/react-table";
import type { ColumnSizingState, Header, Table } from "@tanstack/react-table";
// eslint-disable-next-line no-restricted-imports
import debounce from "lodash/debounce";
import { useCallback, useEffect, useRef, useMemo } from "react";
import { useDebouncedWidth, useDataTable } from ".";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useDataTable, useDebouncedWidth } from ".";
type UseColumnResizingProps<TData> = {
enabled: boolean;
@@ -1,12 +1,11 @@
"use client";
import { type Table } from "@tanstack/react-table";
// eslint-disable-next-line no-restricted-imports
import { useMemo } from "react";
import type { FilterableColumn, FacetedValue } from "@calcom/features/data-table/lib/types";
import type { FacetedValue, FilterableColumn } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { convertMapToFacetedValues } from "@calcom/features/data-table/lib/utils";
import type { Table } from "@tanstack/react-table";
// eslint-disable-next-line no-restricted-imports
import { useMemo } from "react";
export function useFilterableColumns<TData>(table: Table<TData>) {
const columns = useMemo(
@@ -1,21 +1,18 @@
import { recalculateDateRange } from "@calcom/features/data-table/lib/dateRange";
import {
type SegmentIdentifier,
SYSTEM_SEGMENT_PREFIX,
type UseSegments,
} from "@calcom/features/data-table/lib/types";
import { isDateRangeFilterValue } from "@calcom/features/data-table/lib/utils";
import { useMemo } from "react";
import { trpc } from "@calcom/trpc/react";
import { recalculateDateRange } from "@calcom/features/data-table/lib/dateRange";
import { type UseSegments, SYSTEM_SEGMENT_PREFIX } from "@calcom/features/data-table/lib/types";
import { isDateRangeFilterValue } from "@calcom/features/data-table/lib/utils";
export const useSegments: UseSegments = ({ tableIdentifier, providedSegments, systemSegments }) => {
const { data: rawSegments, isSuccess } = trpc.viewer.filterSegments.list.useQuery(
{
tableIdentifier,
},
{
enabled: !providedSegments, // Only fetch if segments are not provided
}
);
const { mutate: setPreference } = trpc.viewer.filterSegments.setPreference.useMutation();
const rawSegments = providedSegments
? { segments: providedSegments, preferredSegmentId: null as SegmentIdentifier | null }
: undefined;
const isSuccess = Boolean(providedSegments);
const setPreference = (_args: { tableIdentifier: string; segmentId: SegmentIdentifier | null }) => {};
const preferredSegmentId = useMemo(() => rawSegments?.preferredSegmentId || null, [rawSegments]);
@@ -1,7 +1,7 @@
// eslint-disable-next-line no-restricted-imports
import { noop } from "lodash";
import { type UseSegments } from "@calcom/features/data-table/lib/types";
import type { UseSegments } from "@calcom/features/data-table/lib/types";
import { noop } from "lodash";
export const useSegmentsNoop: UseSegments = ({}) => {
return {
Loaded 100 of 4080 files, more files were not shown because too many files have changed in this diff. Show more