Use PremiumTextField in v2 (#4577)

* Use PremiumTextField in v2

* Fix tests

* Fix Lint

* Fix TS error

* Fixes

* Fix username input in self hosted scenario

* Fix type error

* Fix Tests

* Fix username text field test

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
Co-authored-by: Omar López <zomars@me.com>
This commit is contained in:
Hariom Balhara 2022-09-22 23:04:17 +05:30 committed by GitHub
parent ce41397517
commit ace27ca84e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 72 additions and 55 deletions

View File

@ -5,14 +5,15 @@ import { MutableRefObject, useCallback, useEffect, useState } from "react";
import { getPremiumPlanMode, getPremiumPlanPriceValue } from "@calcom/app-store/stripepayment/lib/utils"; import { getPremiumPlanMode, getPremiumPlanPriceValue } from "@calcom/app-store/stripepayment/lib/utils";
import { fetchUsername } from "@calcom/lib/fetchUsername"; import { fetchUsername } from "@calcom/lib/fetchUsername";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useLocale } from "@calcom/lib/hooks/useLocale";
import { User } from "@calcom/prisma/client"; import { User } from "@calcom/prisma/client";
import { TRPCClientErrorLike } from "@calcom/trpc/client"; import { TRPCClientErrorLike } from "@calcom/trpc/client";
import { inferQueryOutput, trpc } from "@calcom/trpc/react"; import { inferQueryOutput, trpc } from "@calcom/trpc/react";
import type { AppRouter } from "@calcom/trpc/server/routers/_app"; import type { AppRouter } from "@calcom/trpc/server/routers/_app";
import Button from "@calcom/ui/Button";
import { Dialog, DialogClose, DialogContent, DialogHeader } from "@calcom/ui/Dialog"; import { Dialog, DialogClose, DialogContent, DialogHeader } from "@calcom/ui/Dialog";
import { Icon, StarIconSolid } from "@calcom/ui/Icon"; import { Icon, StarIconSolid } from "@calcom/ui/Icon";
import { Button } from "@calcom/ui/v2";
import { Input, Label } from "@calcom/ui/v2"; import { Input, Label } from "@calcom/ui/v2";
export enum UsernameChangeStatusEnum { export enum UsernameChangeStatusEnum {
@ -25,7 +26,7 @@ interface ICustomUsernameProps {
currentUsername: string | undefined; currentUsername: string | undefined;
setCurrentUsername: (value: string | undefined) => void; setCurrentUsername: (value: string | undefined) => void;
inputUsernameValue: string | undefined; inputUsernameValue: string | undefined;
usernameRef: MutableRefObject<HTMLInputElement>; usernameRef: MutableRefObject<HTMLInputElement | null>;
setInputUsernameValue: (value: string) => void; setInputUsernameValue: (value: string) => void;
onSuccessMutation?: () => void; onSuccessMutation?: () => void;
onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void; onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void;
@ -43,9 +44,8 @@ interface ICustomUsernameProps {
| "plan" | "plan"
| "brandColor" | "brandColor"
| "darkBrandColor" | "darkBrandColor"
| "metadata"
| "timeFormat" | "timeFormat"
| "allowDynamicBooking" | "metadata"
>; >;
readonly?: boolean; readonly?: boolean;
} }
@ -62,24 +62,13 @@ const obtainNewUsernameChangeCondition = ({
if (!userIsPremium && isNewUsernamePremium && !stripeCustomer?.paidForPremium) { if (!userIsPremium && isNewUsernamePremium && !stripeCustomer?.paidForPremium) {
return UsernameChangeStatusEnum.UPGRADE; return UsernameChangeStatusEnum.UPGRADE;
} }
if (userIsPremium && !isNewUsernamePremium && getPremiumPlanMode() === "subscription") { if (userIsPremium && !isNewUsernamePremium && getPremiumPlanMode() === "subscription") {
return UsernameChangeStatusEnum.DOWNGRADE; return UsernameChangeStatusEnum.DOWNGRADE;
} }
return UsernameChangeStatusEnum.NORMAL; return UsernameChangeStatusEnum.NORMAL;
}; };
const useIsUsernamePremium = (username: string) => {
const [isCurrentUsernamePremium, setIsCurrentUsernamePremium] = useState(false);
useEffect(() => {
(async () => {
if (!username) return;
const { data } = await fetchUsername(username);
setIsCurrentUsernamePremium(data.premium);
})();
}, [username]);
return isCurrentUsernamePremium;
};
const PremiumTextfield = (props: ICustomUsernameProps) => { const PremiumTextfield = (props: ICustomUsernameProps) => {
const { t } = useLocale(); const { t } = useLocale();
const { const {
@ -91,6 +80,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
onSuccessMutation, onSuccessMutation,
onErrorMutation, onErrorMutation,
readonly: disabled, readonly: disabled,
user,
} = props; } = props;
const [usernameIsAvailable, setUsernameIsAvailable] = useState(false); const [usernameIsAvailable, setUsernameIsAvailable] = useState(false);
const [markAsError, setMarkAsError] = useState(false); const [markAsError, setMarkAsError] = useState(false);
@ -98,13 +88,14 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
const { paymentStatus: recentAttemptPaymentStatus } = router.query; const { paymentStatus: recentAttemptPaymentStatus } = router.query;
const [openDialogSaveUsername, setOpenDialogSaveUsername] = useState(false); const [openDialogSaveUsername, setOpenDialogSaveUsername] = useState(false);
const { data: stripeCustomer } = trpc.useQuery(["viewer.stripeCustomer"]); const { data: stripeCustomer } = trpc.useQuery(["viewer.stripeCustomer"]);
const isCurrentUsernamePremium = useIsUsernamePremium(currentUsername || ""); const isCurrentUsernamePremium =
user && user.metadata && hasKeyInMetadata(user, "isPremium") ? !!user.metadata.isPremium : false;
const [isInputUsernamePremium, setIsInputUsernamePremium] = useState(false); const [isInputUsernamePremium, setIsInputUsernamePremium] = useState(false);
const debouncedApiCall = useCallback( const debouncedApiCall = useCallback(
debounce(async (username) => { debounce(async (username) => {
const { data } = await fetchUsername(username); const { data } = await fetchUsername(username);
setMarkAsError(!data.available && username !== currentUsername); setMarkAsError(!data.available && username && username !== currentUsername);
setIsInputUsernamePremium(data.premium); setIsInputUsernamePremium(data.premium);
setUsernameIsAvailable(data.available); setUsernameIsAvailable(data.available);
}, 150), }, 150),
@ -183,7 +174,9 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
onClick={() => { onClick={() => {
if (currentUsername) { if (currentUsername) {
setInputUsernameValue(currentUsername); setInputUsernameValue(currentUsername);
usernameRef.current.value = currentUsername; if (usernameRef.current) {
usernameRef.current.value = currentUsername;
}
} }
}}> }}>
{t("cancel")} {t("cancel")}
@ -202,6 +195,20 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
} }
}; };
let paymentMsg = !currentUsername ? (
<span className="text-xs text-orange-400">
You need to reserve your premium username for {getPremiumPlanPriceValue()}
</span>
) : null;
if (recentAttemptPaymentStatus && recentAttemptPaymentStatus !== "paid") {
paymentMsg = (
<span className="text-sm text-red-500">
Your payment could not be completed. Your username is still not reserved
</span>
);
}
return ( return (
<div> <div>
<div className="flex justify-items-center"> <div className="flex justify-items-center">
@ -211,7 +218,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
<span <span
className={classNames( className={classNames(
isInputUsernamePremium ? "border-1 border-orange-400 " : "", isInputUsernamePremium ? "border-1 border-orange-400 " : "",
"hidden items-center rounded-l-md border border-r-0 border-gray-300 border-r-gray-300 bg-gray-50 px-3 text-sm text-gray-500 md:inline-flex" "hidden h-9 items-center rounded-l-md border border-r-0 border-gray-300 border-r-gray-300 bg-gray-50 px-3 text-sm text-gray-500 md:inline-flex"
)}> )}>
{process.env.NEXT_PUBLIC_WEBSITE_URL.replace("https://", "").replace("http://", "")}/ {process.env.NEXT_PUBLIC_WEBSITE_URL.replace("https://", "").replace("http://", "")}/
</span> </span>
@ -237,6 +244,8 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
value={inputUsernameValue} value={inputUsernameValue}
onChange={(event) => { onChange={(event) => {
event.preventDefault(); event.preventDefault();
// Reset payment status
delete router.query.paymentStatus;
setInputUsernameValue(event.target.value); setInputUsernameValue(event.target.value);
}} }}
data-testid="username-input" data-testid="username-input"
@ -248,7 +257,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
isInputUsernamePremium ? "text-orange-400" : "", isInputUsernamePremium ? "text-orange-400" : "",
usernameIsAvailable ? "" : "" usernameIsAvailable ? "" : ""
)}> )}>
{isInputUsernamePremium ? <StarIconSolid className="mt-[4px] w-6" /> : <></>} {isInputUsernamePremium ? <StarIconSolid className="mt-[2px] w-6" /> : <></>}
{!isInputUsernamePremium && usernameIsAvailable ? <Icon.FiCheck className="mt-2 w-6" /> : <></>} {!isInputUsernamePremium && usernameIsAvailable ? <Icon.FiCheck className="mt-2 w-6" /> : <></>}
</span> </span>
</div> </div>
@ -260,17 +269,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
</div> </div>
)} )}
</div> </div>
{paymentRequired ? ( {paymentMsg}
recentAttemptPaymentStatus && recentAttemptPaymentStatus !== "paid" ? (
<span className="text-sm text-red-500">
Your payment could not be completed. Your username is still not reserved
</span>
) : (
<span className="text-xs text-orange-400">
You need to reserve your premium username for {getPremiumPlanPriceValue()}
</span>
)
) : null}
{markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>} {markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>}
{usernameIsAvailable && ( {usernameIsAvailable && (

View File

@ -7,16 +7,15 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { TRPCClientErrorLike } from "@calcom/trpc/client"; import { TRPCClientErrorLike } from "@calcom/trpc/client";
import { trpc } from "@calcom/trpc/react"; import { trpc } from "@calcom/trpc/react";
import { AppRouter } from "@calcom/trpc/server/routers/_app"; import { AppRouter } from "@calcom/trpc/server/routers/_app";
import Button from "@calcom/ui/Button";
import { Dialog, DialogClose, DialogContent, DialogHeader } from "@calcom/ui/Dialog"; import { Dialog, DialogClose, DialogContent, DialogHeader } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon"; import { Icon } from "@calcom/ui/Icon";
import { Input, Label } from "@calcom/ui/v2"; import { Input, Label, Button } from "@calcom/ui/v2";
interface ICustomUsernameProps { interface ICustomUsernameProps {
currentUsername: string | undefined; currentUsername: string | undefined;
setCurrentUsername: (value: string | undefined) => void; setCurrentUsername: (value: string | undefined) => void;
inputUsernameValue: string | undefined; inputUsernameValue: string | undefined;
usernameRef: MutableRefObject<HTMLInputElement>; usernameRef: MutableRefObject<HTMLInputElement | null>;
setInputUsernameValue: (value: string) => void; setInputUsernameValue: (value: string) => void;
onSuccessMutation?: () => void; onSuccessMutation?: () => void;
onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void; onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void;
@ -73,15 +72,14 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
}, },
}); });
const ActionButtons = (props: { index: string }) => { const ActionButtons = () => {
const { index } = props;
return usernameIsAvailable && currentUsername !== inputUsernameValue ? ( return usernameIsAvailable && currentUsername !== inputUsernameValue ? (
<div className="flex flex-row"> <div className="flex flex-row">
<Button <Button
type="button" type="button"
className="mx-2" className="mx-2"
onClick={() => setOpenDialogSaveUsername(true)} onClick={() => setOpenDialogSaveUsername(true)}
data-testid={`update-username-btn-${index}`}> data-testid="update-username-btn">
{t("update")} {t("update")}
</Button> </Button>
<Button <Button
@ -91,7 +89,9 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
onClick={() => { onClick={() => {
if (currentUsername) { if (currentUsername) {
setInputUsernameValue(currentUsername); setInputUsernameValue(currentUsername);
usernameRef.current.value = currentUsername; if (usernameRef.current) {
usernameRef.current.value = currentUsername;
}
} }
}}> }}>
{t("cancel")} {t("cancel")}
@ -122,7 +122,7 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
autoCapitalize="none" autoCapitalize="none"
autoCorrect="none" autoCorrect="none"
className={classNames( className={classNames(
"mb-0 mt-0 rounded-md rounded-l-none", "mb-0 mt-0 h-6 rounded-md rounded-l-none",
markAsError markAsError
? "focus:shadow-0 focus:ring-shadow-0 border-red-500 focus:border-red-500 focus:outline-none focus:ring-0" ? "focus:shadow-0 focus:ring-shadow-0 border-red-500 focus:border-red-500 focus:outline-none focus:ring-0"
: "" : ""
@ -137,20 +137,20 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
{currentUsername !== inputUsernameValue && ( {currentUsername !== inputUsernameValue && (
<div className="absolute right-[2px] top-0 flex flex-row"> <div className="absolute right-[2px] top-0 flex flex-row">
<span className={classNames("mx-2 py-2")}> <span className={classNames("mx-2 py-2")}>
{usernameIsAvailable ? <Icon.FiCheck className="mt-[4px] w-6" /> : <></>} {usernameIsAvailable ? <Icon.FiCheck className="mt-[2px] w-6" /> : <></>}
</span> </span>
</div> </div>
)} )}
</div> </div>
<div className="hidden md:inline"> <div className="hidden md:inline">
<ActionButtons index="desktop" /> <ActionButtons />
</div> </div>
</div> </div>
{markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>} {markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>}
{usernameIsAvailable && currentUsername !== inputUsernameValue && ( {usernameIsAvailable && currentUsername !== inputUsernameValue && (
<div className="mt-2 flex justify-end sm:hidden"> <div className="mt-2 flex justify-end md:hidden">
<ActionButtons index="mobile" /> <ActionButtons />
</div> </div>
)} )}
<Dialog open={openDialogSaveUsername}> <Dialog open={openDialogSaveUsername}>

View File

@ -22,6 +22,7 @@ import showToast from "@calcom/ui/v2/core/notifications";
import { SkeletonContainer, SkeletonText, SkeletonButton, SkeletonAvatar } from "@calcom/ui/v2/core/skeleton"; import { SkeletonContainer, SkeletonText, SkeletonButton, SkeletonAvatar } from "@calcom/ui/v2/core/skeleton";
import TwoFactor from "@components/auth/TwoFactor"; import TwoFactor from "@components/auth/TwoFactor";
import { UsernameAvailability } from "@components/ui/UsernameAvailability";
const SkeletonLoader = () => { const SkeletonLoader = () => {
return ( return (
@ -48,6 +49,7 @@ interface DeleteAccountValues {
const ProfileView = () => { const ProfileView = () => {
const { t } = useLocale(); const { t } = useLocale();
const utils = trpc.useContext(); const utils = trpc.useContext();
const usernameRef = useRef<HTMLInputElement>(null);
const { data: user, isLoading } = trpc.useQuery(["viewer.me"]); const { data: user, isLoading } = trpc.useQuery(["viewer.me"]);
const mutation = trpc.useMutation("viewer.updateProfile", { const mutation = trpc.useMutation("viewer.updateProfile", {
@ -64,7 +66,11 @@ const ProfileView = () => {
const [deleteAccountOpen, setDeleteAccountOpen] = useState(false); const [deleteAccountOpen, setDeleteAccountOpen] = useState(false);
const [hasDeleteErrors, setHasDeleteErrors] = useState(false); const [hasDeleteErrors, setHasDeleteErrors] = useState(false);
const [deleteErrorMessage, setDeleteErrorMessage] = useState(""); const [deleteErrorMessage, setDeleteErrorMessage] = useState("");
const [currentUsername, setCurrentUsername] = useState<string | undefined>(user?.username || undefined);
const [inputUsernameValue, setInputUsernameValue] = useState(currentUsername);
useEffect(() => {
if (user?.username) setCurrentUsername(user?.username);
}, [user?.username]);
const form = useForm<DeleteAccountValues>(); const form = useForm<DeleteAccountValues>();
const emailMd5 = crypto const emailMd5 = crypto
@ -156,8 +162,16 @@ const ProfileView = () => {
[ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t("please_try_again_and_contact_us")}`, [ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t("please_try_again_and_contact_us")}`,
[ErrorCode.ThirdPartyIdentityProviderEnabled]: t("account_created_with_identity_provider"), [ErrorCode.ThirdPartyIdentityProviderEnabled]: t("account_created_with_identity_provider"),
}; };
const onSuccessfulUsernameUpdate = async () => {
showToast(t("settings_updated_successfully"), "success");
await utils.invalidateQueries(["viewer.me"]);
};
if (isLoading) return <SkeletonLoader />; const onErrorInUsernameUpdate = () => {
showToast(t("error_updating_settings"), "error");
};
if (isLoading || !user) return <SkeletonLoader />;
return ( return (
<> <>
@ -194,11 +208,15 @@ const ProfileView = () => {
/> />
</div> </div>
<div className="mt-8"> <div className="mt-8">
<TextField <UsernameAvailability
data-testid="username-input" currentUsername={currentUsername}
label={t("personal_cal_url")} setCurrentUsername={setCurrentUsername}
addOnLeading={WEBSITE_URL + "/"} inputUsernameValue={inputUsernameValue}
{...formMethods.register("username")} usernameRef={usernameRef}
setInputUsernameValue={setInputUsernameValue}
onSuccessMutation={onSuccessfulUsernameUpdate}
onErrorMutation={onErrorInUsernameUpdate}
user={user}
/> />
</div> </div>
<div className="mt-8"> <div className="mt-8">

View File

@ -35,10 +35,10 @@ test.describe("Change username on settings", () => {
const usernameInput = page.locator("[data-testid=username-input]"); const usernameInput = page.locator("[data-testid=username-input]");
await usernameInput.fill("demousernamex"); await usernameInput.fill("demousernamex");
await page.click("[data-testid=update-username-btn]");
await Promise.all([ await Promise.all([
page.click("[data-testid=save-username]"),
page.waitForResponse("**/viewer.updateProfile*"), page.waitForResponse("**/viewer.updateProfile*"),
page.click('button[type="submit"]'),
]); ]);
const newUpdatedUser = await prisma.user.findUniqueOrThrow({ const newUpdatedUser = await prisma.user.findUniqueOrThrow({

View File

@ -25,7 +25,6 @@ export enum UsernameChangeStatusEnum {
export default async function handler(req: NextApiRequest, res: NextApiResponse) { export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") { if (req.method === "GET") {
const userId = req.session?.user.id; const userId = req.session?.user.id;
let { intentUsername = null } = req.query; let { intentUsername = null } = req.query;
const { action, callbackUrl } = req.query; const { action, callbackUrl } = req.query;
if (!userId || !intentUsername) { if (!userId || !intentUsername) {
@ -36,7 +35,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
intentUsername = intentUsername[0]; intentUsername = intentUsername[0];
} }
const customerId = await getStripeCustomerIdFromUserId(userId); const customerId = await getStripeCustomerIdFromUserId(userId);
if (!customerId) { if (!customerId) {
res.status(404).json({ message: "Missing customer id" }); res.status(404).json({ message: "Missing customer id" });
return; return;

View File

@ -73,6 +73,7 @@ async function getUserFromSession({
locale: true, locale: true,
timeFormat: true, timeFormat: true,
trialEndsAt: true, trialEndsAt: true,
metadata: true,
}, },
}); });

View File

@ -179,6 +179,7 @@ const loggedInViewerRouter = createProtectedRouter()
weekStart: user.weekStart, weekStart: user.weekStart,
theme: user.theme, theme: user.theme,
hideBranding: user.hideBranding, hideBranding: user.hideBranding,
metadata: user.metadata,
}; };
}, },
}) })