import { TrashIcon } from "@heroicons/react/solid"; import crypto from "crypto"; import { GetServerSidePropsContext } from "next"; import { signOut } from "next-auth/react"; import { useRouter } from "next/router"; import { ComponentProps, FormEvent, RefObject, useEffect, useMemo, useRef, useState } from "react"; import showToast from "@calcom/lib/notification"; import { Alert } from "@calcom/ui/Alert"; import Button from "@calcom/ui/Button"; import { Dialog, DialogTrigger } from "@calcom/ui/Dialog"; import { TextField } from "@calcom/ui/form/fields"; import { withQuery } from "@lib/QueryCell"; import { asStringOrNull, asStringOrUndefined } from "@lib/asStringOrNull"; import { getSession } from "@lib/auth"; import { nameOfDay } from "@lib/core/i18n/weekday"; import { useLocale } from "@lib/hooks/useLocale"; import { isBrandingHidden } from "@lib/isBrandingHidden"; import prisma from "@lib/prisma"; import { trpc } from "@lib/trpc"; import { inferSSRProps } from "@lib/types/inferSSRProps"; import ImageUploader from "@components/ImageUploader"; import SettingsShell from "@components/SettingsShell"; import Shell from "@components/Shell"; import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent"; import Avatar from "@components/ui/Avatar"; import Badge from "@components/ui/Badge"; import InfoBadge from "@components/ui/InfoBadge"; import ColorPicker from "@components/ui/colorpicker"; import Select from "@components/ui/form/Select"; import TimezoneSelect, { ITimezone } from "@components/ui/form/TimezoneSelect"; import { UpgradeToProDialog } from "../../components/UpgradeToProDialog"; type Props = inferSSRProps; function HideBrandingInput(props: { hideBrandingRef: RefObject; user: Props["user"] }) { const { t } = useLocale(); const [modalOpen, setModalOpen] = useState(false); return ( <> { if (!e.currentTarget.checked || props.user.plan !== "FREE") { return; } // prevent checking the input e.preventDefault(); setModalOpen(true); }} /> {t("remove_cal_branding_description")} ); } function SettingsView(props: ComponentProps & { localeProp: string }) { const utils = trpc.useContext(); const { t } = useLocale(); const router = useRouter(); const mutation = trpc.useMutation("viewer.updateProfile", { onSuccess: async () => { showToast(t("your_user_profile_updated_successfully"), "success"); setHasErrors(false); // dismiss any open errors await utils.invalidateQueries(["viewer.me"]); }, onError: (err) => { setHasErrors(true); setErrorMessage(err.message); document?.getElementsByTagName("main")[0]?.scrollTo({ top: 0, behavior: "smooth" }); }, async onSettled() { await utils.invalidateQueries(["viewer.i18n"]); }, }); const deleteAccount = async () => { await fetch("/api/user/me", { method: "DELETE", headers: { "Content-Type": "application/json", }, }).catch((e) => { console.error(`Error Removing user: ${props.user.id}, email: ${props.user.email} :`, e); }); if (process.env.NEXT_PUBLIC_WEBAPP_URL === "https://app.cal.com") { signOut({ callbackUrl: "/auth/logout?survey=true" }); } else { signOut({ callbackUrl: "/auth/logout" }); } }; const localeOptions = useMemo(() => { return (router.locales || []).map((locale) => ({ value: locale, label: new Intl.DisplayNames(props.localeProp, { type: "language" }).of(locale) || "", })); }, [props.localeProp, router.locales]); const themeOptions = [ { value: "light", label: t("light") }, { value: "dark", label: t("dark") }, ]; const timeFormatOptions = [ { value: 12, label: t("12_hour") }, { value: 24, label: t("24_hour") }, ]; const usernameRef = useRef(null!); const nameRef = useRef(null!); const emailRef = useRef(null!); const descriptionRef = useRef(null!); const avatarRef = useRef(null!); const hideBrandingRef = useRef(null!); const allowDynamicGroupBookingRef = useRef(null!); const [selectedTheme, setSelectedTheme] = useState(); const [selectedTimeFormat, setSelectedTimeFormat] = useState({ value: props.user.timeFormat || 12, label: timeFormatOptions.find((option) => option.value === props.user.timeFormat)?.label || 12, }); const [selectedTimeZone, setSelectedTimeZone] = useState(props.user.timeZone); const [selectedWeekStartDay, setSelectedWeekStartDay] = useState({ value: props.user.weekStart, label: nameOfDay(props.localeProp, props.user.weekStart === "Sunday" ? 0 : 1), }); const [selectedLanguage, setSelectedLanguage] = useState({ value: props.localeProp || "", label: localeOptions.find((option) => option.value === props.localeProp)?.label || "", }); const [imageSrc, setImageSrc] = useState(props.user.avatar || ""); const [hasErrors, setHasErrors] = useState(false); const [errorMessage, setErrorMessage] = useState(""); const [brandColor, setBrandColor] = useState(props.user.brandColor); const [darkBrandColor, setDarkBrandColor] = useState(props.user.darkBrandColor); useEffect(() => { if (!props.user.theme) return; const userTheme = themeOptions.find((theme) => theme.value === props.user.theme); if (!userTheme) return; setSelectedTheme(userTheme); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); async function updateProfileHandler(event: FormEvent) { event.preventDefault(); const enteredUsername = usernameRef.current.value.toLowerCase(); const enteredName = nameRef.current.value; const enteredEmail = emailRef.current.value; const enteredDescription = descriptionRef.current.value; const enteredAvatar = avatarRef.current.value; const enteredBrandColor = brandColor; const enteredDarkBrandColor = darkBrandColor; const enteredTimeZone = typeof selectedTimeZone === "string" ? selectedTimeZone : selectedTimeZone.value; const enteredWeekStartDay = selectedWeekStartDay.value; const enteredHideBranding = hideBrandingRef.current.checked; const enteredAllowDynamicGroupBooking = allowDynamicGroupBookingRef.current.checked; const enteredLanguage = selectedLanguage.value; const enteredTimeFormat = selectedTimeFormat.value; // TODO: Add validation mutation.mutate({ username: enteredUsername, name: enteredName, email: enteredEmail, bio: enteredDescription, avatar: enteredAvatar, timeZone: enteredTimeZone, weekStart: asStringOrUndefined(enteredWeekStartDay), hideBranding: enteredHideBranding, allowDynamicBooking: enteredAllowDynamicGroupBooking, theme: asStringOrNull(selectedTheme?.value), brandColor: enteredBrandColor, darkBrandColor: enteredDarkBrandColor, locale: enteredLanguage, timeFormat: enteredTimeFormat, }); } return (
{hasErrors && }
{process.env.NEXT_PUBLIC_WEBSITE_URL}/ } ref={usernameRef} defaultValue={props.user.username || undefined} />

