feat(market): registration step 5, profile completion

Creator (required, resumable) and investor (optional) profile steps, on the
session after registration step 4.

- Profile repository: `saveDraft` (PATCH /traders/me/profile, markets may be
  empty) and `complete` (POST /traders/me/profile/complete).
- Account repository: avatar upload and removal, `interests`; the account
  payload carries `avatarUrl` and `interests`.
- Actions: completeCreatorProfile (saves the form, then completes; emits
  `profile.complete`) and saveInvestorProfile (photo with progress, then
  markets; emits `auth.profile-saved`).
- Creator models: the page (form from the saved draft, links field array,
  submit), autosave (1 s after typing and on blur, one save at a time, never
  after completion), the photo part (uploads on pick, failed state with retry)
  and the live preview.
- Investor model: photo and markets saved on «ذخیره و ورود», «بعداً» skips;
  both land on ?redirect= or home with the welcome toast.
- The auth-flow store remembers the role registered in this tab, so step 5
  shows the resume banner only after a login or a reload.
- Validations: photo, bio, link rows per platform, markets, consent.
  Utils: social link handle and URL mapping, market toggle. PROFILE_LIMITS
  moves to shared/validations.
- Screens: CreatorProfileStep (mobile column with a preview sheet, desktop
  card beside a sticky preview, end-of-registration view) with its skeleton,
  and InvestorProfileStep.
- Copy for step 5 in the auth namespace; market and status labels in common.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-05 22:33:00 +04:00
parent 9216bc8177
commit 436695ae0b
61 changed files with 2403 additions and 34 deletions

View File

@ -0,0 +1,33 @@
'use client';
import {
useCreatorPhotoPart,
useCreatorProfilePage,
} from '../../../../../../../features/profile';
import { CompletedView } from './components/CompletedView';
import { ProfileForm } from './components/ProfileForm';
import { StepLayout } from './components/StepLayout';
import type { CreatorProfileStepProps } from './types';
/**
* Registration step 5 for a creator, on the normal session: the public profile, required but
* saved as it is typed, so it can be finished later. The page wraps it in Suspense while the
* saved draft loads; then the form, and after «تکمیل ثبت‌نام» the end of registration.
*/
export function CreatorProfileStep(props: CreatorProfileStepProps) {
const page = useCreatorProfilePage();
const photo = useCreatorPhotoPart(page.profile);
if (page.view === 'completed') {
return (
<StepLayout layout={props.layout}>
<CompletedView
username={page.profile.username}
size={props.size}
supportPlacement={props.supportPlacement}
/>
</StepLayout>
);
}
return <ProfileForm {...props} page={page} photo={photo} />;
}

View File

@ -0,0 +1,24 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { StepLayout } from './components/StepLayout';
import type { CreatorProfileStepSkeletonProps } from './types';
/**
* Step 5's shape before the viewer and the draft are known: the form and, on desktop, the
* preview card beside it, at the same size as the step. Server-safe, for the page's guard.
*/
export function CreatorProfileStepSkeleton({
layout,
label,
}: CreatorProfileStepSkeletonProps) {
return (
<StepLayout
layout={layout}
aside={
layout === 'desktop' && <SkeletonPreset preset="header" label={label} />
}
>
<SkeletonPreset preset="form" count={4} label={label} />
</StepLayout>
);
}

View File

@ -0,0 +1,104 @@
'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 type { IconName } from '@lumina/island/atoms/icon';
import { StateArt } from '@lumina/island/atoms/state-art';
import { StatusBadge } from '@lumina/island/atoms/status-badge';
import { Typography } from '@lumina/island/atoms/typography';
import { Card } from '@lumina/island/molecules/card';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../../../../../../navigation';
import { SupportEntry } from '../../../../../../organisms/support-entry';
import type { CompletedViewProps } from '../types';
const NEXT_STEPS = [
{ icon: 'check-circle', text: 'account', tone: 'text-success-text' },
{ icon: 'clock', text: 'review', tone: 'text-text-secondary' },
{ icon: 'tag', text: 'pricing', tone: 'text-text-secondary' },
{ icon: 'lock', text: 'posting', tone: 'text-text-secondary' },
] as const satisfies readonly { icon: IconName; text: string; tone: string }[];
/**
* The end of registration for a creator: identity under review (the dashboard's badge), news by
* SMS and notification, prices can be set now, posting opens after approval. Focus moves to the
* heading so screen readers hear it.
*/
export function CompletedView({
username,
size,
supportPlacement,
}: CompletedViewProps) {
const { t } = useTranslation('auth');
const { t: tCommon } = useTranslation('common');
const headingRef = useRef<HTMLHeadingElement>(null);
useEffect(() => headingRef.current?.focus(), []);
return (
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
<FlexBox
direction="flex-col"
alignItems="items-center"
gap="gap-3"
className="text-center"
>
<StateArt icon="check" tone="success" size="compact" />
<Typography
ref={headingRef}
tabIndex={-1}
tag="h1"
variant="heading-md"
className="outline-none"
>
{t('register.profile.done.title')}
</Typography>
<StatusBadge status="verification.pending">
{tCommon('status.verification.pending')}
</StatusBadge>
</FlexBox>
<Card
tag="ul"
aria-label={t('register.profile.done.steps-label')}
className="flex flex-col gap-3"
>
{NEXT_STEPS.map(({ icon, text, tone }) => (
<FlexBox key={text} tag="li" alignItems="items-start" gap="gap-3">
<Icon
name={icon}
size={20}
className={`mt-0.5 flex-none ${tone}`}
/>
<Typography tag="span" variant="body-sm">
{t(`register.profile.done.${text}`)}
</Typography>
</FlexBox>
))}
</Card>
<FlexBox direction="flex-col" gap="gap-3">
<Button
href={ROUTES.channel(username)}
variant="primary"
size={size}
block
>
{t('register.profile.done.channel')}
</Button>
<Button
href={ROUTES.dashboard.pricing}
variant="secondary"
size={size}
block
>
{t('register.profile.done.set-pricing')}
</Button>
</FlexBox>
<FlexBox justifyContent="justify-center" className="mt-auto">
<SupportEntry trigger="link" placement={supportPlacement} />
</FlexBox>
</FlexBox>
);
}

View File

@ -0,0 +1,132 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { FormSection } from '@lumina/island/molecules/form-section';
import { TextInput } from '@lumina/island/molecules/text-input';
import { number } from '@lumina/tools/format';
import { useRef, useState } from 'react';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { translateMessage } from '../../../../../../../../shared/utils';
import { SOCIAL_HANDLE_ADDRESSES } from '../../../../../../../../shared/validations';
import type { SocialPlatform } from '../../../../../../../../shared/validations';
import type { LinksSectionProps } from '../types';
import { PlatformPicker } from './PlatformPicker';
/**
* Up to eight links, one row each: the platform as the label, its address as a fixed LTR prefix,
* only the handle to type (a pasted address is cut down to it), and remove. «افزودن لینک» picks
* the platform; at eight it is frozen and says why.
*/
export function LinksSection({ control, links, layout }: LinksSectionProps) {
const { t } = useTranslation('auth');
const [isPicking, setIsPicking] = useState(false);
// The picked platform waits for the picker to close: the page is inert until then, so the new
// row could not take focus.
const picked = useRef<SocialPlatform | null>(null);
return (
<FormSection
title={t('register.profile.links.title')}
note={t('register.profile.optional')}
hint={t('register.profile.links.hint')}
>
{links.rows.map((row, index) => {
const platformName = t(`register.profile.platforms.${row.platform}`);
const isWebsite = row.platform === 'website';
return (
<FlexBox key={row.key} alignItems="items-start" gap="gap-2">
<Controller
name={`links.${index}.handle`}
control={control}
render={({ field, fieldState }) => (
<TextInput
{...field}
className="flex-1"
dir="ltr"
inputMode="url"
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
label={platformName}
prefix={
row.platform === 'website'
? undefined
: SOCIAL_HANDLE_ADDRESSES[row.platform].prefix
}
placeholder={
isWebsite
? t('register.profile.links.website-placeholder')
: t('register.profile.links.placeholder')
}
onPaste={(event) => {
const text = event.clipboardData.getData('text');
const handle = links.toHandle(row.platform, text);
if (handle === text.trim()) return;
event.preventDefault();
field.onChange(handle);
}}
onBlur={() => {
const handle = links.toHandle(row.platform, field.value);
if (handle !== field.value) field.onChange(handle);
field.onBlur();
}}
error={translateMessage(t, fieldState.error?.message)}
/>
)}
/>
{/* The label's height, so the button lines up with the field. */}
<Button
variant="ghost"
icon="trash"
label={t('register.profile.links.remove', {
platform: platformName,
})}
className="mt-7.5"
onClick={() => links.remove(index)}
/>
</FlexBox>
);
})}
<FlexBox
alignItems="items-center"
justifyContent="justify-between"
gap="gap-3"
>
<Button
variant="secondary"
icon="plus"
frozen={!links.canAdd}
frozenReason={t('register.profile.links.max', {
max: number(links.max),
})}
onClick={() => setIsPicking(true)}
>
{t('register.profile.links.add')}
</Button>
<Typography tag="span" variant="caption" color="secondary">
{t('register.profile.links.count', {
current: number(links.rows.length),
max: number(links.max),
})}
</Typography>
</FlexBox>
<PlatformPicker
open={isPicking}
layout={layout}
onClose={() => setIsPicking(false)}
onPick={(platform) => {
picked.current = platform;
setIsPicking(false);
}}
onExited={() => {
if (picked.current) links.add(picked.current);
picked.current = null;
}}
/>
</FormSection>
);
}

View File

@ -0,0 +1,70 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { RowButton } from '@lumina/island/atoms/row-button';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { useTranslation } from 'react-i18next';
import {
SOCIAL_HANDLE_ADDRESSES,
SOCIAL_PLATFORMS,
} from '../../../../../../../../shared/validations';
import type { PlatformPickerProps } from '../types';
/**
* «افزودن لینک»: the platforms, each with its fixed address. A tap adds a row for it; a picker
* has no cancel button, only the ✕. A bottom sheet on mobile, a modal on desktop.
*/
export function PlatformPicker({
open,
layout,
onPick,
onClose,
onExited,
}: PlatformPickerProps) {
const { t } = useTranslation('auth');
const title = t('register.profile.links.sheet-title');
const closeLabel = t('register.profile.links.close');
const rows = (
<FlexBox direction="flex-col" gap="gap-2">
{SOCIAL_PLATFORMS.map((platform) => (
<RowButton
key={platform}
icon={platform === 'telegram' ? 'telegram' : 'link'}
meta={
platform === 'website'
? t('register.profile.links.website-meta')
: SOCIAL_HANDLE_ADDRESSES[platform].prefix
}
metaDir={platform === 'website' ? undefined : 'ltr'}
onClick={() => onPick(platform)}
>
{t(`register.profile.platforms.${platform}`)}
</RowButton>
))}
</FlexBox>
);
return layout === 'mobile' ? (
<Sheet
open={open}
title={title}
closeLabel={closeLabel}
onClose={onClose}
onExited={onExited}
>
{rows}
</Sheet>
) : (
<Modal
open={open}
title={title}
closeLabel={closeLabel}
onClose={onClose}
onExited={onExited}
>
{rows}
</Modal>
);
}

