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 { fetchUsername } from "@calcom/lib/fetchUsername";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { User } from "@calcom/prisma/client";
import { TRPCClientErrorLike } from "@calcom/trpc/client";
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
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 { Icon, StarIconSolid } from "@calcom/ui/Icon";
import { Button } from "@calcom/ui/v2";
import { Input, Label } from "@calcom/ui/v2";
export enum UsernameChangeStatusEnum {
@ -25,7 +26,7 @@ interface ICustomUsernameProps {
currentUsername: string | undefined;
setCurrentUsername: (value: string | undefined) => void;
inputUsernameValue: string | undefined;
usernameRef: MutableRefObject<HTMLInputElement>;
usernameRef: MutableRefObject<HTMLInputElement | null>;
setInputUsernameValue: (value: string) => void;
onSuccessMutation?: () => void;
onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void;
@ -43,9 +44,8 @@ interface ICustomUsernameProps {
| "plan"
| "brandColor"
| "darkBrandColor"
| "metadata"
| "timeFormat"
| "allowDynamicBooking"
| "metadata"
>;
readonly?: boolean;
}
@ -62,24 +62,13 @@ const obtainNewUsernameChangeCondition = ({
if (!userIsPremium && isNewUsernamePremium && !stripeCustomer?.paidForPremium) {
return UsernameChangeStatusEnum.UPGRADE;
}
if (userIsPremium && !isNewUsernamePremium && getPremiumPlanMode() === "subscription") {
return UsernameChangeStatusEnum.DOWNGRADE;
}
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 { t } = useLocale();
const {
@ -91,6 +80,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
onSuccessMutation,
onErrorMutation,
readonly: disabled,
user,
} = props;
const [usernameIsAvailable, setUsernameIsAvailable] = useState(false);
const [markAsError, setMarkAsError] = useState(false);
@ -98,13 +88,14 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
const { paymentStatus: recentAttemptPaymentStatus } = router.query;
const [openDialogSaveUsername, setOpenDialogSaveUsername] = useState(false);
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 debouncedApiCall = useCallback(
debounce(async (username) => {
const { data } = await fetchUsername(username);
setMarkAsError(!data.available && username !== currentUsername);
setMarkAsError(!data.available && username && username !== currentUsername);
setIsInputUsernamePremium(data.premium);
setUsernameIsAvailable(data.available);
}, 150),
@ -183,7 +174,9 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
onClick={() => {
if (currentUsername) {
setInputUsernameValue(currentUsername);
usernameRef.current.value = currentUsername;
if (usernameRef.current) {
usernameRef.current.value = currentUsername;
}
}
}}>
{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 (
<div>
<div className="flex justify-items-center">
@ -211,7 +218,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
<span
className={classNames(
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://", "")}/
</span>
@ -237,6 +244,8 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
value={inputUsernameValue}
onChange={(event) => {
event.preventDefault();
// Reset payment status
delete router.query.paymentStatus;
setInputUsernameValue(event.target.value);
}}
data-testid="username-input"
@ -248,7 +257,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
isInputUsernamePremium ? "text-orange-400" : "",
usernameIsAvailable ? "" : ""
)}>
{isInputUsernamePremium ? <StarIconSolid className="mt-[4px] w-6" /> : <></>}
{isInputUsernamePremium ? <StarIconSolid className="mt-[2px] w-6" /> : <></>}
{!isInputUsernamePremium && usernameIsAvailable ? <Icon.FiCheck className="mt-2 w-6" /> : <></>}
</span>
</div>
@ -260,17 +269,7 @@ const PremiumTextfield = (props: ICustomUsernameProps) => {
</div>
)}
</div>
{paymentRequired ? (
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}
{paymentMsg}
{markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>}
{usernameIsAvailable && (

View File

@ -7,16 +7,15 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { TRPCClientErrorLike } from "@calcom/trpc/client";
import { trpc } from "@calcom/trpc/react";
import { AppRouter } from "@calcom/trpc/server/routers/_app";
import Button from "@calcom/ui/Button";
import { Dialog, DialogClose, DialogContent, DialogHeader } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon";
import { Input, Label } from "@calcom/ui/v2";
import { Input, Label, Button } from "@calcom/ui/v2";
interface ICustomUsernameProps {
currentUsername: string | undefined;
setCurrentUsername: (value: string | undefined) => void;
inputUsernameValue: string | undefined;
usernameRef: MutableRefObject<HTMLInputElement>;
usernameRef: MutableRefObject<HTMLInputElement | null>;
setInputUsernameValue: (value: string) => void;
onSuccessMutation?: () => void;
onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void;
@ -73,15 +72,14 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
},
});
const ActionButtons = (props: { index: string }) => {
const { index } = props;
const ActionButtons = () => {
return usernameIsAvailable && currentUsername !== inputUsernameValue ? (
<div className="flex flex-row">
<Button
type="button"
className="mx-2"
onClick={() => setOpenDialogSaveUsername(true)}
data-testid={`update-username-btn-${index}`}>
data-testid="update-username-btn">
{t("update")}
</Button>
<Button
@ -91,7 +89,9 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
onClick={() => {
if (currentUsername) {
setInputUsernameValue(currentUsername);
usernameRef.current.value = currentUsername;
if (usernameRef.current) {
usernameRef.current.value = currentUsername;
}
}
}}>
{t("cancel")}
@ -122,7 +122,7 @@ const UsernameTextfield = (props: ICustomUsernameProps) => {
autoCapitalize="none"
autoCorrect="none"
className={classNames(
"mb-0 mt-0 rounded-md rounded-l-none",
"mb-0 mt-0 h-6 rounded-md rounded-l-none",
markAsError
? "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 && (
<div className="absolute right-[2px] top-0 flex flex-row">
<span className={classNames("mx-2 py-2")}>
{usernameIsAvailable ? <Icon.FiCheck className="mt-[4px] w-6" /> : <></>}
{usernameIsAvailable ? <Icon.FiCheck className="mt-[2px] w-6" /> : <></>}
</span>
</div>
)}
</div>
<div className="hidden md:inline">
<ActionButtons index="desktop" />
<ActionButtons />
</div>
</div>
{markAsError && <p className="mt-1 text-xs text-red-500">Username is already taken</p>}
{usernameIsAvailable && currentUsername !== inputUsernameValue && (
<div className="mt-2 flex justify-end sm:hidden">
<ActionButtons index="mobile" />
<div className="mt-2 flex justify-end md:hidden">
<ActionButtons />
</div>
)}
<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 TwoFactor from "@components/auth/TwoFactor";
import { UsernameAvailability } from "@components/ui/UsernameAvailability";
const SkeletonLoader = () => {
return (
@ -48,6 +49,7 @@ interface DeleteAccountValues {
const ProfileView = () => {
const { t } = useLocale();
const utils = trpc.useContext();
const usernameRef = useRef<HTMLInputElement>(null);
const { data: user, isLoading } = trpc.useQuery(["viewer.me"]);
const mutation = trpc.useMutation("viewer.updateProfile", {
@ -64,7 +66,11 @@ const ProfileView = () => {
const [deleteAccountOpen, setDeleteAccountOpen] = useState(false);
const [hasDeleteErrors, setHasDeleteErrors] = useState(false);
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 emailMd5 = crypto
@ -156,8 +162,16 @@ const ProfileView = () => {
[ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t("please_try_again_and_contact_us")}`,
[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 (
<>
@ -194,11 +208,15 @@ const ProfileView = () => {
/>
</div>
<div className="mt-8">
<TextField
data-testid="username-input"
label={t("personal_cal_url")}
addOnLeading={WEBSITE_URL + "/"}
{...formMethods.register("username")}
<UsernameAvailability
currentUsername={currentUsername}
setCurrentUsername={setCurrentUsername}
inputUsernameValue={inputUsernameValue}
usernameRef={usernameRef}
setInputUsernameValue={setInputUsernameValue}
onSuccessMutation={onSuccessfulUsernameUpdate}
onErrorMutation={onErrorInUsernameUpdate}
user={user}
/>
</div>
<div className="mt-8">

View File

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

View File

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

View File

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

View File

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