diff --git a/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx b/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx
index 518ad6f..771dc0f 100644
--- a/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx
+++ b/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx
@@ -1,27 +1,33 @@
'use client';
import { useRouter } from 'next/navigation';
-import { useEffect } from 'react';
+import { useEffect, useState } from 'react';
import { useViewerStatus } from '../../../stores/auth';
import { safeReturnPath } from '../../navigation';
import type { GuestGuardProps } from './types';
/**
- * Wraps login and registration. A signed-in visitor goes on to `?redirect=` (a path on this site
- * only) or home; a guest sees the page. The skeleton covers the moment before the viewer is known.
+ * Wraps login and registration, which render only in the browser. A visitor who arrives signed in
+ * goes on to `?redirect=` (a path on this site only) or home; a guest sees the page. The skeleton
+ * covers the moment before the viewer is known. A guest who signs in on the page keeps it: the
+ * page shows its progress and sends them on itself.
*/
export function GuestGuard({ fallback, children }: GuestGuardProps) {
const status = useViewerStatus();
const router = useRouter();
+ const [wasGuest, setWasGuest] = useState(false);
+ // Remembered during render, so the render that turns member already knows.
+ if (status === 'guest' && !wasGuest) setWasGuest(true);
useEffect(() => {
- if (status !== 'member') return;
+ if (status !== 'member' || wasGuest) return;
const redirect = new URLSearchParams(window.location.search).get(
'redirect',
);
router.replace(safeReturnPath(redirect));
- }, [status, router]);
+ }, [status, wasGuest, router]);
- return status === 'guest' ? children : fallback;
+ const showsPage = status === 'guest' || (status === 'member' && wasGuest);
+ return showsPage ? children : fallback;
}
diff --git a/platforms/market/src/app/navigation/hooks/.gitkeep b/platforms/market/src/app/navigation/hooks/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/platforms/market/src/app/navigation/hooks/use-auth-routes.ts b/platforms/market/src/app/navigation/hooks/use-auth-routes.ts
new file mode 100644
index 0000000..6227787
--- /dev/null
+++ b/platforms/market/src/app/navigation/hooks/use-auth-routes.ts
@@ -0,0 +1,38 @@
+import { useSearchParams } from 'next/navigation';
+import { useMemo } from 'react';
+
+import type { SignedInViewer } from '../../../features/auth';
+import { ROUTES, withReturnPath } from '../navigation';
+import { safeReturnPath } from '../return-path';
+import type { AuthRoutes } from '../types';
+
+/**
+ * Every login and registration step's path, each keeping `?redirect=`, and where a person lands
+ * once signed in. Browser only: the auth pages render their steps in the browser.
+ */
+export function useAuthRoutes(): AuthRoutes {
+ const redirect = useSearchParams().get('redirect');
+
+ return useMemo(() => {
+ const step = (path: string) => withReturnPath(path, redirect);
+ return {
+ login: step(ROUTES.login),
+ loginVerify: step(ROUTES.loginVerify),
+ register: {
+ type: step(ROUTES.register.type),
+ phone: step(ROUTES.register.phone),
+ verify: step(ROUTES.register.verify),
+ details: step(ROUTES.register.details),
+ },
+ profile: {
+ investor: step(ROUTES.onboarding.investorProfile),
+ creator: step(ROUTES.onboarding.creatorProfile),
+ },
+ landing: ({ role, username, needsProfile }: SignedInViewer) => {
+ if (needsProfile) return step(ROUTES.onboarding.creatorProfile);
+ if (redirect) return safeReturnPath(redirect);
+ return role === 'creator' ? ROUTES.channel(username) : ROUTES.home;
+ },
+ };
+ }, [redirect]);
+}
diff --git a/platforms/market/src/app/navigation/index.ts b/platforms/market/src/app/navigation/index.ts
index b96d541..be2cbf9 100644
--- a/platforms/market/src/app/navigation/index.ts
+++ b/platforms/market/src/app/navigation/index.ts
@@ -1,3 +1,5 @@
export { CHANNEL_PREFIX } from './constants';
-export { loginRoute, ROUTES } from './navigation';
+export { useAuthRoutes } from './hooks/use-auth-routes';
+export { loginRoute, ROUTES, withReturnPath } from './navigation';
export { safeReturnPath } from './return-path';
+export type { AuthRoutes } from './types';
diff --git a/platforms/market/src/app/navigation/navigation.ts b/platforms/market/src/app/navigation/navigation.ts
index 8444a30..0c280d4 100644
--- a/platforms/market/src/app/navigation/navigation.ts
+++ b/platforms/market/src/app/navigation/navigation.ts
@@ -7,6 +7,13 @@ const channel = (username: string) =>
export const ROUTES = {
home: '/',
login: '/auth/login',
+ loginVerify: '/auth/login/verify',
+ register: {
+ type: '/auth/register',
+ phone: '/auth/register/phone',
+ verify: '/auth/register/verify',
+ details: '/auth/register/details',
+ },
account: '/account',
channel,
post: (username: string, id: string) =>
@@ -34,7 +41,16 @@ export const ROUTES = {
/** `/auth/login?redirect=…`: auth returns to the page that asked for it. */
export function loginRoute(returnTo?: string): string {
- return returnTo
- ? `${ROUTES.login}?redirect=${encodeURIComponent(returnTo)}`
- : ROUTES.login;
+ return withReturnPath(ROUTES.login, returnTo);
+}
+
+/**
+ * An auth step's path that keeps `?redirect=`, so every step of login and registration returns
+ * to the page that asked for it.
+ */
+export function withReturnPath(
+ path: string,
+ returnTo: string | null | undefined,
+): string {
+ return returnTo ? `${path}?redirect=${encodeURIComponent(returnTo)}` : path;
}
diff --git a/platforms/market/src/app/navigation/types.ts b/platforms/market/src/app/navigation/types.ts
new file mode 100644
index 0000000..11b8c44
--- /dev/null
+++ b/platforms/market/src/app/navigation/types.ts
@@ -0,0 +1,16 @@
+import type { SignedInViewer } from '../../features/auth';
+
+/** The auth steps' paths with `?redirect=` kept, and where a signed-in person lands. */
+export type AuthRoutes = {
+ login: string;
+ loginVerify: string;
+ register: {
+ type: string;
+ phone: string;
+ verify: string;
+ details: string;
+ };
+ /** Registration step 5, per account type. */
+ profile: { investor: string; creator: string };
+ landing: (viewer: SignedInViewer) => string;
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/LoginStep.tsx b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/LoginStep.tsx
new file mode 100644
index 0000000..73bb94d
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/LoginStep.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Link } from '@lumina/island/atoms/link';
+import { Typography } from '@lumina/island/atoms/typography';
+import { Banner } from '@lumina/island/molecules/banner';
+import { TextInput } from '@lumina/island/molecules/text-input';
+import type { FormEvent } from 'react';
+import { Controller } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { useLoginPage } from '../../../../../../../features/auth';
+import { translateMessage } from '../../../../../../../shared/utils';
+import { useAuthRoutes } from '../../../../../../navigation';
+import { SupportEntry } from '../../../../organisms/support-entry';
+import type { LoginStepProps } from './types';
+
+/**
+ * Login step 1: the mobile number and «دریافت کد» right under it, the way to registration, and
+ * support. A number with no account gets the way to register with it under the field.
+ */
+export function LoginStep({ size, supportPlacement }: LoginStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const {
+ form,
+ submit,
+ isSubmitting,
+ formError,
+ isUnknownPhone,
+ registerHref,
+ carryPhone,
+ } = useLoginPage({
+ codeHref: routes.loginVerify,
+ registerHref: routes.register.type,
+ });
+
+ return (
+
+ {formError && (
+
+ {formError}
+
+ )}
+
+
+ {t('login.title')}
+
+ {t('login.description')}
+
+ {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+
+ (
+
+ )}
+ />
+ {isUnknownPhone && (
+
+ {t('login.register-with-phone')}
+
+ )}
+
+
+
+
+
+ {t('login.no-account')}
+
+
+ {t('login.register')}
+
+
+
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/index.ts
new file mode 100644
index 0000000..1429932
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/index.ts
@@ -0,0 +1,2 @@
+export { LoginStep } from './LoginStep';
+export type { LoginStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/types.ts
new file mode 100644
index 0000000..7ede64f
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/organisms/login-step/types.ts
@@ -0,0 +1,7 @@
+import type { SupportEntryProps } from '../../../../organisms/support-entry';
+
+export type LoginStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/LoginVerifyStep.tsx b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/LoginVerifyStep.tsx
new file mode 100644
index 0000000..e78c4da
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/LoginVerifyStep.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
+import { useTranslation } from 'react-i18next';
+
+import { useLoginVerifyPage } from '../../../../../../../../features/auth';
+import { useAuthRoutes } from '../../../../../../../navigation';
+import { CodeStep } from '../../../../organisms/code-step';
+import { SuspendedNotice } from './components/SuspendedNotice';
+import type { LoginVerifyStepProps } from './types';
+
+/**
+ * Login step 2: the code, then the person lands where they were going. A suspended account sees
+ * the suspended screen here instead. Without a number (after a reload) it waits in its skeleton
+ * while the model sends the person back to the number step.
+ */
+export function LoginVerifyStep({
+ size,
+ supportPlacement,
+}: LoginVerifyStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const model = useLoginVerifyPage({
+ phoneHref: routes.login,
+ landing: routes.landing,
+ });
+
+ if (model.view === 'suspended') {
+ return ;
+ }
+ if (!model.phone) {
+ return ;
+ }
+ return (
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/components/SuspendedNotice.tsx b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/components/SuspendedNotice.tsx
new file mode 100644
index 0000000..40f9e8b
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/components/SuspendedNotice.tsx
@@ -0,0 +1,55 @@
+'use client';
+
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { StateArt } from '@lumina/island/atoms/state-art';
+import { Typography } from '@lumina/island/atoms/typography';
+import { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { SupportEntry } from '../../../../../../organisms/support-entry';
+import type { SuspendedNoticeProps } from '../types';
+
+/**
+ * A valid code for a suspended account: no session, nothing else reachable, one way out to
+ * support. Amber, because a suspension is a state, not an error. It replaces the code step, so
+ * focus moves to its heading. The API gives no reason yet.
+ */
+export function SuspendedNotice({
+ size,
+ supportPlacement,
+}: SuspendedNoticeProps) {
+ const { t } = useTranslation('auth');
+ const headingRef = useRef(null);
+
+ useEffect(() => headingRef.current?.focus(), []);
+
+ return (
+
+
+
+
+ {t('suspended.title')}
+
+ {t('suspended.description')}
+
+
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/index.ts
new file mode 100644
index 0000000..6a58299
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/index.ts
@@ -0,0 +1,2 @@
+export { LoginVerifyStep } from './LoginVerifyStep';
+export type { LoginVerifyStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/types.ts
new file mode 100644
index 0000000..ab5907d
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/login/verify/organisms/login-verify-step/types.ts
@@ -0,0 +1,9 @@
+import type { SupportEntryProps } from '../../../../../organisms/support-entry';
+
+export type LoginVerifyStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+};
+
+export type SuspendedNoticeProps = LoginVerifyStepProps;
diff --git a/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/CodeStep.tsx b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/CodeStep.tsx
new file mode 100644
index 0000000..9374fc9
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/CodeStep.tsx
@@ -0,0 +1,135 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Link } from '@lumina/island/atoms/link';
+import { Typography } from '@lumina/island/atoms/typography';
+import { Banner } from '@lumina/island/molecules/banner';
+import { OtpInput } from '@lumina/island/molecules/otp-input';
+import { ResendCode } from '@lumina/island/molecules/resend-code';
+import type { FormEvent } from 'react';
+import { Controller } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { formatMobile, translateMessage } from '../../../../../../shared/utils';
+import { SupportEntry } from '../../../organisms/support-entry';
+import type { CodeStepProps } from './types';
+
+/**
+ * The 6-digit code step of login and registration: the number it went to, the cells, the resend
+ * wait and the submit button under them. Blocked, the cells and the button rest and the wait
+ * counts to the moment a new code may be asked for; «ویرایش شماره» stays live.
+ */
+export function CodeStep({
+ model,
+ submitLabel,
+ editHref,
+ size,
+ supportPlacement,
+ progress,
+}: CodeStepProps) {
+ const { t } = useTranslation('auth');
+ const { form, status, attempt, submit, complete, resend } = model;
+ const isBlocked = status === 'blocked';
+ const formError = form.formState.errors.root?.server?.message;
+
+ return (
+
+ {isBlocked && (
+
+ {t('code.blocked-description')}
+
+ )}
+ {formError && !isBlocked && {formError}}
+ {progress}
+
+
+ {t('code.title')}
+
+
+ {t('code.description', {
+ // Isolated left to right inside the sentence.
+ phone: `${formatMobile(model.phone ?? '')}`,
+ })}
+
+
+ {t('code.edit-phone')}
+
+
+ {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ (
+
+ )}
+ />
+
+
+
+ {!isBlocked && (
+
+ )}
+
+
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/index.ts
new file mode 100644
index 0000000..994a30c
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/index.ts
@@ -0,0 +1,2 @@
+export { CodeStep } from './CodeStep';
+export type { CodeStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/types.ts
new file mode 100644
index 0000000..09b5d02
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/organisms/code-step/types.ts
@@ -0,0 +1,18 @@
+import type { ReactNode } from 'react';
+
+import type { CodeStepModel } from '../../../../../../features/auth';
+import type { SupportEntryProps } from '../../../organisms/support-entry';
+
+export type CodeStepProps = {
+ /** The page model's code step (`useCodeStep`). */
+ model: CodeStepModel;
+ /** «ورود» for login, «تأیید و ادامه» for registration. */
+ submitLabel: string;
+ /** «ویرایش شماره»: back to the number step, which keeps the number. */
+ editHref: string;
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+ /** Registration's step bar, above the heading. */
+ progress?: ReactNode;
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/RegisterDetailsStep.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/RegisterDetailsStep.tsx
new file mode 100644
index 0000000..da26d15
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/RegisterDetailsStep.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
+import { useTranslation } from 'react-i18next';
+
+import { useRegisterDetailsPage } from '../../../../../../../../features/auth';
+import { useAuthRoutes } from '../../../../../../../navigation';
+import { CreatorIdentityForm } from './components/CreatorIdentityForm';
+import { InvestorDetailsForm } from './components/InvestorDetailsForm';
+import type { RegisterDetailsStepProps } from './types';
+
+/**
+ * Registration step 4, on the 15-minute token: account details for an investor, identity for a
+ * creator. There is no back: the code is used. Without a token (after a reload) it waits in its
+ * skeleton while the page sends the person back to the number.
+ */
+export function RegisterDetailsStep(props: RegisterDetailsStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const page = useRegisterDetailsPage({
+ phoneHref: routes.register.phone,
+ codeHref: routes.register.verify,
+ });
+
+ if (!page.role || page.expiresAt === null) {
+ return ;
+ }
+ const partOptions = {
+ profileHref: routes.profile[page.role],
+ onExpired: page.expire,
+ };
+ return page.role === 'creator' ? (
+
+ ) : (
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/CreatorIdentityForm.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/CreatorIdentityForm.tsx
new file mode 100644
index 0000000..98ae269
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/CreatorIdentityForm.tsx
@@ -0,0 +1,195 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Icon } from '@lumina/island/atoms/icon';
+import { Typography } from '@lumina/island/atoms/typography';
+import { FileField } from '@lumina/island/molecules/file-field';
+import { TextInput } from '@lumina/island/molecules/text-input';
+import { number } from '@lumina/tools/format';
+import { useId } from 'react';
+import type { ReactNode } from 'react';
+import { Controller } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { useCreatorIdentityPart } from '../../../../../../../../../features/auth';
+import type { IdCardSide } from '../../../../../../../../../features/auth';
+import { translateMessage } from '../../../../../../../../../shared/utils';
+import { ID_CARD_IMAGE } from '../../../../../../../../../shared/validations';
+import type { DetailsFormProps } from '../types';
+import { DetailsFrame } from './DetailsFrame';
+import { NameFields } from './NameFields';
+import { TermsLine } from './TermsLine';
+import { UsernameField } from './UsernameField';
+
+const ID_CARD_SIDES = [
+ { side: 'idCardFront', label: 'id-card-front' },
+ { side: 'idCardBack', label: 'id-card-back' },
+] as const satisfies readonly { side: IdCardSide; label: string }[];
+
+const BYTES_PER_MB = 1024 * 1024;
+
+/** A labelled group with its privacy line: what investors see, and what only the review sees. */
+function Group({
+ title,
+ note,
+ noteIcon,
+ children,
+}: {
+ title: string;
+ note: string;
+ noteIcon?: 'lock';
+ children: ReactNode;
+}) {
+ const titleId = useId();
+ return (
+
+
+
+ {title}
+
+
+ {noteIcon && (
+
+ )}
+
+ {note}
+
+
+
+ {children}
+
+ );
+}
+
+/**
+ * Step 4 for a creator: the public username, then the private identity (names, national code,
+ * both sides of the ID card) for the admin review. The images upload with a bar and can be
+ * cancelled; a failure keeps every value and image.
+ */
+export function CreatorIdentityForm(props: DetailsFormProps) {
+ const { t } = useTranslation('auth');
+ const {
+ form,
+ submit,
+ isSubmitting,
+ formError,
+ pickImage,
+ progress,
+ cancelUpload,
+ draft,
+ } = useCreatorIdentityPart(props.partOptions);
+
+ return (
+ void submit()}
+ footer={
+ <>
+
+ {progress !== undefined && (
+
+ )}
+
+ >
+ }
+ >
+
+
+
+
+
+ (
+
+ )}
+ />
+ {ID_CARD_SIDES.map(({ side, label }) => (
+ (
+ pickImage(side, file)}
+ onBlur={field.onBlur}
+ accept={ID_CARD_IMAGE.types.join(',')}
+ label={t(`register.fields.${label}`)}
+ hint={t('register.fields.id-card-hint')}
+ size={
+ field.value &&
+ t('register.fields.file-size', {
+ size: number(field.value.size / BYTES_PER_MB, 1),
+ })
+ }
+ error={translateMessage(t, fieldState.error?.message)}
+ progress={progress}
+ disabled={isSubmitting}
+ labels={{
+ pick: t('register.fields.id-card-pick'),
+ rules: t('register.fields.id-card-rules'),
+ remove: t('register.fields.id-card-remove'),
+ uploading: (percent) =>
+ t('register.fields.id-card-uploading', { percent }),
+ }}
+ />
+ )}
+ />
+ ))}
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/DetailsFrame.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/DetailsFrame.tsx
new file mode 100644
index 0000000..cd19f9f
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/DetailsFrame.tsx
@@ -0,0 +1,77 @@
+'use client';
+
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Typography } from '@lumina/island/atoms/typography';
+import { Banner } from '@lumina/island/molecules/banner';
+import type { FormEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { SupportEntry } from '../../../../../../organisms/support-entry';
+import { RegisterProgress } from '../../../../organisms/register-progress';
+import type { DetailsFrameProps } from '../types';
+import { ExpiryHalt } from './ExpiryHalt';
+import { ExpiryWarning } from './ExpiryWarning';
+
+/**
+ * What both account types' step 4 share: the token's warning and halt, the server-failure banner,
+ * the step bar and heading, the form with its submit under the fields, and support.
+ */
+export function DetailsFrame({
+ page,
+ title,
+ description,
+ formError,
+ footer,
+ draft,
+ onSubmit,
+ supportPlacement,
+ haltPlacement,
+ children,
+}: DetailsFrameProps) {
+ const { t } = useTranslation('auth');
+
+ return (
+
+ {page.phase === 'warning' && page.expiresAt !== null && (
+
+ )}
+ {formError && (
+
+ {formError}
+
+ )}
+
+
+
+ {title}
+
+ {description}
+
+ {
+ event.preventDefault();
+ onSubmit();
+ }}
+ >
+ {children}
+
+ {footer}
+
+
+
+
+
+ {page.phase === 'expired' && (
+ page.reverify(draft())}
+ />
+ )}
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryHalt.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryHalt.tsx
new file mode 100644
index 0000000..17ce12d
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryHalt.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { Modal } from '@lumina/island/molecules/modal';
+import { Sheet } from '@lumina/island/molecules/sheet';
+import { useTranslation } from 'react-i18next';
+
+import type { ExpiryHaltProps } from '../types';
+
+/**
+ * The registration token ran out: a blocking halt with no ✕ and no cancel. The one way on is a
+ * new code to the same number; after it, step 4 comes back with everything typed.
+ */
+export function ExpiryHalt({
+ placement,
+ isSending,
+ onConfirm,
+}: ExpiryHaltProps) {
+ const { t } = useTranslation('auth');
+ const title = t('register.expiry.title');
+ const description = t('register.expiry.description');
+ const button = (
+
+ );
+
+ return placement === 'sheet' ? (
+
+ {description}
+
+ ) : (
+
+ {description}
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryWarning.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryWarning.tsx
new file mode 100644
index 0000000..069cdc1
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/ExpiryWarning.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { Countdown } from '@lumina/island/atoms/countdown';
+import { Banner } from '@lumina/island/molecules/banner';
+import { useTranslation } from 'react-i18next';
+
+import type { ExpiryWarningProps } from '../types';
+
+/**
+ * Two minutes before the registration token runs out. Announced once (the banner's status
+ * role), never every second: the clock inside is not a live region.
+ */
+export function ExpiryWarning({ expiresAt }: ExpiryWarningProps) {
+ const { t } = useTranslation('auth');
+
+ return (
+
+ {t('register.expiry.warning-before')}{' '}
+ {' '}
+ {t('register.expiry.warning-after')}
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/InvestorDetailsForm.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/InvestorDetailsForm.tsx
new file mode 100644
index 0000000..b689d42
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/InvestorDetailsForm.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { useTranslation } from 'react-i18next';
+
+import { useInvestorDetailsPart } from '../../../../../../../../../features/auth';
+import type { DetailsFormProps } from '../types';
+import { DetailsFrame } from './DetailsFrame';
+import { NameFields } from './NameFields';
+import { TermsLine } from './TermsLine';
+import { UsernameField } from './UsernameField';
+
+/** Step 4 for an investor: name, last name and username, then «ساخت حساب». */
+export function InvestorDetailsForm(props: DetailsFormProps) {
+ const { t } = useTranslation('auth');
+ const { form, submit, isSubmitting, formError, draft } =
+ useInvestorDetailsPart(props.partOptions);
+
+ return (
+ void submit()}
+ footer={
+ <>
+
+
+ >
+ }
+ >
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/NameFields.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/NameFields.tsx
new file mode 100644
index 0000000..62c825a
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/NameFields.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { GridBox } from '@lumina/island/atoms/grid-box';
+import { TextInput } from '@lumina/island/molecules/text-input';
+import { Controller } from 'react-hook-form';
+import type { FieldValues, Path } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { translateMessage } from '../../../../../../../../../shared/utils';
+import type { NameFieldsProps } from '../types';
+
+const NAME_FIELDS = [
+ { name: 'firstName', label: 'first-name', autoComplete: 'given-name' },
+ { name: 'lastName', label: 'last-name', autoComplete: 'family-name' },
+] as const;
+
+/** First and last name in Persian: stacked on mobile, side by side on desktop. Private. */
+export function NameFields({
+ control,
+ isPaired,
+}: NameFieldsProps) {
+ const { t } = useTranslation('auth');
+
+ return (
+
+ {NAME_FIELDS.map(({ name, label, autoComplete }) => (
+ }
+ control={control}
+ render={({ field, fieldState }) => (
+
+ )}
+ />
+ ))}
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/TermsLine.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/TermsLine.tsx
new file mode 100644
index 0000000..224919c
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/TermsLine.tsx
@@ -0,0 +1,19 @@
+import { Typography } from '@lumina/island/atoms/typography';
+import { useTranslation } from 'react-i18next';
+
+import type { TermsLineProps } from '../types';
+
+/**
+ * Accepting the rules by submitting, with no checkbox. The rules page isn't designed yet, so the
+ * line names it without a link.
+ */
+export function TermsLine({ before }: TermsLineProps) {
+ const { t } = useTranslation('auth');
+
+ return (
+
+ {before}
+ {t('register.terms-link')}
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/UsernameField.tsx b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/UsernameField.tsx
new file mode 100644
index 0000000..a91681e
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/components/UsernameField.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { TextInput } from '@lumina/island/molecules/text-input';
+import { Controller } from 'react-hook-form';
+import type { FieldValues } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { translateMessage } from '../../../../../../../../../shared/utils';
+import { USERNAME_LENGTH } from '../../../../../../../../../shared/validations';
+import type { UsernameFieldProps } from '../types';
+
+/** The public username: left to right after a fixed «@», lower-case, 3 to 30 characters. */
+export function UsernameField({
+ control,
+ name,
+ placeholder,
+ hint,
+}: UsernameFieldProps) {
+ const { t } = useTranslation('auth');
+
+ return (
+ (
+
+ )}
+ />
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/index.ts
new file mode 100644
index 0000000..90f8468
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/index.ts
@@ -0,0 +1,2 @@
+export { RegisterDetailsStep } from './RegisterDetailsStep';
+export type { RegisterDetailsStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/types.ts
new file mode 100644
index 0000000..a2878a1
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/details/organisms/register-details-step/types.ts
@@ -0,0 +1,64 @@
+import type { ReactNode } from 'react';
+import type { Control, FieldValues, Path } from 'react-hook-form';
+
+import type {
+ RegisterDetailsPageModel,
+ UseDetailsPartOptions,
+} from '../../../../../../../../features/auth';
+import type { SupportEntryProps } from '../../../../../organisms/support-entry';
+
+export type RegisterDetailsStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+ /** The halt when the token runs out: a bottom sheet on mobile, a modal on desktop. */
+ haltPlacement: 'sheet' | 'modal';
+};
+
+/** What each account type's form gets from the step. */
+export type DetailsFormProps = RegisterDetailsStepProps & {
+ page: RegisterDetailsPageModel;
+ partOptions: UseDetailsPartOptions;
+};
+
+export type DetailsFrameProps = DetailsFormProps & {
+ /** Step 4's name in the bar and the heading. */
+ title: string;
+ description: string;
+ formError: string | undefined;
+ /** The submit button and what sits under it. */
+ footer: ReactNode;
+ /** The values to keep for the halt's new code. */
+ draft: () => Parameters[0];
+ onSubmit: () => void;
+ children: ReactNode;
+};
+
+export type ExpiryWarningProps = {
+ expiresAt: number;
+};
+
+export type ExpiryHaltProps = {
+ placement: RegisterDetailsStepProps['haltPlacement'];
+ isSending: boolean;
+ onConfirm: () => void;
+};
+
+export type TermsLineProps = {
+ /** «با ساخت حساب، » or «با ثبت اطلاعات، ». */
+ before: string;
+};
+
+export type UsernameFieldProps = {
+ control: Control;
+ name: Path;
+ placeholder: string;
+ /** A rule shown before typing, replaced by an error. */
+ hint?: string;
+};
+
+export type NameFieldsProps = {
+ control: Control;
+ /** Side by side on desktop. */
+ isPaired: boolean;
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/RegisterProgress.tsx b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/RegisterProgress.tsx
new file mode 100644
index 0000000..36ffa11
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/RegisterProgress.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { StepProgress } from '@lumina/island/molecules/step-progress';
+import { useTranslation } from 'react-i18next';
+
+import type { RegisterProgressProps } from './types';
+
+/** «مرحله n از ۵» over every registration step; step 4's name follows the account type. */
+export function RegisterProgress({ current, role }: RegisterProgressProps) {
+ const { t } = useTranslation('auth');
+ const steps = [
+ t('register.steps.type'),
+ t('register.steps.phone'),
+ t('register.steps.code'),
+ role === 'creator'
+ ? t('register.steps.identity')
+ : t('register.steps.details'),
+ t('register.steps.profile'),
+ ];
+
+ return (
+ t('register.step-count', { step, total })}
+ />
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/index.ts b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/index.ts
new file mode 100644
index 0000000..5e236f6
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/index.ts
@@ -0,0 +1,2 @@
+export { RegisterProgress } from './RegisterProgress';
+export type { RegisterProgressProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/types.ts b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/types.ts
new file mode 100644
index 0000000..82c0f87
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-progress/types.ts
@@ -0,0 +1,8 @@
+import type { UserRole } from '../../../../../../../features/auth';
+
+export type RegisterProgressProps = {
+ /** 0-based: account type, number, code, details or identity, profile. */
+ current: number;
+ /** Names step 4: «احراز هویت» for a creator, «اطلاعات حساب» otherwise. */
+ role: UserRole | null;
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/RegisterTypeStep.tsx b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/RegisterTypeStep.tsx
new file mode 100644
index 0000000..4f022c1
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/RegisterTypeStep.tsx
@@ -0,0 +1,134 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Icon } from '@lumina/island/atoms/icon';
+import { Link } from '@lumina/island/atoms/link';
+import { Typography } from '@lumina/island/atoms/typography';
+import { ChoiceCard } from '@lumina/island/molecules/choice-card';
+import type { FormEvent } from 'react';
+import { Controller, useWatch } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { useRegisterTypePage } from '../../../../../../../features/auth';
+import type { UserRole } from '../../../../../../../features/auth';
+import { translateMessage } from '../../../../../../../shared/utils';
+import { useAuthRoutes } from '../../../../../../navigation';
+import { SupportEntry } from '../../../../organisms/support-entry';
+import { RegisterProgress } from '../register-progress';
+import type { RegisterTypeStepProps } from './types';
+
+const ACCOUNT_TYPES = [
+ { value: 'investor', icon: 'investor' },
+ { value: 'creator', icon: 'analyst' },
+] as const satisfies readonly { value: UserRole; icon: string }[];
+
+/**
+ * Registration step 1: two cards, one line each on what the account is for, nothing
+ * pre-selected. The account type can't change later, so the note says so before the choice.
+ */
+export function RegisterTypeStep({
+ size,
+ supportPlacement,
+}: RegisterTypeStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const { form, submit } = useRegisterTypePage({
+ phoneHref: routes.register.phone,
+ });
+ const role = useWatch({ control: form.control, name: 'role' });
+
+ return (
+
+
+
+
+ {t('register.type.title')}
+
+
+ {t('register.type.description')}
+
+
+ {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ {
+ const error = translateMessage(t, fieldState.error?.message);
+ return (
+
+
+ {t('register.type.label')}
+
+ {ACCOUNT_TYPES.map(({ value, icon }) => (
+ field.onChange(value)}
+ title={t(`register.type.${value}`)}
+ description={t(`register.type.${value}-description`)}
+ invalid={error !== undefined}
+ />
+ ))}
+
+
+
+ {error ?? t('register.type.note')}
+
+
+
+ );
+ }}
+ />
+
+
+
+
+ {t('register.has-account')}
+
+ {t('register.login')}
+
+
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/index.ts
new file mode 100644
index 0000000..c213987
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/index.ts
@@ -0,0 +1,2 @@
+export { RegisterTypeStep } from './RegisterTypeStep';
+export type { RegisterTypeStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/types.ts
new file mode 100644
index 0000000..d688e2e
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/organisms/register-type-step/types.ts
@@ -0,0 +1,7 @@
+import type { SupportEntryProps } from '../../../../organisms/support-entry';
+
+export type RegisterTypeStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/RegisterPhoneStep.tsx b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/RegisterPhoneStep.tsx
new file mode 100644
index 0000000..78e6bf6
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/RegisterPhoneStep.tsx
@@ -0,0 +1,152 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { Icon } from '@lumina/island/atoms/icon';
+import { Link } from '@lumina/island/atoms/link';
+import { Typography } from '@lumina/island/atoms/typography';
+import { Banner } from '@lumina/island/molecules/banner';
+import { TextInput } from '@lumina/island/molecules/text-input';
+import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
+import type { FormEvent } from 'react';
+import { Controller } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { useRegisterPhonePage } from '../../../../../../../../features/auth';
+import { translateMessage } from '../../../../../../../../shared/utils';
+import { useAuthRoutes } from '../../../../../../../navigation';
+import { SupportEntry } from '../../../../../organisms/support-entry';
+import { RegisterProgress } from '../../../organisms/register-progress';
+import type { RegisterPhoneStepProps } from './types';
+
+/**
+ * Registration step 2: the number, with the chosen account type still in view and «تغییر» back
+ * to step 1. A number that already has an account offers to sign in with it.
+ */
+export function RegisterPhoneStep({
+ size,
+ supportPlacement,
+}: RegisterPhoneStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const {
+ role,
+ form,
+ submit,
+ isSubmitting,
+ formError,
+ isTakenPhone,
+ loginWithPhone,
+ isLoggingIn,
+ carryPhone,
+ } = useRegisterPhonePage({
+ typeHref: routes.register.type,
+ codeHref: routes.register.verify,
+ loginCodeHref: routes.loginVerify,
+ });
+
+ if (!role) return ;
+
+ return (
+
+ {formError && (
+
+ {formError}
+
+ )}
+
+
+
+ {t('register.phone.title')}
+
+
+ {t('register.phone.description')}
+
+
+
+
+
+ {role === 'creator'
+ ? t('register.phone.as-creator')
+ : t('register.phone.as-investor')}
+
+
+ {t('register.phone.change')}
+
+
+ {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+
+ (
+
+ )}
+ />
+ {isTakenPhone && (
+
+ )}
+
+
+
+
+
+ {t('register.has-account')}
+
+
+ {t('register.login')}
+
+
+
+
+
+
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/index.ts
new file mode 100644
index 0000000..d4ef48b
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/index.ts
@@ -0,0 +1,2 @@
+export { RegisterPhoneStep } from './RegisterPhoneStep';
+export type { RegisterPhoneStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/types.ts
new file mode 100644
index 0000000..d32c601
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/phone/organisms/register-phone-step/types.ts
@@ -0,0 +1,7 @@
+import type { SupportEntryProps } from '../../../../../organisms/support-entry';
+
+export type RegisterPhoneStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+};
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/RegisterVerifyStep.tsx b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/RegisterVerifyStep.tsx
new file mode 100644
index 0000000..3daa25c
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/RegisterVerifyStep.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
+import { useTranslation } from 'react-i18next';
+
+import { useRegisterVerifyPage } from '../../../../../../../../features/auth';
+import { useAuthRoutes } from '../../../../../../../navigation';
+import { CodeStep } from '../../../../organisms/code-step';
+import { RegisterProgress } from '../../../organisms/register-progress';
+import type { RegisterVerifyStepProps } from './types';
+
+/**
+ * Registration step 3: login's code step with the step bar and «تأیید و ادامه». A verified code
+ * opens step 4 on the 15-minute registration token.
+ */
+export function RegisterVerifyStep({
+ size,
+ supportPlacement,
+}: RegisterVerifyStepProps) {
+ const { t } = useTranslation('auth');
+ const routes = useAuthRoutes();
+ const model = useRegisterVerifyPage({
+ phoneHref: routes.register.phone,
+ detailsHref: routes.register.details,
+ });
+
+ if (!model.phone) {
+ return ;
+ }
+ return (
+ }
+ submitLabel={t('register.verify.submit')}
+ editHref={routes.register.phone}
+ size={size}
+ supportPlacement={supportPlacement}
+ />
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/index.ts b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/index.ts
new file mode 100644
index 0000000..a85f75e
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/index.ts
@@ -0,0 +1,2 @@
+export { RegisterVerifyStep } from './RegisterVerifyStep';
+export type { RegisterVerifyStepProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/types.ts b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/types.ts
new file mode 100644
index 0000000..a23a268
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/auth/register/verify/organisms/register-verify-step/types.ts
@@ -0,0 +1,7 @@
+import type { SupportEntryProps } from '../../../../../organisms/support-entry';
+
+export type RegisterVerifyStepProps = {
+ /** `lg` on mobile, `md` on desktop. */
+ size: 'md' | 'lg';
+ supportPlacement: SupportEntryProps['placement'];
+};
diff --git a/platforms/market/src/app/screens/(auth)/organisms/support-entry/SupportEntry.tsx b/platforms/market/src/app/screens/(auth)/organisms/support-entry/SupportEntry.tsx
new file mode 100644
index 0000000..28404d4
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/organisms/support-entry/SupportEntry.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { Button } from '@lumina/island/atoms/button';
+import { FlexBox } from '@lumina/island/atoms/flex-box';
+import { SupportLink } from '@lumina/island/atoms/support-link';
+import { SupportSheet } from '@lumina/island/organisms/support-sheet';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getEnv } from '../../../../../env';
+import { ROUTES } from '../../../../navigation';
+import { SUPPORT_CHAT_URLS } from './constants';
+import type { SupportEntryProps } from './types';
+
+/**
+ * One way into support: its trigger and the support sheet it opens (a bottom sheet on mobile, a
+ * popover under the trigger on desktop). The chats and hours come from config.
+ */
+export function SupportEntry({
+ trigger,
+ placement,
+ size = 'lg',
+}: SupportEntryProps) {
+ const { t } = useTranslation('auth');
+ const [isOpen, setIsOpen] = useState(false);
+ const { baleHandle, telegramHandle, supportHours } = getEnv();
+ const toggle = () => setIsOpen((open) => !open);
+ const dialogProps = {
+ 'aria-haspopup': 'dialog',
+ 'aria-expanded': isOpen,
+ onClick: toggle,
+ } as const;
+
+ const button =
+ trigger === 'icon' ? (
+
+ ) : trigger === 'link' ? (
+
+ {t('support.link')}
+
+ ) : (
+
+ );
+
+ const sheet = (
+ setIsOpen(false)}
+ baleHref={SUPPORT_CHAT_URLS.bale(baleHandle)}
+ telegramHref={SUPPORT_CHAT_URLS.telegram(telegramHandle)}
+ termsHref={ROUTES.terms}
+ labels={{
+ title: t('support.title'),
+ bale: t('support.bale'),
+ telegram: t('support.telegram'),
+ hours: t('support.hours', { hours: supportHours }),
+ terms: t('support.terms'),
+ close: t('support.close'),
+ opensNewTab: t('support.opens-new-tab'),
+ }}
+ />
+ );
+
+ // A popover hangs from a positioned parent that also holds its trigger.
+ return placement === 'popover' ? (
+
+ {button}
+ {sheet}
+
+ ) : (
+ <>
+ {button}
+ {sheet}
+ >
+ );
+}
diff --git a/platforms/market/src/app/screens/(auth)/organisms/support-entry/constants.ts b/platforms/market/src/app/screens/(auth)/organisms/support-entry/constants.ts
new file mode 100644
index 0000000..4cfbb8a
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/organisms/support-entry/constants.ts
@@ -0,0 +1,5 @@
+/** The support chats' addresses; only the handles come from config. */
+export const SUPPORT_CHAT_URLS = {
+ bale: (handle: string) => `https://ble.ir/${handle}`,
+ telegram: (handle: string) => `https://t.me/${handle}`,
+} as const;
diff --git a/platforms/market/src/app/screens/(auth)/organisms/support-entry/index.ts b/platforms/market/src/app/screens/(auth)/organisms/support-entry/index.ts
new file mode 100644
index 0000000..89b6d23
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/organisms/support-entry/index.ts
@@ -0,0 +1,2 @@
+export { SupportEntry } from './SupportEntry';
+export type { SupportEntryProps } from './types';
diff --git a/platforms/market/src/app/screens/(auth)/organisms/support-entry/types.ts b/platforms/market/src/app/screens/(auth)/organisms/support-entry/types.ts
new file mode 100644
index 0000000..5406b96
--- /dev/null
+++ b/platforms/market/src/app/screens/(auth)/organisms/support-entry/types.ts
@@ -0,0 +1,13 @@
+import type { SupportPlacement } from '@lumina/island/organisms/support-sheet';
+
+export type SupportEntryProps = {
+ /**
+ * icon: the headset in a header. link: «تماس با پشتیبانی» on its own line under a form.
+ * button: the primary action of a screen that leaves nothing else to do (suspended).
+ */
+ trigger: 'icon' | 'link' | 'button';
+ /** bottom: the mobile sheet. popover: desktop, hanging under its trigger. */
+ placement: Extract;
+ /** The button trigger's size: `lg` on mobile, `md` on desktop. */
+ size?: 'md' | 'lg';
+};
diff --git a/platforms/market/src/features/auth/actions/login/actions.ts b/platforms/market/src/features/auth/actions/login/actions.ts
index b05e39a..a2fd87c 100644
--- a/platforms/market/src/features/auth/actions/login/actions.ts
+++ b/platforms/market/src/features/auth/actions/login/actions.ts
@@ -1,25 +1,35 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
-import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth';
+import type { VerifyOtpArgs } from '../../repositories/auth';
+import type { LoginOutcome } from './types';
/**
* Verifies the login code; the gateway sets the session cookies and the auth store learns the
- * account, so every auth-dependent part renders its member variant. Emits `auth.login`.
+ * account, so every auth-dependent part renders its member variant. A suspended account gets no
+ * session: the gateway still opens one, so it is closed again at once. Emits `auth.login` when
+ * the person is signed in.
*/
export async function login(
args: VerifyOtpArgs,
{ emit = true }: { emit?: boolean } = {},
-): Promise {
- const session = await authRepository.verifyLoginOtp(args);
- useAuthStore.getState().setSession({ account: session.account });
+): Promise {
+ const { account } = await authRepository.verifyLoginOtp(args);
+ if (account.status === 'suspended') {
+ await authRepository.logout();
+ useAuthFlowStore.getState().reset();
+ return { status: 'suspended' };
+ }
+ useAuthFlowStore.getState().reset();
+ useAuthStore.getState().setSession({ account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.login, {
- userId: session.account.id,
- role: session.account.role,
+ userId: account.id,
+ role: account.role,
});
}
- return session;
+ return { status: 'signed-in', account };
}
diff --git a/platforms/market/src/features/auth/actions/login/index.ts b/platforms/market/src/features/auth/actions/login/index.ts
index 00d9ea2..c4d9971 100644
--- a/platforms/market/src/features/auth/actions/login/index.ts
+++ b/platforms/market/src/features/auth/actions/login/index.ts
@@ -1 +1,2 @@
export { login } from './actions';
+export type { LoginOutcome } from './types';
diff --git a/platforms/market/src/features/auth/actions/login/types.ts b/platforms/market/src/features/auth/actions/login/types.ts
new file mode 100644
index 0000000..730699a
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/login/types.ts
@@ -0,0 +1,6 @@
+import type { AccountPayload } from '../../repositories/account';
+
+/** Signed in, or turned away because the account is suspended (no session). */
+export type LoginOutcome =
+ | { status: 'signed-in'; account: AccountPayload }
+ | { status: 'suspended' };
diff --git a/platforms/market/src/features/auth/actions/register-creator/actions.ts b/platforms/market/src/features/auth/actions/register-creator/actions.ts
index c057fb6..c299a94 100644
--- a/platforms/market/src/features/auth/actions/register-creator/actions.ts
+++ b/platforms/market/src/features/auth/actions/register-creator/actions.ts
@@ -1,6 +1,8 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
+import type { UploadProgress } from '@lumina/libs/http';
import { useAuthStore } from '../../../../stores/auth';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
@@ -8,12 +10,28 @@ import type {
RegisterCreatorArgs,
} from '../../repositories/auth';
-/** Creates a creator account with lite KYC and signs it in (cookies and auth store). Emits `auth.register`. */
+/**
+ * Creates a creator account with lite KYC (the ID images upload with progress and can be
+ * cancelled) and signs it in (cookies and auth store); the flow's number and token are dropped.
+ * Emits `auth.register`.
+ */
export async function registerCreator(
args: RegisterCreatorArgs,
- { emit = true }: { emit?: boolean } = {},
+ {
+ emit = true,
+ signal,
+ onProgress,
+ }: {
+ emit?: boolean;
+ signal?: AbortSignal;
+ onProgress?: (progress: UploadProgress) => void;
+ } = {},
): Promise {
- const registration = await authRepository.registerCreator(args);
+ const registration = await authRepository.registerCreator(args, {
+ signal,
+ onProgress,
+ });
+ useAuthFlowStore.getState().reset();
useAuthStore.getState().setSession({ account: registration.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
diff --git a/platforms/market/src/features/auth/actions/register-investor/actions.ts b/platforms/market/src/features/auth/actions/register-investor/actions.ts
index a5e104e..00ebea0 100644
--- a/platforms/market/src/features/auth/actions/register-investor/actions.ts
+++ b/platforms/market/src/features/auth/actions/register-investor/actions.ts
@@ -1,6 +1,7 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
@@ -8,12 +9,13 @@ import type {
SessionPayload,
} from '../../repositories/auth';
-/** Creates an investor account and signs it in (cookies and auth store). Emits `auth.register`. */
+/** Creates an investor account and signs it in (cookies and auth store); the flow's number and token are dropped. Emits `auth.register`. */
export async function registerInvestor(
args: RegisterInvestorArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise {
const session = await authRepository.registerInvestor(args);
+ useAuthFlowStore.getState().reset();
useAuthStore.getState().setSession({ account: session.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
diff --git a/platforms/market/src/features/auth/actions/send-code/actions.ts b/platforms/market/src/features/auth/actions/send-code/actions.ts
new file mode 100644
index 0000000..835f0af
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/send-code/actions.ts
@@ -0,0 +1,37 @@
+import { eventEmitter } from '@lumina/libs/event-emitter';
+
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { AUTH_EVENTS } from '../../constants';
+import {
+ AUTH_ERROR_CODES,
+ authErrorCode,
+ authRepository,
+} from '../../repositories/auth';
+import type { SendCodeArgs } from './types';
+
+/**
+ * Sends a sign-in or registration code to the number and starts the resend wait. Also the resend:
+ * a new code replaces the previous one. Asked again for the same number inside the server's
+ * cooldown, the code already sent still works, so that counts as sent. Emits `auth.code-sent`.
+ */
+export async function sendCode(
+ { purpose, phone }: SendCodeArgs,
+ { emit = true }: { emit?: boolean } = {},
+): Promise<'ok'> {
+ try {
+ if (purpose === 'login') await authRepository.requestLoginOtp({ phone });
+ else await authRepository.sendRegistrationOtp({ phone });
+ } catch (error) {
+ const flow = useAuthFlowStore.getState();
+ const isSameCode =
+ authErrorCode(error) === AUTH_ERROR_CODES.cooldown &&
+ flow.purpose === purpose &&
+ flow.phone === phone &&
+ flow.codeSentAt !== null;
+ if (!isSameCode) throw error;
+ return 'ok';
+ }
+ useAuthFlowStore.getState().codeSent(purpose, phone, Date.now());
+ if (emit) eventEmitter.emit(AUTH_EVENTS.codeSent, { purpose });
+ return 'ok';
+}
diff --git a/platforms/market/src/features/auth/actions/send-code/index.ts b/platforms/market/src/features/auth/actions/send-code/index.ts
new file mode 100644
index 0000000..29246e9
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/send-code/index.ts
@@ -0,0 +1,2 @@
+export { sendCode } from './actions';
+export type { SendCodeArgs } from './types';
diff --git a/platforms/market/src/features/auth/actions/send-code/types.ts b/platforms/market/src/features/auth/actions/send-code/types.ts
new file mode 100644
index 0000000..7a17150
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/send-code/types.ts
@@ -0,0 +1,7 @@
+import type { AuthPurpose } from '../../types';
+
+export type SendCodeArgs = {
+ purpose: AuthPurpose;
+ /** 09XXXXXXXXX; the repository sends E.164. */
+ phone: string;
+};
diff --git a/platforms/market/src/features/auth/actions/verify-registration-code/actions.ts b/platforms/market/src/features/auth/actions/verify-registration-code/actions.ts
new file mode 100644
index 0000000..ecd9a10
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/verify-registration-code/actions.ts
@@ -0,0 +1,26 @@
+import { eventEmitter } from '@lumina/libs/event-emitter';
+
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { AUTH_EVENTS } from '../../constants';
+import { authRepository } from '../../repositories/auth';
+import type { VerifyOtpArgs } from '../../repositories/auth';
+
+/**
+ * Proves the number for a new account. The registration token it returns lives in memory only
+ * (the flow store), for step 4, and is never stored. Emits `auth.phone-verified`.
+ */
+export async function verifyRegistrationCode(
+ args: VerifyOtpArgs,
+ { emit = true }: { emit?: boolean } = {},
+): Promise<'ok'> {
+ const { registrationToken, expiresInSeconds } =
+ await authRepository.verifyRegistrationOtp(args);
+ useAuthFlowStore.getState().phoneVerified({
+ token: registrationToken,
+ expiresAt: Date.now() + expiresInSeconds * 1000,
+ });
+ if (emit) {
+ eventEmitter.emit(AUTH_EVENTS.phoneVerified, { purpose: 'register' });
+ }
+ return 'ok';
+}
diff --git a/platforms/market/src/features/auth/actions/verify-registration-code/index.ts b/platforms/market/src/features/auth/actions/verify-registration-code/index.ts
new file mode 100644
index 0000000..41f7410
--- /dev/null
+++ b/platforms/market/src/features/auth/actions/verify-registration-code/index.ts
@@ -0,0 +1 @@
+export { verifyRegistrationCode } from './actions';
diff --git a/platforms/market/src/features/auth/constants.ts b/platforms/market/src/features/auth/constants.ts
index d4b53a8..d01e184 100644
--- a/platforms/market/src/features/auth/constants.ts
+++ b/platforms/market/src/features/auth/constants.ts
@@ -1,7 +1,27 @@
/** Events auth actions emit when they succeed; the AppShell reacts to them. */
export const AUTH_EVENTS = {
restore: 'auth.restore',
+ codeSent: 'auth.code-sent',
+ phoneVerified: 'auth.phone-verified',
login: 'auth.login',
register: 'auth.register',
logout: 'auth.logout',
} as const;
+
+/** Why a code is sent: to sign in to an account, or to prove the number for a new one. */
+export const AUTH_PURPOSES = ['login', 'register'] as const;
+
+/**
+ * The code rules the pages show. The server owns them (a code lives 10 minutes, the third wrong
+ * code blocks the number for 10 minutes); the 2-minute resend wait is the product's, longer than
+ * the server's 60-second cooldown.
+ */
+export const CODE_RULES = {
+ length: 6,
+ resendWaitSeconds: 120,
+ maxMisses: 3,
+ blockSeconds: 600,
+} as const;
+
+/** Step 4 warns this long before the registration token runs out. */
+export const REGISTRATION_WARNING_SECONDS = 120;
diff --git a/platforms/market/src/features/auth/index.ts b/platforms/market/src/features/auth/index.ts
index d410726..eecde36 100644
--- a/platforms/market/src/features/auth/index.ts
+++ b/platforms/market/src/features/auth/index.ts
@@ -1,16 +1,78 @@
import './types';
export { login } from './actions/login';
+export type { LoginOutcome } from './actions/login';
export { logout } from './actions/logout';
export { registerCreator } from './actions/register-creator';
export { registerInvestor } from './actions/register-investor';
export { restoreSession } from './actions/restore-session';
-export { AUTH_EVENTS } from './constants';
+export { sendCode } from './actions/send-code';
+export type { SendCodeArgs } from './actions/send-code';
+export { verifyRegistrationCode } from './actions/verify-registration-code';
+export {
+ AUTH_EVENTS,
+ AUTH_PURPOSES,
+ CODE_RULES,
+ REGISTRATION_WARNING_SECONDS,
+} from './constants';
export type { UserRole, UserStatus } from './entities/user';
+export { useCodeStep } from './models/code-step';
+export type {
+ CodeStepModel,
+ CodeStepStatus,
+ CodeVerifiedOutcome,
+ ResendPhase,
+ UseCodeStepOptions,
+} from './models/code-step';
+export { useLoginPage } from './models/login';
+export type { LoginPageModel, UseLoginPageOptions } from './models/login';
+export { useLoginVerifyPage } from './models/login-verify';
+export type {
+ LoginVerifyPageModel,
+ LoginVerifyView,
+ SignedInViewer,
+ UseLoginVerifyPageOptions,
+} from './models/login-verify';
+export {
+ useCreatorIdentityPart,
+ useInvestorDetailsPart,
+ useRegisterDetailsPage,
+} from './models/register-details';
+export type {
+ CreatorIdentityPartModel,
+ IdCardSide,
+ InvestorDetailsPartModel,
+ RegisterDetailsPageModel,
+ RegistrationTimePhase,
+ UseDetailsPartOptions,
+ UseRegisterDetailsPageOptions,
+} from './models/register-details';
+export { useRegisterPhonePage } from './models/register-phone';
+export type {
+ RegisterPhonePageModel,
+ UseRegisterPhonePageOptions,
+} from './models/register-phone';
+export { useRegisterTypePage } from './models/register-type';
+export type {
+ RegisterTypePageModel,
+ UseRegisterTypePageOptions,
+} from './models/register-type';
+export { useRegisterVerifyPage } from './models/register-verify';
+export type {
+ RegisterVerifyPageModel,
+ UseRegisterVerifyPageOptions,
+} from './models/register-verify';
export { accountKeys, accountRepository } from './repositories/account';
export type { AccountPayload, UpdateAccountArgs } from './repositories/account';
-export { AUTH_ENDPOINTS, authRepository } from './repositories/auth';
+export {
+ AUTH_ENDPOINTS,
+ AUTH_ERROR_CODES,
+ AUTH_ERROR_COPY,
+ authErrorCode,
+ authRepository,
+} from './repositories/auth';
export type {
+ AuthErrorCode,
CreatorRegisteredPayload,
OtpSentPayload,
RegisterCreatorArgs,
@@ -21,4 +83,4 @@ export type {
SessionStatePayload,
VerifyOtpArgs,
} from './repositories/auth';
-export type { LogoutReason } from './types';
+export type { AuthPurpose, LogoutReason } from './types';
diff --git a/platforms/market/src/features/auth/models/.gitkeep b/platforms/market/src/features/auth/models/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/platforms/market/src/features/auth/models/code-step/constants.ts b/platforms/market/src/features/auth/models/code-step/constants.ts
new file mode 100644
index 0000000..24cb835
--- /dev/null
+++ b/platforms/market/src/features/auth/models/code-step/constants.ts
@@ -0,0 +1,2 @@
+/** How long «کد جدید ارسال شد.» stays before the wait counts again. */
+export const SENT_NOTICE_MS = 2000;
diff --git a/platforms/market/src/features/auth/models/code-step/index.ts b/platforms/market/src/features/auth/models/code-step/index.ts
new file mode 100644
index 0000000..2a0a4bd
--- /dev/null
+++ b/platforms/market/src/features/auth/models/code-step/index.ts
@@ -0,0 +1,8 @@
+export { useCodeStep } from './use-code-step';
+export type {
+ CodeStepModel,
+ CodeStepStatus,
+ CodeVerifiedOutcome,
+ ResendPhase,
+ UseCodeStepOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/code-step/types.ts b/platforms/market/src/features/auth/models/code-step/types.ts
new file mode 100644
index 0000000..e0e9031
--- /dev/null
+++ b/platforms/market/src/features/auth/models/code-step/types.ts
@@ -0,0 +1,43 @@
+import type { UseFormReturn } from 'react-hook-form';
+
+import type { CodeFormValues } from '../../../../shared/validations';
+import type { VerifyOtpArgs } from '../../repositories/auth';
+import type { AuthPurpose } from '../../types';
+
+/** stay: the code step stays (a suspended account). leave: the page is moving on. */
+export type CodeVerifiedOutcome = 'stay' | 'leave';
+
+export type UseCodeStepOptions = {
+ purpose: AuthPurpose;
+ /** The number step, where a missing number (after a reload) sends the person back. */
+ phoneHref: string;
+ /** What failed, for the toast: «ورود انجام نشد». */
+ failedMessage: string;
+ /** The purpose's action; resolves once the page knows where to go. */
+ verify: (args: VerifyOtpArgs) => Promise;
+};
+
+/** idle: typing. verifying: a code is checked, or the page is moving on. blocked: too many wrong codes. */
+export type CodeStepStatus = 'idle' | 'verifying' | 'blocked';
+
+/** The resend control's own phase: the wait (or the button), a send in flight, its confirmation. */
+export type ResendPhase = 'auto' | 'sending' | 'sent';
+
+export type CodeStepModel = {
+ /** `null` until the number is known; the page then redirects. */
+ phone: string | null;
+ form: UseFormReturn;
+ status: CodeStepStatus;
+ /** Remounts the cells after a wrong code or a new one, so focus is back on the first cell. */
+ attempt: number;
+ submit: () => Promise;
+ /** The 6th digit submits on its own. */
+ complete: (code: string) => void;
+ resend: {
+ /** When the wait (or the block) ends, ms since epoch. */
+ endsAt: number | undefined;
+ phase: ResendPhase;
+ onResend: () => void;
+ };
+ blockedUntil: number | null;
+};
diff --git a/platforms/market/src/features/auth/models/code-step/use-code-step.ts b/platforms/market/src/features/auth/models/code-step/use-code-step.ts
new file mode 100644
index 0000000..d353dd5
--- /dev/null
+++ b/platforms/market/src/features/auth/models/code-step/use-code-step.ts
@@ -0,0 +1,161 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { useRouter } from 'next/navigation';
+import { useEffect, useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { applyServerErrors, showActionError } from '../../../../shared/utils';
+import { codeSchema } from '../../../../shared/validations';
+import type { CodeFormValues } from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { sendCode } from '../../actions/send-code';
+import { CODE_RULES } from '../../constants';
+import {
+ AUTH_ERROR_CODES,
+ authErrorCode,
+ blockEndOf,
+} from '../../repositories/auth';
+import { SENT_NOTICE_MS } from './constants';
+import type { CodeStepModel, ResendPhase, UseCodeStepOptions } from './types';
+
+/** A wrong code counts; the third one blocks the number until the returned time. Event handlers only. */
+function countMiss(): number | null {
+ useAuthFlowStore.getState().codeMissed();
+ return useAuthFlowStore.getState().misses >= CODE_RULES.maxMisses
+ ? Date.now() + CODE_RULES.blockSeconds * 1000
+ : null;
+}
+
+/**
+ * The code step that login and registration share: the 6-digit field, the resend wait, wrong and
+ * expired codes, and the 10-minute block. The server never says how many tries are left, so the
+ * misses are counted here; the third one blocks the number, as the server does.
+ */
+export function useCodeStep({
+ purpose,
+ phoneHref,
+ failedMessage,
+ verify,
+}: UseCodeStepOptions): CodeStepModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ // Read once: a successful sign-in clears the flow while this page is still on screen.
+ const [phone] = useState(() => useAuthFlowStore.getState().phone);
+ const codeSentAt = useAuthFlowStore((state) => state.codeSentAt);
+ const blockedUntil = useAuthFlowStore((state) => state.blockedUntil);
+ const [attempt, setAttempt] = useState(0);
+ const [phase, setPhase] = useState('auto');
+ const [isLeaving, setIsLeaving] = useState(false);
+ const form = useForm({
+ resolver: valibotResolver(codeSchema),
+ defaultValues: { code: '' },
+ });
+
+ // A reload forgets the number (it is never in the URL), so the flow starts again at its number.
+ useEffect(() => {
+ if (!phone) router.replace(phoneHref);
+ }, [phone, phoneHref, router]);
+
+ useEffect(() => {
+ if (blockedUntil === null) return undefined;
+ const timer = setTimeout(
+ () => useAuthFlowStore.getState().block(null),
+ Math.max(0, blockedUntil - Date.now()),
+ );
+ return () => clearTimeout(timer);
+ }, [blockedUntil]);
+
+ useEffect(() => {
+ if (phase !== 'sent') return undefined;
+ const timer = setTimeout(() => setPhase('auto'), SENT_NOTICE_MS);
+ return () => clearTimeout(timer);
+ }, [phase]);
+
+ /** Empty cells and focus on the first one. Clears errors too, so set them after. */
+ const restart = () => {
+ form.reset({ code: '' });
+ setAttempt((count) => count + 1);
+ };
+
+ const fail = (error: unknown) => {
+ const options = { t, failedMessage };
+ const code = authErrorCode(error);
+ const isWrong = code === AUTH_ERROR_CODES.codeWrong;
+ const blockEnd = isWrong ? countMiss() : blockEndOf(error);
+ if (isWrong || blockEnd !== null || code === AUTH_ERROR_CODES.codeExpired) {
+ restart();
+ }
+ if (blockEnd !== null) {
+ useAuthFlowStore.getState().block(blockEnd);
+ showActionError(error, options);
+ return;
+ }
+ if (isWrong) {
+ const isLastTry =
+ useAuthFlowStore.getState().misses === CODE_RULES.maxMisses - 1;
+ form.setError('code', {
+ type: 'server',
+ message: isLastTry ? 'auth:code.wrong-last' : 'auth:code.wrong',
+ });
+ showActionError(error, options);
+ return;
+ }
+ applyServerErrors(form, error, options);
+ };
+
+ const submit = form.handleSubmit(async ({ code }) => {
+ if (!phone) return;
+ try {
+ if ((await verify({ phone, code })) === 'leave') setIsLeaving(true);
+ } catch (error) {
+ fail(error);
+ }
+ });
+
+ const onResend = () => {
+ if (!phone || phase === 'sending') return;
+ setPhase('sending');
+ sendCode({ purpose, phone })
+ .then(() => {
+ restart();
+ setPhase('sent');
+ })
+ .catch((error: unknown) => {
+ setPhase('auto');
+ const blockEnd = blockEndOf(error);
+ if (blockEnd !== null) useAuthFlowStore.getState().block(blockEnd);
+ showActionError(error, {
+ t,
+ failedMessage: t('code.resend-failed'),
+ retry: onResend,
+ });
+ });
+ };
+
+ return {
+ phone,
+ form,
+ status:
+ blockedUntil !== null
+ ? 'blocked'
+ : form.formState.isSubmitting || isLeaving
+ ? 'verifying'
+ : 'idle',
+ attempt,
+ submit: () => submit(),
+ complete: (code) => {
+ form.setValue('code', code);
+ void submit();
+ },
+ resend: {
+ endsAt:
+ blockedUntil ??
+ (codeSentAt === null
+ ? undefined
+ : codeSentAt + CODE_RULES.resendWaitSeconds * 1000),
+ phase,
+ onResend,
+ },
+ blockedUntil,
+ };
+}
diff --git a/platforms/market/src/features/auth/models/login-verify/index.ts b/platforms/market/src/features/auth/models/login-verify/index.ts
new file mode 100644
index 0000000..c45f26b
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login-verify/index.ts
@@ -0,0 +1,7 @@
+export { useLoginVerifyPage } from './use-login-verify-page';
+export type {
+ LoginVerifyPageModel,
+ LoginVerifyView,
+ SignedInViewer,
+ UseLoginVerifyPageOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/login-verify/types.ts b/platforms/market/src/features/auth/models/login-verify/types.ts
new file mode 100644
index 0000000..08ffe5c
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login-verify/types.ts
@@ -0,0 +1,22 @@
+import type { UserRole } from '../../entities/user';
+import type { CodeStepModel } from '../code-step';
+
+/** Who just signed in, for picking where they land. */
+export type SignedInViewer = {
+ role: UserRole;
+ username: string;
+ /** A creator who left registration before the profile step. */
+ needsProfile: boolean;
+};
+
+export type UseLoginVerifyPageOptions = {
+ /** The number step, keeping `?redirect=`. */
+ phoneHref: string;
+ /** Where a signed-in person goes: the page that asked, else their role's home. */
+ landing: (viewer: SignedInViewer) => string;
+};
+
+/** code: the code step. suspended: a valid code for a suspended account, with no session. */
+export type LoginVerifyView = 'code' | 'suspended';
+
+export type LoginVerifyPageModel = CodeStepModel & { view: LoginVerifyView };
diff --git a/platforms/market/src/features/auth/models/login-verify/use-login-verify-page.ts b/platforms/market/src/features/auth/models/login-verify/use-login-verify-page.ts
new file mode 100644
index 0000000..e3472a6
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login-verify/use-login-verify-page.ts
@@ -0,0 +1,57 @@
+import { showToast } from '@lumina/island/molecules/toast';
+import { handleError } from '@lumina/libs/error-handler';
+import { useRouter } from 'next/navigation';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { profileRepository } from '../../../profile';
+import { login } from '../../actions/login';
+import { useCodeStep } from '../code-step';
+import type {
+ LoginVerifyPageModel,
+ LoginVerifyView,
+ UseLoginVerifyPageOptions,
+} from './types';
+
+/** A creator who left registration before the profile step goes back to it. A failed read never blocks sign-in. */
+async function needsCreatorProfile(): Promise {
+ try {
+ return !(await profileRepository.getMine()).profileComplete;
+ } catch (error) {
+ handleError(error, { where: 'action', name: 'creator-landing' });
+ return false;
+ }
+}
+
+/**
+ * Login step 2: the code. A valid code signs the person in and sends them on with the toast; a
+ * suspended account stays here on the suspended screen, with no session.
+ */
+export function useLoginVerifyPage({
+ phoneHref,
+ landing,
+}: UseLoginVerifyPageOptions): LoginVerifyPageModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ const [view, setView] = useState('code');
+
+ const step = useCodeStep({
+ purpose: 'login',
+ phoneHref,
+ failedMessage: t('login.verify-failed'),
+ verify: async (args) => {
+ const result = await login(args);
+ if (result.status === 'suspended') {
+ setView('suspended');
+ return 'stay';
+ }
+ const { role, username } = result.account;
+ const needsProfile = role === 'creator' && (await needsCreatorProfile());
+ showToast({ tone: 'success', message: t('login.success') });
+ router.replace(landing({ role, username, needsProfile }));
+ return 'leave';
+ },
+ });
+
+ return { ...step, view };
+}
diff --git a/platforms/market/src/features/auth/models/login/index.ts b/platforms/market/src/features/auth/models/login/index.ts
new file mode 100644
index 0000000..493834a
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login/index.ts
@@ -0,0 +1,2 @@
+export { useLoginPage } from './use-login-page';
+export type { LoginPageModel, UseLoginPageOptions } from './types';
diff --git a/platforms/market/src/features/auth/models/login/types.ts b/platforms/market/src/features/auth/models/login/types.ts
new file mode 100644
index 0000000..c2a827e
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login/types.ts
@@ -0,0 +1,26 @@
+import type { UseFormReturn } from 'react-hook-form';
+
+import type {
+ PhoneFormOutput,
+ PhoneFormValues,
+} from '../../../../shared/validations';
+
+export type UseLoginPageOptions = {
+ /** The code step, keeping `?redirect=`. */
+ codeHref: string;
+ /** Registration, keeping `?redirect=`. */
+ registerHref: string;
+};
+
+export type LoginPageModel = {
+ form: UseFormReturn;
+ submit: () => Promise;
+ isSubmitting: boolean;
+ /** The code could not be sent for a reason that isn't the number's (network, server). */
+ formError: string | undefined;
+ /** The server knows no account for the number: offer registration with it. */
+ isUnknownPhone: boolean;
+ registerHref: string;
+ /** Carries the typed number to registration's number step. */
+ carryPhone: () => void;
+};
diff --git a/platforms/market/src/features/auth/models/login/use-login-page.ts b/platforms/market/src/features/auth/models/login/use-login-page.ts
new file mode 100644
index 0000000..aaa342d
--- /dev/null
+++ b/platforms/market/src/features/auth/models/login/use-login-page.ts
@@ -0,0 +1,61 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { useRouter } from 'next/navigation';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { applyServerErrors, toLocalMobile } from '../../../../shared/utils';
+import { phoneSchema } from '../../../../shared/validations';
+import type {
+ PhoneFormOutput,
+ PhoneFormValues,
+} from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { sendCode } from '../../actions/send-code';
+import { AUTH_ERROR_COPY } from '../../repositories/auth';
+import type { LoginPageModel, UseLoginPageOptions } from './types';
+
+/**
+ * Login step 1: the number. A valid number gets a code and moves to the code step; the number
+ * stays in the flow store, never in the URL. A number with no account offers registration.
+ */
+export function useLoginPage({
+ codeHref,
+ registerHref,
+}: UseLoginPageOptions): LoginPageModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ // Back from the code step, or over from registration: the number is already typed.
+ const [phone] = useState(() => useAuthFlowStore.getState().phone ?? '');
+ const form = useForm({
+ resolver: valibotResolver(phoneSchema),
+ mode: 'onTouched',
+ defaultValues: { phone },
+ });
+
+ const submit = form.handleSubmit(async (values) => {
+ try {
+ await sendCode({ purpose: 'login', phone: values.phone });
+ router.push(codeHref);
+ } catch (error) {
+ applyServerErrors(form, error, {
+ t,
+ failedMessage: t('phone.send-failed'),
+ });
+ }
+ });
+
+ const { errors, isSubmitting } = form.formState;
+ return {
+ form,
+ submit: () => submit(),
+ isSubmitting,
+ formError: errors.root?.server?.message,
+ isUnknownPhone: errors.phone?.message === AUTH_ERROR_COPY.phoneUnknown,
+ registerHref,
+ carryPhone: () =>
+ useAuthFlowStore
+ .getState()
+ .carryPhone(toLocalMobile(form.getValues('phone'))),
+ };
+}
diff --git a/platforms/market/src/features/auth/models/register-details/index.ts b/platforms/market/src/features/auth/models/register-details/index.ts
new file mode 100644
index 0000000..9b61b2d
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/index.ts
@@ -0,0 +1,12 @@
+export { useCreatorIdentityPart } from './use-creator-identity-part';
+export { useInvestorDetailsPart } from './use-investor-details-part';
+export { useRegisterDetailsPage } from './use-register-details-page';
+export type {
+ CreatorIdentityPartModel,
+ IdCardSide,
+ InvestorDetailsPartModel,
+ RegisterDetailsPageModel,
+ RegistrationTimePhase,
+ UseDetailsPartOptions,
+ UseRegisterDetailsPageOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/register-details/types.ts b/platforms/market/src/features/auth/models/register-details/types.ts
new file mode 100644
index 0000000..36fb5e2
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/types.ts
@@ -0,0 +1,72 @@
+import type { UseFormReturn } from 'react-hook-form';
+
+import type {
+ CreatorIdentityFormOutput,
+ CreatorIdentityFormValues,
+ InvestorDetailsFormOutput,
+ InvestorDetailsFormValues,
+} from '../../../../shared/validations';
+import type { RegistrationDraft } from '../../../../stores/auth-flow';
+import type { UserRole } from '../../entities/user';
+
+export type UseRegisterDetailsPageOptions = {
+ /** Step 2, where a missing token (after a reload) sends the person back. */
+ phoneHref: string;
+ /** Step 3, for a new code once the token ran out. */
+ codeHref: string;
+};
+
+/** open: time enough. warning: two minutes left. expired: the token is gone; a new code is needed. */
+export type RegistrationTimePhase = 'open' | 'warning' | 'expired';
+
+export type RegisterDetailsPageModel = {
+ /** `null` until known; the page then redirects to step 2. */
+ role: UserRole | null;
+ phase: RegistrationTimePhase;
+ /** When the token runs out, ms since epoch. */
+ expiresAt: number | null;
+ /** The server said the token is gone before the clock did. */
+ expire: () => void;
+ /** Keeps step 4's values, sends a new code to the same number and opens step 3. */
+ reverify: (draft: RegistrationDraft) => void;
+ isReverifying: boolean;
+};
+
+export type UseDetailsPartOptions = {
+ /** Step 5, the profile, keeping `?redirect=`. */
+ profileHref: string;
+ /** The token ran out on submit. */
+ onExpired: () => void;
+};
+
+export type InvestorDetailsPartModel = {
+ form: UseFormReturn<
+ InvestorDetailsFormValues,
+ unknown,
+ InvestorDetailsFormOutput
+ >;
+ submit: () => Promise;
+ isSubmitting: boolean;
+ formError: string | undefined;
+ /** The values to keep while the number is confirmed again. */
+ draft: () => RegistrationDraft;
+};
+
+export type IdCardSide = 'idCardFront' | 'idCardBack';
+
+export type CreatorIdentityPartModel = {
+ form: UseFormReturn<
+ CreatorIdentityFormValues,
+ unknown,
+ CreatorIdentityFormOutput
+ >;
+ submit: () => Promise;
+ isSubmitting: boolean;
+ formError: string | undefined;
+ /** A picked image is checked at once; a rejected one leaves the box empty with its message. */
+ pickImage: (side: IdCardSide, file: File | null) => void;
+ /** 0–100 while the images upload. */
+ progress: number | undefined;
+ cancelUpload: () => void;
+ draft: () => RegistrationDraft;
+};
diff --git a/platforms/market/src/features/auth/models/register-details/use-creator-identity-part.ts b/platforms/market/src/features/auth/models/register-details/use-creator-identity-part.ts
new file mode 100644
index 0000000..a0732bd
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/use-creator-identity-part.ts
@@ -0,0 +1,131 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { showToast } from '@lumina/island/molecules/toast';
+import { useRouter } from 'next/navigation';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+import * as v from 'valibot';
+
+import { applyServerErrors } from '../../../../shared/utils';
+import {
+ creatorIdentitySchema,
+ idCardImage,
+} from '../../../../shared/validations';
+import type {
+ CreatorIdentityFormOutput,
+ CreatorIdentityFormValues,
+} from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { registerCreator } from '../../actions/register-creator';
+import { AUTH_ERROR_CODES, authErrorCode } from '../../repositories/auth';
+import type {
+ CreatorIdentityPartModel,
+ IdCardSide,
+ UseDetailsPartOptions,
+} from './types';
+import { useLeaveGuard } from './use-leave-guard';
+
+/**
+ * Step 4 for a creator: the public username and the private identity (names, national code, both
+ * sides of the ID card), sent together for the admin review. The images stay in memory, upload
+ * with progress and can be cancelled. The username stands in for the display name the API wants
+ * now; the profile step sets the real one.
+ */
+export function useCreatorIdentityPart({
+ profileHref,
+ onExpired,
+}: UseDetailsPartOptions): CreatorIdentityPartModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ const [draft] = useState(() => useAuthFlowStore.getState().draft);
+ const [progress, setProgress] = useState();
+ const [isDone, setIsDone] = useState(false);
+ const [upload, setUpload] = useState(null);
+ const form = useForm<
+ CreatorIdentityFormValues,
+ unknown,
+ CreatorIdentityFormOutput
+ >({
+ resolver: valibotResolver(creatorIdentitySchema),
+ mode: 'onTouched',
+ defaultValues: {
+ username: draft?.username ?? '',
+ firstName: draft?.firstName ?? '',
+ lastName: draft?.lastName ?? '',
+ nationalId: draft?.nationalId ?? '',
+ idCardFront: draft?.idCardFront ?? null,
+ idCardBack: draft?.idCardBack ?? null,
+ },
+ });
+ const { errors, isSubmitting, isDirty } = form.formState;
+ useLeaveGuard(isDirty && !isDone);
+
+ const pickImage = (side: IdCardSide, file: File | null) => {
+ const checked = file ? v.safeParse(idCardImage, file) : null;
+ if (checked && !checked.success) {
+ form.setValue(side, null, { shouldDirty: true });
+ form.setError(side, { type: 'pick', message: checked.issues[0].message });
+ return;
+ }
+ form.setValue(side, file, {
+ shouldDirty: true,
+ shouldValidate: form.getFieldState(side).isTouched || file !== null,
+ });
+ };
+
+ const submit = form.handleSubmit(async (values) => {
+ const { phone, registration } = useAuthFlowStore.getState();
+ if (!phone || !registration) {
+ onExpired();
+ return;
+ }
+ const controller = new AbortController();
+ setUpload(controller);
+ setProgress(0);
+ try {
+ await registerCreator(
+ {
+ phone,
+ registrationToken: registration.token,
+ username: values.username,
+ displayName: values.username,
+ firstName: values.firstName,
+ lastName: values.lastName,
+ nationalIdNumber: values.nationalId,
+ nationalIdFrontImage: values.idCardFront,
+ nationalIdBackImage: values.idCardBack,
+ },
+ {
+ signal: controller.signal,
+ onProgress: ({ percent }) => setProgress(percent),
+ },
+ );
+ setIsDone(true);
+ showToast({ tone: 'success', message: t('register.identity.success') });
+ router.replace(profileHref);
+ } catch (error) {
+ if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
+ onExpired();
+ return;
+ }
+ applyServerErrors(form, error, {
+ t,
+ failedMessage: t('register.identity.failed'),
+ });
+ } finally {
+ setUpload(null);
+ setProgress(undefined);
+ }
+ });
+
+ return {
+ form,
+ submit: () => submit(),
+ isSubmitting,
+ formError: errors.root?.server?.message,
+ pickImage,
+ progress,
+ cancelUpload: () => upload?.abort(),
+ draft: () => form.getValues(),
+ };
+}
diff --git a/platforms/market/src/features/auth/models/register-details/use-investor-details-part.ts b/platforms/market/src/features/auth/models/register-details/use-investor-details-part.ts
new file mode 100644
index 0000000..07b079b
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/use-investor-details-part.ts
@@ -0,0 +1,84 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { showToast } from '@lumina/island/molecules/toast';
+import { useRouter } from 'next/navigation';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { applyServerErrors } from '../../../../shared/utils';
+import { investorDetailsSchema } from '../../../../shared/validations';
+import type {
+ InvestorDetailsFormOutput,
+ InvestorDetailsFormValues,
+} from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { registerInvestor } from '../../actions/register-investor';
+import { AUTH_ERROR_CODES, authErrorCode } from '../../repositories/auth';
+import type { InvestorDetailsPartModel, UseDetailsPartOptions } from './types';
+import { useLeaveGuard } from './use-leave-guard';
+
+/**
+ * Step 4 for an investor: name, last name and username. «ساخت حساب» creates the account, swaps
+ * the token for the session and opens the profile step. Errors show on blur and on submit; a
+ * banner only for network or server failures.
+ */
+export function useInvestorDetailsPart({
+ profileHref,
+ onExpired,
+}: UseDetailsPartOptions): InvestorDetailsPartModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ // Back from a new code after the token ran out: what was typed comes back.
+ const [draft] = useState(() => useAuthFlowStore.getState().draft);
+ const form = useForm<
+ InvestorDetailsFormValues,
+ unknown,
+ InvestorDetailsFormOutput
+ >({
+ resolver: valibotResolver(investorDetailsSchema),
+ mode: 'onTouched',
+ defaultValues: {
+ firstName: draft?.firstName ?? '',
+ lastName: draft?.lastName ?? '',
+ username: draft?.username ?? '',
+ },
+ });
+ const [isDone, setIsDone] = useState(false);
+ const { errors, isSubmitting, isDirty } = form.formState;
+ useLeaveGuard(isDirty && !isDone);
+
+ const submit = form.handleSubmit(async (values) => {
+ const { phone, registration } = useAuthFlowStore.getState();
+ if (!phone || !registration) {
+ onExpired();
+ return;
+ }
+ try {
+ await registerInvestor({
+ phone,
+ registrationToken: registration.token,
+ ...values,
+ });
+ setIsDone(true);
+ showToast({ tone: 'success', message: t('register.details.success') });
+ router.replace(profileHref);
+ } catch (error) {
+ if (authErrorCode(error) === AUTH_ERROR_CODES.registrationExpired) {
+ onExpired();
+ return;
+ }
+ applyServerErrors(form, error, {
+ t,
+ failedMessage: t('register.details.failed'),
+ });
+ }
+ });
+
+ return {
+ form,
+ submit: () => submit(),
+ isSubmitting,
+ formError: errors.root?.server?.message,
+ draft: () => form.getValues(),
+ };
+}
diff --git a/platforms/market/src/features/auth/models/register-details/use-leave-guard.ts b/platforms/market/src/features/auth/models/register-details/use-leave-guard.ts
new file mode 100644
index 0000000..9758442
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/use-leave-guard.ts
@@ -0,0 +1,11 @@
+import { useEffect } from 'react';
+
+/** While the form holds unsent values, leaving the page asks first (the browser's own prompt). */
+export function useLeaveGuard(isDirty: boolean): void {
+ useEffect(() => {
+ if (!isDirty) return undefined;
+ const ask = (event: BeforeUnloadEvent) => event.preventDefault();
+ window.addEventListener('beforeunload', ask);
+ return () => window.removeEventListener('beforeunload', ask);
+ }, [isDirty]);
+}
diff --git a/platforms/market/src/features/auth/models/register-details/use-register-details-page.ts b/platforms/market/src/features/auth/models/register-details/use-register-details-page.ts
new file mode 100644
index 0000000..9bb1d05
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-details/use-register-details-page.ts
@@ -0,0 +1,78 @@
+import { useRouter } from 'next/navigation';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { showActionError } from '../../../../shared/utils';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import type { RegistrationDraft } from '../../../../stores/auth-flow';
+import { sendCode } from '../../actions/send-code';
+import { REGISTRATION_WARNING_SECONDS } from '../../constants';
+import type {
+ RegisterDetailsPageModel,
+ RegistrationTimePhase,
+ UseRegisterDetailsPageOptions,
+} from './types';
+
+/**
+ * Registration step 4's page: the account type it asks for, and the 15-minute token it runs on.
+ * Two minutes before the end it warns; at the end (or when the server says so) it halts, and a
+ * new code brings the person back with everything they typed. The API can't renew the token.
+ */
+export function useRegisterDetailsPage({
+ phoneHref,
+ codeHref,
+}: UseRegisterDetailsPageOptions): RegisterDetailsPageModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ // Read once: registering resets the flow while this page is still on screen.
+ const [{ role, phone, registration }] = useState(() =>
+ useAuthFlowStore.getState(),
+ );
+ const expiresAt = registration?.expiresAt ?? null;
+ const [phase, setPhase] = useState('open');
+ const [isReverifying, setIsReverifying] = useState(false);
+
+ // A reload forgets the token, so the number is confirmed again.
+ useEffect(() => {
+ if (!role || !phone || !registration) router.replace(phoneHref);
+ }, [role, phone, registration, phoneHref, router]);
+
+ useEffect(() => {
+ if (expiresAt === null) return undefined;
+ const left = expiresAt - Date.now();
+ const warning = setTimeout(
+ () => setPhase((current) => (current === 'open' ? 'warning' : current)),
+ Math.max(0, left - REGISTRATION_WARNING_SECONDS * 1000),
+ );
+ const expired = setTimeout(() => setPhase('expired'), Math.max(0, left));
+ return () => {
+ clearTimeout(warning);
+ clearTimeout(expired);
+ };
+ }, [expiresAt]);
+
+ const reverify = (draft: RegistrationDraft) => {
+ if (!phone) return;
+ useAuthFlowStore.getState().keepDraft(draft);
+ setIsReverifying(true);
+ sendCode({ purpose: 'register', phone })
+ .then(() => router.replace(codeHref))
+ .catch((error: unknown) => {
+ setIsReverifying(false);
+ showActionError(error, {
+ t,
+ failedMessage: t('phone.send-failed'),
+ retry: () => reverify(draft),
+ });
+ });
+ };
+
+ return {
+ role,
+ phase,
+ expiresAt,
+ expire: () => setPhase('expired'),
+ reverify,
+ isReverifying,
+ };
+}
diff --git a/platforms/market/src/features/auth/models/register-phone/index.ts b/platforms/market/src/features/auth/models/register-phone/index.ts
new file mode 100644
index 0000000..f43f3b8
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-phone/index.ts
@@ -0,0 +1,5 @@
+export { useRegisterPhonePage } from './use-register-phone-page';
+export type {
+ RegisterPhonePageModel,
+ UseRegisterPhonePageOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/register-phone/types.ts b/platforms/market/src/features/auth/models/register-phone/types.ts
new file mode 100644
index 0000000..9508b94
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-phone/types.ts
@@ -0,0 +1,32 @@
+import type { UseFormReturn } from 'react-hook-form';
+
+import type {
+ PhoneFormOutput,
+ PhoneFormValues,
+} from '../../../../shared/validations';
+import type { UserRole } from '../../entities/user';
+
+export type UseRegisterPhonePageOptions = {
+ /** Step 1, where a missing account type (after a reload) sends the person back. */
+ typeHref: string;
+ /** Step 3. */
+ codeHref: string;
+ /** Login's code step, for a number that already has an account. */
+ loginCodeHref: string;
+};
+
+export type RegisterPhonePageModel = {
+ /** `null` until known; the page then redirects to step 1. */
+ role: UserRole | null;
+ form: UseFormReturn;
+ submit: () => Promise;
+ isSubmitting: boolean;
+ formError: string | undefined;
+ /** The number already has an account: offer to sign in with it. */
+ isTakenPhone: boolean;
+ /** Sends a login code to the number and opens login's code step. */
+ loginWithPhone: () => void;
+ isLoggingIn: boolean;
+ /** Carries the typed number to login. */
+ carryPhone: () => void;
+};
diff --git a/platforms/market/src/features/auth/models/register-phone/use-register-phone-page.ts b/platforms/market/src/features/auth/models/register-phone/use-register-phone-page.ts
new file mode 100644
index 0000000..10cee90
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-phone/use-register-phone-page.ts
@@ -0,0 +1,91 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { useRouter } from 'next/navigation';
+import { useEffect, useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import {
+ applyServerErrors,
+ showActionError,
+ toLocalMobile,
+} from '../../../../shared/utils';
+import { phoneSchema } from '../../../../shared/validations';
+import type {
+ PhoneFormOutput,
+ PhoneFormValues,
+} from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import { sendCode } from '../../actions/send-code';
+import { AUTH_ERROR_COPY } from '../../repositories/auth';
+import type {
+ RegisterPhonePageModel,
+ UseRegisterPhonePageOptions,
+} from './types';
+
+/**
+ * Registration step 2: the number, for the account type chosen at step 1. A number that already
+ * has an account gets no code; the way out is signing in with it.
+ */
+export function useRegisterPhonePage({
+ typeHref,
+ codeHref,
+ loginCodeHref,
+}: UseRegisterPhonePageOptions): RegisterPhonePageModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ const [{ role, phone }] = useState(() => useAuthFlowStore.getState());
+ const [isLoggingIn, setIsLoggingIn] = useState(false);
+ const form = useForm({
+ resolver: valibotResolver(phoneSchema),
+ mode: 'onTouched',
+ defaultValues: { phone: phone ?? '' },
+ });
+
+ // A reload forgets the account type, so registration starts again at step 1.
+ useEffect(() => {
+ if (!role) router.replace(typeHref);
+ }, [role, typeHref, router]);
+
+ const submit = form.handleSubmit(async (values) => {
+ try {
+ await sendCode({ purpose: 'register', phone: values.phone });
+ router.push(codeHref);
+ } catch (error) {
+ applyServerErrors(form, error, {
+ t,
+ failedMessage: t('phone.send-failed'),
+ });
+ }
+ });
+
+ const loginWithPhone = () => {
+ const typed = toLocalMobile(form.getValues('phone'));
+ setIsLoggingIn(true);
+ sendCode({ purpose: 'login', phone: typed })
+ .then(() => router.push(loginCodeHref))
+ .catch((error: unknown) => {
+ setIsLoggingIn(false);
+ showActionError(error, {
+ t,
+ failedMessage: t('phone.send-failed'),
+ retry: loginWithPhone,
+ });
+ });
+ };
+
+ const { errors, isSubmitting } = form.formState;
+ return {
+ role,
+ form,
+ submit: () => submit(),
+ isSubmitting,
+ formError: errors.root?.server?.message,
+ isTakenPhone: errors.phone?.message === AUTH_ERROR_COPY.phoneTaken,
+ loginWithPhone,
+ isLoggingIn,
+ carryPhone: () =>
+ useAuthFlowStore
+ .getState()
+ .carryPhone(toLocalMobile(form.getValues('phone'))),
+ };
+}
diff --git a/platforms/market/src/features/auth/models/register-type/index.ts b/platforms/market/src/features/auth/models/register-type/index.ts
new file mode 100644
index 0000000..e6fd5ea
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-type/index.ts
@@ -0,0 +1,5 @@
+export { useRegisterTypePage } from './use-register-type-page';
+export type {
+ RegisterTypePageModel,
+ UseRegisterTypePageOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/register-type/types.ts b/platforms/market/src/features/auth/models/register-type/types.ts
new file mode 100644
index 0000000..2921b2f
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-type/types.ts
@@ -0,0 +1,16 @@
+import type { UseFormReturn } from 'react-hook-form';
+
+import type {
+ AccountTypeFormOutput,
+ AccountTypeFormValues,
+} from '../../../../shared/validations';
+
+export type UseRegisterTypePageOptions = {
+ /** Step 2, keeping `?redirect=`. */
+ phoneHref: string;
+};
+
+export type RegisterTypePageModel = {
+ form: UseFormReturn;
+ submit: () => Promise;
+};
diff --git a/platforms/market/src/features/auth/models/register-type/use-register-type-page.ts b/platforms/market/src/features/auth/models/register-type/use-register-type-page.ts
new file mode 100644
index 0000000..e5d0b90
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-type/use-register-type-page.ts
@@ -0,0 +1,38 @@
+import { valibotResolver } from '@hookform/resolvers/valibot';
+import { useRouter } from 'next/navigation';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+
+import { accountTypeSchema } from '../../../../shared/validations';
+import type {
+ AccountTypeFormOutput,
+ AccountTypeFormValues,
+} from '../../../../shared/validations';
+import { useAuthFlowStore } from '../../../../stores/auth-flow';
+import type {
+ RegisterTypePageModel,
+ UseRegisterTypePageOptions,
+} from './types';
+
+/**
+ * Registration step 1: the account type. Nothing is pre-selected and «ادامه» is never disabled:
+ * pressed with no choice, it says so. The choice travels in the flow store to step 2.
+ */
+export function useRegisterTypePage({
+ phoneHref,
+}: UseRegisterTypePageOptions): RegisterTypePageModel {
+ const router = useRouter();
+ // Back from step 2: the choice is still made.
+ const [role] = useState(() => useAuthFlowStore.getState().role ?? '');
+ const form = useForm({
+ resolver: valibotResolver(accountTypeSchema),
+ defaultValues: { role },
+ });
+
+ const submit = form.handleSubmit((values) => {
+ useAuthFlowStore.getState().chooseRole(values.role);
+ router.push(phoneHref);
+ });
+
+ return { form, submit: () => submit() };
+}
diff --git a/platforms/market/src/features/auth/models/register-verify/index.ts b/platforms/market/src/features/auth/models/register-verify/index.ts
new file mode 100644
index 0000000..dfaa3e7
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-verify/index.ts
@@ -0,0 +1,5 @@
+export { useRegisterVerifyPage } from './use-register-verify-page';
+export type {
+ RegisterVerifyPageModel,
+ UseRegisterVerifyPageOptions,
+} from './types';
diff --git a/platforms/market/src/features/auth/models/register-verify/types.ts b/platforms/market/src/features/auth/models/register-verify/types.ts
new file mode 100644
index 0000000..45d27ef
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-verify/types.ts
@@ -0,0 +1,13 @@
+import type { UserRole } from '../../entities/user';
+import type { CodeStepModel } from '../code-step';
+
+export type UseRegisterVerifyPageOptions = {
+ /** Step 2, keeping `?redirect=`. */
+ phoneHref: string;
+ /** Step 4. */
+ detailsHref: string;
+};
+
+export type RegisterVerifyPageModel = CodeStepModel & {
+ role: UserRole | null;
+};
diff --git a/platforms/market/src/features/auth/models/register-verify/use-register-verify-page.ts b/platforms/market/src/features/auth/models/register-verify/use-register-verify-page.ts
new file mode 100644
index 0000000..1c2fa80
--- /dev/null
+++ b/platforms/market/src/features/auth/models/register-verify/use-register-verify-page.ts
@@ -0,0 +1,36 @@
+import { useRouter } from 'next/navigation';
+import { useTranslation } from 'react-i18next';
+
+import { useFlowRole } from '../../../../stores/auth-flow';
+import { verifyRegistrationCode } from '../../actions/verify-registration-code';
+import { useCodeStep } from '../code-step';
+import type {
+ RegisterVerifyPageModel,
+ UseRegisterVerifyPageOptions,
+} from './types';
+
+/**
+ * Registration step 3: login's code step, ending in the 15-minute registration token. The code
+ * is used up, so step 4 replaces this page in the history.
+ */
+export function useRegisterVerifyPage({
+ phoneHref,
+ detailsHref,
+}: UseRegisterVerifyPageOptions): RegisterVerifyPageModel {
+ const { t } = useTranslation('auth');
+ const router = useRouter();
+ const role = useFlowRole();
+
+ const step = useCodeStep({
+ purpose: 'register',
+ phoneHref,
+ failedMessage: t('register.verify.failed'),
+ verify: async (args) => {
+ await verifyRegistrationCode(args);
+ router.replace(detailsHref);
+ return 'leave';
+ },
+ });
+
+ return { ...step, role };
+}
diff --git a/platforms/market/src/features/auth/repositories/auth/auth.ts b/platforms/market/src/features/auth/repositories/auth/auth.ts
index a270dbd..e4307b5 100644
--- a/platforms/market/src/features/auth/repositories/auth/auth.ts
+++ b/platforms/market/src/features/auth/repositories/auth/auth.ts
@@ -1,6 +1,9 @@
+import type { UploadProgress } from '@lumina/libs/http';
+
import { renameFieldErrors } from '../../../../shared/utils';
import { authHttp } from '../../http';
import { AUTH_ENDPOINTS, AUTH_FIELD_NAMES } from './constants';
+import { toAuthError } from './errors';
import {
toCreatorRegisteredPayload,
toOtpSentPayload,
@@ -33,12 +36,13 @@ import type {
* Passwordless phone auth. Every request sends `skipRefresh`: these run without a session, and the
* API answers a wrong code with 400 and field errors, so a 401 here never means "refresh". A
* successful sign-in or registration sets the HttpOnly session cookies; the body is the account.
+ * Failures carry an auth code and Persian copy (`toAuthError`).
*/
async function send(request: () => Promise): Promise {
try {
return await request();
} catch (error) {
- throw renameFieldErrors(error, AUTH_FIELD_NAMES);
+ throw toAuthError(renameFieldErrors(error, AUTH_FIELD_NAMES));
}
}
@@ -90,14 +94,22 @@ export const authRepository = {
return toSessionPayload(response);
},
+ /** Multipart with the two ID images; reports upload progress and can be cancelled. */
async registerCreator(
args: RegisterCreatorArgs,
+ {
+ signal,
+ onProgress,
+ }: {
+ signal?: AbortSignal;
+ onProgress?: (progress: UploadProgress) => void;
+ } = {},
): Promise {
const response = await send(() =>
authHttp.upload(
AUTH_ENDPOINTS.registerCreator,
toRegisterCreatorFormData(args),
- { skipRefresh: true },
+ { skipRefresh: true, signal, onProgress },
),
);
return toCreatorRegisteredPayload(response);
diff --git a/platforms/market/src/features/auth/repositories/auth/constants.ts b/platforms/market/src/features/auth/repositories/auth/constants.ts
index ed7d1cc..3d03465 100644
--- a/platforms/market/src/features/auth/repositories/auth/constants.ts
+++ b/platforms/market/src/features/auth/repositories/auth/constants.ts
@@ -18,3 +18,102 @@ export const AUTH_FIELD_NAMES = {
phone_number: 'phone',
otp: 'code',
} as const;
+
+/** Auth failures the pages tell apart, set as `HttpError.code` by the repository. */
+export const AUTH_ERROR_CODES = {
+ codeWrong: 'AUTH_CODE_WRONG',
+ codeExpired: 'AUTH_CODE_EXPIRED',
+ blocked: 'AUTH_BLOCKED',
+ cooldown: 'AUTH_COOLDOWN',
+ phoneUnknown: 'AUTH_PHONE_UNKNOWN',
+ phoneTaken: 'AUTH_PHONE_TAKEN',
+ usernameTaken: 'AUTH_USERNAME_TAKEN',
+ registrationExpired: 'AUTH_REGISTRATION_EXPIRED',
+ fileTooLarge: 'AUTH_FILE_TOO_LARGE',
+} as const;
+
+/** Each auth failure's copy, an `errors:` key the error handler and the fields translate. */
+export const AUTH_ERROR_COPY = {
+ codeWrong: 'errors:auth.code-wrong',
+ codeExpired: 'errors:auth.code-expired',
+ blocked: 'errors:auth.blocked',
+ blockedHint: 'errors:auth.blocked-hint',
+ cooldown: 'errors:auth.cooldown',
+ phoneUnknown: 'errors:auth.phone-unknown',
+ phoneTaken: 'errors:auth.phone-taken',
+ usernameTaken: 'errors:auth.username-taken',
+ registrationExpired: 'errors:auth.registration-expired',
+ fileTooLarge: 'errors:auth.file-too-large',
+} as const;
+
+/**
+ * The gateway answers auth failures with English text and no code, so each rule matches the start
+ * of its text and gives the code, its copy under `errors:auth`, and the `*Args` field it belongs
+ * to. Text that matches no rule passes through unchanged.
+ */
+export const AUTH_ERROR_RULES = [
+ {
+ text: 'Invalid OTP',
+ code: AUTH_ERROR_CODES.codeWrong,
+ message: AUTH_ERROR_COPY.codeWrong,
+ field: 'code',
+ },
+ {
+ text: 'OTP expired',
+ code: AUTH_ERROR_CODES.codeExpired,
+ message: AUTH_ERROR_COPY.codeExpired,
+ field: 'code',
+ },
+ {
+ text: 'No active OTP',
+ code: AUTH_ERROR_CODES.codeExpired,
+ message: AUTH_ERROR_COPY.codeExpired,
+ field: 'code',
+ },
+ {
+ text: 'Too many failed OTP attempts',
+ code: AUTH_ERROR_CODES.blocked,
+ message: AUTH_ERROR_COPY.blocked,
+ hint: AUTH_ERROR_COPY.blockedHint,
+ },
+ {
+ text: 'Please wait before requesting a new OTP',
+ code: AUTH_ERROR_CODES.cooldown,
+ message: AUTH_ERROR_COPY.cooldown,
+ },
+ {
+ text: 'User not found',
+ code: AUTH_ERROR_CODES.phoneUnknown,
+ message: AUTH_ERROR_COPY.phoneUnknown,
+ field: 'phone',
+ },
+ {
+ text: 'Phone number already registered',
+ code: AUTH_ERROR_CODES.phoneTaken,
+ message: AUTH_ERROR_COPY.phoneTaken,
+ field: 'phone',
+ },
+ {
+ // The phone was checked at step 2, so a clash at step 4 is the username.
+ text: 'Phone number or username already registered',
+ code: AUTH_ERROR_CODES.usernameTaken,
+ message: AUTH_ERROR_COPY.usernameTaken,
+ field: 'username',
+ },
+ {
+ text: 'Phone verification is required',
+ code: AUTH_ERROR_CODES.registrationExpired,
+ message: AUTH_ERROR_COPY.registrationExpired,
+ },
+ {
+ text: 'File too large',
+ code: AUTH_ERROR_CODES.fileTooLarge,
+ message: AUTH_ERROR_COPY.fileTooLarge,
+ },
+] as const satisfies readonly {
+ text: string;
+ code: string;
+ message: string;
+ hint?: string;
+ field?: string;
+}[];
diff --git a/platforms/market/src/features/auth/repositories/auth/errors.ts b/platforms/market/src/features/auth/repositories/auth/errors.ts
new file mode 100644
index 0000000..ceaf743
--- /dev/null
+++ b/platforms/market/src/features/auth/repositories/auth/errors.ts
@@ -0,0 +1,52 @@
+import { HttpError, isHttpError } from '@lumina/libs/http';
+
+import { AUTH_ERROR_CODES, AUTH_ERROR_RULES } from './constants';
+import type { AuthErrorCode } from './types';
+
+const CODES: ReadonlySet = new Set(Object.values(AUTH_ERROR_CODES));
+
+/**
+ * Gives a known auth failure its code, its Persian copy (an `errors:` key the error handler
+ * translates) and its field, so pages can branch on the code and forms show the message under the
+ * right field. Anything else passes through unchanged.
+ */
+export function toAuthError(error: unknown): unknown {
+ if (!isHttpError(error)) return error;
+ const rule = AUTH_ERROR_RULES.find(({ text }) =>
+ error.message.startsWith(text),
+ );
+ if (!rule) return error;
+ return new HttpError({
+ ...error.toJSON(),
+ code: rule.code,
+ message: rule.message,
+ hint: 'hint' in rule ? rule.hint : error.hint,
+ fieldErrors:
+ 'field' in rule ? { [rule.field]: rule.message } : error.fieldErrors,
+ cause: error,
+ });
+}
+
+/** The auth failure an error stands for, or `null` for any other error. */
+export function authErrorCode(error: unknown): AuthErrorCode | null {
+ return isHttpError(error) && CODES.has(error.code)
+ ? (error.code as AuthErrorCode)
+ : null;
+}
+
+/**
+ * When a blocked number may try again (ms since epoch): the server's `blockedUntil`, else its
+ * `retryAfterSeconds` from now, else `null` for an error that is no block.
+ */
+export function blockEndOf(error: unknown): number | null {
+ if (
+ authErrorCode(error) !== AUTH_ERROR_CODES.blocked ||
+ !isHttpError(error)
+ ) {
+ return null;
+ }
+ const until = error.details?.blockedUntil;
+ const parsed = typeof until === 'string' ? Date.parse(until) : Number.NaN;
+ if (!Number.isNaN(parsed)) return parsed;
+ return error.retryAfter ? Date.now() + error.retryAfter * 1000 : null;
+}
diff --git a/platforms/market/src/features/auth/repositories/auth/index.ts b/platforms/market/src/features/auth/repositories/auth/index.ts
index f161439..0badf62 100644
--- a/platforms/market/src/features/auth/repositories/auth/index.ts
+++ b/platforms/market/src/features/auth/repositories/auth/index.ts
@@ -1,6 +1,8 @@
export { authRepository } from './auth';
-export { AUTH_ENDPOINTS } from './constants';
+export { AUTH_ENDPOINTS, AUTH_ERROR_CODES, AUTH_ERROR_COPY } from './constants';
+export { authErrorCode, blockEndOf } from './errors';
export type {
+ AuthErrorCode,
CreatorRegisteredPayload,
OtpSentPayload,
RegisterCreatorArgs,
diff --git a/platforms/market/src/features/auth/repositories/auth/types.ts b/platforms/market/src/features/auth/repositories/auth/types.ts
index 072d9f7..1908b51 100644
--- a/platforms/market/src/features/auth/repositories/auth/types.ts
+++ b/platforms/market/src/features/auth/repositories/auth/types.ts
@@ -1,5 +1,9 @@
import type { UserEntity, UserRole } from '../../entities/user';
import type { AccountPayload } from '../account';
+import type { AUTH_ERROR_CODES } from './constants';
+
+export type AuthErrorCode =
+ (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
// Phone numbers are typed in any digits and form; mappers send E.164.
diff --git a/platforms/market/src/features/auth/types.ts b/platforms/market/src/features/auth/types.ts
index f383fbf..fbf2f7f 100644
--- a/platforms/market/src/features/auth/types.ts
+++ b/platforms/market/src/features/auth/types.ts
@@ -1,12 +1,17 @@
import type { ViewerStatus } from '../../stores/auth';
+import type { AUTH_PURPOSES } from './constants';
import type { UserRole } from './entities/user';
+export type AuthPurpose = (typeof AUTH_PURPOSES)[number];
+
/** Why the session ended: the user signed out, or the refresh token was dead. */
export type LogoutReason = 'signed-out' | 'session-ended';
declare module '@lumina/libs/event-emitter' {
interface EventMap {
'auth.restore': { status: ViewerStatus };
+ 'auth.code-sent': { purpose: AuthPurpose };
+ 'auth.phone-verified': { purpose: AuthPurpose };
'auth.login': { userId: string; role: UserRole };
'auth.register': { userId: string; role: UserRole };
'auth.logout': { reason: LogoutReason };
diff --git a/platforms/market/src/shared/locales/fa/auth.json b/platforms/market/src/shared/locales/fa/auth.json
new file mode 100644
index 0000000..cfd7f1f
--- /dev/null
+++ b/platforms/market/src/shared/locales/fa/auth.json
@@ -0,0 +1,173 @@
+{
+ "header": {
+ "brand": "لومینا",
+ "home": "صفحه اصلی لومینا",
+ "back": "بازگشت به مرحله قبل",
+ "support": "پشتیبانی"
+ },
+ "support": {
+ "link": "تماس با پشتیبانی",
+ "title": "پشتیبانی لومینا",
+ "bale": "گفتگو در بله",
+ "telegram": "گفتگو در تلگرام",
+ "hours": "ساعت پاسخگویی: {{hours}}",
+ "terms": "شرایط اشتراک",
+ "close": "بستن",
+ "opens-new-tab": "در برنامه یا زبانهی جدید باز میشود"
+ },
+ "loading": "در حال بارگذاری…",
+ "phone": {
+ "label": "شماره موبایل",
+ "placeholder": "0912 345 6789",
+ "send-failed": "کد تأیید ارسال نشد",
+ "send-failed-banner": "ارسال کد تأیید ناموفق بود. دوباره تلاش کنید."
+ },
+ "login": {
+ "meta-title": "ورود",
+ "header": "ورود",
+ "title": "ورود به لومینا",
+ "description": "شماره موبایل خود را وارد کنید.",
+ "submit": "دریافت کد",
+ "no-account": "حساب کاربری ندارید؟",
+ "register": "ثبتنام",
+ "register-with-phone": "ثبتنام با این شماره",
+ "verify-meta-title": "کد تأیید ورود",
+ "verify-submit": "ورود",
+ "verify-failed": "ورود انجام نشد",
+ "success": "با موفقیت وارد شدید."
+ },
+ "code": {
+ "title": "کد تأیید را وارد کنید",
+ "description": "کد 6 رقمی ارسالشده به {{phone}} را وارد کنید.",
+ "label": "کد تأیید 6 رقمی",
+ "edit-phone": "ویرایش شماره",
+ "wrong": "کد واردشده اشتباه است. لطفاً دوباره تلاش کنید.",
+ "wrong-last": "کد واردشده اشتباه است. یک تلاش دیگر باقی مانده است.",
+ "blocked-title": "تعداد تلاشهای مجاز به پایان رسید.",
+ "blocked-description": "10 دقیقه دیگر تلاش کنید.",
+ "resend-failed": "کد جدید ارسال نشد",
+ "resend": {
+ "counting": "ارسال دوباره کد تا",
+ "ready": "ارسال دوباره کد",
+ "sending": "در حال ارسال…",
+ "sent": "کد جدید ارسال شد.",
+ "limited": "ارسال دوباره کد پس از",
+ "hint": "کد را دریافت نکردید؟",
+ "ready-announcement": "اکنون میتوانید کد جدید دریافت کنید."
+ }
+ },
+ "suspended": {
+ "title": "حساب شما تعلیق شده است.",
+ "description": "برای اطلاعات بیشتر با پشتیبانی تماس بگیرید."
+ },
+ "register": {
+ "meta-title": "ثبتنام",
+ "header": "ثبتنام",
+ "steps-label": "مراحل ثبتنام",
+ "step-count": "مرحله {{step}} از {{total}}",
+ "steps": {
+ "type": "نوع حساب",
+ "phone": "شماره موبایل",
+ "code": "کد تأیید",
+ "details": "اطلاعات حساب",
+ "identity": "احراز هویت",
+ "profile": "پروفایل"
+ },
+ "has-account": "حساب کاربری دارید؟",
+ "login": "ورود",
+ "login-with-phone": "ورود با این شماره",
+ "type": {
+ "title": "ثبتنام در لومینا",
+ "description": "نوع حساب خود را انتخاب کنید.",
+ "label": "نوع حساب",
+ "investor": "سرمایهگذار",
+ "investor-description": "تحلیلگران را با کارنامهشان مقایسه میکنم و در کانالشان مشترک میشوم.",
+ "creator": "تحلیلگر",
+ "creator-description": "تحلیل و پیشبینی منتشر میکنم و از اشتراک کانالم درآمد دارم.",
+ "note": "نوع حساب پس از ثبتنام قابل تغییر نیست.",
+ "submit": "ادامه"
+ },
+ "phone": {
+ "title": "شماره موبایل خود را وارد کنید",
+ "description": "کد تأیید به این شماره پیامک میشود.",
+ "as-investor": "ثبتنام بهعنوان سرمایهگذار",
+ "as-creator": "ثبتنام بهعنوان تحلیلگر",
+ "change": "تغییر",
+ "submit": "دریافت کد"
+ },
+ "verify": {
+ "meta-title": "کد تأیید ثبتنام",
+ "submit": "تأیید و ادامه",
+ "failed": "شماره تأیید نشد"
+ },
+ "details": {
+ "meta-title": "اطلاعات حساب",
+ "title": "اطلاعات حساب",
+ "description": "نام شما فقط در اطلاعات کاربری دیده میشود؛ دیگران شما را با نام کاربری میشناسند.",
+ "submit": "ساخت حساب",
+ "terms-before": "با ساخت حساب، ",
+ "failed": "حساب ساخته نشد",
+ "network-title": "خطا در ثبت اطلاعات.",
+ "success": "حساب شما ساخته شد."
+ },
+ "identity": {
+ "title": "احراز هویت",
+ "description": "این اطلاعات فقط برای تأیید هویت شما است و به سرمایهگذاران نمایش داده نمیشود.",
+ "public-title": "شناسه عمومی",
+ "public-description": "سرمایهگذاران شما را با این نام میشناسند.",
+ "username-note": "نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت اولیه قابل تغییر نیست.",
+ "private-title": "اطلاعات هویتی",
+ "private-description": "محرمانه است و فقط برای تأیید هویت بررسی میشود.",
+ "submit": "ثبت و ادامه",
+ "terms-before": "با ثبت اطلاعات، ",
+ "failed": "اطلاعات ثبت نشد",
+ "success": "اطلاعات شما برای بررسی ارسال شد.",
+ "cancel": "لغو ارسال"
+ },
+ "terms-link": "قوانین لومینا را میپذیرید.",
+ "fields": {
+ "first-name": "نام",
+ "first-name-placeholder": "مثال: علی",
+ "last-name": "نام خانوادگی",
+ "last-name-placeholder": "مثال: رضایی",
+ "username": "نام کاربری",
+ "username-placeholder": "ali_investor",
+ "username-hint": "فقط حروف انگلیسی، عدد و _ ، از 3 تا 30 کاراکتر. پس از ثبت قابل تغییر نیست.",
+ "national-id": "کد ملی",
+ "national-id-placeholder": "0012345678",
+ "id-card-front": "تصویر کارت ملی (رو)",
+ "id-card-back": "تصویر کارت ملی (پشت)",
+ "id-card-hint": "یک تصویر واضح از کارت ملی خود آپلود کنید.",
+ "id-card-pick": "انتخاب فایل",
+ "id-card-rules": "JPG یا PNG، حداکثر 5 مگابایت",
+ "id-card-remove": "حذف تصویر",
+ "id-card-uploading": "در حال بارگذاری… {{percent}}٪",
+ "file-size": "{{size}} مگابایت"
+ },
+ "expiry": {
+ "warning-title": "زمان این مرحله رو به پایان است.",
+ "title": "زمان ثبتنام به پایان رسید",
+ "description": "برای امنیت حساب، شماره موبایل خود را دوباره تأیید کنید. اطلاعاتی که وارد کردهاید حفظ میشود.",
+ "submit": "ارسال کد تأیید",
+ "warning-before": "برای امنیت حساب، این صفحه تا",
+ "warning-after": "دیگر باز است."
+ }
+ },
+ "validation": {
+ "phone-invalid": "شماره موبایل واردشده معتبر نیست.",
+ "code-length": "کد 6 رقمی را کامل وارد کنید.",
+ "role-required": "نوع حساب را انتخاب کنید.",
+ "required": "این فیلد الزامی است.",
+ "first-name-persian": "لطفاً نام را به فارسی وارد کنید.",
+ "last-name-persian": "لطفاً نام خانوادگی را به فارسی وارد کنید.",
+ "username-required": "وارد کردن نام کاربری الزامی است.",
+ "username-characters": "نام کاربری فقط میتواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.",
+ "username-short": "نام کاربری باید حداقل 3 کاراکتر باشد.",
+ "username-long": "نام کاربری حداکثر 30 کاراکتر است.",
+ "national-id-length": "کد ملی باید 10 رقم باشد.",
+ "national-id-invalid": "کد ملی معتبر نیست.",
+ "id-card-required": "تصویر کارت ملی را بارگذاری کنید.",
+ "id-card-type": "فقط فایلهای JPG یا PNG مجاز هستند.",
+ "id-card-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد."
+ }
+}
diff --git a/platforms/market/src/shared/locales/fa/errors.json b/platforms/market/src/shared/locales/fa/errors.json
index 4461da8..f731186 100644
--- a/platforms/market/src/shared/locales/fa/errors.json
+++ b/platforms/market/src/shared/locales/fa/errors.json
@@ -50,5 +50,25 @@
"description": "اگر فکر میکنید اشتباهی رخ داده است، با پشتیبانی تماس بگیرید."
},
"home": "بازگشت به خانه"
+ },
+ "action": {
+ "try-again": "تلاش مجدد",
+ "reload": "بارگذاری دوباره"
+ },
+ "support": {
+ "with-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، کد پیگیری {{referenceId}} را به پشتیبانی بگویید.",
+ "without-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید."
+ },
+ "auth": {
+ "code-wrong": "کد واردشده اشتباه است. لطفاً دوباره تلاش کنید.",
+ "code-expired": "کد منقضی شده. یک کد جدید دریافت کنید.",
+ "blocked": "تعداد تلاشهای مجاز به پایان رسید.",
+ "blocked-hint": "10 دقیقه دیگر تلاش کنید.",
+ "cooldown": "برای این شماره همین حالا کد ارسال شده است.",
+ "phone-unknown": "حسابی با این شماره وجود ندارد.",
+ "phone-taken": "این شماره قبلاً ثبت شده است.",
+ "username-taken": "این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.",
+ "registration-expired": "زمان ثبتنام به پایان رسید.",
+ "file-too-large": "حجم فایل نباید بیشتر از 5 مگابایت باشد."
}
}
diff --git a/platforms/market/src/shared/locales/resources.ts b/platforms/market/src/shared/locales/resources.ts
index 668d758..464ca48 100644
--- a/platforms/market/src/shared/locales/resources.ts
+++ b/platforms/market/src/shared/locales/resources.ts
@@ -1,7 +1,8 @@
+import faAuth from './fa/auth.json';
import faCommon from './fa/common.json';
import faErrors from './fa/errors.json';
-/** The product is Persian only; every route loads both namespaces, because any route can fail. */
+/** The product is Persian only; every route loads every namespace, because any route can fail. */
export const DEFAULT_LOCALE = 'fa';
export const DEFAULT_NAMESPACE = 'common';
@@ -9,6 +10,7 @@ export const DEFAULT_NAMESPACE = 'common';
export const resources = {
fa: {
common: faCommon,
+ auth: faAuth,
errors: faErrors,
},
} as const;
diff --git a/platforms/market/src/shared/utils/apply-server-errors.ts b/platforms/market/src/shared/utils/apply-server-errors.ts
new file mode 100644
index 0000000..18cfb04
--- /dev/null
+++ b/platforms/market/src/shared/utils/apply-server-errors.ts
@@ -0,0 +1,52 @@
+import { classifyError, describeError } from '@lumina/libs/error-handler';
+import { isHttpError } from '@lumina/libs/http';
+import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
+
+import { showActionError } from './show-action-error';
+import { asTranslateFn } from './translate-message';
+import type { ShowActionErrorOptions } from './show-action-error';
+
+/**
+ * A failed form submission: each server field error goes under its field (the first one gets
+ * focus), field errors for fields the form doesn't render and errors about the whole submission go
+ * to the form alert (`root.server`), then the action-error toast. A field counts as rendered when
+ * it has a value, so every form sets `defaultValues` for every field. The form keeps every value.
+ */
+export function applyServerErrors(
+ form: UseFormReturn,
+ error: unknown,
+ options: ShowActionErrorOptions,
+): void {
+ if (classifyError(error).action === 'silent') return;
+
+ const unmatched: string[] = [];
+ let hasFieldError = false;
+ const fieldErrors = isHttpError(error) ? (error.fieldErrors ?? {}) : {};
+ for (const [field, message] of Object.entries(fieldErrors)) {
+ if (form.getValues(field as Path) === undefined) {
+ unmatched.push(message);
+ continue;
+ }
+ form.setError(
+ field as Path,
+ { type: 'server', message },
+ { shouldFocus: !hasFieldError },
+ );
+ hasFieldError = true;
+ }
+
+ if (!hasFieldError && unmatched.length === 0) {
+ unmatched.push(
+ describeError(error, asTranslateFn(options.t)).message ??
+ options.failedMessage,
+ );
+ }
+ if (unmatched.length > 0) {
+ form.setError('root.server', {
+ type: 'server',
+ message: unmatched.join(' '),
+ });
+ }
+
+ showActionError(error, options);
+}
diff --git a/platforms/market/src/shared/utils/index.ts b/platforms/market/src/shared/utils/index.ts
index 1286383..abb3fe6 100644
--- a/platforms/market/src/shared/utils/index.ts
+++ b/platforms/market/src/shared/utils/index.ts
@@ -1,3 +1,8 @@
+export { applyServerErrors } from './apply-server-errors';
export { toApiUrl } from './api-url';
-export { toE164Mobile } from './mobile';
+export { formatMobile, toE164Mobile, toLocalMobile } from './mobile';
export { renameFieldErrors } from './rename-field-errors';
+export { showActionError } from './show-action-error';
+export type { ShowActionErrorOptions } from './show-action-error';
+export { asTranslateFn, translateMessage } from './translate-message';
+export type { AnyTranslate } from './translate-message';
diff --git a/platforms/market/src/shared/utils/mobile.ts b/platforms/market/src/shared/utils/mobile.ts
index 962b1d1..a2e0437 100644
--- a/platforms/market/src/shared/utils/mobile.ts
+++ b/platforms/market/src/shared/utils/mobile.ts
@@ -1,12 +1,34 @@
import { latinDigits } from '@lumina/tools/format';
+const MOBILE_PATTERN = /^(?:\+98|0098|98|0)?(9\d{9})$/;
+
+/** Latin digits without spaces, dashes or brackets. */
+function bareDigits(value: string): string {
+ return latinDigits(value).replace(/[\s()-]/g, '');
+}
+
/**
* An Iranian mobile number as typed (`۰۹۱۲ ۳۴۵ ۶۷۸۹`, `0912…`, `+98912…`, `98912…`) → E.164
* (`+989123456789`), the one form the API stores. Anything else is returned trimmed, so the
* server can reject it with its own message.
*/
export function toE164Mobile(value: string): string {
- const digits = latinDigits(value).replace(/[\s()-]/g, '');
- const match = /^(?:\+98|0098|98|0)?(9\d{9})$/.exec(digits);
+ const digits = bareDigits(value);
+ const match = MOBILE_PATTERN.exec(digits);
return match ? `+98${match[1]}` : digits;
}
+
+/** The same number in its local form (`09123456789`), the one the pages keep. Anything else: its bare digits. */
+export function toLocalMobile(value: string): string {
+ const digits = bareDigits(value);
+ const match = MOBILE_PATTERN.exec(digits);
+ return match ? `0${match[1]}` : digits;
+}
+
+/** `09123456789` → `0912 345 6789`, shown left to right; the font draws the digits in Persian. */
+export function formatMobile(value: string): string {
+ const local = toLocalMobile(value);
+ return /^09\d{9}$/.test(local)
+ ? `${local.slice(0, 4)} ${local.slice(4, 7)} ${local.slice(7)}`
+ : value;
+}
diff --git a/platforms/market/src/shared/utils/show-action-error.ts b/platforms/market/src/shared/utils/show-action-error.ts
new file mode 100644
index 0000000..2fe1631
--- /dev/null
+++ b/platforms/market/src/shared/utils/show-action-error.ts
@@ -0,0 +1,51 @@
+import { showToast } from '@lumina/island/molecules/toast';
+import { describeError, handleError } from '@lumina/libs/error-handler';
+
+import { asTranslateFn } from './translate-message';
+import type { AnyTranslate } from './translate-message';
+
+export type ShowActionErrorOptions = {
+ t: AnyTranslate;
+ /** What failed, naming the object: «کد تأیید ارسال نشد». */
+ failedMessage: string;
+ /** Only when running the action again is safe. */
+ retry?: () => void;
+ /** Refetches the data the action changed, for 409 and 404. */
+ reload?: () => void;
+};
+
+/**
+ * The one error toast for a failed action. It handles the error once, says what failed, adds the
+ * server's message and hint (or a support sentence with the reference code), and offers the button
+ * the error's retry kind allows. It stays until dismissed; a repeated failure replaces it.
+ */
+export function showActionError(
+ error: unknown,
+ { t: anyT, failedMessage, retry, reload }: ShowActionErrorOptions,
+): void {
+ const t = asTranslateFn(anyT);
+ const errorClass = handleError(error, { where: 'action' });
+ if (errorClass.action === 'silent') return;
+
+ const { message, hint, referenceId } = describeError(error, t);
+ const details = [message, hint].filter(Boolean).join(' ');
+ const action =
+ errorClass.retry === 'again' && retry
+ ? { label: t('errors:action.try-again'), onClick: retry }
+ : errorClass.retry === 'reload' && reload
+ ? { label: t('errors:action.reload'), onClick: reload }
+ : undefined;
+
+ showToast({
+ id: `action-error:${failedMessage}`,
+ tone: 'error',
+ message: failedMessage,
+ description:
+ details ||
+ (referenceId
+ ? t('errors:support.with-reference', { referenceId })
+ : t('errors:support.without-reference')),
+ action,
+ duration: Infinity,
+ });
+}
diff --git a/platforms/market/src/shared/utils/translate-message.ts b/platforms/market/src/shared/utils/translate-message.ts
new file mode 100644
index 0000000..20da558
--- /dev/null
+++ b/platforms/market/src/shared/utils/translate-message.ts
@@ -0,0 +1,27 @@
+import type { TranslateFn } from '@lumina/libs/error-handler';
+
+/**
+ * i18next's `t` from `useTranslation`, for any namespace. Its key types reject the keys the error
+ * handler passes (`errors:http.network`), so the helpers here take it untyped.
+ */
+export type AnyTranslate = (...args: never[]) => unknown;
+
+export function asTranslateFn(t: AnyTranslate): TranslateFn {
+ return t as unknown as TranslateFn;
+}
+
+/** `auth:validation.phone-invalid`, `errors:auth.code-wrong`: a namespace, a colon and a dotted key. */
+const KEY_PATTERN = /^[a-z]+:[\w.-]+$/;
+
+/**
+ * A form message as the field shows it. Validation messages and mapped server errors are i18n
+ * keys and get translated; any other server text is already the user's language and passes
+ * through.
+ */
+export function translateMessage(
+ t: AnyTranslate,
+ message: string | undefined,
+): string | undefined {
+ if (!message) return undefined;
+ return KEY_PATTERN.test(message) ? asTranslateFn(t)(message) : message;
+}
diff --git a/platforms/market/src/shared/validations/.gitkeep b/platforms/market/src/shared/validations/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/platforms/market/src/shared/validations/auth-validations.ts b/platforms/market/src/shared/validations/auth-validations.ts
new file mode 100644
index 0000000..8d8fe3a
--- /dev/null
+++ b/platforms/market/src/shared/validations/auth-validations.ts
@@ -0,0 +1,78 @@
+import * as v from 'valibot';
+
+import { mobileNumber, nationalId, persianName } from './base-validations';
+import {
+ ACCOUNT_TYPES,
+ CODE_PATTERN,
+ ID_CARD_IMAGE,
+ USERNAME_LENGTH,
+ USERNAME_PATTERN,
+} from './constants';
+
+export const phoneSchema = v.object({
+ phone: mobileNumber('auth:validation.phone-invalid'),
+});
+
+export const codeSchema = v.object({
+ code: v.pipe(
+ v.string(),
+ v.regex(CODE_PATTERN, 'auth:validation.code-length'),
+ ),
+});
+
+/** Nothing is pre-selected, so the empty choice is the form's start. */
+export const accountTypeSchema = v.object({
+ role: v.pipe(
+ v.string(),
+ v.nonEmpty('auth:validation.role-required'),
+ v.picklist(ACCOUNT_TYPES, 'auth:validation.role-required'),
+ ),
+});
+
+/** Stored lower-case, so capitals are taken as typed and lowered. */
+const username = v.pipe(
+ v.string(),
+ v.trim(),
+ v.toLowerCase(),
+ v.nonEmpty('auth:validation.username-required'),
+ v.regex(USERNAME_PATTERN, 'auth:validation.username-characters'),
+ v.minLength(USERNAME_LENGTH.min, 'auth:validation.username-short'),
+ v.maxLength(USERNAME_LENGTH.max, 'auth:validation.username-long'),
+);
+
+const names = {
+ firstName: persianName(
+ 'auth:validation.required',
+ 'auth:validation.first-name-persian',
+ ),
+ lastName: persianName(
+ 'auth:validation.required',
+ 'auth:validation.last-name-persian',
+ ),
+};
+
+/** JPG or PNG up to 5 MB, checked when picked and again on submit. */
+export const idCardImage = v.pipe(
+ v.nullable(v.file()),
+ v.check((file) => file !== null, 'auth:validation.id-card-required'),
+ v.transform((file) => file as File),
+ v.file(),
+ v.mimeType(ID_CARD_IMAGE.types, 'auth:validation.id-card-type'),
+ v.maxSize(ID_CARD_IMAGE.maxBytes, 'auth:validation.id-card-size'),
+);
+
+export const investorDetailsSchema = v.object({
+ ...names,
+ username,
+});
+
+export const creatorIdentitySchema = v.object({
+ username,
+ ...names,
+ nationalId: nationalId(
+ 'auth:validation.national-id-length',
+ 'auth:validation.national-id-invalid',
+ ),
+ idCardFront: idCardImage,
+ idCardBack: idCardImage,
+});
diff --git a/platforms/market/src/shared/validations/base-validations.ts b/platforms/market/src/shared/validations/base-validations.ts
new file mode 100644
index 0000000..36ed906
--- /dev/null
+++ b/platforms/market/src/shared/validations/base-validations.ts
@@ -0,0 +1,32 @@
+import { latinDigits } from '@lumina/tools/format';
+import * as v from 'valibot';
+
+import { toLocalMobile } from '../utils/mobile';
+import { NATIONAL_ID_LENGTH, PERSIAN_NAME_PATTERN } from './constants';
+import { isNationalId } from './national-id';
+
+// Every message is an i18n key; the field translates it.
+
+export const requiredString = (message: string) =>
+ v.pipe(v.string(), v.trim(), v.nonEmpty(message));
+
+/** Any way a mobile number is typed (Persian digits, +98, spaces) → `09XXXXXXXXX`. */
+export const mobileNumber = (message: string) =>
+ v.pipe(v.string(), v.transform(toLocalMobile), v.regex(/^09\d{9}$/, message));
+
+export const persianName = (required: string, persian: string) =>
+ v.pipe(
+ v.string(),
+ v.trim(),
+ v.nonEmpty(required),
+ v.regex(PERSIAN_NAME_PATTERN, persian),
+ );
+
+/** 10 digits (Persian digits accepted) with a matching check digit. */
+export const nationalId = (length: string, invalid: string) =>
+ v.pipe(
+ v.string(),
+ v.transform((value) => latinDigits(value).replace(/\s/g, '')),
+ v.regex(new RegExp(`^\\d{${NATIONAL_ID_LENGTH}}$`), length),
+ v.check(isNationalId, invalid),
+ );
diff --git a/platforms/market/src/shared/validations/constants.ts b/platforms/market/src/shared/validations/constants.ts
new file mode 100644
index 0000000..6dbca4b
--- /dev/null
+++ b/platforms/market/src/shared/validations/constants.ts
@@ -0,0 +1,19 @@
+/** Persian letters, the space and the zero-width non-joiner (ZWNJ), for names. */
+export const PERSIAN_NAME_PATTERN = /^[ء-غف-يً-ْآپچژکگی ]+$/;
+
+/** Lower-case Latin letters, digits and the underscore. */
+export const USERNAME_PATTERN = /^[a-z0-9_]+$/;
+
+export const USERNAME_LENGTH = { min: 3, max: 30 } as const;
+
+export const NATIONAL_ID_LENGTH = 10;
+
+/** The national ID card images the API accepts. */
+export const ID_CARD_IMAGE = {
+ types: ['image/jpeg', 'image/png'],
+ maxBytes: 5 * 1024 * 1024,
+} as const;
+
+export const ACCOUNT_TYPES = ['investor', 'creator'] as const;
+
+export const CODE_PATTERN = /^\d{6}$/;
diff --git a/platforms/market/src/shared/validations/index.ts b/platforms/market/src/shared/validations/index.ts
new file mode 100644
index 0000000..e01c9cc
--- /dev/null
+++ b/platforms/market/src/shared/validations/index.ts
@@ -0,0 +1,20 @@
+export {
+ accountTypeSchema,
+ codeSchema,
+ creatorIdentitySchema,
+ idCardImage,
+ investorDetailsSchema,
+ phoneSchema,
+} from './auth-validations';
+export { ID_CARD_IMAGE, USERNAME_LENGTH } from './constants';
+export type {
+ AccountTypeFormOutput,
+ AccountTypeFormValues,
+ CodeFormValues,
+ CreatorIdentityFormOutput,
+ CreatorIdentityFormValues,
+ InvestorDetailsFormOutput,
+ InvestorDetailsFormValues,
+ PhoneFormOutput,
+ PhoneFormValues,
+} from './types';
diff --git a/platforms/market/src/shared/validations/national-id.ts b/platforms/market/src/shared/validations/national-id.ts
new file mode 100644
index 0000000..2671ba7
--- /dev/null
+++ b/platforms/market/src/shared/validations/national-id.ts
@@ -0,0 +1,18 @@
+import { NATIONAL_ID_LENGTH } from './constants';
+
+/**
+ * The Iranian national ID check digit: the first nine digits weighted 10…2, summed, mod 11; the
+ * last digit is that remainder when it is below 2, else 11 minus it. Ten equal digits pass the
+ * sum but are never issued.
+ */
+export function isNationalId(value: string): boolean {
+ if (!new RegExp(`^\\d{${NATIONAL_ID_LENGTH}}$`).test(value)) return false;
+ if (/^(\d)\1+$/.test(value)) return false;
+ const digits = [...value].map(Number);
+ const sum = digits
+ .slice(0, 9)
+ .reduce((total, digit, index) => total + digit * (10 - index), 0);
+ const remainder = sum % 11;
+ const check = remainder < 2 ? remainder : 11 - remainder;
+ return digits[9] === check;
+}
diff --git a/platforms/market/src/shared/validations/types.ts b/platforms/market/src/shared/validations/types.ts
new file mode 100644
index 0000000..3d6db85
--- /dev/null
+++ b/platforms/market/src/shared/validations/types.ts
@@ -0,0 +1,28 @@
+import type * as v from 'valibot';
+
+import type {
+ accountTypeSchema,
+ codeSchema,
+ creatorIdentitySchema,
+ investorDetailsSchema,
+ phoneSchema,
+} from './auth-validations';
+
+/** What each form holds while typing (`useForm`'s values) and what its schema hands the submit. */
+export type PhoneFormValues = v.InferInput;
+export type PhoneFormOutput = v.InferOutput;
+export type CodeFormValues = v.InferInput;
+export type AccountTypeFormValues = v.InferInput;
+export type AccountTypeFormOutput = v.InferOutput;
+export type InvestorDetailsFormValues = v.InferInput<
+ typeof investorDetailsSchema
+>;
+export type InvestorDetailsFormOutput = v.InferOutput<
+ typeof investorDetailsSchema
+>;
+export type CreatorIdentityFormValues = v.InferInput<
+ typeof creatorIdentitySchema
+>;
+export type CreatorIdentityFormOutput = v.InferOutput<
+ typeof creatorIdentitySchema
+>;
diff --git a/platforms/market/src/stores/auth-flow/auth-flow-store.ts b/platforms/market/src/stores/auth-flow/auth-flow-store.ts
new file mode 100644
index 0000000..cfe0da2
--- /dev/null
+++ b/platforms/market/src/stores/auth-flow/auth-flow-store.ts
@@ -0,0 +1,66 @@
+import { create } from 'zustand';
+import { immer } from 'zustand/middleware/immer';
+
+import type { AuthFlowState } from './types';
+
+const INITIAL = {
+ purpose: null,
+ role: null,
+ phone: null,
+ codeSentAt: null,
+ misses: 0,
+ blockedUntil: null,
+ registration: null,
+ draft: null,
+} satisfies Partial;
+
+/**
+ * Login and registration in progress, in the browser only. Never written during a server render:
+ * the auth pages render their steps in the browser alone. A successful sign-in or registration
+ * resets it, so no number or token outlives the flow.
+ */
+export const useAuthFlowStore = create()(
+ immer((set) => ({
+ ...INITIAL,
+ chooseRole: (role) =>
+ set((state) => {
+ state.role = role;
+ }),
+ carryPhone: (phone) =>
+ set((state) => {
+ state.phone = phone;
+ }),
+ codeSent: (purpose, phone, sentAt) =>
+ set((state) => {
+ // A different number starts clean: the block and the misses belong to the old one.
+ if (state.phone !== phone) state.blockedUntil = null;
+ state.purpose = purpose;
+ state.phone = phone;
+ state.codeSentAt = sentAt;
+ state.misses = 0;
+ state.registration = null;
+ }),
+ codeMissed: () =>
+ set((state) => {
+ state.misses += 1;
+ }),
+ block: (until) =>
+ set((state) => {
+ state.blockedUntil = until;
+ state.misses = 0;
+ }),
+ phoneVerified: (registration) =>
+ set((state) => {
+ state.registration = registration;
+ state.misses = 0;
+ }),
+ keepDraft: (draft) =>
+ set((state) => {
+ state.draft = draft;
+ }),
+ reset: () => set(INITIAL),
+ })),
+);
+
+export const useFlowPhone = () => useAuthFlowStore((state) => state.phone);
+export const useFlowRole = () => useAuthFlowStore((state) => state.role);
diff --git a/platforms/market/src/stores/auth-flow/index.ts b/platforms/market/src/stores/auth-flow/index.ts
new file mode 100644
index 0000000..976c0d6
--- /dev/null
+++ b/platforms/market/src/stores/auth-flow/index.ts
@@ -0,0 +1,6 @@
+export { useAuthFlowStore, useFlowPhone, useFlowRole } from './auth-flow-store';
+export type {
+ AuthFlowState,
+ RegistrationDraft,
+ RegistrationGrant,
+} from './types';
diff --git a/platforms/market/src/stores/auth-flow/types.ts b/platforms/market/src/stores/auth-flow/types.ts
new file mode 100644
index 0000000..2bb498a
--- /dev/null
+++ b/platforms/market/src/stores/auth-flow/types.ts
@@ -0,0 +1,49 @@
+import type { AuthPurpose, UserRole } from '../../features/auth';
+
+/** Step 4's values, kept while the person confirms the number again after the token ran out. */
+export type RegistrationDraft = {
+ username: string;
+ firstName: string;
+ lastName: string;
+ nationalId?: string;
+ idCardFront?: File | null;
+ idCardBack?: File | null;
+};
+
+/** The phone is proven: step 4 runs on this token until `expiresAt` (ms since epoch). */
+export type RegistrationGrant = {
+ token: string;
+ expiresAt: number;
+};
+
+/**
+ * One login or registration in progress, in memory only: a reload starts over, and nothing here
+ * ever reaches a cookie or local storage. Times are ms since epoch, set in event handlers.
+ */
+export type AuthFlowState = {
+ purpose: AuthPurpose | null;
+ /** The account type chosen at registration step 1. */
+ role: UserRole | null;
+ /** 09XXXXXXXXX, carried between the number and the code steps, never in the URL. */
+ phone: string | null;
+ /** When the current code was sent; the resend wait counts from it. */
+ codeSentAt: number | null;
+ /** Wrong codes typed against the current code; the server blocks the number at the third. */
+ misses: number;
+ /** Until when the number may not try a code or ask for one. */
+ blockedUntil: number | null;
+ registration: RegistrationGrant | null;
+ draft: RegistrationDraft | null;
+
+ chooseRole: (role: UserRole) => void;
+ /** A typed number travels to the other flow (login ↔ registration) without sending a code. */
+ carryPhone: (phone: string) => void;
+ codeSent: (purpose: AuthPurpose, phone: string, sentAt: number) => void;
+ codeMissed: () => void;
+ /** `null` lifts the block when its time is up. */
+ block: (until: number | null) => void;
+ phoneVerified: (registration: RegistrationGrant) => void;
+ /** Leaving step 4 for a new code: its values come back after the code, until the flow resets. */
+ keepDraft: (draft: RegistrationDraft) => void;
+ reset: () => void;
+};