diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStep.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStep.tsx new file mode 100644 index 0000000..9394576 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStep.tsx @@ -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 ( + + + + ); + } + return ; +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStepSkeleton.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStepSkeleton.tsx new file mode 100644 index 0000000..a26ab29 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/CreatorProfileStepSkeleton.tsx @@ -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 ( + + } + > + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/CompletedView.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/CompletedView.tsx new file mode 100644 index 0000000..1d501d4 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/CompletedView.tsx @@ -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(null); + + useEffect(() => headingRef.current?.focus(), []); + + return ( + + + + + {t('register.profile.done.title')} + + + {tCommon('status.verification.pending')} + + + + {NEXT_STEPS.map(({ icon, text, tone }) => ( + + + + {t(`register.profile.done.${text}`)} + + + ))} + + + + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/LinksSection.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/LinksSection.tsx new file mode 100644 index 0000000..dca7cdb --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/LinksSection.tsx @@ -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(null); + + return ( + + {links.rows.map((row, index) => { + const platformName = t(`register.profile.platforms.${row.platform}`); + const isWebsite = row.platform === 'website'; + return ( + + ( + { + 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. */} + + + {t('register.profile.links.count', { + current: number(links.rows.length), + max: number(links.max), + })} + + + setIsPicking(false)} + onPick={(platform) => { + picked.current = platform; + setIsPicking(false); + }} + onExited={() => { + if (picked.current) links.add(picked.current); + picked.current = null; + }} + /> + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/PlatformPicker.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/PlatformPicker.tsx new file mode 100644 index 0000000..7e781bb --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/PlatformPicker.tsx @@ -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 = ( + + {SOCIAL_PLATFORMS.map((platform) => ( + onPick(platform)} + > + {t(`register.profile.platforms.${platform}`)} + + ))} + + ); + + return layout === 'mobile' ? ( + + {rows} + + ) : ( + + {rows} + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfileForm.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfileForm.tsx new file mode 100644 index 0000000..f5d8bc3 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfileForm.tsx @@ -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 = ( + + ); + + return ( + + + + + {t('register.profile.preview.live')} + + + {preview} + + ) + } + > + + {page.isResuming && ( + + {t('register.profile.creator.resume-description')} + + )} + {page.formError && ( + + {page.formError} + + )} + + + + {t('register.profile.creator.title')} + + + {t('register.profile.creator.description')} + + {layout === 'mobile' && ( + setIsPreviewOpen(true)} + > + {t('register.profile.preview.open')} + + )} + + { + event.preventDefault(); + void page.submit(); + }} + > + + + t('register.profile.photo.uploading', { percent }), + }} + /> + + ( + + )} + /> + + ( + { + field.onChange(toggleMarket(field.value, market)); + field.onBlur(); + }} + error={translateMessage(t, fieldState.error?.message)} + /> + )} + /> + + + {links.rows.length > 0 && ( + ( + + field.onChange(event.target.checked)} + onBlur={field.onBlur} + invalid={fieldState.error != null} + aria-describedby={ + fieldState.error ? consentErrorId : undefined + } + > + {t('register.profile.links.consent')} + + {fieldState.error && ( + + {translateMessage(t, fieldState.error.message)} + + )} + + )} + /> + )} + + + + + + + + + {layout === 'mobile' && ( + setIsPreviewOpen(false)} + > + + {preview} + + {t('register.profile.preview.note')} + + + + )} + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfilePreview.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfilePreview.tsx new file mode 100644 index 0000000..608df04 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/ProfilePreview.tsx @@ -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 ( + + + + + + @{username} + + + {t('register.profile.preview.channel')} + + + + {preview.bio && ( + + {preview.bio} + + )} + {preview.markets.length > 0 && ( + + {preview.markets.map((market) => ( + + {tCommon(`markets.${market}`)} + + ))} + + )} + {preview.links.length > 0 && ( + + {preview.links.map((link) => ( + + + + {link} + + + ))} + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/SaveStatus.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/SaveStatus.tsx new file mode 100644 index 0000000..002f8bc --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/SaveStatus.tsx @@ -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 ( + + + + {text} + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/StepLayout.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/StepLayout.tsx new file mode 100644 index 0000000..0cf4e2c --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/components/StepLayout.tsx @@ -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 = ( + + {children} + + ); + if (!aside) return main; + + return ( + + {main} + + {aside} + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/index.ts b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/index.ts new file mode 100644 index 0000000..e5de671 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/index.ts @@ -0,0 +1,7 @@ +export { CreatorProfileStep } from './CreatorProfileStep'; +export { CreatorProfileStepSkeleton } from './CreatorProfileStepSkeleton'; +export type { + CreatorProfileLayout, + CreatorProfileStepProps, + CreatorProfileStepSkeletonProps, +} from './types'; diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/types.ts b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/types.ts new file mode 100644 index 0000000..5619eb6 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/creator-profile/organisms/creator-profile-step/types.ts @@ -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; +}; diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/InvestorProfileStep.tsx b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/InvestorProfileStep.tsx new file mode 100644 index 0000000..d06b303 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/InvestorProfileStep.tsx @@ -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 ( + + {page.formError && ( + + {page.formError} + + )} + + + + {t('register.profile.investor.title')} + + + {t('register.profile.investor.description')} + + + { + event.preventDefault(); + void page.submit(); + }} + > + + 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 }), + }} + /> + + + ( + + field.onChange(toggleMarket(field.value, market)) + } + /> + )} + /> + + + + + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/index.ts b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/index.ts new file mode 100644 index 0000000..fe30006 --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/index.ts @@ -0,0 +1,2 @@ +export { InvestorProfileStep } from './InvestorProfileStep'; +export type { InvestorProfileStepProps } from './types'; diff --git a/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/types.ts b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/types.ts new file mode 100644 index 0000000..0eeac3c --- /dev/null +++ b/platforms/market/src/app/screens/(onboarding)/onboarding/investor-profile/organisms/investor-profile-step/types.ts @@ -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']; +}; 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 c299a94..ffe90ca 100644 --- a/platforms/market/src/features/auth/actions/register-creator/actions.ts +++ b/platforms/market/src/features/auth/actions/register-creator/actions.ts @@ -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, { 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 00ebea0..b71f84e 100644 --- a/platforms/market/src/features/auth/actions/register-investor/actions.ts +++ b/platforms/market/src/features/auth/actions/register-investor/actions.ts @@ -16,6 +16,7 @@ export async function registerInvestor( ): Promise { 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, { diff --git a/platforms/market/src/features/auth/actions/save-investor-profile/actions.ts b/platforms/market/src/features/auth/actions/save-investor-profile/actions.ts new file mode 100644 index 0000000..7c3942e --- /dev/null +++ b/platforms/market/src/features/auth/actions/save-investor-profile/actions.ts @@ -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 { + 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; +} diff --git a/platforms/market/src/features/auth/actions/save-investor-profile/index.ts b/platforms/market/src/features/auth/actions/save-investor-profile/index.ts new file mode 100644 index 0000000..3df2fb7 --- /dev/null +++ b/platforms/market/src/features/auth/actions/save-investor-profile/index.ts @@ -0,0 +1,5 @@ +export { saveInvestorProfile } from './actions'; +export type { + SaveInvestorProfileArgs, + SaveInvestorProfileOptions, +} from './types'; diff --git a/platforms/market/src/features/auth/actions/save-investor-profile/types.ts b/platforms/market/src/features/auth/actions/save-investor-profile/types.ts new file mode 100644 index 0000000..9f68a0f --- /dev/null +++ b/platforms/market/src/features/auth/actions/save-investor-profile/types.ts @@ -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; +}; diff --git a/platforms/market/src/features/auth/constants.ts b/platforms/market/src/features/auth/constants.ts index d01e184..f642788 100644 --- a/platforms/market/src/features/auth/constants.ts +++ b/platforms/market/src/features/auth/constants.ts @@ -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; diff --git a/platforms/market/src/features/auth/entities/user/types.ts b/platforms/market/src/features/auth/entities/user/types.ts index 04f5f68..1cbb167 100644 --- a/platforms/market/src/features/auth/entities/user/types.ts +++ b/platforms/market/src/features/auth/entities/user/types.ts @@ -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[]; }; diff --git a/platforms/market/src/features/auth/index.ts b/platforms/market/src/features/auth/index.ts index eecde36..71e8191 100644 --- a/platforms/market/src/features/auth/index.ts +++ b/platforms/market/src/features/auth/index.ts @@ -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, diff --git a/platforms/market/src/features/auth/models/investor-profile/index.ts b/platforms/market/src/features/auth/models/investor-profile/index.ts new file mode 100644 index 0000000..8cd6cf2 --- /dev/null +++ b/platforms/market/src/features/auth/models/investor-profile/index.ts @@ -0,0 +1,6 @@ +export { useInvestorProfilePage } from './use-investor-profile-page'; +export type { + InvestorPhotoStatus, + InvestorProfilePageModel, + UseInvestorProfilePageOptions, +} from './types'; diff --git a/platforms/market/src/features/auth/models/investor-profile/types.ts b/platforms/market/src/features/auth/models/investor-profile/types.ts new file mode 100644 index 0000000..87af858 --- /dev/null +++ b/platforms/market/src/features/auth/models/investor-profile/types.ts @@ -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; + /** «بعداً»: enters without saving anything. */ + skip: () => void; + isSubmitting: boolean; + formError: string | undefined; +}; diff --git a/platforms/market/src/features/auth/models/investor-profile/use-investor-profile-page.ts b/platforms/market/src/features/auth/models/investor-profile/use-investor-profile-page.ts new file mode 100644 index 0000000..d5cf0bd --- /dev/null +++ b/platforms/market/src/features/auth/models/investor-profile/use-investor-profile-page.ts @@ -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('idle'); + const [photoError, setPhotoError] = useState(); + const [progress, setProgress] = useState(); + 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, + }; +} diff --git a/platforms/market/src/features/auth/repositories/account/account.ts b/platforms/market/src/features/auth/repositories/account/account.ts index 10947d2..c6a4892 100644 --- a/platforms/market/src/features/auth/repositories/account/account.ts +++ b/platforms/market/src/features/auth/repositories/account/account.ts @@ -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 { - const response = await authHttp.get(ACCOUNT_ENDPOINT, { - signal, - }); + const response = await authHttp.get( + ACCOUNT_ENDPOINTS.mine, + { signal }, + ); return toAccountPayload(response); }, async update(args: UpdateAccountArgs): Promise { const response = await authHttp.patch( - 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 { + const response = await authHttp.upload( + ACCOUNT_ENDPOINTS.avatar, + args.avatar, + { method: 'PUT', fieldName: ACCOUNT_AVATAR_FIELD, signal, onProgress }, + ); + return toAccountPayload(response); + }, + + async removeAvatar(): Promise { + const response = await authHttp.delete( + ACCOUNT_ENDPOINTS.avatar, + ); + return toAccountPayload(response); + }, }; diff --git a/platforms/market/src/features/auth/repositories/account/constants.ts b/platforms/market/src/features/auth/repositories/account/constants.ts index 37c8b53..511ccdf 100644 --- a/platforms/market/src/features/auth/repositories/account/constants.ts +++ b/platforms/market/src/features/auth/repositories/account/constants.ts @@ -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, diff --git a/platforms/market/src/features/auth/repositories/account/index.ts b/platforms/market/src/features/auth/repositories/account/index.ts index decb8d1..d1f3629 100644 --- a/platforms/market/src/features/auth/repositories/account/index.ts +++ b/platforms/market/src/features/auth/repositories/account/index.ts @@ -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'; diff --git a/platforms/market/src/features/auth/repositories/account/mappers.ts b/platforms/market/src/features/auth/repositories/account/mappers.ts index b47ac6f..690a08a 100644 --- a/platforms/market/src/features/auth/repositories/account/mappers.ts +++ b/platforms/market/src/features/auth/repositories/account/mappers.ts @@ -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, }; } diff --git a/platforms/market/src/features/auth/repositories/account/types.ts b/platforms/market/src/features/auth/repositories/account/types.ts index 86470de..433e247 100644 --- a/platforms/market/src/features/auth/repositories/account/types.ts +++ b/platforms/market/src/features/auth/repositories/account/types.ts @@ -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 }; diff --git a/platforms/market/src/features/auth/types.ts b/platforms/market/src/features/auth/types.ts index fbf2f7f..0bb8e21 100644 --- a/platforms/market/src/features/auth/types.ts +++ b/platforms/market/src/features/auth/types.ts @@ -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 }; } } diff --git a/platforms/market/src/features/profile/actions/complete-creator-profile/actions.ts b/platforms/market/src/features/profile/actions/complete-creator-profile/actions.ts new file mode 100644 index 0000000..2cec2f1 --- /dev/null +++ b/platforms/market/src/features/profile/actions/complete-creator-profile/actions.ts @@ -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 { + await profileRepository.saveDraft(args); + const profile = await profileRepository.complete(); + if (emit) { + eventEmitter.emit(PROFILE_EVENTS.complete, { + creatorId: profile.creatorId, + }); + } + return profile; +} diff --git a/platforms/market/src/features/profile/actions/complete-creator-profile/index.ts b/platforms/market/src/features/profile/actions/complete-creator-profile/index.ts new file mode 100644 index 0000000..200d6db --- /dev/null +++ b/platforms/market/src/features/profile/actions/complete-creator-profile/index.ts @@ -0,0 +1 @@ +export { completeCreatorProfile } from './actions'; diff --git a/platforms/market/src/features/profile/constants.ts b/platforms/market/src/features/profile/constants.ts index d05396f..bd8f195 100644 --- a/platforms/market/src/features/profile/constants.ts +++ b/platforms/market/src/features/profile/constants.ts @@ -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; diff --git a/platforms/market/src/features/profile/index.ts b/platforms/market/src/features/profile/index.ts index bf56498..e51717f 100644 --- a/platforms/market/src/features/profile/index.ts +++ b/platforms/market/src/features/profile/index.ts @@ -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, diff --git a/platforms/market/src/features/profile/models/creator-profile/constants.ts b/platforms/market/src/features/profile/models/creator-profile/constants.ts new file mode 100644 index 0000000..6337c04 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/constants.ts @@ -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; diff --git a/platforms/market/src/features/profile/models/creator-profile/form-values.ts b/platforms/market/src/features/profile/models/creator-profile/form-values.ts new file mode 100644 index 0000000..812fe14 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/form-values.ts @@ -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)); +} diff --git a/platforms/market/src/features/profile/models/creator-profile/index.ts b/platforms/market/src/features/profile/models/creator-profile/index.ts new file mode 100644 index 0000000..baa96d8 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/index.ts @@ -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'; diff --git a/platforms/market/src/features/profile/models/creator-profile/types.ts b/platforms/market/src/features/profile/models/creator-profile/types.ts new file mode 100644 index 0000000..9c0ef7f --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/types.ts @@ -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['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; + 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[]; +}; diff --git a/platforms/market/src/features/profile/models/creator-profile/use-creator-photo-part.ts b/platforms/market/src/features/profile/models/creator-profile/use-creator-photo-part.ts new file mode 100644 index 0000000..fed1c2f --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/use-creator-photo-part.ts @@ -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(null); + const [error, setError] = useState(); + const [progress, setProgress] = useState(); + + 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, + }; +} diff --git a/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-page.ts b/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-page.ts new file mode 100644 index 0000000..56b6649 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-page.ts @@ -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('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, + }; +} diff --git a/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-preview.ts b/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-preview.ts new file mode 100644 index 0000000..6872239 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/use-creator-profile-preview.ts @@ -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) }; +} diff --git a/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts b/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts new file mode 100644 index 0000000..d0bd2a9 --- /dev/null +++ b/platforms/market/src/features/profile/models/creator-profile/use-profile-autosave.ts @@ -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({ phase: 'idle' }); + const lastSaved = useRef(JSON.stringify(initial)); + const timer = useRef>(undefined); + const running = useRef | null>(null); + const isStopped = useRef(false); + + const save = useCallback(async (): Promise => { + 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; + }, + }; +} diff --git a/platforms/market/src/features/profile/repositories/profile/constants.ts b/platforms/market/src/features/profile/repositories/profile/constants.ts index 547af3c..8532900 100644 --- a/platforms/market/src/features/profile/repositories/profile/constants.ts +++ b/platforms/market/src/features/profile/repositories/profile/constants.ts @@ -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; diff --git a/platforms/market/src/features/profile/repositories/profile/index.ts b/platforms/market/src/features/profile/repositories/profile/index.ts index 3f51df3..a08e5d2 100644 --- a/platforms/market/src/features/profile/repositories/profile/index.ts +++ b/platforms/market/src/features/profile/repositories/profile/index.ts @@ -2,6 +2,7 @@ export { profileKeys } from './constants'; export { profileRepository } from './profile'; export type { CreatorProfilePayload, + SaveProfileDraftArgs, SocialLinkArgs, SocialLinkPayload, UpdateProfileArgs, diff --git a/platforms/market/src/features/profile/repositories/profile/mappers.ts b/platforms/market/src/features/profile/repositories/profile/mappers.ts index 0db8107..a422492 100644 --- a/platforms/market/src/features/profile/repositories/profile/mappers.ts +++ b/platforms/market/src/features/profile/repositories/profile/mappers.ts @@ -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), }; } diff --git a/platforms/market/src/features/profile/repositories/profile/profile.ts b/platforms/market/src/features/profile/repositories/profile/profile.ts index 9bc00c6..c88516e 100644 --- a/platforms/market/src/features/profile/repositories/profile/profile.ts +++ b/platforms/market/src/features/profile/repositories/profile/profile.ts @@ -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 { + const response = await profileHttp.patch( + PROFILE_ENDPOINTS.mine, + toSaveProfileDraftDto(args), + { signal }, + ); + return toCreatorProfilePayload(response); + }, + + /** Ends registration step 5. A 400 when no market is saved yet. */ + async complete(): Promise { + const response = await profileHttp.post( + PROFILE_ENDPOINTS.complete, + ); + return toCreatorProfilePayload(response); + }, + /** Uploads or replaces the avatar. */ async uploadAvatar( args: UploadAvatarArgs, diff --git a/platforms/market/src/features/profile/repositories/profile/types.ts b/platforms/market/src/features/profile/repositories/profile/types.ts index df7b3d5..668332e 100644 --- a/platforms/market/src/features/profile/repositories/profile/types.ts +++ b/platforms/market/src/features/profile/repositories/profile/types.ts @@ -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; diff --git a/platforms/market/src/features/profile/types.ts b/platforms/market/src/features/profile/types.ts new file mode 100644 index 0000000..7cf40cb --- /dev/null +++ b/platforms/market/src/features/profile/types.ts @@ -0,0 +1,7 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'profile.complete': { creatorId: string }; + } +} + +export {}; diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index 7441c67..98b2082 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -90,7 +90,6 @@ export type { VerificationStatus, } from './shared/constants'; export { - PROFILE_LIMITS, profileKeys, profileRepository, TRADING_STYLES, diff --git a/platforms/market/src/shared/locales/fa/auth.json b/platforms/market/src/shared/locales/fa/auth.json index cfd7f1f..3eaa129 100644 --- a/platforms/market/src/shared/locales/fa/auth.json +++ b/platforms/market/src/shared/locales/fa/auth.json @@ -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": "برای ادامه، باید شرایط فوق را بپذیرید." } } diff --git a/platforms/market/src/shared/locales/fa/common.json b/platforms/market/src/shared/locales/fa/common.json index 4f65abb..bb8f07a 100644 --- a/platforms/market/src/shared/locales/fa/common.json +++ b/platforms/market/src/shared/locales/fa/common.json @@ -14,5 +14,22 @@ "slow": "اتصال کند است", "slow-description": "ممکن است بارگذاری کمی طول بکشد.", "frozen": "برای این کار به اینترنت نیاز دارید." + }, + "markets": { + "crypto": "کریپتو", + "gold": "طلا و سکه", + "equities": "بورس", + "forex": "فارکس", + "funds": "صندوق‌های سرمایه‌گذاری", + "real_estate": "مسکن", + "automotive": "خودرو", + "USDT": "تتر (دلار و ارز)" + }, + "status": { + "verification": { + "pending": "در انتظار احراز هویت", + "approved": "تأییدشده", + "rejected": "رد شده" + } } } diff --git a/platforms/market/src/shared/utils/index.ts b/platforms/market/src/shared/utils/index.ts index abb3fe6..1c62be3 100644 --- a/platforms/market/src/shared/utils/index.ts +++ b/platforms/market/src/shared/utils/index.ts @@ -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'; diff --git a/platforms/market/src/shared/utils/markets.ts b/platforms/market/src/shared/utils/markets.ts new file mode 100644 index 0000000..8ec8c7c --- /dev/null +++ b/platforms/market/src/shared/utils/markets.ts @@ -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)); +} diff --git a/platforms/market/src/shared/utils/social-links.ts b/platforms/market/src/shared/utils/social-links.ts new file mode 100644 index 0000000..446a771 --- /dev/null +++ b/platforms/market/src/shared/utils/social-links.ts @@ -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(/\/$/, ''); +} diff --git a/platforms/market/src/shared/validations/constants.ts b/platforms/market/src/shared/validations/constants.ts index 6dbca4b..196199e 100644 --- a/platforms/market/src/shared/validations/constants.ts +++ b/platforms/market/src/shared/validations/constants.ts @@ -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_.-]+$/; diff --git a/platforms/market/src/shared/validations/index.ts b/platforms/market/src/shared/validations/index.ts index e01c9cc..5968651 100644 --- a/platforms/market/src/shared/validations/index.ts +++ b/platforms/market/src/shared/validations/index.ts @@ -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'; diff --git a/platforms/market/src/shared/validations/profile-validations.ts b/platforms/market/src/shared/validations/profile-validations.ts new file mode 100644 index 0000000..2bb29fa --- /dev/null +++ b/platforms/market/src/shared/validations/profile-validations.ts @@ -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)), +}); diff --git a/platforms/market/src/shared/validations/types.ts b/platforms/market/src/shared/validations/types.ts index 3d6db85..4460841 100644 --- a/platforms/market/src/shared/validations/types.ts +++ b/platforms/market/src/shared/validations/types.ts @@ -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; @@ -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]; diff --git a/platforms/market/src/stores/auth-flow/auth-flow-store.ts b/platforms/market/src/stores/auth-flow/auth-flow-store.ts index cfe0da2..05d556d 100644 --- a/platforms/market/src/stores/auth-flow/auth-flow-store.ts +++ b/platforms/market/src/stores/auth-flow/auth-flow-store.ts @@ -12,12 +12,14 @@ const INITIAL = { blockedUntil: null, registration: null, draft: null, + registeredAs: 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. + * 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()( immer((set) => ({ @@ -58,6 +60,10 @@ export const useAuthFlowStore = create()( set((state) => { state.draft = draft; }), + markRegistered: (role) => + set((state) => { + state.registeredAs = role; + }), reset: () => set(INITIAL), })), ); diff --git a/platforms/market/src/stores/auth-flow/types.ts b/platforms/market/src/stores/auth-flow/types.ts index 2bb498a..0d7bab7 100644 --- a/platforms/market/src/stores/auth-flow/types.ts +++ b/platforms/market/src/stores/auth-flow/types.ts @@ -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; };