View File

@ -0,0 +1,269 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { Checkbox } from '@lumina/island/atoms/checkbox';
import { FieldError } from '@lumina/island/atoms/field-error';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { LinkButton } from '@lumina/island/atoms/link-button';
import { Typography } from '@lumina/island/atoms/typography';
import { AvatarField } from '@lumina/island/molecules/avatar-field';
import { Banner } from '@lumina/island/molecules/banner';
import { ChipGroup } from '@lumina/island/molecules/chip-group';
import { FormSection } from '@lumina/island/molecules/form-section';
import { Sheet } from '@lumina/island/molecules/sheet';
import { TextInput } from '@lumina/island/molecules/text-input';
import { useId, useState } from 'react';
import type { FormEvent } from 'react';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { MARKETS } from '../../../../../../../../shared/constants';
import {
toggleMarket,
translateMessage,
} from '../../../../../../../../shared/utils';
import {
AVATAR_IMAGE,
PROFILE_LIMITS,
} from '../../../../../../../../shared/validations';
import { SupportEntry } from '../../../../../../organisms/support-entry';
import { RegisterProgress } from '../../../../../../organisms/register-progress';
import type { ProfileFormProps } from '../types';
import { LinksSection } from './LinksSection';
import { ProfilePreview } from './ProfilePreview';
import { SaveStatus } from './SaveStatus';
import { StepLayout } from './StepLayout';
/**
* Step 5's form for a creator, top to bottom: photo, bio, markets, links and, once there is a
* link, the consent; «تکمیل ثبت‌نام» under it with the autosave line. Leaving a field saves at
* once. The preview opens in a sheet on mobile and stays beside the form on desktop.
*/
export function ProfileForm({
page,
photo,
size,
layout,
supportPlacement,
}: ProfileFormProps) {
const { t } = useTranslation('auth');
const { t: tCommon } = useTranslation('common');
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const consentErrorId = useId();
const { form, links, profile } = page;
const marketOptions = MARKETS.map((market) => ({
value: market,
label: tCommon(`markets.${market}`),
}));
const preview = (
<ProfilePreview
control={form.control}
username={profile.username}
avatarSrc={photo.src}
/>
);
return (
<StepLayout
layout={layout}
aside={
layout === 'desktop' && (
<FlexBox direction="flex-col" gap="gap-4">
<FlexBox alignItems="items-center" className="gap-1.5">
<Icon name="eye" size={16} className="text-text-secondary" />
<Typography
tag="h2"
variant="caption"
color="secondary"
className="font-semibold"
>
{t('register.profile.preview.live')}
</Typography>
</FlexBox>
{preview}
</FlexBox>
)
}
>
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
{page.isResuming && (
<Banner
tone="info"
title={t('register.profile.creator.resume-title')}
>
{t('register.profile.creator.resume-description')}
</Banner>
)}
{page.formError && (
<Banner
tone="danger"
title={t('register.profile.creator.network-title')}
>
{page.formError}
</Banner>
)}
<RegisterProgress current={4} role="creator" />
<FlexBox
direction="flex-col"
alignItems="items-start"
className="gap-1.5"
>
<Typography tag="h1" variant="heading-md">
{t('register.profile.creator.title')}
</Typography>
<Typography color="secondary">
{t('register.profile.creator.description')}
</Typography>
{layout === 'mobile' && (
<LinkButton
standalone
iconStart="eye"
aria-haspopup="dialog"
onClick={() => setIsPreviewOpen(true)}
>
{t('register.profile.preview.open')}
</LinkButton>
)}
</FlexBox>
<FlexBox
tag="form"
noValidate
direction="flex-col"
gap="gap-6"
onBlur={page.saveNow}
onSubmit={(event: FormEvent) => {
event.preventDefault();
void page.submit();
}}
>
<FormSection
title={t('register.profile.photo.title')}
note={t('register.profile.optional')}
hint={t('register.profile.photo.hint')}
>
<AvatarField
name={profile.username}
src={photo.src}
status={photo.status}
progress={photo.progress}
error={translateMessage(t, photo.error)}
accept={AVATAR_IMAGE.types.join(',')}
onPick={photo.pick}
onRetry={photo.retry}
onRemove={photo.isRemoving ? undefined : photo.remove}
labels={{
pick: t('register.profile.photo.pick'),
change: t('register.profile.photo.change'),
remove: t('register.profile.photo.remove'),
retry: t('register.profile.photo.retry'),
preview: t('register.profile.photo.preview'),
uploading: (percent) =>
t('register.profile.photo.uploading', { percent }),
}}
/>
</FormSection>
<Controller
name="bio"
control={form.control}
render={({ field, fieldState }) => (
<TextInput
{...field}
multiline
rows={5}
showCount
maxLength={PROFILE_LIMITS.bioMaxLength}
limitMessage={t('register.profile.bio.limit')}
label={t('register.profile.bio.label')}
placeholder={t('register.profile.bio.placeholder')}
hint={t('register.profile.bio.hint')}
error={translateMessage(t, fieldState.error?.message)}
/>
)}
/>
<FormSection
title={t('register.profile.creator.markets-title')}
hint={t('register.profile.creator.markets-hint')}
>
<Controller
name="markets"
control={form.control}
render={({ field, fieldState }) => (
<ChipGroup
ref={field.ref}
label={t('register.profile.creator.markets-title')}
options={marketOptions}
value={field.value}
onToggle={(market) => {
field.onChange(toggleMarket(field.value, market));
field.onBlur();
}}
error={translateMessage(t, fieldState.error?.message)}
/>
)}
/>
</FormSection>
<LinksSection control={form.control} links={links} layout={layout} />
{links.rows.length > 0 && (
<Controller
name="consent"
control={form.control}
render={({ field, fieldState }) => (
<FlexBox direction="flex-col" gap="gap-1">
<Checkbox
ref={field.ref}
name={field.name}
checked={field.value}
onChange={(event) => field.onChange(event.target.checked)}
onBlur={field.onBlur}
invalid={fieldState.error != null}
aria-describedby={
fieldState.error ? consentErrorId : undefined
}
>
{t('register.profile.links.consent')}
</Checkbox>
{fieldState.error && (
<FieldError id={consentErrorId}>
{translateMessage(t, fieldState.error.message)}
</FieldError>
)}
</FlexBox>
)}
/>
)}
<FlexBox direction="flex-col" gap="gap-3">
<Button
type="submit"
variant="primary"
size={size}
block
isLoading={page.isSubmitting}
>
{t('register.profile.creator.submit')}
</Button>
<SaveStatus status={page.autosave} />
</FlexBox>
</FlexBox>
<FlexBox justifyContent="justify-center" className="mt-auto">
<SupportEntry trigger="link" placement={supportPlacement} />
</FlexBox>
{layout === 'mobile' && (
<Sheet
open={isPreviewOpen}
title={t('register.profile.preview.title')}
closeLabel={t('register.profile.preview.close')}
onClose={() => setIsPreviewOpen(false)}
>
<FlexBox direction="flex-col" gap="gap-4">
{preview}
<Typography variant="caption" color="secondary">
{t('register.profile.preview.note')}
</Typography>
</FlexBox>
</Sheet>
)}
</FlexBox>
</StepLayout>
);
}

View File

@ -0,0 +1,85 @@
'use client';
import { Avatar } from '@lumina/island/atoms/avatar';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Tag } from '@lumina/island/atoms/tag';
import { Typography } from '@lumina/island/atoms/typography';
import { Element } from '@lumina/island/primitives/element';
import { useTranslation } from 'react-i18next';
import { useCreatorProfilePreview } from '../../../../../../../../features/profile';
import type { ProfilePreviewProps } from '../types';
/**
* The channel header as investors will see it, with what is filled in so far: photo, username,
* bio, markets and links. Only this part re-renders while the creator types.
*/
export function ProfilePreview({
control,
username,
avatarSrc,
}: ProfilePreviewProps) {
const { t } = useTranslation('auth');
const { t: tCommon } = useTranslation('common');
const preview = useCreatorProfilePreview(control);
return (
<FlexBox direction="flex-col" className="gap-3.5">
<FlexBox alignItems="items-center" className="gap-3.5">
<Avatar name={username} src={avatarSrc} size="lg" />
<FlexBox direction="flex-col" className="min-w-0">
<Typography
tag="bdi"
dir="ltr"
variant="heading-sm"
className="truncate text-start"
>
@{username}
</Typography>
<Typography tag="span" variant="caption" color="secondary">
{t('register.profile.preview.channel')}
</Typography>
</FlexBox>
</FlexBox>
{preview.bio && (
<Typography
variant="body-sm"
className="break-words whitespace-pre-line"
>
{preview.bio}
</Typography>
)}
{preview.markets.length > 0 && (
<FlexBox tag="ul" wrap="flex-wrap" className="gap-1.5">
{preview.markets.map((market) => (
<Element key={market} tag="li">
<Tag>{tCommon(`markets.${market}`)}</Tag>
</Element>
))}
</FlexBox>
)}
{preview.links.length > 0 && (
<FlexBox tag="ul" direction="flex-col" gap="gap-1">
{preview.links.map((link) => (
<FlexBox key={link} tag="li" alignItems="items-center" gap="gap-2">
<Icon
name="link"
size={16}
className="flex-none text-text-secondary"
/>
<Typography
tag="bdi"
dir="ltr"
variant="body-sm"
className="truncate"
>
{link}
</Typography>
</FlexBox>
))}
</FlexBox>
)}
</FlexBox>
);
}

View File

@ -0,0 +1,43 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Icon } from '@lumina/island/atoms/icon';
import { Typography } from '@lumina/island/atoms/typography';
import { time } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import type { SaveStatusProps } from '../types';
/** The line under «تکمیل ثبت‌نام»: that the step saves itself, when it last did, or that it didn't. */
export function SaveStatus({ status }: SaveStatusProps) {
const { t } = useTranslation('auth');
const isFailed = status.phase === 'failed';
const text =
status.phase === 'saved'
? t('register.profile.autosave.saved', { time: time(status.at) })
: isFailed
? t('register.profile.autosave.failed')
: t('register.profile.autosave.idle');
return (
<FlexBox
tag="output"
alignItems="items-center"
justifyContent="justify-center"
className="gap-1.5"
>
<Icon
name={isFailed ? 'alert' : 'check-circle'}
size={16}
className={isFailed ? 'text-danger-text' : 'text-text-secondary'}
/>
<Typography
tag="span"
variant="caption"
color={isFailed ? 'danger' : 'secondary'}
>
{text}
</Typography>
</FlexBox>
);
}

