The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(vendor): add seller registration page with (#774)
Jakub Sieradzki60f834ba9c23
diff --git a/packages/dashboard-sdk/src/types.ts b/packages/dashboard-sdk/src/types.tsindex 947fad722..4b274d352 100644--- a/packages/dashboard-sdk/src/types.ts+++ b/packages/dashboard-sdk/src/types.ts@@ -12,6 +12,7 @@ export interface MercurConfig {defaultLanguage: string}backendUrl?: string;+ enableSellerRegistration?: boolean;}export interface BuiltMercurConfig extends MercurConfig {diff --git a/packages/vendor/src/get-route-map.tsx b/packages/vendor/src/get-route-map.tsxindex ebfe9acf9..afdd6e3d7 100644--- a/packages/vendor/src/get-route-map.tsx+++ b/packages/vendor/src/get-route-map.tsx@@ -1315,6 +1315,14 @@ export function getRouteMap({path: "/reset-password",lazy: () => import("./pages/reset-password"),},+ {+ path: "/register",+ lazy: async () => {+ const { RegisterPage } =+ await import("./pages/register");+ return { Component: RegisterPage };+ },+ },...customPublicRoutes,{path: "*",diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.jsonindex 3d7b301ba..771b23fb0 100644--- a/packages/vendor/src/i18n/translations/en.json+++ b/packages/vendor/src/i18n/translations/en.json@@ -2941,7 +2941,21 @@"login": {"forgotPassword": "Forgot password? - <0>Reset</0>","title": "Welcome to {{name}}",- "hint": "Sign in to access the vendor hub"+ "hint": "Sign in to access the vendor hub",+ "notSellerYet": "Not a seller yet? - <0>Create an account</0>"+ },+ "register": {+ "title": "Join Mercur Seller Panel",+ "hint": "Sign up to start selling",+ "companyName": "Company name",+ "confirmPassword": "Confirm password",+ "signUp": "Sign up",+ "alreadySeller": "Already have an account? - <0>Sign In</0>",+ "passwordMismatch": "Passwords don't match",+ "emailTaken": "Provided email is already taken",+ "successTitle": "Thank you for registering!",+ "successHint": "You may need to wait for admin authorization before logging in. A confirmation email will be sent to you shortly.",+ "backToLogin": "Back to login"},"validation": {"rules": {diff --git a/packages/vendor/src/pages/login/login.tsx b/packages/vendor/src/pages/login/login.tsxindex 13f3c4b80..4d71a7e3b 100644--- a/packages/vendor/src/pages/login/login.tsx+++ b/packages/vendor/src/pages/login/login.tsx@@ -168,18 +168,34 @@ const LoginForm = () => {const LoginFooter = () => {return (- <span className="text-ui-fg-muted txt-small my-6">- <Trans- i18nKey="login.forgotPassword"- components={[- <Link- key="reset-password-link"- to="/reset-password"- className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"- />,- ]}- />- </span>+ <div className="flex flex-col items-center">+ <span className="text-ui-fg-muted txt-small my-6">+ <Trans+ i18nKey="login.forgotPassword"+ components={[+ <Link+ key="reset-password-link"+ to="/reset-password"+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"+ />,+ ]}+ />+ </span>+ {config.enableSellerRegistration && (+ <span className="text-ui-fg-muted txt-small">+ <Trans+ i18nKey="login.notSellerYet"+ components={[+ <Link+ key="register-link"+ to="/register"+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"+ />,+ ]}+ />+ </span>+ )}+ </div>)}diff --git a/packages/vendor/src/pages/register/index.ts b/packages/vendor/src/pages/register/index.tsnew file mode 100644index 000000000..3a45b1e76--- /dev/null+++ b/packages/vendor/src/pages/register/index.ts@@ -0,0 +1 @@+export { RegisterPage } from "./register"diff --git a/packages/vendor/src/pages/register/password-validator.tsx b/packages/vendor/src/pages/register/password-validator.tsxnew file mode 100644index 000000000..9df2e08b4--- /dev/null+++ b/packages/vendor/src/pages/register/password-validator.tsx@@ -0,0 +1,115 @@+import { useCallback, useEffect, useState } from "react"++import { CheckCircle } from "@medusajs/icons"+import { Container, Text } from "@medusajs/ui"+import { useTranslation } from "react-i18next"++export interface PasswordValidationState {+ isValid: boolean+ lower: boolean+ upper: boolean+ "12chars": boolean+ digit: boolean+ specialChar: boolean+}++export const INITIAL_VALIDATION_STATE: PasswordValidationState = {+ isValid: false,+ lower: false,+ upper: false,+ "12chars": false,+ digit: false,+ specialChar: false,+}++function validatePassword(password: string) {+ const errors = {+ tooShort: password.length < 12,+ noLower: !/[a-z]/.test(password),+ noUpper: !/[A-Z]/.test(password),+ noDigit: !/[0-9]/.test(password),+ noSpecialChar: !/[!@#$%^&*(),.?":{}|<>_\-+=\[\]\\\/~`]/.test(password),+ }++ return {+ isValid: !Object.values(errors).some(Boolean),+ errors,+ }+}++type RuleKey = Exclude<keyof PasswordValidationState, "isValid">++const RULE_KEYS: RuleKey[] = ["12chars", "lower", "upper", "digit", "specialChar"]++const RULE_I18N_MAP: Record<RuleKey, string> = {+ lower: "validation.rules.lower",+ upper: "validation.rules.upper",+ "12chars": "validation.rules.12chars",+ digit: "validation.rules.digit",+ specialChar: "validation.rules.specialChar",+}++const PasswordRule = ({+ ruleKey,+ hasError,+}: {+ ruleKey: RuleKey+ hasError: boolean+}) => {+ const { t } = useTranslation()++ return (+ <Text+ as="p"+ size="xsmall"+ className={`flex items-center gap-2 ${hasError ? "text-ui-fg-error" : "text-ui-tag-green-text"}`}+ >+ <CheckCircle /> {t(RULE_I18N_MAP[ruleKey])}+ </Text>+ )+}++export const PasswordValidator = ({+ password,+ onValidationChange,+}: {+ password: string+ onValidationChange: (state: PasswordValidationState) => void+}) => {+ const [dirty, setDirty] = useState(false)+ const [state, setState] = useState<PasswordValidationState>(INITIAL_VALIDATION_STATE)++ const handleValidationChange = useCallback(onValidationChange, [])++ useEffect(() => {+ if (!dirty && password.length > 0) {+ setDirty(true)+ }++ const validation = validatePassword(password)++ const nextState: PasswordValidationState = {+ isValid: validation.isValid,+ lower: validation.errors.noLower,+ upper: validation.errors.noUpper,+ "12chars": validation.errors.tooShort,+ digit: validation.errors.noDigit,+ specialChar: validation.errors.noSpecialChar,+ }++ handleValidationChange(nextState)+ setState(nextState)+ }, [password, handleValidationChange])++ if (!dirty) {+ return null+ }++ return (+ <Container className="flex flex-col gap-y-1 p-2">+ {RULE_KEYS.map((key) => (+ <PasswordRule key={key} ruleKey={key} hasError={state[key]} />+ ))}+ </Container>+ )+}diff --git a/packages/vendor/src/pages/register/register-schema.ts b/packages/vendor/src/pages/register/register-schema.tsnew file mode 100644index 000000000..cdf468937--- /dev/null+++ b/packages/vendor/src/pages/register/register-schema.ts@@ -0,0 +1,20 @@+import { i18n } from "@components/utilities/i18n"+import * as z from "zod"++export const RegisterSchema = z+ .object({+ name: z.string().min(2),+ email: z.string().email(),+ password: z+ .string()+ .min(12)+ .regex(/[a-z]/)+ .regex(/[A-Z]/)+ .regex(/[0-9]/)+ .regex(/[!@#$%^&*(),.?":{}|<>_\-+=\[\]\\\/~`]/),+ confirmPassword: z.string(),+ })+ .refine((data) => data.password === data.confirmPassword, {+ message: i18n.t("register.passwordMismatch"),+ path: ["confirmPassword"],+ })diff --git a/packages/vendor/src/pages/register/register.tsx b/packages/vendor/src/pages/register/register.tsxnew file mode 100644index 000000000..abef43646--- /dev/null+++ b/packages/vendor/src/pages/register/register.tsx@@ -0,0 +1,287 @@+import { Children, ReactNode, useState } from "react"++import { zodResolver } from "@hookform/resolvers/zod"+import { Alert, Button, Heading, Hint, Input, Text } from "@medusajs/ui"+import { useForm } from "react-hook-form"+import { Trans, useTranslation } from "react-i18next"+import { Link, Navigate } from "react-router-dom"+import config from "virtual:mercur/config"+import * as z from "zod"++import { Form } from "@components/common/form"+import AvatarBox from "@components/common/logo-box/avatar-box"+import { useSignUpWithEmailPass } from "@hooks/api"+import { fetchQuery } from "@lib/client"++import {+ INITIAL_VALIDATION_STATE,+ PasswordValidationState,+ PasswordValidator,+} from "./password-validator"+import { RegisterSchema } from "./register-schema"++const RegisterLogo = () => {+ return <AvatarBox />+}++const RegisterHeader = () => {+ const { t } = useTranslation()++ return (+ <div className="mb-4 flex flex-col items-center">+ <Heading>{t("register.title")}</Heading>+ <Text size="small" className="text-ui-fg-subtle text-center">+ {t("register.hint")}+ </Text>+ </div>+ )+}++const RegisterForm = () => {+ const { t } = useTranslation()+ const [success, setSuccess] = useState(false)++ const [passwordValidation, setPasswordValidation] =+ useState<PasswordValidationState>(INITIAL_VALIDATION_STATE)++ const form = useForm<z.infer<typeof RegisterSchema>>({+ resolver: zodResolver(RegisterSchema),+ defaultValues: {+ name: "",+ email: "",+ password: "",+ confirmPassword: "",+ },+ })++ const { mutateAsync, isPending } = useSignUpWithEmailPass()+ const [isCreatingSeller, setIsCreatingSeller] = useState(false)++ const handleSubmit = form.handleSubmit(async ({ name, email, password, confirmPassword }) => {+ if (!passwordValidation.isValid) {+ return+ }++ try {+ const authResponse = await mutateAsync({ name, email, password, confirmPassword })+ const token = (authResponse as { token: string }).token++ setIsCreatingSeller(true)++ await fetchQuery("/vendor/sellers", {+ method: "POST",+ body: { name, email },+ headers: {+ Authorization: `Bearer ${token}`,+ },+ })++ setSuccess(true)+ } catch (error: any) {+ setIsCreatingSeller(false)+ const status = "status" in error ? error.status : undefined++ if (status === 401) {+ form.setError("email", {+ type: "manual",+ message: error.message,+ })+ return+ }++ if (status === 409) {+ form.setError("email", {+ type: "manual",+ message: t("register.emailTaken"),+ })+ return+ }++ form.setError("root.serverError", {+ type: "manual",+ message: error.message,+ })+ }+ })++ const serverError = form.formState.errors?.root?.serverError?.message+ const validationError =+ form.formState.errors.email?.message ||+ form.formState.errors.password?.message ||+ form.formState.errors.name?.message ||+ form.formState.errors.confirmPassword?.message++ if (success) {+ return <RegisterSuccess />+ }++ return (+ <div className="flex w-full flex-col gap-y-3">+ <Form {...form}>+ <form+ onSubmit={handleSubmit}+ className="flex w-full flex-col gap-y-6"+ >+ <div className="flex flex-col gap-y-2">+ <Form.Field+ control={form.control}+ name="name"+ render={({ field }) => (+ <Form.Item>+ <Form.Control>+ <Input+ autoComplete="organization"+ {...field}+ className="bg-ui-bg-field-component"+ placeholder={t("register.companyName")}+ />+ </Form.Control>+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="email"+ render={({ field }) => (+ <Form.Item>+ <Form.Control>+ <Input+ autoComplete="email"+ {...field}+ className="bg-ui-bg-field-component"+ placeholder={t("fields.email")}+ />+ </Form.Control>+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="password"+ render={({ field }) => (+ <Form.Item>+ <Form.Control>+ <Input+ type="password"+ autoComplete="new-password"+ {...field}+ className="bg-ui-bg-field-component"+ placeholder={t("fields.password")}+ />+ </Form.Control>+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="confirmPassword"+ render={({ field }) => (+ <Form.Item>+ <Form.Control>+ <Input+ type="password"+ autoComplete="new-password"+ {...field}+ className="bg-ui-bg-field-component"+ placeholder={t("register.confirmPassword")}+ />+ </Form.Control>+ </Form.Item>+ )}+ />+ <PasswordValidator+ password={form.watch("password")}+ onValidationChange={setPasswordValidation}+ />+ </div>+ {validationError && (+ <div className="text-center">+ <Hint className="inline-flex" variant={"error"}>+ {validationError}+ </Hint>+ </div>+ )}+ {serverError && (+ <Alert+ className="items-center bg-ui-bg-base p-2"+ dismissible+ variant="error"+ >+ {serverError}+ </Alert>+ )}+ <Button className="w-full" type="submit" isLoading={isPending || isCreatingSeller}>+ {t("register.signUp")}+ </Button>+ </form>+ </Form>+ </div>+ )+}++const RegisterSuccess = () => {+ const { t } = useTranslation()++ return (+ <div className="flex flex-col items-center">+ <Heading>{t("register.successTitle")}</Heading>+ <Text+ size="small"+ className="mt-2 max-w-[320px] text-center text-ui-fg-subtle"+ >+ {t("register.successHint")}+ </Text>+ <Link to="/login">+ <Button className="mt-8">{t("register.backToLogin")}</Button>+ </Link>+ </div>+ )+}++const RegisterFooter = () => {+ return (+ <span className="txt-small my-6 text-ui-fg-muted">+ <Trans+ i18nKey="register.alreadySeller"+ components={[+ <Link+ key="login-link"+ to="/login"+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"+ />,+ ]}+ />+ </span>+ )+}++const Root = ({ children }: { children?: ReactNode }) => {+ if (!config.enableSellerRegistration) {+ return <Navigate to="/login" replace />+ }++ return (+ <div className="bg-ui-bg-subtle flex min-h-dvh w-dvw items-center justify-center">+ <div className="m-4 flex w-full max-w-[280px] flex-col items-center">+ {Children.count(children) > 0 ? (+ children+ ) : (+ <>+ <RegisterLogo />+ <RegisterHeader />+ <RegisterForm />+ <RegisterFooter />+ </>+ )}+ </div>+ </div>+ )+}++export const RegisterPage = Object.assign(Root, {+ Logo: RegisterLogo,+ Header: RegisterHeader,+ Form: RegisterForm,+ Success: RegisterSuccess,+ Footer: RegisterFooter,+})