{t("change_email_tip")}

{ avatarRef.current.value = newAvatar; const nativeInputValueSetter = Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, "value" )?.set; nativeInputValueSetter?.call(avatarRef.current, newAvatar); const ev2 = new Event("input", { bubbles: true }); avatarRef.current.dispatchEvent(ev2); updateProfileHandler(ev2 as unknown as FormEvent); setImageSrc(newAvatar); }} imageSrc={imageSrc} />

v && setSelectedTimeFormat(v)} className="mt-1 block w-full rounded-sm capitalize shadow-sm sm:text-sm" options={timeFormatOptions} />
setSelectedTheme(e.target.checked ? undefined : themeOptions[0])} checked={!selectedTheme} className="h-4 w-4 rounded-sm border-gray-300 text-neutral-900 " />

{t("disable_cal_branding_description")}

{t("danger_zone")}

{t("confirm_delete_account")} } onConfirm={() => deleteAccount()}> {t("delete_account_confirmation_message")}

); } const WithQuery = withQuery(["viewer.i18n"]); export default function Settings(props: Props) { const { t } = useLocale(); return ( } /> ); } export const getServerSideProps = async (context: GetServerSidePropsContext) => { const session = await getSession(context); if (!session?.user?.id) { return { redirect: { permanent: false, destination: "/auth/login" } }; } const user = await prisma.user.findUnique({ where: { id: session.user.id, }, select: { id: true, username: true, name: true, email: true, bio: true, avatar: true, timeZone: true, weekStart: true, hideBranding: true, theme: true, plan: true, brandColor: true, darkBrandColor: true, metadata: true, timeFormat: true, allowDynamicBooking: true, }, }); if (!user) { throw new Error("User seems logged in but cannot be found in the db"); } return { props: { user: { ...user, emailMd5: crypto.createHash("md5").update(user.email).digest("hex"), }, }, }; };