View File

@ -0,0 +1,32 @@
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Card } from '@lumina/island/molecules/card';
import type { StepLayoutProps } from '../types';
/**
* Where step 5 sits. Mobile: the page's column. Desktop: a 560 card, with the live preview
* beside it when there is one; the preview stays in view while the form scrolls.
*/
export function StepLayout({ layout, aside, children }: StepLayoutProps) {
if (layout === 'mobile') return children;
const main = (
<Card padding="none" className="w-full max-w-form px-10 pt-10 pb-8">
{children}
</Card>
);
if (!aside) return main;
return (
<GridBox
alignItems="items-start"
gap="gap-8"
className="w-full max-w-max grid-cols-[minmax(0,var(--container-form))_22.5rem]"
>
{main}
<Card tag="aside" padding="lg" className="sticky top-6">
{aside}
</Card>
</GridBox>
);
}

View File

@ -0,0 +1,7 @@
export { CreatorProfileStep } from './CreatorProfileStep';
export { CreatorProfileStepSkeleton } from './CreatorProfileStepSkeleton';
export type {
CreatorProfileLayout,
CreatorProfileStepProps,
CreatorProfileStepSkeletonProps,
} from './types';

View File

@ -0,0 +1,71 @@
import type { ReactNode } from 'react';
import type {
AutosaveStatus,
CreatorPhotoPartModel,
CreatorProfileFormControl,
CreatorProfileLinks,
CreatorProfilePageModel,
} from '../../../../../../../features/profile';
import type { SocialPlatform } from '../../../../../../../shared/validations';
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
/** mobile: one column, the preview in a bottom sheet. desktop: the form card beside a live preview. */
export type CreatorProfileLayout = 'mobile' | 'desktop';
export type CreatorProfileStepProps = {
/** `lg` on mobile, `md` on desktop. */
size: 'md' | 'lg';
layout: CreatorProfileLayout;
supportPlacement: SupportEntryProps['placement'];
};
export type CreatorProfileStepSkeletonProps = {
layout: CreatorProfileLayout;
/** Hidden status text: «در حال بارگذاری…». */
label: string;
};
export type StepLayoutProps = {
layout: CreatorProfileLayout;
/** On desktop, the column beside the main card; omit it for a single card. */
aside?: ReactNode;
children: ReactNode;
};
export type ProfileFormProps = CreatorProfileStepProps & {
page: CreatorProfilePageModel;
photo: CreatorPhotoPartModel;
};
export type LinksSectionProps = {
control: CreatorProfileFormControl;
links: CreatorProfileLinks;
layout: CreatorProfileLayout;
};
export type PlatformPickerProps = {
open: boolean;
layout: CreatorProfileLayout;
onPick: (platform: SocialPlatform) => void;
onClose: () => void;
/** Closed, with the page usable again: the moment a new row can take focus. */
onExited: () => void;
};
export type ProfilePreviewProps = {
control: CreatorProfileFormControl;
username: string;
avatarSrc: string | null;
};
export type SaveStatusProps = {
status: AutosaveStatus;
};
export type CompletedViewProps = Pick<
CreatorProfileStepProps,
'size' | 'supportPlacement'
> & {
username: string;
};

View File

@ -0,0 +1,159 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { AvatarField } from '@lumina/island/molecules/avatar-field';
import { Banner } from '@lumina/island/molecules/banner';
import { ChipGroup } from '@lumina/island/molecules/chip-group';
import { FormSection } from '@lumina/island/molecules/form-section';
import { useState } from 'react';
import type { FormEvent } from 'react';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useInvestorProfilePage } from '../../../../../../../features/auth';
import { MARKETS } from '../../../../../../../shared/constants';
import {
toggleMarket,
translateMessage,
} from '../../../../../../../shared/utils';
import { AVATAR_IMAGE } from '../../../../../../../shared/validations';
import { useCurrentAccount } from '../../../../../../../stores/auth';
import { useAuthRoutes } from '../../../../../../navigation';
import { RegisterProgress } from '../../../../../organisms/register-progress';
import { SupportEntry } from '../../../../../organisms/support-entry';
import type { InvestorProfileStepProps } from './types';
/**
* Registration step 5 for an investor, optional: a photo and the markets they follow, then
* «ذخیره و ورود», or «بعداً» to enter without saving. Both land on `?redirect=` or home.
*/
export function InvestorProfileStep({
size,
supportPlacement,
}: InvestorProfileStepProps) {
const { t } = useTranslation('auth');
const { t: tCommon } = useTranslation('common');
const routes = useAuthRoutes();
const account = useCurrentAccount();
// Where both buttons lead, fixed when the step opens.
const [landingHref] = useState(() =>
routes.landing({
role: 'investor',
username: account?.username ?? '',
needsProfile: false,
}),
);
const page = useInvestorProfilePage({ landingHref });
const { photo } = page;
const marketOptions = MARKETS.map((market) => ({
value: market,
label: tCommon(`markets.${market}`),
}));
return (
<FlexBox direction="flex-col" gap="gap-6" className="flex-1">
{page.formError && (
<Banner
tone="danger"
title={t('register.profile.investor.network-title')}
>
{page.formError}
</Banner>
)}
<RegisterProgress current={4} role="investor" />
<FlexBox direction="flex-col" className="gap-1.5">
<Typography tag="h1" variant="heading-md">
{t('register.profile.investor.title')}
</Typography>
<Typography color="secondary">
{t('register.profile.investor.description')}
</Typography>
</FlexBox>
<FlexBox
tag="form"
noValidate
direction="flex-col"
gap="gap-6"
onSubmit={(event: FormEvent) => {
event.preventDefault();
void page.submit();
}}
>
<FormSection
title={t('register.profile.photo.title')}
note={t('register.profile.optional')}
hint={t('register.profile.photo.hint')}
>
<AvatarField
name={page.username}
src={photo.src}
status={photo.status}
progress={photo.progress}
error={translateMessage(t, photo.error)}
accept={AVATAR_IMAGE.types.join(',')}
disabled={page.isSubmitting}
onPick={photo.pick}
onRemove={photo.remove}
onRetry={() => void page.submit()}
labels={{
pick: t('register.profile.photo.pick'),
change: t('register.profile.photo.change'),
remove: t('register.profile.photo.remove'),
retry: t('register.profile.photo.retry'),
preview: t('register.profile.photo.preview'),
uploading: (percent) =>
t('register.profile.photo.uploading', { percent }),
}}
/>
</FormSection>
<FormSection
title={t('register.profile.investor.markets-title')}
note={t('register.profile.optional')}
hint={t('register.profile.investor.markets-hint')}
>
<Controller
name="markets"
control={page.form.control}
render={({ field }) => (
<ChipGroup
ref={field.ref}
label={t('register.profile.investor.markets-title')}
options={marketOptions}
value={field.value}
disabled={page.isSubmitting}
onToggle={(market) =>
field.onChange(toggleMarket(field.value, market))
}
/>
)}
/>
</FormSection>
<FlexBox direction="flex-col" gap="gap-3">
<Button
type="submit"
variant="primary"
size={size}
block
isLoading={page.isSubmitting}
>
{t('register.profile.investor.submit')}
</Button>
<Button
variant="secondary"
size={size}
block
disabled={page.isSubmitting}
onClick={page.skip}
>
{t('register.profile.investor.skip')}
</Button>
</FlexBox>
</FlexBox>
<FlexBox justifyContent="justify-center" className="mt-auto">
<SupportEntry trigger="link" placement={supportPlacement} />
</FlexBox>
</FlexBox>
);
}

View File

@ -0,0 +1,2 @@
export { InvestorProfileStep } from './InvestorProfileStep';
export type { InvestorProfileStepProps } from './types';

View File

@ -0,0 +1,7 @@
import type { SupportEntryProps } from '../../../../../organisms/support-entry';
export type InvestorProfileStepProps = {
/** `lg` on mobile, `md` on desktop. */
size: 'md' | 'lg';
supportPlacement: SupportEntryProps['placement'];
};

View File

@ -32,6 +32,7 @@ export async function registerCreator(
onProgress,
});
useAuthFlowStore.getState().reset();
useAuthFlowStore.getState().markRegistered(registration.account.role);
useAuthStore.getState().setSession({ account: registration.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {

View File

@ -16,6 +16,7 @@ export async function registerInvestor(
): Promise<SessionPayload> {
const session = await authRepository.registerInvestor(args);
useAuthFlowStore.getState().reset();
useAuthFlowStore.getState().markRegistered(session.account.role);
useAuthStore.getState().setSession({ account: session.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {

View File

@ -0,0 +1,38 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { accountRepository } from '../../repositories/account';
import type { AccountPayload } from '../../repositories/account';
import type {
SaveInvestorProfileArgs,
SaveInvestorProfileOptions,
} from './types';
/**
* Registration step 5 for an investor: uploads the picked photo (with progress), then saves the
* markets they follow; the auth store learns the new photo and markets. Emits
* `auth.profile-saved`.
*/
export async function saveInvestorProfile(
{ photo, interests }: SaveInvestorProfileArgs,
{
emit = true,
signal,
onProgress,
onPhotoSaved,
}: SaveInvestorProfileOptions = {},
): Promise<AccountPayload> {
if (photo) {
const withPhoto = await accountRepository.uploadAvatar(
{ avatar: photo },
{ signal, onProgress },
);
useAuthStore.getState().setSession({ account: withPhoto });
onPhotoSaved?.(withPhoto);
}
const account = await accountRepository.update({ interests });
useAuthStore.getState().setSession({ account });
if (emit) eventEmitter.emit(AUTH_EVENTS.profileSaved, { userId: account.id });
return account;
}

View File

@ -0,0 +1,5 @@
export { saveInvestorProfile } from './actions';
export type {
SaveInvestorProfileArgs,
SaveInvestorProfileOptions,
} from './types';

View File

@ -0,0 +1,18 @@
import type { UploadProgress } from '@lumina/libs/http';
import type { Market } from '../../../../shared/constants';
import type { AccountPayload } from '../../repositories/account';
export type SaveInvestorProfileArgs = {
/** A picked photo to upload, or `null` to keep the current one. */
photo: File | null;
interests: Market[];
};
export type SaveInvestorProfileOptions = {
emit?: boolean;
signal?: AbortSignal;
onProgress?: (progress: UploadProgress) => void;
/** The photo arrived; a retry after a later failure needn't send it again. */
onPhotoSaved?: (account: AccountPayload) => void;
};

View File

@ -5,6 +5,7 @@ export const AUTH_EVENTS = {
phoneVerified: 'auth.phone-verified',
login: 'auth.login',
register: 'auth.register',
profileSaved: 'auth.profile-saved',
logout: 'auth.logout',
} as const;

View File

@ -1,3 +1,5 @@
import type { Market } from '../../../../shared/constants';
/** The two account roles. Creators are «تحلیلگر» in every UI string, investors «سرمایه‌گذار». */
export type UserRole = 'investor' | 'creator';
@ -14,4 +16,8 @@ export type UserEntity = {
role: UserRole;
phone_verified: boolean;
status: UserStatus;
/** The account's own photo; a creator's public photo lives on the creator profile. */
avatar?: string | null;
/** The markets an investor follows, chosen at registration step 5. */
interests?: Market[];
};

View File

@ -6,6 +6,11 @@ export { logout } from './actions/logout';
export { registerCreator } from './actions/register-creator';
export { registerInvestor } from './actions/register-investor';
export { restoreSession } from './actions/restore-session';
export { saveInvestorProfile } from './actions/save-investor-profile';
export type {
SaveInvestorProfileArgs,
SaveInvestorProfileOptions,
} from './actions/save-investor-profile';
export { sendCode } from './actions/send-code';
export type { SendCodeArgs } from './actions/send-code';
export { verifyRegistrationCode } from './actions/verify-registration-code';
@ -24,6 +29,12 @@ export type {
ResendPhase,
UseCodeStepOptions,
} from './models/code-step';
export { useInvestorProfilePage } from './models/investor-profile';
export type {
InvestorPhotoStatus,
InvestorProfilePageModel,
UseInvestorProfilePageOptions,
} from './models/investor-profile';
export { useLoginPage } from './models/login';
export type { LoginPageModel, UseLoginPageOptions } from './models/login';
export { useLoginVerifyPage } from './models/login-verify';
@ -63,7 +74,11 @@ export type {
UseRegisterVerifyPageOptions,
} from './models/register-verify';
export { accountKeys, accountRepository } from './repositories/account';
export type { AccountPayload, UpdateAccountArgs } from './repositories/account';
export type {
AccountPayload,
UpdateAccountArgs,
UploadAccountAvatarArgs,
} from './repositories/account';
export {
AUTH_ENDPOINTS,
AUTH_ERROR_CODES,

View File

@ -0,0 +1,6 @@
export { useInvestorProfilePage } from './use-investor-profile-page';
export type {
InvestorPhotoStatus,
InvestorProfilePageModel,
UseInvestorProfilePageOptions,
} from './types';

View File

@ -0,0 +1,43 @@
import type { UseFormReturn } from 'react-hook-form';
import type {
InvestorProfileFormOutput,
InvestorProfileFormValues,
} from '../../../../shared/validations';
export type UseInvestorProfilePageOptions = {
/** Where both buttons lead: the page that asked (`?redirect=`), else home. */
landingHref: string;
};
/** idle: nothing in flight. uploading: the photo is on its way. failed: it didn't arrive. */
export type InvestorPhotoStatus = 'idle' | 'uploading' | 'failed';
export type InvestorProfilePageModel = {
/** The username, whose first letter stands in for a missing photo. */
username: string;
form: UseFormReturn<
InvestorProfileFormValues,
unknown,
InvestorProfileFormOutput
>;
photo: {
/** The picked photo's preview, else the saved one. */
src: string | null;
status: InvestorPhotoStatus;
/** 0–100 while uploading. */
progress: number | undefined;
/** An i18n key: a rejected pick or a failed upload. */
error: string | undefined;
/** Checks the type and size; the photo is sent with «ذخیره و ورود». */
pick: (file: File) => void;
/** Drops the picked photo; nothing was sent yet. */
remove: (() => void) | undefined;
};
/** «ذخیره و ورود»: saves the photo and markets, then enters. */
submit: () => Promise<void>;
/** «بعداً»: enters without saving anything. */
skip: () => void;
isSubmitting: boolean;
formError: string | undefined;
};

View File

@ -0,0 +1,141 @@
import { valibotResolver } from '@hookform/resolvers/valibot';
import { showToast } from '@lumina/island/molecules/toast';
import { classifyError, handleError } from '@lumina/libs/error-handler';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import * as v from 'valibot';
import { applyServerErrors } from '../../../../shared/utils';
import {
avatarImage,
investorProfileSchema,
} from '../../../../shared/validations';
import type {
InvestorProfileFormOutput,
InvestorProfileFormValues,
} from '../../../../shared/validations';
import { useAuthStore } from '../../../../stores/auth';
import { saveInvestorProfile } from '../../actions/save-investor-profile';
import type {
InvestorPhotoStatus,
InvestorProfilePageModel,
UseInvestorProfilePageOptions,
} from './types';
const UPLOAD_FAILED = 'auth:register.profile.photo-failed';
/**
* Registration step 5 for an investor, optional: a photo and the markets they follow. Nothing is
* saved until «ذخیره و ورود», which uploads the photo and saves the markets; «بعداً» enters as is.
* Both land on `landingHref` with the welcome toast. A failed upload shows under the photo, with
* the form kept for another try.
*/
export function useInvestorProfilePage({
landingHref,
}: UseInvestorProfilePageOptions): InvestorProfilePageModel {
const { t } = useTranslation('auth');
const router = useRouter();
// The guard renders this page for a signed-in investor only.
const [account] = useState(() => useAuthStore.getState().session?.account);
const [savedAvatarUrl, setSavedAvatarUrl] = useState(
account?.avatarUrl ?? null,
);
const [photoStatus, setPhotoStatus] = useState<InvestorPhotoStatus>('idle');
const [photoError, setPhotoError] = useState<string>();
const [progress, setProgress] = useState<number>();
const form = useForm<
InvestorProfileFormValues,
unknown,
InvestorProfileFormOutput
>({
resolver: valibotResolver(investorProfileSchema),
defaultValues: { photo: null, markets: account?.interests ?? [] },
});
const { errors, isSubmitting } = form.formState;
const photo = useWatch({ control: form.control, name: 'photo' });
const previewUrl = useMemo(
() => (photo ? URL.createObjectURL(photo) : null),
[photo],
);
useEffect(
() => () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
},
[previewUrl],
);
const enter = () => {
showToast({ tone: 'success', message: t('register.profile.welcome') });
router.replace(landingHref);
};
const submit = form.handleSubmit(async (values) => {
setPhotoError(undefined);
if (values.photo) setPhotoStatus('uploading');
try {
await saveInvestorProfile(
{ photo: values.photo, interests: values.markets },
{
onProgress: ({ percent }) => setProgress(percent),
onPhotoSaved: (saved) => {
// A retry after a later failure needn't send the photo again.
form.setValue('photo', null);
setSavedAvatarUrl(saved.avatarUrl);
setPhotoStatus('idle');
},
},
);
enter();
} catch (error) {
if (form.getValues('photo') && classifyError(error).action !== 'silent') {
// The upload failed: the message sits under the photo, like the creator's.
handleError(error, { where: 'action', name: 'investor-photo' });
setPhotoStatus('failed');
setPhotoError(UPLOAD_FAILED);
return;
}
setPhotoStatus('idle');
applyServerErrors(form, error, {
t,
failedMessage: t('register.profile.investor-failed'),
retry: () => void submit(),
});
} finally {
setProgress(undefined);
}
});
return {
username: account?.username ?? '',
form,
photo: {
src: previewUrl ?? savedAvatarUrl,
status: photoStatus,
progress,
error: photoError,
pick: (file) => {
const checked = v.safeParse(avatarImage, file);
if (!checked.success) {
setPhotoError(checked.issues[0].message);
return;
}
setPhotoError(undefined);
setPhotoStatus('idle');
form.setValue('photo', file, { shouldDirty: true });
},
remove: photo
? () => {
setPhotoError(undefined);
setPhotoStatus('idle');
form.setValue('photo', null, { shouldDirty: true });
}
: undefined,
},
submit: () => submit(),
skip: enter,
isSubmitting,
formError: errors.root?.server?.message,
};
}

View File

@ -1,10 +1,13 @@
import type { UploadProgress } from '@lumina/libs/http';
import { authHttp } from '../../http';
import { ACCOUNT_ENDPOINT } from './constants';
import { ACCOUNT_AVATAR_FIELD, ACCOUNT_ENDPOINTS } from './constants';
import { toAccountPayload, toUpdateAccountDto } from './mappers';
import type {
AccountPayload,
AccountResponseDto,
UpdateAccountArgs,
UploadAccountAvatarArgs,
} from './types';
/** The signed-in account (`/users/profile`), any role. 401 without a session. */
@ -12,17 +15,47 @@ export const accountRepository = {
async getCurrent({
signal,
}: { signal?: AbortSignal } = {}): Promise<AccountPayload> {
const response = await authHttp.get<AccountResponseDto>(ACCOUNT_ENDPOINT, {
signal,
});
const response = await authHttp.get<AccountResponseDto>(
ACCOUNT_ENDPOINTS.mine,
{ signal },
);
return toAccountPayload(response);
},
async update(args: UpdateAccountArgs): Promise<AccountPayload> {
const response = await authHttp.patch<AccountResponseDto>(
ACCOUNT_ENDPOINT,
ACCOUNT_ENDPOINTS.mine,
toUpdateAccountDto(args),
);
return toAccountPayload(response);
},
/**
* Uploads or replaces the account photo. A wrong format or size is a plain 400 message, which
* the form checks first.
*/
async uploadAvatar(
args: UploadAccountAvatarArgs,
{
signal,
onProgress,
}: {
signal?: AbortSignal;
onProgress?: (progress: UploadProgress) => void;
} = {},
): Promise<AccountPayload> {
const response = await authHttp.upload<AccountResponseDto>(
ACCOUNT_ENDPOINTS.avatar,
args.avatar,
{ method: 'PUT', fieldName: ACCOUNT_AVATAR_FIELD, signal, onProgress },
);
return toAccountPayload(response);
},
async removeAvatar(): Promise<AccountPayload> {
const response = await authHttp.delete<AccountResponseDto>(
ACCOUNT_ENDPOINTS.avatar,
);
return toAccountPayload(response);
},
};

View File

@ -1,4 +1,10 @@
export const ACCOUNT_ENDPOINT = '/users/profile';
export const ACCOUNT_ENDPOINTS = {
mine: '/users/profile',
avatar: '/users/profile/avatar',
} as const;
/** The multipart field the avatar upload reads. */
export const ACCOUNT_AVATAR_FIELD = 'avatar';
export const accountKeys = {
all: ['auth', 'account'] as const,

View File

@ -1,3 +1,7 @@
export { accountRepository } from './account';
export { accountKeys } from './constants';
export type { AccountPayload, UpdateAccountArgs } from './types';
export type {
AccountPayload,
UpdateAccountArgs,
UploadAccountAvatarArgs,
} from './types';

View File

@ -1,3 +1,4 @@
import { toApiUrl } from '../../../../shared/utils';
import type {
AccountPayload,
AccountResponseDto,
@ -16,6 +17,8 @@ export function toAccountPayload(dto: AccountResponseDto): AccountPayload {
role: dto.role,
phoneVerified: dto.phone_verified,
status: dto.status,
avatarUrl: toApiUrl(dto.avatar),
interests: dto.interests ?? [],
};
}
@ -24,5 +27,6 @@ export function toUpdateAccountDto(args: UpdateAccountArgs): UpdateAccountDto {
firstName: args.firstName?.trim(),
lastName: args.lastName?.trim(),
email: args.email?.trim().toLowerCase() || undefined,
interests: args.interests,
};
}

View File

@ -1,3 +1,4 @@
import type { Market } from '../../../../shared/constants';
import type { UserEntity, UserRole, UserStatus } from '../../entities/user';
/** The signed-in account, as apps and stores use it. */
@ -11,14 +12,22 @@ export type AccountPayload = {
role: UserRole;
phoneVerified: boolean;
status: UserStatus;
avatarUrl: string | null;
/** The markets an investor follows; empty until chosen. */
interests: Market[];
};
export type AccountResponseDto = UserEntity;
/** Fields left out keep their stored value; `interests` replaces the whole list. */
export type UpdateAccountArgs = {
firstName?: string;
lastName?: string;
email?: string;
interests?: Market[];
};
export type UpdateAccountDto = UpdateAccountArgs;
/** A JPG or PNG of at most 5 MB (`AVATAR_IMAGE`). */
export type UploadAccountAvatarArgs = { avatar: File };

View File

@ -14,6 +14,7 @@ declare module '@lumina/libs/event-emitter' {
'auth.phone-verified': { purpose: AuthPurpose };
'auth.login': { userId: string; role: UserRole };
'auth.register': { userId: string; role: UserRole };
'auth.profile-saved': { userId: string };
'auth.logout': { reason: LogoutReason };
}
}

View File

@ -0,0 +1,27 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { PROFILE_EVENTS } from '../../constants';
import { profileRepository } from '../../repositories/profile';
import type {
CreatorProfilePayload,
SaveProfileDraftArgs,
} from '../../repositories/profile';
/**
* Ends registration step 5 for a creator: saves the form as it stands, then completes the
* profile, which needs at least one market. Nothing is public before this. Emits
* `profile.complete`.
*/
export async function completeCreatorProfile(
args: SaveProfileDraftArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<CreatorProfilePayload> {
await profileRepository.saveDraft(args);
const profile = await profileRepository.complete();
if (emit) {
eventEmitter.emit(PROFILE_EVENTS.complete, {
creatorId: profile.creatorId,
});
}
return profile;
}

View File

@ -0,0 +1 @@
export { completeCreatorProfile } from './actions';

View File

@ -1,5 +1,10 @@
import type { TradingStyle } from './entities/creator-profile';
/** Events profile actions emit when they succeed. */
export const PROFILE_EVENTS = {
complete: 'profile.complete',
} as const;
/** Every trading style, in the server's order, for pickers. */
export const TRADING_STYLES: readonly TradingStyle[] = [
'scalping',
@ -10,15 +15,3 @@ export const TRADING_STYLES: readonly TradingStyle[] = [
'discretionary',
'options',
];
/** The server's profile rules (`CREATOR_PROFILE_LIMITS`), so forms reject what the API would. */
export const PROFILE_LIMITS = {
displayNameMaxLength: 80,
bioMaxLength: 300,
bioMaxLineBreaks: 3,
socialLinkLabelMaxLength: 30,
socialLinkUrlMaxLength: 2048,
socialLinksMax: 8,
avatarMaxBytes: 5 * 1024 * 1024,
avatarMimeTypes: ['image/jpeg', 'image/png'],
} as const;

View File

@ -1,8 +1,27 @@
export { PROFILE_LIMITS, TRADING_STYLES } from './constants';
import './types';
export { completeCreatorProfile } from './actions/complete-creator-profile';
export { PROFILE_EVENTS, TRADING_STYLES } from './constants';
export type { KycStatus, TradingStyle } from './entities/creator-profile';
export {
useCreatorPhotoPart,
useCreatorProfilePage,
useCreatorProfilePreview,
} from './models/creator-profile';
export type {
AutosaveStatus,
CreatorPhotoPartModel,
CreatorProfileFormControl,
CreatorProfileLinks,
CreatorProfilePageModel,
CreatorProfilePreview,
CreatorProfileView,
PhotoStatus,
} from './models/creator-profile';
export { profileKeys, profileRepository } from './repositories/profile';
export type {
CreatorProfilePayload,
SaveProfileDraftArgs,
SocialLinkArgs,
SocialLinkPayload,
UpdateProfileArgs,

View File

@ -0,0 +1,2 @@
/** The draft is saved this long after typing stops, and at once when a field loses focus. */
export const AUTOSAVE_DELAY_MS = 1000;

View File

@ -0,0 +1,61 @@
import * as v from 'valibot';
import {
displaySocialUrl,
fromSocialUrl,
toSocialUrl,
} from '../../../../shared/utils';
import { profileBio, socialLinkRow } from '../../../../shared/validations';
import type { CreatorProfileFormValues } from '../../../../shared/validations';
import type {
CreatorProfilePayload,
SaveProfileDraftArgs,
} from '../../repositories/profile';
type LinkRow = CreatorProfileFormValues['links'][number];
const isValidRow = (row: LinkRow) => v.is(socialLinkRow, row);
/** The saved draft as the form starts: one row per stored link. The consent is asked again. */
export function toCreatorProfileFormValues(
profile: CreatorProfilePayload,
): CreatorProfileFormValues {
return {
bio: profile.bio ?? '',
markets: profile.markets,
links: profile.socialLinks.map(({ label, url }) =>
fromSocialUrl(label, url),
),
consent: false,
};
}
/**
* What the draft keeps of the form: every part that is valid now, so a half-typed link never
* holds back the bio or the markets. A link's label names its platform.
*/
export function toDraftArgs(
values: CreatorProfileFormValues,
): SaveProfileDraftArgs {
return {
bio: v.is(profileBio, values.bio) ? values.bio : undefined,
markets: values.markets,
socialLinks: values.links
.filter(isValidRow)
.map(({ platform, handle }) => ({
label: platform,
url: toSocialUrl(platform, handle),
})),
};
}
/** The valid links as the profile shows them, each once: `t.me/ali_gold`. */
export function toPreviewLinks(links: LinkRow[]): string[] {
const shown = links
.filter(isValidRow)
.map(({ platform, handle }) =>
displaySocialUrl(toSocialUrl(platform, handle)),
);
// A link added twice shows once, as it would on the channel page.
return Array.from(new Set(shown));
}

View File

@ -0,0 +1,13 @@
export { useCreatorPhotoPart } from './use-creator-photo-part';
export { useCreatorProfilePage } from './use-creator-profile-page';
export { useCreatorProfilePreview } from './use-creator-profile-preview';
export type {
AutosaveStatus,
CreatorPhotoPartModel,
CreatorProfileFormControl,
CreatorProfileLinks,
CreatorProfilePageModel,
CreatorProfilePreview,
CreatorProfileView,
PhotoStatus,
} from './types';

View File

@ -0,0 +1,92 @@
import type {
Control,
UseFieldArrayReturn,
UseFormReturn,
} from 'react-hook-form';
import type { Market } from '../../../../shared/constants';
import type {
CreatorProfileFormOutput,
CreatorProfileFormValues,
SocialPlatform,
} from '../../../../shared/validations';
import type { CreatorProfilePayload } from '../../repositories/profile';
/** editing: the form. completed: registration is over and the next steps show. */
export type CreatorProfileView = 'editing' | 'completed';
/**
* idle: nothing saved in this visit yet. saved: the draft is on the server. failed: the last save
* didn't arrive; the next change tries again, and completing saves everything anyway.
*/
export type AutosaveStatus =
| { phase: 'idle' }
| { phase: 'saved'; at: number }
| { phase: 'failed' };
export type CreatorProfileForm = UseFormReturn<
CreatorProfileFormValues,
unknown,
CreatorProfileFormOutput
>;
export type CreatorProfileFormControl = Control<
CreatorProfileFormValues,
unknown,
CreatorProfileFormOutput
>;
export type CreatorProfileLinks = {
/** One row per link, keyed by `key`. */
rows: UseFieldArrayReturn<CreatorProfileFormValues, 'links', 'key'>['fields'];
max: number;
canAdd: boolean;
/** Adds an empty row for the platform and focuses it. A platform may appear twice. */
add: (platform: SocialPlatform) => void;
remove: (index: number) => void;
/** What a row keeps of typed or pasted text: a pasted full address becomes its handle. */
toHandle: (platform: SocialPlatform, input: string) => string;
};
export type CreatorProfilePageModel = {
profile: CreatorProfilePayload;
view: CreatorProfileView;
/** Back after a login or a reload rather than straight from step 4: the draft came back. */
isResuming: boolean;
form: CreatorProfileForm;
links: CreatorProfileLinks;
autosave: AutosaveStatus;
/** Saves what is pending at once, such as when a field loses focus. */
saveNow: () => void;
submit: () => Promise<void>;
isSubmitting: boolean;
/** A failure that belongs to no field, for the banner over the form. */
formError: string | undefined;
};
/** idle: nothing in flight. uploading: the picked photo is on its way. failed: it didn't arrive. */
export type PhotoStatus = 'idle' | 'uploading' | 'failed';
export type CreatorPhotoPartModel = {
/** The picked photo while it uploads or after it failed, else the saved one. */
src: string | null;
status: PhotoStatus;
/** 0–100 while uploading. */
progress: number | undefined;
/** An i18n key: a rejected pick or a failed upload. */
error: string | undefined;
/** Checks the type and size, then uploads at once; a rejected file keeps the current photo. */
pick: (file: File) => void;
/** Sends the same file again. */
retry: () => void;
remove: () => void;
isRemoving: boolean;
};
/** The channel header as investors will see it, from what is typed so far. */
export type CreatorProfilePreview = {
bio: string;
markets: Market[];
/** Valid links only, without the scheme: `t.me/ali_gold`. */
links: string[];
};

View File

@ -0,0 +1,102 @@
import { handleError } from '@lumina/libs/error-handler';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import * as v from 'valibot';
import { showActionError } from '../../../../shared/utils';
import { avatarImage } from '../../../../shared/validations';
import { profileKeys, profileRepository } from '../../repositories/profile';
import type { CreatorProfilePayload } from '../../repositories/profile';
import type { CreatorPhotoPartModel, PhotoStatus } from './types';
const UPLOAD_FAILED = 'auth:register.profile.photo-failed';
type PickedPhoto = { file: File; url: string };
/**
* The creator's photo at step 5. It is checked when picked and uploads at once; the picked photo
* shows while it uploads. A failed upload keeps it, dimmed, with «تلاش مجدد», and leaves the rest
* of the form alone, so it shows inline and is reported, never toasted.
*/
export function useCreatorPhotoPart(
profile: CreatorProfilePayload,
): CreatorPhotoPartModel {
const { t } = useTranslation('auth');
const queryClient = useQueryClient();
// Set while a picked photo uploads or after it failed; cleared once it is saved.
const [picked, setPicked] = useState<PickedPhoto | null>(null);
const [error, setError] = useState<string>();
const [progress, setProgress] = useState<number>();
useEffect(
() => () => {
if (picked) URL.revokeObjectURL(picked.url);
},
[picked],
);
const upload = useMutation({
mutationFn: (file: File) =>
profileRepository.uploadAvatar(
{ avatar: file },
{ onProgress: ({ percent }) => setProgress(percent) },
),
onMutate: () => {
setError(undefined);
setProgress(0);
},
onSuccess: (updated) => {
queryClient.setQueryData(profileKeys.mine(), updated);
setPicked(null);
},
onError: (failure) => {
const errorClass = handleError(failure, {
where: 'action',
name: 'profile-photo',
});
if (errorClass.action === 'silent') setPicked(null);
else setError(UPLOAD_FAILED);
},
onSettled: () => setProgress(undefined),
});
const removal = useMutation({
mutationFn: () => profileRepository.removeAvatar(),
onSuccess: (updated) =>
queryClient.setQueryData(profileKeys.mine(), updated),
onError: (failure) =>
showActionError(failure, {
t,
failedMessage: t('register.profile.photo-remove-failed'),
retry: () => removal.mutate(),
}),
});
const status: PhotoStatus = upload.isPending
? 'uploading'
: picked
? 'failed'
: 'idle';
return {
src: picked?.url ?? profile.avatarUrl,
status,
progress,
error,
pick: (file) => {
const checked = v.safeParse(avatarImage, file);
if (!checked.success) {
setError(checked.issues[0].message);
return;
}
setPicked({ file, url: URL.createObjectURL(file) });
upload.mutate(file);
},
retry: () => {
if (picked) upload.mutate(picked.file);
},
remove: () => removal.mutate(),
isRemoving: removal.isPending,
};
}

View File

@ -0,0 +1,95 @@
import { valibotResolver } from '@hookform/resolvers/valibot';
import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { applyServerErrors, toSocialHandle } from '../../../../shared/utils';
import {
creatorProfileSchema,
PROFILE_LIMITS,
} from '../../../../shared/validations';
import type {
CreatorProfileFormOutput,
CreatorProfileFormValues,
} from '../../../../shared/validations';
import { useAuthFlowStore } from '../../../../stores/auth-flow';
import { completeCreatorProfile } from '../../actions/complete-creator-profile';
import { profileKeys, profileRepository } from '../../repositories/profile';
import { toCreatorProfileFormValues, toDraftArgs } from './form-values';
import type { CreatorProfilePageModel, CreatorProfileView } from './types';
import { useProfileAutosave } from './use-profile-autosave';
/**
* Registration step 5 for a creator, on the normal session: the public profile (photo, bio,
* markets, links) that investors see before subscribing. It starts from the saved draft, saves as
* it is typed, and «تکمیل ثبت‌نام» completes it (at least one market; the consent once there is a
* link). A failed first read throws to the page boundary.
*/
export function useCreatorProfilePage(): CreatorProfilePageModel {
const { t } = useTranslation('auth');
const queryClient = useQueryClient();
const { data: profile } = useSuspenseQuery({
queryKey: profileKeys.mine(),
queryFn: ({ signal }) => profileRepository.getMine({ signal }),
});
// Read once: registering in this tab is what tells a first visit from a resumed one.
const [isResuming] = useState(
() => useAuthFlowStore.getState().registeredAs !== 'creator',
);
const [view, setView] = useState<CreatorProfileView>('editing');
const [initialValues] = useState(() => toCreatorProfileFormValues(profile));
const form = useForm<
CreatorProfileFormValues,
unknown,
CreatorProfileFormOutput
>({
resolver: valibotResolver(creatorProfileSchema),
mode: 'onTouched',
defaultValues: initialValues,
});
const links = useFieldArray({
control: form.control,
name: 'links',
keyName: 'key',
});
const autosave = useProfileAutosave(form, toDraftArgs(initialValues));
const { errors, isSubmitting } = form.formState;
const submit = form.handleSubmit(async (values) => {
await autosave.stop();
try {
const completed = await completeCreatorProfile(toDraftArgs(values));
queryClient.setQueryData(profileKeys.mine(), completed);
setView('completed');
} catch (error) {
autosave.resume();
applyServerErrors(form, error, {
t,
failedMessage: t('register.profile.failed'),
retry: () => void submit(),
});
}
});
return {
profile,
view,
isResuming,
form,
links: {
rows: links.fields,
max: PROFILE_LIMITS.socialLinksMax,
canAdd: links.fields.length < PROFILE_LIMITS.socialLinksMax,
add: (platform) =>
links.append({ platform, handle: '' }, { shouldFocus: true }),
remove: links.remove,
toHandle: toSocialHandle,
},
autosave: autosave.status,
saveNow: autosave.saveNow,
submit: () => submit(),
isSubmitting,
formError: errors.root?.server?.message,
};
}

View File

@ -0,0 +1,15 @@
import { useWatch } from 'react-hook-form';
import { toPreviewLinks } from './form-values';
import type { CreatorProfileFormControl, CreatorProfilePreview } from './types';
/** The channel header as investors will see it, updated as the creator types. */
export function useCreatorProfilePreview(
control: CreatorProfileFormControl,
): CreatorProfilePreview {
const [bio, markets, links] = useWatch({
control,
name: ['bio', 'markets', 'links'],
});
return { bio: bio.trim(), markets, links: toPreviewLinks(links) };
}

View File

@ -0,0 +1,99 @@
import { handleError } from '@lumina/libs/error-handler';
import { useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useRef, useState } from 'react';
import { profileKeys, profileRepository } from '../../repositories/profile';
import type { SaveProfileDraftArgs } from '../../repositories/profile';
import { AUTOSAVE_DELAY_MS } from './constants';
import { toDraftArgs } from './form-values';
import type { AutosaveStatus, CreatorProfileForm } from './types';
/**
* Saves the creator's step 5 as a draft about a second after typing stops, at once on request
* (a field lost focus), and when the page closes. Saves run one at a time, each from the newest
* values, and a save that would change nothing is skipped. A failure is reported and shown in the
* status line; it never toasts, because the next change tries again.
*/
export function useProfileAutosave(
form: CreatorProfileForm,
initial: SaveProfileDraftArgs,
) {
const queryClient = useQueryClient();
const [status, setStatus] = useState<AutosaveStatus>({ phase: 'idle' });
const lastSaved = useRef(JSON.stringify(initial));
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
const running = useRef<Promise<void> | null>(null);
const isStopped = useRef(false);
const save = useCallback(async (): Promise<void> => {
clearTimeout(timer.current);
while (running.current) await running.current;
if (isStopped.current) return;
const args = toDraftArgs(form.getValues());
const key = JSON.stringify(args);
if (key === lastSaved.current) return;
const request = profileRepository
.saveDraft(args)
.then(
(profile) => {
lastSaved.current = key;
queryClient.setQueryData(profileKeys.mine(), profile);
setStatus({ phase: 'saved', at: Date.now() });
},
(error: unknown) => {
const errorClass = handleError(error, {
where: 'action',
name: 'profile-autosave',
});
if (errorClass.action !== 'silent') setStatus({ phase: 'failed' });
},
)
.finally(() => {
running.current = null;
});
running.current = request;
await request;
}, [form, queryClient]);
useEffect(() => {
const unsubscribe = form.subscribe({
formState: { values: true },
callback: () => {
clearTimeout(timer.current);
timer.current = setTimeout(() => void save(), AUTOSAVE_DELAY_MS);
},
});
return () => {
unsubscribe();
clearTimeout(timer.current);
};
}, [form, save]);
// Closing the tab or leaving for another page keeps what is pending.
useEffect(() => {
const flush = () => void save();
window.addEventListener('pagehide', flush);
return () => {
window.removeEventListener('pagehide', flush);
flush();
};
}, [save]);
return {
status,
saveNow: () => void save(),
/**
* Completing saves everything itself: no new draft starts, and the one in flight lands first,
* so an older draft never overwrites the completed profile.
*/
stop: async () => {
isStopped.current = true;
clearTimeout(timer.current);
while (running.current) await running.current;
},
resume: () => {
isStopped.current = false;
},
};
}

View File

@ -1,5 +1,7 @@
export const PROFILE_ENDPOINTS = {
mine: '/traders/me/profile',
/** Ends registration step 5: needs at least one market. */
complete: '/traders/me/profile/complete',
avatar: '/traders/me/profile/avatar',
} as const;

View File

@ -2,6 +2,7 @@ export { profileKeys } from './constants';
export { profileRepository } from './profile';
export type {
CreatorProfilePayload,
SaveProfileDraftArgs,
SocialLinkArgs,
SocialLinkPayload,
UpdateProfileArgs,

View File

@ -2,10 +2,20 @@ import { toApiUrl } from '../../../../shared/utils';
import type {
CreatorProfilePayload,
CreatorProfileResponseDto,
SaveProfileDraftArgs,
SaveProfileDraftDto,
SocialLinkArgs,
UpdateProfileArgs,
UpdateProfileDto,
} from './types';
function toSocialLinkDtos(links: SocialLinkArgs[]): SocialLinkArgs[] {
return links.map(({ label, url }) => ({
label: label.trim(),
url: url.trim(),
}));
}
export function toCreatorProfilePayload(
dto: CreatorProfileResponseDto,
): CreatorProfilePayload {
@ -35,9 +45,16 @@ export function toUpdateProfileDto(args: UpdateProfileArgs): UpdateProfileDto {
markets: args.markets,
bio: args.bio?.trim(),
tradingStyle: args.tradingStyle,
socialLinks: args.socialLinks?.map(({ label, url }) => ({
label: label.trim(),
url: url.trim(),
})),
socialLinks: args.socialLinks && toSocialLinkDtos(args.socialLinks),
};
}
export function toSaveProfileDraftDto(
args: SaveProfileDraftArgs,
): SaveProfileDraftDto {
return {
bio: args.bio?.trim(),
markets: args.markets,
socialLinks: args.socialLinks && toSocialLinkDtos(args.socialLinks),
};
}

View File

@ -2,10 +2,15 @@ import type { UploadProgress } from '@lumina/libs/http';
import { profileHttp } from '../../http';
import { AVATAR_FIELD, PROFILE_ENDPOINTS } from './constants';
import { toCreatorProfilePayload, toUpdateProfileDto } from './mappers';
import {
toCreatorProfilePayload,
toSaveProfileDraftDto,
toUpdateProfileDto,
} from './mappers';
import type {
CreatorProfilePayload,
CreatorProfileResponseDto,
SaveProfileDraftArgs,
UpdateProfileArgs,
UploadAvatarArgs,
} from './types';
@ -35,6 +40,27 @@ export const profileRepository = {
return toCreatorProfilePayload(response);
},
/** Registration step 5's autosave: keeps what was typed without completing the profile. */
async saveDraft(
args: SaveProfileDraftArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<CreatorProfilePayload> {
const response = await profileHttp.patch<CreatorProfileResponseDto>(
PROFILE_ENDPOINTS.mine,
toSaveProfileDraftDto(args),
{ signal },
);
return toCreatorProfilePayload(response);
},
/** Ends registration step 5. A 400 when no market is saved yet. */
async complete(): Promise<CreatorProfilePayload> {
const response = await profileHttp.post<CreatorProfileResponseDto>(
PROFILE_ENDPOINTS.complete,
);
return toCreatorProfilePayload(response);
},
/** Uploads or replaces the avatar. */
async uploadAvatar(
args: UploadAvatarArgs,

View File

@ -1,7 +1,4 @@
import type {
Market,
VerificationStatus,
} from '../../../../shared/constants';
import type { Market, VerificationStatus } from '../../../../shared/constants';
import type {
CreatorProfileEntity,
KycStatus,
@ -61,3 +58,15 @@ export type UpdateProfileDto = {
/** A JPG or PNG of at most 5 MB (`PROFILE_LIMITS`). */
export type UploadAvatarArgs = { avatar: File };
/**
* Registration step 5's autosave. Only the fields sent change; `markets` may be empty and nothing
* counts as complete until `complete` runs.
*/
export type SaveProfileDraftArgs = {
bio?: string;
markets?: Market[];
socialLinks?: SocialLinkArgs[];
};
export type SaveProfileDraftDto = SaveProfileDraftArgs;

View File

@ -0,0 +1,7 @@
declare module '@lumina/libs/event-emitter' {
interface EventMap {
'profile.complete': { creatorId: string };
}
}
export {};

View File

@ -90,7 +90,6 @@ export type {
VerificationStatus,
} from './shared/constants';
export {
PROFILE_LIMITS,
profileKeys,
profileRepository,
TRADING_STYLES,

View File

@ -151,6 +151,96 @@
"submit": "ارسال کد تأیید",
"warning-before": "برای امنیت حساب، این صفحه تا",
"warning-after": "دیگر باز است."
},
"profile": {
"meta-title": "تکمیل پروفایل",
"optional": "(اختیاری)",
"creator": {
"title": "پروفایل عمومی خود را بسازید",
"description": "سرمایه‌گذاران پیش از اشتراک، این اطلاعات را در صفحه کانال شما می‌بینند.",
"resume-title": "ثبت‌نام شما هنوز کامل نشده است.",
"resume-description": "اطلاعات قبلی شما ذخیره شده است؛ پروفایل را تکمیل کنید تا کانال شما ساخته شود.",
"markets-title": "تخصص بازارها",
"markets-hint": "بازارهایی که در آن‌ها تحلیل ارائه می‌دهید را انتخاب کنید.",
"submit": "تکمیل ثبت‌نام",
"network-title": "خطا در ذخیره‌سازی."
},
"investor": {
"title": "پروفایل خود را کامل کنید",
"description": "این مرحله اختیاری است و هر زمان از «اطلاعات کاربری» قابل تغییر است.",
"markets-title": "بازارهای مورد علاقه",
"markets-hint": "تحلیلگران همین بازارها را در خانه بیشتر می‌بینید.",
"submit": "ذخیره و ورود",
"skip": "بعداً",
"network-title": "خطا در ذخیره‌سازی."
},
"photo": {
"title": "تصویر پروفایل",
"hint": "تصویر مربعی با کیفیت بالا توصیه می‌شود.",
"pick": "انتخاب تصویر",
"change": "تغییر تصویر",
"remove": "حذف تصویر",
"retry": "تلاش مجدد",
"preview": "پیش‌نمایش برش دایره‌ای تصویر پروفایل",
"uploading": "در حال بارگذاری… {{percent}}٪"
},
"bio": {
"label": "بیو (اختیاری)",
"placeholder": "تحلیلگر بازار کریپتو و طلا با 5 سال سابقه...",
"hint": "خود و حوزه تخصصی‌تان را معرفی کنید.",
"limit": "به حداکثر تعداد کاراکتر رسیدید."
},
"links": {
"title": "لینک‌ها",
"hint": "لینک کانال‌ها، صفحات یا وب‌سایت خود را اضافه کنید.",
"add": "افزودن لینک",
"count": "{{current}} از {{max}}",
"max": "حداکثر {{max}} لینک می‌توانید اضافه کنید.",
"placeholder": "نام کاربری یا آدرس",
"website-placeholder": "https://example.com",
"website-meta": "آدرس کامل",
"remove": "حذف لینک {{platform}}",
"sheet-title": "افزودن لینک",
"close": "بستن",
"consent": "مسئولیت تمامی لینک‌های افزوده‌شده، از جمله انطباق آن‌ها با قوانین جمهوری اسلامی ایران و قوانین پلتفرم، به‌عهده من است."
},
"platforms": {
"telegram": "تلگرام",
"instagram": "اینستاگرام",
"x": "ایکس",
"youtube": "یوتیوب",
"aparat": "آپارات",
"linkedin": "لینکدین",
"website": "وب‌سایت"
},
"autosave": {
"idle": "تغییرات خودکار ذخیره می‌شود؛ می‌توانید بعداً ادامه دهید.",
"saved": "ذخیره شد · {{time}}",
"failed": "ذخیره نشد؛ با تغییر بعدی دوباره تلاش می‌کنیم."
},
"preview": {
"open": "پیش‌نمایش پروفایل",
"title": "پیش‌نمایش پروفایل",
"live": "پیش‌نمایش زنده — سرمایه‌گذاران این را می‌بینند",
"channel": "کانال در لومینا",
"note": "آمار و کارنامه پیش‌بینی‌ها پس از اولین پیش‌بینی‌های شما در همین صفحه نمایش داده می‌شود.",
"close": "بستن پیش‌نمایش"
},
"done": {
"title": "ثبت‌نام شما کامل شد",
"steps-label": "مراحل بعد",
"account": "حساب تحلیلگر شما ساخته شد و پروفایل ذخیره شد.",
"review": "نتیجه بررسی هویت را با پیامک و اعلان به شما خبر می‌دهیم.",
"pricing": "تا آن زمان می‌توانید قیمت طرح‌های اشتراک را تعیین کنید.",
"posting": "انتشار پست پس از تأیید هویت فعال می‌شود.",
"channel": "رفتن به کانال",
"set-pricing": "تعیین قیمت طرح‌ها"
},
"failed": "ثبت‌نام کامل نشد",
"investor-failed": "پروفایل ذخیره نشد",
"photo-failed": "آپلود ناموفق بود. دوباره تلاش کنید.",
"photo-remove-failed": "تصویر پروفایل حذف نشد",
"welcome": "به لومینا خوش آمدید."
}
},
"validation": {
@ -168,6 +258,15 @@
"national-id-invalid": "کد ملی معتبر نیست.",
"id-card-required": "تصویر کارت ملی را بارگذاری کنید.",
"id-card-type": "فقط فایل‌های JPG یا PNG مجاز هستند.",
"id-card-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد."
"id-card-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد.",
"photo-type": "فقط فایل‌های JPG و PNG مجاز هستند.",
"photo-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد.",
"bio-long": "به حداکثر تعداد کاراکتر رسیدید.",
"bio-lines": "بیو حداکثر 4 خط می‌تواند داشته باشد.",
"markets-required": "انتخاب حداقل یک تخصص الزامی است.",
"link-empty": "نام کاربری را وارد کنید یا این ردیف را حذف کنید.",
"link-invalid": "آدرس وارد‌شده معتبر نیست.",
"links-max": "حداکثر 8 لینک می‌توانید اضافه کنید.",
"consent-required": "برای ادامه، باید شرایط فوق را بپذیرید."
}
}

View File

@ -14,5 +14,22 @@
"slow": "اتصال کند است",
"slow-description": "ممکن است بارگذاری کمی طول بکشد.",
"frozen": "برای این کار به اینترنت نیاز دارید."
},
"markets": {
"crypto": "کریپتو",
"gold": "طلا و سکه",
"equities": "بورس",
"forex": "فارکس",
"funds": "صندوق‌های سرمایه‌گذاری",
"real_estate": "مسکن",
"automotive": "خودرو",
"USDT": "تتر (دلار و ارز)"
},
"status": {
"verification": {
"pending": "در انتظار احراز هویت",
"approved": "تأییدشده",
"rejected": "رد شده"
}
}
}

View File

@ -1,8 +1,15 @@
export { applyServerErrors } from './apply-server-errors';
export { toApiUrl } from './api-url';
export { toggleMarket } from './markets';
export { formatMobile, toE164Mobile, toLocalMobile } from './mobile';
export { renameFieldErrors } from './rename-field-errors';
export { showActionError } from './show-action-error';
export {
displaySocialUrl,
fromSocialUrl,
toSocialHandle,
toSocialUrl,
} from './social-links';
export type { ShowActionErrorOptions } from './show-action-error';
export { asTranslateFn, translateMessage } from './translate-message';
export type { AnyTranslate } from './translate-message';

View File

@ -0,0 +1,13 @@
import { MARKETS } from '../constants';
import type { Market } from '../constants';
/** Adds or removes a market from a picked set, keeping the pickers' order. */
export function toggleMarket(
markets: readonly Market[],
market: Market,
): Market[] {
const next = new Set(markets);
if (next.has(market)) next.delete(market);
else next.add(market);
return MARKETS.filter((item) => next.has(item));
}

View File

@ -0,0 +1,87 @@
import { SOCIAL_HANDLE_ADDRESSES } from '../validations/constants';
import type { SocialPlatform } from '../validations/types';
type HandlePlatform = keyof typeof SOCIAL_HANDLE_ADDRESSES;
const isHandlePlatform = (platform: string): platform is HandlePlatform =>
platform in SOCIAL_HANDLE_ADDRESSES;
/** `https://www.t.me/ali_gold/` → `{ host: 't.me', path: 'ali_gold' }`; not an address → `null`. */
function parseAddress(value: string): { host: string; path: string } | null {
const trimmed = value.trim();
if (!/^(https?:\/\/)?[^\s/]+\.[^\s/]+(\/|$)/i.test(trimmed)) return null;
try {
const url = new URL(
/^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`,
);
return {
host: url.hostname.toLowerCase().replace(/^www\./, ''),
path: decodeURIComponent(url.pathname).replace(/^\/+|\/+$/g, ''),
};
} catch {
return null;
}
}
/** The handle out of a path: `in/ali` on LinkedIn, `@ali` on YouTube, `ali` elsewhere. */
function handleFromPath(platform: HandlePlatform, path: string): string {
const fixed = SOCIAL_HANDLE_ADDRESSES[platform].prefix.split('/').slice(1);
const lead = fixed.join('/');
return lead && path.startsWith(lead) ? path.slice(lead.length) : path;
}
/**
* What a platform row keeps from typed or pasted text: a pasted `https://t.me/ali_gold` becomes
* `ali_gold`, and a leading `@` is dropped. A website keeps the whole address.
*/
export function toSocialHandle(
platform: SocialPlatform,
input: string,
): string {
if (!isHandlePlatform(platform)) return input.trim();
const address = parseAddress(input);
const rules = SOCIAL_HANDLE_ADDRESSES[platform];
if (address && (rules.hosts as readonly string[]).includes(address.host)) {
return handleFromPath(platform, address.path);
}
return input.trim().replace(/^@/, '');
}
/** The address a row stands for: `telegram` + `ali_gold` → `https://t.me/ali_gold`. */
export function toSocialUrl(platform: SocialPlatform, handle: string): string {
const value = handle.trim();
if (!isHandlePlatform(platform)) {
return /^https?:\/\//i.test(value) ? value : `https://${value}`;
}
return `https://${SOCIAL_HANDLE_ADDRESSES[platform].prefix}${value}`;
}
/**
* A stored link back into a row. The label names the platform for links this form saved; older
* links fall back to their host, and anything else is a website.
*/
export function fromSocialUrl(
label: string,
url: string,
): { platform: SocialPlatform; handle: string } {
const address = parseAddress(url);
const byLabel = isHandlePlatform(label) ? label : null;
const byHost = address
? (Object.keys(SOCIAL_HANDLE_ADDRESSES) as HandlePlatform[]).find(
(platform) =>
(
SOCIAL_HANDLE_ADDRESSES[platform].hosts as readonly string[]
).includes(address.host),
)
: undefined;
const platform = byLabel ?? byHost;
if (platform && address) {
return { platform, handle: handleFromPath(platform, address.path) };
}
return { platform: 'website', handle: url };
}
/** The address as the profile shows it, without the scheme: `t.me/ali_gold`. */
export function displaySocialUrl(url: string): string {
return url.replace(/^https?:\/\//i, '').replace(/\/$/, '');
}

View File

@ -17,3 +17,46 @@ export const ID_CARD_IMAGE = {
export const ACCOUNT_TYPES = ['investor', 'creator'] as const;
export const CODE_PATTERN = /^\d{6}$/;
/** The server's creator profile rules (`CREATOR_PROFILE_LIMITS`), so forms reject what the API would. */
export const PROFILE_LIMITS = {
displayNameMaxLength: 80,
bioMaxLength: 300,
bioMaxLineBreaks: 3,
socialLinkLabelMaxLength: 30,
socialLinkUrlMaxLength: 2048,
socialLinksMax: 8,
} as const;
/** The profile photos the API accepts, for creators and investors alike. */
export const AVATAR_IMAGE = {
types: ['image/jpeg', 'image/png'],
maxBytes: 5 * 1024 * 1024,
} as const;
/** Where a creator's link points, in the order the picker lists them. */
export const SOCIAL_PLATFORMS = [
'telegram',
'instagram',
'x',
'youtube',
'aparat',
'linkedin',
'website',
] as const;
/**
* Each platform's fixed address before the handle, and the hosts a pasted link may come from. A
* website takes a whole address instead.
*/
export const SOCIAL_HANDLE_ADDRESSES = {
telegram: { prefix: 't.me/', hosts: ['t.me', 'telegram.me'] },
instagram: { prefix: 'instagram.com/', hosts: ['instagram.com'] },
x: { prefix: 'x.com/', hosts: ['x.com', 'twitter.com'] },
youtube: { prefix: 'youtube.com/@', hosts: ['youtube.com', 'm.youtube.com'] },
aparat: { prefix: 'aparat.com/', hosts: ['aparat.com'] },
linkedin: { prefix: 'linkedin.com/in/', hosts: ['linkedin.com'] },
} as const;
/** Latin letters, digits, the underscore, the dot and the hyphen. */
export const SOCIAL_HANDLE_PATTERN = /^[A-Za-z0-9_.-]+$/;

View File

@ -6,15 +6,34 @@ export {
investorDetailsSchema,
phoneSchema,
} from './auth-validations';
export { ID_CARD_IMAGE, USERNAME_LENGTH } from './constants';
export {
AVATAR_IMAGE,
ID_CARD_IMAGE,
PROFILE_LIMITS,
SOCIAL_HANDLE_ADDRESSES,
SOCIAL_PLATFORMS,
USERNAME_LENGTH,
} from './constants';
export {
avatarImage,
creatorProfileSchema,
investorProfileSchema,
profileBio,
socialLinkRow,
} from './profile-validations';
export type {
AccountTypeFormOutput,
AccountTypeFormValues,
CodeFormValues,
CreatorIdentityFormOutput,
CreatorIdentityFormValues,
CreatorProfileFormOutput,
CreatorProfileFormValues,
InvestorDetailsFormOutput,
InvestorDetailsFormValues,
InvestorProfileFormOutput,
InvestorProfileFormValues,
PhoneFormOutput,
PhoneFormValues,
SocialPlatform,
} from './types';

View File

@ -0,0 +1,102 @@
import * as v from 'valibot';
import { MARKETS } from '../constants';
import {
AVATAR_IMAGE,
PROFILE_LIMITS,
SOCIAL_HANDLE_PATTERN,
SOCIAL_PLATFORMS,
} from './constants';
const LINE_BREAK = /\r\n|\r|\n/g;
/** A website row takes a whole address with a domain: `https://example.com` or `example.com`. */
function isWebsite(value: string): boolean {
try {
const url = new URL(
/^https?:\/\//i.test(value) ? value : `https://${value}`,
);
const host = url.hostname;
return host.includes('.') && !host.startsWith('.') && !host.endsWith('.');
} catch {
return false;
}
}
/** JPG or PNG up to 5 MB, checked when picked; a rejected photo keeps the current one. */
export const avatarImage = v.pipe(
v.file(),
v.mimeType(AVATAR_IMAGE.types, 'auth:validation.photo-type'),
v.maxSize(AVATAR_IMAGE.maxBytes, 'auth:validation.photo-size'),
);
/** Up to 300 characters in at most four lines. Optional. */
export const profileBio = v.pipe(
v.string(),
v.maxLength(PROFILE_LIMITS.bioMaxLength, 'auth:validation.bio-long'),
v.check(
(value) =>
(value.match(LINE_BREAK)?.length ?? 0) <= PROFILE_LIMITS.bioMaxLineBreaks,
'auth:validation.bio-lines',
),
);
/**
* One link row: the platform and the handle typed after its fixed address. An empty row must be
* filled or removed; a website takes a whole address.
*/
export const socialLinkRow = v.pipe(
v.object({
platform: v.picklist(SOCIAL_PLATFORMS),
handle: v.pipe(v.string(), v.trim()),
}),
v.forward(
v.check(({ handle }) => handle !== '', 'auth:validation.link-empty'),
['handle'],
),
v.forward(
v.check(
({ platform, handle }) =>
handle === '' ||
(platform === 'website'
? isWebsite(handle) &&
handle.length <= PROFILE_LIMITS.socialLinkUrlMaxLength
: SOCIAL_HANDLE_PATTERN.test(handle)),
'auth:validation.link-invalid',
),
['handle'],
),
);
/**
* A creator's public profile at registration step 5. At least one market; links are optional, and
* the consent is required once there is one.
*/
export const creatorProfileSchema = v.pipe(
v.object({
bio: profileBio,
markets: v.pipe(
v.array(v.picklist(MARKETS)),
v.minLength(1, 'auth:validation.markets-required'),
),
links: v.pipe(
v.array(socialLinkRow),
v.maxLength(PROFILE_LIMITS.socialLinksMax, 'auth:validation.links-max'),
),
consent: v.boolean(),
}),
v.forward(
v.partialCheck(
[['links'], ['consent']],
({ links, consent }) => links.length === 0 || consent,
'auth:validation.consent-required',
),
['consent'],
),
);
/** An investor's optional step 5: a photo, checked when picked, and the markets they follow. */
export const investorProfileSchema = v.object({
photo: v.nullable(avatarImage),
markets: v.array(v.picklist(MARKETS)),
});

View File

@ -7,6 +7,11 @@ import type {
investorDetailsSchema,
phoneSchema,
} from './auth-validations';
import type { SOCIAL_PLATFORMS } from './constants';
import type {
creatorProfileSchema,
investorProfileSchema,
} from './profile-validations';
/** What each form holds while typing (`useForm`'s values) and what its schema hands the submit. */
export type PhoneFormValues = v.InferInput<typeof phoneSchema>;
@ -26,3 +31,17 @@ export type CreatorIdentityFormValues = v.InferInput<
export type CreatorIdentityFormOutput = v.InferOutput<
typeof creatorIdentitySchema
>;
export type CreatorProfileFormValues = v.InferInput<
typeof creatorProfileSchema
>;
export type CreatorProfileFormOutput = v.InferOutput<
typeof creatorProfileSchema
>;
export type InvestorProfileFormValues = v.InferInput<
typeof investorProfileSchema
>;
export type InvestorProfileFormOutput = v.InferOutput<
typeof investorProfileSchema
>;
export type SocialPlatform = (typeof SOCIAL_PLATFORMS)[number];

View File

@ -12,12 +12,14 @@ const INITIAL = {
blockedUntil: null,
registration: null,
draft: null,
registeredAs: null,
} satisfies Partial<AuthFlowState>;
/**
* 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.
* resets it, so no number or token outlives the flow; registration then keeps only the new
* account's type, for step 5.
*/
export const useAuthFlowStore = create<AuthFlowState>()(
immer((set) => ({
@ -58,6 +60,10 @@ export const useAuthFlowStore = create<AuthFlowState>()(
set((state) => {
state.draft = draft;
}),
markRegistered: (role) =>
set((state) => {
state.registeredAs = role;
}),
reset: () => set(INITIAL),
})),
);

View File

@ -34,6 +34,11 @@ export type AuthFlowState = {
blockedUntil: number | null;
registration: RegistrationGrant | null;
draft: RegistrationDraft | null;
/**
* The account type registered in this tab, set after the flow resets. Step 5 tells a person
* coming straight from step 4 from one resuming after a login or a reload.
*/
registeredAs: UserRole | null;
chooseRole: (role: UserRole) => void;
/** A typed number travels to the other flow (login ↔ registration) without sending a code. */
@ -45,5 +50,7 @@ export type AuthFlowState = {
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;
/** Registration created the account; runs after `reset`. */
markRegistered: (role: UserRole) => void;
reset: () => void;
};