feat(legal): add rules caption, analyst agreement and re-acceptance gate

Reads the three legal documents from the API, so /terms and
/terms/subscription render in the browser under a (tabs) route group, and
adds /terms/analyst-agreement. The login and sign-up phone pages accept the
rules through a caption, the analyst sign-up requires the agreement and sends
its version, and a blocking gate opens from the session or a 403
agreement_required. Account rows and the rules_updated notification follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-11-02 01:28:42 +04:00
parent 684aa404f2
commit 01c838e869
127 changed files with 2019 additions and 725 deletions

View File

@ -1,14 +1,6 @@
// First: the rules sheet reads a server-only namespace, which the server bootstrap adds to i18n
// when this module loads (0055).
import '../../../../../bootstrap/bootstrap.server';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { GuestGuard } from '@lumina/market/app/guards/guest-guard';
import { ROUTES } from '@lumina/market/app/navigation';
import {
GeneralRules,
generalRulesLabels,
} from '@lumina/market/app/screens/organisms/general-rules';
import { RegisterDetailsStep } from '@lumina/market/app/screens/(auth)/auth/register/details/organisms/register-details-step';
import type { Metadata } from 'next';
@ -37,12 +29,6 @@ export default function RegisterDetailsPage() {
size="md"
supportPlacement="popover"
haltPlacement="modal"
rules={
<GeneralRules
layout="sheet"
labels={generalRulesLabels(i18n.getFixedT(null, 'rules'))}
/>
}
/>
</GuestGuard>
</AuthTemplate>

View File

@ -1,6 +1,6 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../bootstrap/bootstrap.server';
import '../../../../bootstrap/bootstrap.server';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { DesktopHeader, DesktopPageTitle } from '@lumina/market/app/navigation';
@ -8,7 +8,7 @@ import { RulesTabs } from '@lumina/market/app/screens/(flow)/terms/organisms/rul
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { i18n } from '../../../i18n';
import { i18n } from '../../../../i18n';
// Only the landing is indexed (0071); both tabs inherit this.
export const metadata: Metadata = {
@ -18,8 +18,8 @@ export const metadata: Metadata = {
};
/**
* «قوانین لومینا» on desktop (G-2r): the 640 column under the header, with back beside the title
* «قوانین لومینا» and the tab row «قوانین عمومی» · «شرایط اشتراک»; each tab's text sits in a panel.
* «قوانین و مقررات لومینا» on desktop (G-2r): the 640 column under the header, with back beside the title
* «قوانین و مقررات لومینا» and the tab row «قوانین و مقررات» · «شرایط اشتراک»; each tab's text sits in a panel.
* Each tab is its own route with its own loading, so the title and the row stay while one loads;
* back returns to where the rules were opened. No nav item is active.
*/

View File

@ -1,9 +1,9 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { Card } from '@lumina/island/molecules/card';
import { i18n } from '../../../i18n';
import { i18n } from '../../../../i18n';
/** «قوانین عمومی» before it arrives, under the section's title and tabs: its panel of lines. */
/** «قوانین و مقررات» before it arrives, under the section's title and tabs: its panel of lines. */
export default function Loading() {
return (
<SkeletonRegion delayed label={i18n.t('rules:meta-title')}>

View File

@ -0,0 +1,23 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import { Card } from '@lumina/island/molecules/card';
import { LegalDocumentView } from '@lumina/market/app/screens/organisms/legal-document';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:meta-title'),
description: i18n.t('rules:meta-description'),
};
/** «قوانین و مقررات», the first tab of «قوانین و مقررات لومینا» (G-2r); its text is read in the browser (0070). */
export default function RulesPage() {
return (
<Card padding="lg">
<LegalDocumentView documentKey="platform_rules" layout="desktop" />
</Card>
);
}

View File

@ -1,7 +1,7 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { Card } from '@lumina/island/molecules/card';
import { i18n } from '../../../../i18n';
import { i18n } from '../../../../../i18n';
/** The terms before they arrive, under the section's title and tabs: their panel of lines. */
export default function Loading() {

View File

@ -0,0 +1,23 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../../bootstrap/bootstrap.server';
import { Card } from '@lumina/island/molecules/card';
import { SubscriptionTerms } from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import type { Metadata } from 'next';
import { i18n } from '../../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
/** «شرایط اشتراک», the second tab of «قوانین و مقررات لومینا» (S5, G-2); its text is read in the browser (0070). */
export default function SubscriptionTermsPage() {
return (
<Card padding="lg">
<SubscriptionTerms layout="desktop" />
</Card>
);
}

View File

@ -0,0 +1,44 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { DesktopHeader, DesktopPageTitle } from '@lumina/market/app/navigation';
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:agreement.meta-title'),
robots: { index: false },
};
/** «توافق‌نامه تحلیلگر» on desktop: the 640 column under the header, with back beside the title. */
export default function AnalystAgreementLayout({
children,
}: {
children: ReactNode;
}) {
const t = i18n.getFixedT(null, 'rules');
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-content"
>
<DesktopPageTitle title={t('agreement.title')} />
{children}
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -0,0 +1,8 @@
import { LegalDocumentSkeleton } from '@lumina/market/app/screens/organisms/legal-document';
import { i18n } from '../../../../i18n';
/** The agreement before it arrives, under the page's bar or title. */
export default function Loading() {
return <LegalDocumentSkeleton label={i18n.t('legal:document.loading')} />;
}

View File

@ -0,0 +1,22 @@
import { Card } from '@lumina/island/molecules/card';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { AnalystAgreement } from '@lumina/market/app/screens/(flow)/terms/analyst-agreement/organisms/analyst-agreement';
import { LegalDocumentSkeleton } from '@lumina/market/app/screens/organisms/legal-document';
import { i18n } from '../../../../i18n';
/** The agreement and the analyst's own record; both read in the browser (0070). Analysts only. */
export default function AnalystAgreementPage() {
return (
<AuthGuard
role="creator"
fallback={
<LegalDocumentSkeleton label={i18n.t('legal:document.loading')} />
}
>
<Card padding="lg">
<AnalystAgreement layout="desktop" />
</Card>
</AuthGuard>
);
}

View File

@ -1,29 +0,0 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../bootstrap/bootstrap.server';
import { Card } from '@lumina/island/molecules/card';
import {
GeneralRules,
generalRulesLabels,
} from '@lumina/market/app/screens/organisms/general-rules';
import type { Metadata } from 'next';
import { i18n } from '../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:meta-title'),
description: i18n.t('rules:meta-description'),
};
/** «قوانین عمومی», the first tab of «قوانین لومینا» on desktop (G-2r): the text in a panel. */
export default function GeneralRulesPage() {
return (
<Card padding="lg">
<GeneralRules
layout="desktop"
labels={generalRulesLabels(i18n.getFixedT(null, 'rules'))}
/>
</Card>
);
}

View File

@ -1,41 +0,0 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import { Card } from '@lumina/island/molecules/card';
import {
SubscriptionTerms,
subscriptionTermsLabels,
} from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import { supportChatUrls } from '@lumina/market/app/screens/organisms/support-entry';
import { getEnv } from '@lumina/market/env';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
/**
* «شرایط اشتراک», the second tab of «قوانین لومینا» on desktop (S5 ۲.۱, G-2): the text in a panel
* of the section's 640 column, about 75 characters a line; the title and tabs come from the layout.
*/
export default function SubscriptionTermsPage() {
const labels = subscriptionTermsLabels(
i18n.getFixedT(null, 'terms'),
i18n.getFixedT(null, 'auth'),
getEnv().supportHours,
);
return (
<Card padding="lg">
<SubscriptionTerms
layout="desktop"
chats={supportChatUrls()}
labels={labels}
/>
</Card>
);
}

View File

@ -12,7 +12,7 @@ import type { AppProvidersProps } from './types';
/** The app's root client component: runs the client bootstrap, then the platform's shell. */
export function AppProviders({ children }: AppProvidersProps) {
return (
<AppShell queryClient={getQueryClient()} i18n={i18n}>
<AppShell queryClient={getQueryClient()} i18n={i18n} layout="desktop">
{children}
</AppShell>
);

View File

@ -9,6 +9,7 @@ import {
AUTH_EVENTS,
endSuspendedSession,
isSessionSuspended,
noteAgreementRequired,
suspendedSessionOf,
} from '@lumina/market/features/auth';
@ -45,6 +46,7 @@ http.configure({
http.interceptors.response.use(undefined, (error) => {
const suspension = suspendedSessionOf(error);
if (suspension) endSuspendedSession(suspension);
noteAgreementRequired(error);
return error;
});
configureErrorHandler(ERROR_HANDLER_CONFIG);

View File

@ -1,14 +1,6 @@
// First: the rules sheet reads a server-only namespace, which the server bootstrap adds to i18n
// when this module loads (0055).
import '../../../../../bootstrap/bootstrap.server';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { GuestGuard } from '@lumina/market/app/guards/guest-guard';
import { ROUTES } from '@lumina/market/app/navigation';
import {
GeneralRules,
generalRulesLabels,
} from '@lumina/market/app/screens/organisms/general-rules';
import { RegisterDetailsStep } from '@lumina/market/app/screens/(auth)/auth/register/details/organisms/register-details-step';
import type { Metadata } from 'next';
@ -45,12 +37,6 @@ export default function RegisterDetailsPage() {
size="lg"
supportPlacement="bottom"
haltPlacement="sheet"
rules={
<GeneralRules
layout="sheet"
labels={generalRulesLabels(i18n.getFixedT(null, 'rules'))}
/>
}
/>
</GuestGuard>
</AuthTemplate>

View File

@ -1,6 +1,6 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../bootstrap/bootstrap.server';
import '../../../../bootstrap/bootstrap.server';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { MobileTopBar } from '@lumina/market/app/navigation';
@ -8,7 +8,7 @@ import { RulesTabs } from '@lumina/market/app/screens/(flow)/terms/organisms/rul
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { i18n } from '../../../i18n';
import { i18n } from '../../../../i18n';
// Only the landing is indexed (0071); both tabs inherit this.
export const metadata: Metadata = {
@ -18,9 +18,9 @@ export const metadata: Metadata = {
};
/**
* «قوانین لومینا» on mobile (G-2r): a task page pushed from حساب کاربری, checkout, a suspended card
* or the support sheet: back · «قوانین لومینا» · support, no bottom nav, then the tab row
* «قوانین عمومی» · «شرایط اشتراک». Each tab is its own route with its own loading, so the bar and
* «قوانین و مقررات لومینا» on mobile (G-2r): a task page pushed from حساب کاربری, checkout, a suspended card
* or the support sheet: back · «قوانین و مقررات لومینا» · support, no bottom nav, then the tab row
* «قوانین و مقررات» · «شرایط اشتراک». Each tab is its own route with its own loading, so the bar and
* the row stay while one loads; back returns to where the rules were opened.
*/
export default function RulesLayout({ children }: { children: ReactNode }) {

View File

@ -1,8 +1,8 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { i18n } from '../../../i18n';
import { i18n } from '../../../../i18n';
/** «قوانین عمومی» before it arrives, under the section's bar and tabs: a few sections' worth of lines. */
/** «قوانین و مقررات» before it arrives, under the section's bar and tabs: a few sections' worth of lines. */
export default function Loading() {
return (
<SkeletonRegion delayed label={i18n.t('rules:meta-title')}>

View File

@ -0,0 +1,18 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import { LegalDocumentView } from '@lumina/market/app/screens/organisms/legal-document';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:meta-title'),
description: i18n.t('rules:meta-description'),
};
/** «قوانین و مقررات», the first tab of «قوانین و مقررات لومینا» (G-2r); its text is read in the browser (0070). */
export default function RulesPage() {
return <LegalDocumentView documentKey="platform_rules" layout="mobile" />;
}

View File

@ -1,6 +1,6 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { i18n } from '../../../../i18n';
import { i18n } from '../../../../../i18n';
/** The terms before they arrive, under the section's bar and tabs: a few paragraphs' worth of lines. */
export default function Loading() {

View File

@ -0,0 +1,18 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../../bootstrap/bootstrap.server';
import { SubscriptionTerms } from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import type { Metadata } from 'next';
import { i18n } from '../../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
/** «شرایط اشتراک», the second tab of «قوانین و مقررات لومینا» (S5, G-2); its text is read in the browser (0070). */
export default function SubscriptionTermsPage() {
return <SubscriptionTerms layout="mobile" />;
}

View File

@ -0,0 +1,37 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { MobileTopBar } from '@lumina/market/app/navigation';
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:agreement.meta-title'),
robots: { index: false },
};
/** «توافق‌نامه تحلیلگر» on mobile: a task page pushed from حساب کاربری, with back and no bottom nav. */
export default function AnalystAgreementLayout({
children,
}: {
children: ReactNode;
}) {
const t = i18n.getFixedT(null, 'rules');
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-surface">
<MobileTopBar title={t('agreement.title')} />
<FlexBox
tag="main"
direction="flex-col"
className="flex-1 px-4 pt-4 pb-8"
>
{children}
</FlexBox>
</FlexBox>
);
}

View File

@ -0,0 +1,8 @@
import { LegalDocumentSkeleton } from '@lumina/market/app/screens/organisms/legal-document';
import { i18n } from '../../../../i18n';
/** The agreement before it arrives, under the page's bar or title. */
export default function Loading() {
return <LegalDocumentSkeleton label={i18n.t('legal:document.loading')} />;
}

View File

@ -0,0 +1,19 @@
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { AnalystAgreement } from '@lumina/market/app/screens/(flow)/terms/analyst-agreement/organisms/analyst-agreement';
import { LegalDocumentSkeleton } from '@lumina/market/app/screens/organisms/legal-document';
import { i18n } from '../../../../i18n';
/** The agreement and the analyst's own record; both read in the browser (0070). Analysts only. */
export default function AnalystAgreementPage() {
return (
<AuthGuard
role="creator"
fallback={
<LegalDocumentSkeleton label={i18n.t('legal:document.loading')} />
}
>
<AnalystAgreement layout="mobile" />
</AuthGuard>
);
}

View File

@ -1,26 +0,0 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../bootstrap/bootstrap.server';
import {
GeneralRules,
generalRulesLabels,
} from '@lumina/market/app/screens/organisms/general-rules';
import type { Metadata } from 'next';
import { i18n } from '../../../i18n';
export const metadata: Metadata = {
title: i18n.t('rules:meta-title'),
description: i18n.t('rules:meta-description'),
};
/** «قوانین عمومی», the first tab of «قوانین لومینا» on mobile (G-2r), under the section's bar. */
export default function GeneralRulesPage() {
return (
<GeneralRules
layout="mobile"
labels={generalRulesLabels(i18n.getFixedT(null, 'rules'))}
/>
);
}

View File

@ -1,39 +0,0 @@
// First: the static `metadata` below reads a server-only namespace, which the server bootstrap
// adds to i18n when this module loads, whichever module Next loads first (0055).
import '../../../../bootstrap/bootstrap.server';
import {
SubscriptionTerms,
subscriptionTermsLabels,
} from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import { supportChatUrls } from '@lumina/market/app/screens/organisms/support-entry';
import { getEnv } from '@lumina/market/env';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export const metadata: Metadata = {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
/**
* «شرایط اشتراک», the second tab of «قوانین لومینا» on mobile (S5 ۱.۱, G-2): the section's bar and
* tabs come from its layout; back returns to where the rules were opened (checkout, a suspended
* card, the support sheet).
*/
export default function SubscriptionTermsPage() {
const labels = subscriptionTermsLabels(
i18n.getFixedT(null, 'terms'),
i18n.getFixedT(null, 'auth'),
getEnv().supportHours,
);
return (
<SubscriptionTerms
layout="mobile"
chats={supportChatUrls()}
labels={labels}
/>
);
}

View File

@ -12,7 +12,7 @@ import type { AppProvidersProps } from './types';
/** The app's root client component: runs the client bootstrap, then the platform's shell. */
export function AppProviders({ children }: AppProvidersProps) {
return (
<AppShell queryClient={getQueryClient()} i18n={i18n}>
<AppShell queryClient={getQueryClient()} i18n={i18n} layout="mobile">
{children}
</AppShell>
);

View File

@ -9,6 +9,7 @@ import {
AUTH_EVENTS,
endSuspendedSession,
isSessionSuspended,
noteAgreementRequired,
suspendedSessionOf,
} from '@lumina/market/features/auth';
@ -45,6 +46,7 @@ http.configure({
http.interceptors.response.use(undefined, (error) => {
const suspension = suspendedSessionOf(error);
if (suspension) endSuspendedSession(suspension);
noteAgreementRequired(error);
return error;
});
configureErrorHandler(ERROR_HANDLER_CONFIG);

View File

@ -6,13 +6,13 @@ bull (mobile) and bear (desktop) share one doc per route under `market/`, with b
## market
Only `/` is indexable (0071), and it is the only page whose content the server renders (0070). Every other page is `noindex`; all but the rules pages render their content in the browser.
Only `/` is indexable (0071), and it is the only page whose content the server renders (0070). Every other page is `noindex` and renders its content in the browser.
Layouts and error pages:
- root layout · [layout.md](market/layout.md) · — · — · browser: NetworkStatus, Toaster, ToastPlacementMarker (bear)
- `(main)` layout · [layout-main.md](market/layout-main.md) · — · — · browser: bear header nav, search field, publish menu, notification bell, notification panel, login button or account menu, `@modal` slot; bull BottomNav
- `(flow)/terms` layout · [layout-terms.md](market/layout-terms.md) · — · — · browser: MobileTopBar title (bull), DesktopHeader viewer parts (bear)
- `(flow)/terms/(tabs)` layout · [layout-terms.md](market/layout-terms.md) · — · — · browser: MobileTopBar title (bull), DesktopHeader viewer parts (bear)
- `(main)/dashboard/(creator)` layout · [layout-dashboard-creator.md](market/layout-dashboard-creator.md) · — · — · browser: OnboardingGuard redirect, notification bell and account avatar (bull)
- `(main)/dashboard/(investor)` layout · [layout-dashboard-investor.md](market/layout-dashboard-investor.md) · — · — · browser: notification bell and account avatar (bull)
- not-found and error · [not-found.md](market/not-found.md) · noindex · none · browser: not-found top bar, every group `error.tsx`, `global-error.tsx`
@ -20,8 +20,6 @@ Layouts and error pages:
Rendered on the server:
- `/` · [home.md](market/home.md) · index · FAQPage · browser: LandingRedirect
- `/terms` · [terms.md](market/terms.md) · noindex · none · browser: none
- `/terms/subscription` · [terms-subscription.md](market/terms-subscription.md) · noindex · none · browser: none
`(main)`:
@ -44,6 +42,9 @@ Rendered on the server:
`(flow)`:
- `/terms` · [terms.md](market/terms.md) · noindex · none · browser: LegalDocumentView
- `/terms/subscription` · [terms-subscription.md](market/terms-subscription.md) · noindex · none · browser: SubscriptionTerms
- `/terms/analyst-agreement` · [terms-analyst-agreement.md](market/terms-analyst-agreement.md) · noindex · none · browser: top-bar title, AnalystAgreement
- `/account/profile` · [account-profile.md](market/account-profile.md) · noindex · none · browser: AccountProfile (investor form or creator profile edit), LeaveDialog
- `/checkout/[username]` · [checkout-username.md](market/checkout-username.md) · noindex · none · browser: CheckoutCreator, CheckoutPanel, CheckoutForm (tiers, code, pay footer), CheckoutHalts, NoCodeSheet
- `/compose/post` · [compose-post.md](market/compose-post.md) · noindex · none · browser: PostComposer, ComposerForm, LeaveConfirm, PostComposerDialog (bear `@modal`)

View File

@ -17,17 +17,17 @@
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| ------------------------------- | ------------- | ----------- | ------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MobileTopBar (bull) | config | first flush | hydrate | no | a pushed page's bar: back and support |
| ↳ Title or login link (bull) | viewer | skeleton | hydrate | no | |
| DesktopPageTitle (bear) | config | first flush | hydrate | no | «بازگشت» and the H1 |
| AccountOverview | viewer | skeleton | hydrate | no | `AuthGuard` with `AccountOverviewSkeleton`, in `PartBoundary name="account-overview"`; bear: `framed` |
| ↳ IdentityCard, CreatorFacts | viewer, query | skeleton | hydrate | no | creators also get the review badge, followers and subscribers: browser `useQuery`s that never throw and leave out what fails |
| ↳ PrivacyNote | config | skeleton | hydrate | no | investors only |
| ↳ Settings and help lists | viewer | skeleton | hydrate | no | `ListRow` links to `/account/profile`, `/dashboard/finance#…` (creators), `/account/notifications`, `/account/install` (not in the installed app), `/terms`; پشتیبانی opens `SupportDialog` |
| ↳ Sign-out button | — | skeleton | hydrate | no | `SignOutConfirm` asks first (0041) |
| ↳ SupportDialog, SignOutConfirm | — | none | hydrate | no | rendered with `open`; statically imported |
| Section | Data | HTML | JS | Index | Notes |
| ------------------------------- | ------------- | ----------- | ------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| MobileTopBar (bull) | config | first flush | hydrate | no | a pushed page's bar: back and support |
| ↳ Title or login link (bull) | viewer | skeleton | hydrate | no | |
| DesktopPageTitle (bear) | config | first flush | hydrate | no | «بازگشت» and the H1 |
| AccountOverview | viewer | skeleton | hydrate | no | `AuthGuard` with `AccountOverviewSkeleton`, in `PartBoundary name="account-overview"`; bear: `framed` |
| ↳ IdentityCard, CreatorFacts | viewer, query | skeleton | hydrate | no | creators also get the review badge, followers and subscribers: browser `useQuery`s that never throw and leave out what fails |
| ↳ PrivacyNote | config | skeleton | hydrate | no | investors only |
| ↳ Settings and help lists | viewer | skeleton | hydrate | no | `ListRow` links to `/account/profile`, `/dashboard/finance#…` (creators), `/account/notifications`, `/account/install` (not in the installed app), `/terms`, `/terms/analyst-agreement` (creators, with version and date from `GET /me/legal-acceptances`); پشتیبانی opens `SupportDialog` |
| ↳ Sign-out button | — | skeleton | hydrate | no | `SignOutConfirm` asks first (0041) |
| ↳ SupportDialog, SignOutConfirm | — | none | hydrate | no | rendered with `open`; statically imported |
## Notes

View File

@ -26,6 +26,7 @@ In bull's document order.
| ↳ SupportDialog | config | none | hydrate | no | island `Dialog` mounts its content only while open |
| NetworkBar | — | none | hydrate | no | under the bar, only while offline or reconnecting |
| LoginStep | viewer | skeleton | hydrate | no | `GuestGuard` shows `SkeletonPreset preset="form"` until the viewer is known; guest: H1, phone form, register link, support; member: replaced to `?redirect=`, home, or step 5 when `needsProfile` |
| ↳ RulesCaption | config | none | hydrate | no | under the submit button; its link opens `LegalDocumentDialog`, which reads `GET /legal/platform_rules` only when opened; a sheet on bull, a modal on bear |
## Notes

View File

@ -17,21 +17,20 @@
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| -------------------------- | ------ | ----------- | ------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AuthTopBar (bull) | config | first flush | none | no | back button and `auth:register.header` |
| ↳ BackButton (bull) | URL | first flush | hydrate | no | `<a href="/">`, keeping `?redirect=` |
| AuthTemplate header (bear) | config | first flush | none | no | brand `<a href="/">` |
| StepBack (bear) | URL | first flush | hydrate | no | «بازگشت» above the card to `/` |
| SupportEntry | — | first flush | hydrate | no | in the bar; the dialog mounts only when open |
| NetworkBar | — | none | hydrate | no | under the bar, only while offline or reconnecting |
| RegisterDetailsStep | viewer | skeleton | hydrate | no | `GuestGuard` fallback `SkeletonPreset preset="form" count={3}`; investor: `InvestorDetailsForm`; creator: `CreatorIdentityForm`, both in `DetailsFrame` |
| ↳ ExpiryWarning | clock | none | hydrate | no | two minutes before the token ends; `Countdown kind="otp"` and «تمدید زمان» |
| ↳ ExpiryHalt | viewer | none | hydrate | no | when the token ends; bull: sheet; bear: modal |
| ↳ LeaveRegistrationDialog | — | none | hydrate | no | back asks whether to leave and resume later (J02-3f) |
| ↳ RulesSheet | config | none | hydrate | no | «قوانین لومینا» in `TermsLine`; `GeneralRules` rendered on the server and passed as `rules`; bull: sheet; bear: modal; mounts when opened |
| Section | Data | HTML | JS | Index | Notes |
| -------------------------- | ------ | ----------- | ------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AuthTopBar (bull) | config | first flush | none | no | back button and `auth:register.header` |
| ↳ BackButton (bull) | URL | first flush | hydrate | no | `<a href="/">`, keeping `?redirect=` |
| AuthTemplate header (bear) | config | first flush | none | no | brand `<a href="/">` |
| StepBack (bear) | URL | first flush | hydrate | no | «بازگشت» above the card to `/` |
| SupportEntry | — | first flush | hydrate | no | in the bar; the dialog mounts only when open |
| NetworkBar | — | none | hydrate | no | under the bar, only while offline or reconnecting |
| RegisterDetailsStep | viewer | skeleton | hydrate | no | `GuestGuard` fallback `SkeletonPreset preset="form" count={3}`; investor: `InvestorDetailsForm`; creator: `CreatorIdentityForm`, both in `DetailsFrame` |
| ↳ ExpiryWarning | clock | none | hydrate | no | two minutes before the token ends; `Countdown kind="otp"` and «تمدید زمان» |
| ↳ ExpiryHalt | viewer | none | hydrate | no | when the token ends; bull: sheet; bear: modal |
| ↳ LeaveRegistrationDialog | — | none | hydrate | no | back asks whether to leave and resume later (J02-3f) |
| ↳ AgreementBlock (creator) | query | none | hydrate | no | the first block for an analyst: `GET /legal/analyst_agreement`, «خواندن متن» opens `LegalDocumentDialog`, the checkbox unfreezes «ثبت و ادامه», and the version goes with the form |
## Notes
- Decision 0013: the step renders only in the browser on the 15-minute token, held in memory.
- `GeneralRules` is a Server Component passed into the client step, so its text is in the RSC payload of every response, though it reaches the DOM only when the sheet opens.

View File

@ -17,15 +17,16 @@
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| -------------------------- | ------ | ----------- | ------- | ----- | -------------------------------------------------------------------------------------------------------- |
| AuthTopBar (bull) | config | first flush | none | no | back button and `auth:register.header` |
| ↳ BackButton (bull) | URL | first flush | hydrate | no | `<a href>` to `/auth/register`, keeping `?redirect=` |
| AuthTemplate header (bear) | config | first flush | none | no | brand `<a href="/">` |
| StepBack (bear) | URL | first flush | hydrate | no | «بازگشت» above the card to `/auth/register` |
| SupportEntry | — | first flush | hydrate | no | in the bar; the dialog mounts only when open |
| NetworkBar | — | none | hydrate | no | under the bar, only while offline or reconnecting |
| RegisterPhoneStep | viewer | skeleton | hydrate | no | `GuestGuard` fallback `SkeletonPreset preset="form" count={1}`; guest: progress, H1, phone form, support |
| Section | Data | HTML | JS | Index | Notes |
| -------------------------- | ------ | ----------- | ------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AuthTopBar (bull) | config | first flush | none | no | back button and `auth:register.header` |
| ↳ BackButton (bull) | URL | first flush | hydrate | no | `<a href>` to `/auth/register`, keeping `?redirect=` |
| AuthTemplate header (bear) | config | first flush | none | no | brand `<a href="/">` |
| StepBack (bear) | URL | first flush | hydrate | no | «بازگشت» above the card to `/auth/register` |
| SupportEntry | — | first flush | hydrate | no | in the bar; the dialog mounts only when open |
| NetworkBar | — | none | hydrate | no | under the bar, only while offline or reconnecting |
| RegisterPhoneStep | viewer | skeleton | hydrate | no | `GuestGuard` fallback `SkeletonPreset preset="form" count={1}`; guest: progress, H1, phone form, support |
| ↳ RulesCaption | config | none | hydrate | no | under the submit button; its link opens `LegalDocumentDialog`, which reads `GET /legal/platform_rules` only when opened; a sheet on bull, a modal on bear |
## Notes

View File

@ -32,4 +32,4 @@ In bull's document order.
## Notes
- bear: `@modal/feed/page.tsx` renders null, so a «پست جدید» dialog closes when a navigation lands on خانه (0023).
- Debt: no H1 in either app. Give the page an `sr-only` H1, as `GeneralRules` does.
- Debt: no H1 in either app. Give the page an `sr-only` H1, as `LegalDocumentView` does.

View File

@ -1,10 +1,10 @@
# Layout: terms
`apps/{bull,bear}/src/app/(flow)/terms/layout.tsx` · wraps `/terms` and `/terms/subscription` · it awaits no read: its text is server i18n (`rules`), so it adds nothing to the first byte
`apps/{bull,bear}/src/app/(flow)/terms/(tabs)/layout.tsx` · wraps `/terms` and `/terms/subscription` · it awaits no read: its bar and tabs are server i18n (`rules`), so it adds nothing to the first byte; each page reads its text in the browser
| Section | Data | HTML | JS | Index | Notes |
| ------------------------------------ | ------ | ----------- | ------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| MobileTopBar (bull) | viewer | skeleton | hydrate | no | back to where the rules were opened, and support, in the first flush; the title «قوانین لومینا» waits for the viewer |
| MobileTopBar (bull) | viewer | skeleton | hydrate | no | back to where the rules were opened, and support, in the first flush; the title «قوانین و مقررات لومینا» waits for the viewer |
| DesktopHeader (bear) | viewer | skeleton | hydrate | no | brand `<a href>` and support in the first flush; nav, bell, account menu and login wait for the viewer ([layout-main.md](layout-main.md)) |
| DesktopPageTitle, with the H1 (bear) | config | first flush | hydrate | no | «بازگشت» and the H1 `rules:title`; bull puts its H1 in each page instead |
| RulesTabs | config | first flush | hydrate | no | `TabLinks`: `<a href>` to `/terms` and `/terms/subscription`; `usePathname` marks the current tab |
@ -13,4 +13,4 @@ Scripts: none.
- (flow) adds `force-dynamic` and no UI. The layout's static `metadata` gives `rules:meta-title` and `rules:meta-description`; each page overrides them.
- bull: a white page with no bottom nav; bear: `DesktopHeader` over the 640px column, since (flow) has no header of its own.
- Debt: bear's H1 lives here, so `/terms/subscription` gets «قوانین لومینا» on bear and «شرایط اشتراک» on bull (`apps/bear/src/app/(flow)/terms/layout.tsx:40`). Pass each page's own title to `DesktopPageTitle`, or render the H1 in the page as bull does.
- Debt: bear's H1 lives here, so `/terms/subscription` gets «قوانین و مقررات لومینا» on bear and «شرایط اشتراک» on bull (`apps/bear/src/app/(flow)/terms/(tabs)/layout.tsx`). Pass each page's own title to `DesktopPageTitle`, or render the H1 in the page as bull does.

View File

@ -0,0 +1,28 @@
# Analyst agreement
`/terms/analyst-agreement` · `apps/{bull,bear}/src/app/(flow)/terms/analyst-agreement/page.tsx` · Type: account and data · Layout: its own, [layout.md](layout.md)
| Field | Value |
| ----------- | ------------------------------------------------------------------------ |
| Robots | `noindex` (the page's layout, 0071) |
| Status | `200` |
| loading.tsx | `apps/{bull,bear}/src/app/(flow)/terms/analyst-agreement/loading.tsx` |
| First flush | the bar or header and the title `rules:agreement.title` |
| Canonical | none: `noindex` |
| H1 | bull: the document's title, screen-reader-only; bear: `DesktopPageTitle` |
| JSON-LD | none |
| Scripts | none |
## Sections
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| -------------------------------------- | ------------- | ----------- | ------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------- |
| MobileTopBar (bull) | config | first flush | hydrate | no | back, with «توافق‌نامه تحلیلگر» as the title; no bottom nav |
| DesktopHeader, DesktopPageTitle (bear) | config | first flush | hydrate | no | the 640 column under the header |
| AnalystAgreement | viewer, query | skeleton | hydrate | no | `AuthGuard role="creator"`; `GET /legal/analyst_agreement`, then «نسخه … · پذیرفته‌شده در …، ساعت …» from `GET /me/legal-acceptances` |
## Notes
- It sits outside the `(tabs)` route group, so it has neither the tabs nor their title.

View File

@ -1,26 +1,26 @@
# Subscription terms
`/terms/subscription` · `apps/{bull,bear}/src/app/(flow)/terms/subscription/page.tsx` · Type: static and policy · Layout: [layout-terms.md](layout-terms.md), [layout.md](layout.md)
`/terms/subscription` · `apps/{bull,bear}/src/app/(flow)/terms/(tabs)/subscription/page.tsx` · Type: account and data · Layout: [layout-terms.md](layout-terms.md), [layout.md](layout.md)
| Field | Value |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Robots | `noindex` (`terms` layout `metadata`, 0071) |
| Status | `200` |
| loading.tsx | `apps/{bull,bear}/src/app/(flow)/terms/subscription/loading.tsx` (debt, Notes) |
| First flush | none: config, server i18n (`terms`, `auth`) and `getEnv().supportHours` |
| Canonical | none: `noindex` |
| H1 | bull: `terms:title` «شرایط اشتراک», screen-reader-only, in `SubscriptionTerms`; bear: `rules:title` «قوانین لومینا» from the layout (debt) |
| JSON-LD | none |
| Scripts | none |
| Field | Value |
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
| Robots | `noindex` (`terms` layout `metadata`, 0071) |
| Status | `200` |
| loading.tsx | `apps/{bull,bear}/src/app/(flow)/terms/(tabs)/subscription/loading.tsx` |
| First flush | the layout's bar and tabs |
| Canonical | none: `noindex` |
| H1 | bull: the document's title, screen-reader-only, in `LegalDocumentView`; bear: `rules:title` from the layout (debt) |
| JSON-LD | none |
| Scripts | none |
## Sections
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| ------------------------- | ------ | ----------- | ---- | ----- | ---------------------------------------------------------------------------------------------- |
| SubscriptionTerms | config | first flush | none | no | one `<section>` per term with its heading; bear: in a `Card` |
| ↳ Support hours and chats | config | first flush | none | no | island `SupportSheet` rows: `<a href>` to the Bale and Telegram chats, inside the last section |
| Section | Data | HTML | JS | Index | Notes |
| ------------------------- | ------ | -------- | ------- | ----- | ------------------------------------------------------------------------------------- |
| SubscriptionTerms | query | skeleton | hydrate | no | `GET /legal/subscription_terms` through `LegalDocumentView`; bear: in a `Card` |
| ↳ Support hours and chats | config | skeleton | hydrate | no | island `SupportSheet` rows: `<a href>` to the Bale and Telegram chats, under the text |
## Notes

View File

@ -1,24 +1,27 @@
# General rules
# Rules and regulations
`/terms` · `apps/{bull,bear}/src/app/(flow)/terms/page.tsx` · Type: static and policy · Layout: [layout-terms.md](layout-terms.md), [layout.md](layout.md)
`/terms` · `apps/{bull,bear}/src/app/(flow)/terms/(tabs)/page.tsx` · Type: account and data · Layout: [layout-terms.md](layout-terms.md), [layout.md](layout.md)
| Field | Value |
| ----------- | ------------------------------------------------------------------------------------------------------ |
| Robots | `noindex` (`terms` layout `metadata`, 0071) |
| Status | `200` |
| loading.tsx | `apps/{bull,bear}/src/app/(flow)/terms/loading.tsx` (debt, Notes) |
| First flush | none: config and server i18n (`rules`) |
| Canonical | none: `noindex` |
| H1 | `rules:title`; bull: a screen-reader-only H1 in `GeneralRules`; bear: `DesktopPageTitle` in the layout |
| JSON-LD | none |
| Scripts | none |
| Field | Value |
| ----------- | --------------------------------------------------------------------------------------------------------- |
| Robots | `noindex` (`terms` layout `metadata`, 0071) |
| Status | `200` |
| loading.tsx | `apps/{bull,bear}/src/app/(flow)/terms/(tabs)/loading.tsx` |
| First flush | the layout's bar and tabs |
| Canonical | none: `noindex` |
| H1 | bull: the document's title, screen-reader-only, in `LegalDocumentView`; bear: `rules:title` in the layout |
| JSON-LD | none |
| Scripts | none |
## Sections
In bull's document order.
| Section | Data | HTML | JS | Index | Notes |
| ------------ | ------ | ----------- | ---- | ----- | ---------------------------------------------------------------------------------------- |
| GeneralRules | config | first flush | none | no | one `<section>` per rule with its heading, then the last-updated line; bear: in a `Card` |
| Section | Data | HTML | JS | Index | Notes |
| ----------------- | ----- | -------- | ------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LegalDocumentView | query | skeleton | hydrate | no | `GET /legal/platform_rules` in the browser (0070), with `ErrorState` and a retry; «قوانین پلتفرم» and «حریم خصوصی», then the footer «نسخه … · آخرین به‌روزرسانی: …»; bear: in a `Card` |
## Notes
- The text lives in the database, so it changes without a deploy (`features/legal`). `parseLegalMarkdown` turns it into blocks; it never renders as HTML.
- A major `platform_rules` version sends every user the `rules_updated` notification, which opens this page.

View File

@ -156,6 +156,11 @@ export function ratio(a: number, b: number, decimals = 1): string {
return iso(`${number(a)} : ${number(b, decimals)}`);
}
/** A document's version: `1٫0`; the font shows Persian digits but not the decimal point. */
export function version(value: string): string {
return value.replaceAll('.', DECIMAL_SEPARATOR);
}
/** Shamsi date in Tehran time: `15 خرداد 1404، ساعت 14:30`, or `15 خرداد 1404` with `{ time: false }`. */
export function date(
value: DateInput,

View File

@ -16,6 +16,7 @@ export {
signed,
signedPercent,
time,
version,
} from './format';
export { LOCALE, TIME_ZONE } from './constants';
export type { DateFormatOptions, DateInput, ShebaFormatOptions } from './types';

View File

@ -5,6 +5,7 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { useEffect } from 'react';
import { I18nextProvider } from 'react-i18next';
import { AgreementGate } from '../screens/organisms/agreement-gate';
import { useCheckoutDraftStore } from '../../stores/checkout-draft';
import { usePostDraftStore } from '../../stores/post-draft';
import { NetworkBoundary } from './components/NetworkBoundary';
@ -23,9 +24,15 @@ import type { AppShellProps } from './types';
*
* The toasts sit above whatever the screen declares with island's `useToastPlacement`: the bottom
* nav (80px), a pinned footer (152px), the desktop app (32px, declared by bear's root layout), and
* low (24px) on a task page or over a sheet.
* low (24px) on a task page or over a sheet. An analyst who owes a newer major agreement gets its
* blocking modal over any page (J01-4).
*/
export function AppShell({ queryClient, i18n, children }: AppShellProps) {
export function AppShell({
queryClient,
i18n,
layout,
children,
}: AppShellProps) {
useSession(queryClient);
useSuspendedHalt();
useSettleAbandonedPayment(queryClient);
@ -40,6 +47,7 @@ export function AppShell({ queryClient, i18n, children }: AppShellProps) {
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<NetworkBoundary>{children}</NetworkBoundary>
<AgreementGate layout={layout} />
<Toaster
label={i18n.t('toaster')}
closeLabel={i18n.t('toast-close')}

View File

@ -8,6 +8,8 @@ export type AppShellProps = {
queryClient: QueryClient;
/** The app's i18n instance, initialised with the platform's resources. */
i18n: i18n;
/** bull: bottom sheets. bear: modals. */
layout: 'mobile' | 'desktop';
children: ReactNode;
};

View File

@ -72,10 +72,11 @@ export const ROUTES = {
creatorProfileDone: '/onboarding/creator-profile/done',
investorProfile: '/onboarding/investor-profile',
},
/** «قوانین لومینا» (G-2r): «قوانین عمومی» and «شرایط اشتراک», one tab each. */
/** «قوانین و مقررات لومینا» (G-2r): «قوانین و مقررات» and «شرایط اشتراک», one tab each. */
rules: {
general: '/terms',
subscription: '/terms/subscription',
analystAgreement: '/terms/analyst-agreement',
},
} as const;

View File

@ -14,6 +14,7 @@ import { useLoginPage } from '../../../../../../../features/auth';
import { translateMessage } from '../../../../../../../shared/utils';
import { useAuthRoutes } from '../../../../../../navigation';
import { SupportEntry } from '../../../../../organisms/support-entry';
import { RulesCaption } from '../../../organisms/rules-caption';
import type { LoginStepProps } from './types';
/**
@ -108,6 +109,7 @@ export function LoginStep({ size, supportPlacement }: LoginStepProps) {
>
{t('login.submit')}
</Button>
<RulesCaption placement={size === 'lg' ? 'sheet' : 'modal'} />
</FlexBox>
<FlexBox
alignItems="items-center"

View File

@ -0,0 +1,67 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createInstance } from 'i18next';
import type { ReactNode } from 'react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resources } from '../../../../../../shared/locales/resources';
import { legalRepository } from '../../../../../../features/legal/repositories/legal/legal';
import { RulesCaption } from './RulesCaption';
vi.mock('../../../../../../features/legal/repositories/legal/legal', () => ({
legalRepository: { getDocument: vi.fn() },
}));
const i18n = createInstance();
void i18n.use(initReactI18next).init({
lng: 'fa',
resources,
interpolation: { escapeValue: false },
});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={new QueryClient()}>
<I18nextProvider i18n={i18n}>{children}</I18nextProvider>
</QueryClientProvider>
);
describe('RulesCaption', () => {
beforeEach(() => {
vi.mocked(legalRepository.getDocument).mockResolvedValue({
key: 'platform_rules',
version: '1.0',
title: 'قوانین و مقررات لومینا',
bodyMd: '## قوانین پلتفرم\n\nمتن قوانین',
isMajor: false,
changeSummary: null,
publishedAt: '2026-11-01T00:00:00Z',
effectiveAt: '2026-11-01T00:00:00Z',
});
});
it('says signing in accepts the rules, with no checkbox and no read yet', () => {
const { container } = render(<RulesCaption placement="sheet" />, {
wrapper,
});
expect(container.textContent).toContain(
'ورود یا ثبت‌نام به معنی پذیرش قوانین و مقررات لومینا است.',
);
expect(screen.queryByRole('checkbox')).toBeNull();
expect(legalRepository.getDocument).not.toHaveBeenCalled();
});
it('opens the rules with «متوجه شدم» from its link', async () => {
render(<RulesCaption placement="sheet" />, { wrapper });
await userEvent.click(
screen.getByRole('button', { name: 'قوانین و مقررات لومینا' }),
);
expect(await screen.findByText('متن قوانین')).toBeTruthy();
expect(screen.getByText('متوجه شدم')).toBeTruthy();
expect(legalRepository.getDocument).toHaveBeenCalledWith(
{ key: 'platform_rules' },
expect.anything(),
);
});
});

View File

@ -0,0 +1,46 @@
'use client';
import { LinkButton } from '@lumina/island/atoms/link-button';
import { Typography } from '@lumina/island/atoms/typography';
import { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { LegalDocumentDialog } from '../../../../organisms/legal-document';
import type { RulesCaptionProps } from './types';
/**
* Under «دریافت کد» on the login and sign-up phone pages: signing in or up accepts the rules, with
* no checkbox. The link opens them over the page, so the typed number stays.
*/
export function RulesCaption({ placement }: RulesCaptionProps) {
const { t } = useTranslation(['auth', 'legal']);
const [isOpen, setIsOpen] = useState(false);
return (
<>
<Typography variant="body-sm" color="secondary" className="text-center">
<Trans
t={t}
i18nKey="rules-caption"
components={{
rules: (
<LinkButton
aria-haspopup="dialog"
onClick={() => setIsOpen(true)}
>
{t('legal:dialog.rules-title')}
</LinkButton>
),
}}
/>
</Typography>
<LegalDocumentDialog
documentKey="platform_rules"
title={t('legal:dialog.rules-title')}
open={isOpen}
placement={placement}
onClose={() => setIsOpen(false)}
/>
</>
);
}

View File

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

View File

@ -0,0 +1,4 @@
export type RulesCaptionProps = {
/** A bottom sheet on mobile, a modal on desktop. */
placement: 'sheet' | 'modal';
};

View File

@ -0,0 +1,66 @@
'use client';
import { Checkbox } from '@lumina/island/atoms/checkbox';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { LinkButton } from '@lumina/island/atoms/link-button';
import { Typography } from '@lumina/island/atoms/typography';
import { Card } from '@lumina/island/molecules/card';
import { ErrorState } from '@lumina/island/molecules/error-state';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { LegalDocumentDialog } from '../../../../../../../organisms/legal-document';
import type { AgreementBlockProps } from '../types';
/**
* The first block of the analyst's sign-up (J02-4), before any identity data: read the agreement
* over the form, so nothing typed is lost, and tick that you accept it. The box can't be ticked
* until the version it accepts is known.
*/
export function AgreementBlock({ agreement, placement }: AgreementBlockProps) {
const { t } = useTranslation(['legal', 'errors']);
const [isReading, setIsReading] = useState(false);
return (
<Card padding="md">
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-3">
<FlexBox direction="flex-col" gap="gap-1">
<Typography tag="h2" variant="heading-sm">
{t('agreement.kyc.title')}
</Typography>
<Typography variant="body-sm" color="secondary">
{t('agreement.kyc.text')}
</Typography>
</FlexBox>
<LinkButton aria-haspopup="dialog" onClick={() => setIsReading(true)}>
{t('agreement.kyc.read')}
</LinkButton>
{agreement.isError && (
<ErrorState
kind="error"
size="inline"
title={t('agreement.kyc.failed')}
onRetry={agreement.reload}
retryLabel={t('errors:fallback.retry')}
retryingLabel={t('errors:fallback.retrying')}
retrying={agreement.isReloading}
/>
)}
<Checkbox
checked={agreement.isTicked}
disabled={agreement.version === null}
onChange={(event) => agreement.setTicked(event.target.checked)}
>
{t('agreement.kyc.checkbox')}
</Checkbox>
</FlexBox>
<LegalDocumentDialog
documentKey="analyst_agreement"
title={t('dialog.agreement-title')}
open={isReading}
placement={placement}
onClose={() => setIsReading(false)}
/>
</Card>
);
}

View File

@ -1,6 +1,5 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { FileField } from '@lumina/island/molecules/file-field';
import { FormSection } from '@lumina/island/molecules/form-section';
import { TextInput } from '@lumina/island/molecules/text-input';
@ -15,15 +14,16 @@ import {
ID_CARD_SIDES,
} from '../../../../../../../../../shared/validations';
import type { DetailsFormProps } from '../types';
import { AgreementBlock } from './AgreementBlock';
import { DetailsFrame } from './DetailsFrame';
import { IdentitySubmit } from './IdentitySubmit';
import { NameFields } from './NameFields';
import { TermsLine } from './TermsLine';
import { UsernameField } from './UsernameField';
const BYTES_PER_MB = 1024 * 1024;
/**
* Step 4 for a creator: the public username, then the private identity (names, national code,
* Step 4 for a creator: the analyst agreement before any identity data, the public username, then the private identity (names, national code,
* both sides of the ID card) for the admin review. The images upload with a bar; repeat taps are
* ignored while sending, and a failure keeps every value and image.
*/
@ -39,6 +39,7 @@ export function CreatorIdentityForm(props: DetailsFormProps) {
progress,
draft,
leave,
agreement,
} = useCreatorIdentityPart(props.partOptions);
return (
@ -51,24 +52,14 @@ export function CreatorIdentityForm(props: DetailsFormProps) {
leave={leave}
onSubmit={() => void submit()}
footer={
<>
<Button
type="submit"
variant="primary"
size={props.size}
block
isLoading={isSubmitting}
>
{t('register.identity.submit')}
</Button>
<TermsLine
before={t('register.identity.terms-before')}
rules={props.rules}
placement={props.haltPlacement}
/>
</>
<IdentitySubmit
agreement={agreement}
size={props.size}
isSubmitting={isSubmitting}
/>
}
>
<AgreementBlock agreement={agreement} placement={props.haltPlacement} />
{/* What investors see, and what only the review sees (its heading carries the lock). */}
<FormSection
title={t('register.identity.public-title')}

View File

@ -0,0 +1,48 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { IdentitySubmit } from './IdentitySubmit';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const agreement = (isTicked: boolean) => ({
version: '1.0',
isLoading: false,
isError: false,
isReloading: false,
reload: vi.fn(),
isTicked,
setTicked: vi.fn(),
});
const submit = () =>
screen.getByText('register.identity.submit').closest('button')!;
describe('IdentitySubmit', () => {
it('stays frozen with its reason until the agreement is ticked', () => {
render(
<IdentitySubmit
agreement={agreement(false)}
size="lg"
isSubmitting={false}
/>,
);
expect(submit().classList.contains('frozen')).toBe(true);
expect(submit().getAttribute('type')).not.toBe('submit');
expect(screen.getByText('legal:agreement.kyc.frozen')).toBeTruthy();
});
it('submits once it is ticked', () => {
render(
<IdentitySubmit
agreement={agreement(true)}
size="lg"
isSubmitting={false}
/>,
);
expect(submit().classList.contains('frozen')).toBe(false);
expect(submit().getAttribute('type')).toBe('submit');
});
});

View File

@ -0,0 +1,27 @@
import { Button } from '@lumina/island/atoms/button';
import { useTranslation } from 'react-i18next';
import type { IdentitySubmitProps } from '../types';
/** «ثبت و ادامه», frozen with its reason until the agreement is ticked. */
export function IdentitySubmit({
agreement,
size,
isSubmitting,
}: IdentitySubmitProps) {
const { t } = useTranslation(['auth', 'legal']);
return (
<Button
type="submit"
variant="primary"
size={size}
block
frozen={!agreement.isTicked}
frozenReason={t('legal:agreement.kyc.frozen')}
isLoading={isSubmitting}
>
{t('register.identity.submit')}
</Button>
);
}

View File

@ -7,7 +7,6 @@ import { useInvestorDetailsPart } from '../../../../../../../../../features/auth
import type { DetailsFormProps } from '../types';
import { DetailsFrame } from './DetailsFrame';
import { NameFields } from './NameFields';
import { TermsLine } from './TermsLine';
import { UsernameField } from './UsernameField';
/** Step 4 for an investor: name, last name and username, then «ساخت حساب». */
@ -26,22 +25,15 @@ export function InvestorDetailsForm(props: DetailsFormProps) {
leave={leave}
onSubmit={() => void submit()}
footer={
<>
<Button
type="submit"
variant="primary"
size={props.size}
block
isLoading={isSubmitting}
>
{t('register.details.submit')}
</Button>
<TermsLine
before={t('register.details.terms-before')}
rules={props.rules}
placement={props.haltPlacement}
/>
</>
<Button
type="submit"
variant="primary"
size={props.size}
block
isLoading={isSubmitting}
>
{t('register.details.submit')}
</Button>
}
>
<NameFields control={form.control} isPaired={props.size === 'md'} />

View File

@ -1,37 +0,0 @@
'use client';
import { LinkButton } from '@lumina/island/atoms/link-button';
import { Typography } from '@lumina/island/atoms/typography';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { TermsLineProps } from '../types';
import { RulesSheet } from './RulesSheet';
/**
* Accepting the rules by submitting, with no checkbox. «قوانین لومینا» opens the general rules in
* a sheet over the form (G-2s), so nothing typed is lost.
*/
export function TermsLine({ before, rules, placement }: TermsLineProps) {
const { t } = useTranslation('auth');
const [isOpen, setIsOpen] = useState(false);
return (
<>
<Typography variant="body-sm" color="secondary" className="text-center">
{before}
<LinkButton aria-haspopup="dialog" onClick={() => setIsOpen(true)}>
{t('register.terms-link')}
</LinkButton>
{t('register.terms-after')}
</Typography>
<RulesSheet
open={isOpen}
placement={placement}
onClose={() => setIsOpen(false)}
>
{rules}
</RulesSheet>
</>
);
}

View File

@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
import type { Control, FieldValues, Path } from 'react-hook-form';
import type {
CreatorIdentityPartModel,
RegisterDetailsPageModel,
RegisterLeaveModel,
UseDetailsPartOptions,
@ -14,12 +15,10 @@ export type RegisterDetailsStepProps = {
size: 'md' | 'lg';
supportPlacement: SupportEntryProps['placement'];
/**
* The halt when the token runs out, the leave dialog and the rules: a bottom sheet on mobile, a
* modal on desktop.
* The halt when the token runs out, the leave dialog and the agreement: a bottom sheet on mobile,
* a modal on desktop.
*/
haltPlacement: 'sheet' | 'modal';
/** «قوانین عمومی», rendered on the server, for the terms line's rules sheet (G-2s). */
rules: ReactNode;
};
/** What each account type's form gets from the step. */
@ -65,22 +64,6 @@ export type ExpiryHaltProps = {
onConfirm: () => void;
};
export type TermsLineProps = {
/** «با ساخت حساب، » or «با ثبت اطلاعات، ». */
before: string;
/** The general rules the link opens. */
rules: ReactNode;
placement: RegisterDetailsStepProps['haltPlacement'];
};
export type RulesSheetProps = {
open: boolean;
placement: RegisterDetailsStepProps['haltPlacement'];
onClose: () => void;
/** The rules' text. */
children: ReactNode;
};
export type UsernameFieldProps<T extends FieldValues> = {
control: Control<T>;
name: Path<T>;
@ -98,3 +81,14 @@ export type NameFieldsProps<T extends FieldValues> = {
/** Side by side on desktop. */
isPaired: boolean;
};
export type AgreementBlockProps = {
agreement: CreatorIdentityPartModel['agreement'];
placement: RegisterDetailsStepProps['haltPlacement'];
};
export type IdentitySubmitProps = {
agreement: CreatorIdentityPartModel['agreement'];
size: RegisterDetailsStepProps['size'];
isSubmitting: boolean;
};

View File

@ -17,6 +17,7 @@ import { translateMessage } from '../../../../../../../../shared/utils';
import { useAuthRoutes } from '../../../../../../../navigation';
import { SupportEntry } from '../../../../../../organisms/support-entry';
import { RegisterProgress } from '../../../../../../organisms/register-progress';
import { RulesCaption } from '../../../../organisms/rules-caption';
import type { RegisterPhoneStepProps } from './types';
/**
@ -149,6 +150,7 @@ export function RegisterPhoneStep({
>
{t('register.phone.submit')}
</Button>
<RulesCaption placement={size === 'lg' ? 'sheet' : 'modal'} />
</FlexBox>
<FlexBox
alignItems="items-center"

View File

@ -0,0 +1,29 @@
'use client';
import { Typography } from '@lumina/island/atoms/typography';
import { date, time, version } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import { useAgreementAcceptance } from '../../../../../../../features/legal';
import { LegalDocumentView } from '../../../../../organisms/legal-document';
import type { AnalystAgreementProps } from './types';
/** «توافق‌نامه تحلیلگر» with the analyst's own record: which version they accepted, and when. */
export function AnalystAgreement({ layout }: AnalystAgreementProps) {
const { t } = useTranslation('legal');
const acceptance = useAgreementAcceptance();
return (
<LegalDocumentView documentKey="analyst_agreement" layout={layout}>
{acceptance && (
<Typography variant="body-sm" color="secondary">
{t('agreement.record', {
version: version(acceptance.version),
date: date(acceptance.acceptedAt, { time: false }),
time: time(acceptance.acceptedAt),
})}
</Typography>
)}
</LegalDocumentView>
);
}

View File

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

View File

@ -0,0 +1,3 @@
export type AnalystAgreementProps = {
layout: 'mobile' | 'desktop';
};

View File

@ -7,7 +7,7 @@ import { ROUTES } from '../../../../../navigation';
import type { RulesTabsProps } from './types';
/**
* «قوانین لومینا»'s two tabs (G-2r): «قوانین عمومی» · «شرایط اشتراک», the current one from the URL,
* «قوانین و مقررات لومینا»'s two tabs (G-2r): «قوانین و مقررات» · «شرایط اشتراک», the current one from the URL,
* which the server render already knows. The section's layout renders it once, so it stays put
* while a tab loads. A tab replaces the history entry, so back still returns to the page that
* opened the rules.

View File

@ -1,7 +1,7 @@
export type RulesTabsLabels = {
/** The nav's name: «قوانین لومینا». */
/** The nav's name: «قوانین و مقررات لومینا». */
label: string;
/** «قوانین عمومی». */
/** «قوانین و مقررات». */
general: string;
/** «شرایط اشتراک». */
subscription: string;

View File

@ -1,85 +1,39 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { SupportSheet } from '@lumina/island/organisms/support-sheet';
import { Element } from '@lumina/island/primitives/element';
import { useTranslation } from 'react-i18next';
import { getEnv } from '../../../../../../../env';
import { LegalDocumentView } from '../../../../../organisms/legal-document';
import { supportChatUrls } from '../../../../../organisms/support-entry';
import type { SubscriptionTermsProps } from './types';
/**
* «شرایط اشتراک» (S5): eight numbered sections, verbatim. In §۳ the two options sit as a numbered
* list on a sunken panel with bold lead-ins, between its first paragraph and the rest; §۸ ends with
* the support hours and the two chat rows. The same for every visitor, so it renders on the server.
*/
export function SubscriptionTerms({
layout,
chats,
labels,
}: SubscriptionTermsProps) {
const last = labels.sections.length - 1;
/** «شرایط اشتراک» (S5): the versioned text, then the support hours and the two chat rows. */
export function SubscriptionTerms({ layout }: SubscriptionTermsProps) {
const { t } = useTranslation(['legal', 'auth']);
const chats = supportChatUrls();
return (
<FlexBox tag="article" direction="flex-col" gap="gap-6">
{/* Desktop's column title is the h1; the mobile bar's name is not a heading. */}
{layout === 'mobile' && (
<Typography tag="h1" className="sr-only">
{labels.title}
<LegalDocumentView documentKey="subscription_terms" layout={layout}>
<FlexBox direction="flex-col" gap="gap-2">
<Typography color="secondary">
{t('subscription.hours', { hours: getEnv().supportHours })}
</Typography>
)}
{labels.sections.map((section, index) => {
const [first, ...rest] = section.paragraphs;
const titleId = `terms-${section.id}`;
return (
<FlexBox
key={section.id}
tag="section"
aria-labelledby={titleId}
direction="flex-col"
gap="gap-2"
>
<Typography tag="h2" id={titleId} variant="heading-sm">
{section.title}
</Typography>
<Typography>{first}</Typography>
{section.options && (
<FlexBox
tag="ol"
direction="flex-col"
gap="gap-2"
className="m-0 list-decimal rounded-md bg-surface-sunken py-3 ps-9 pe-4"
>
{section.options.map((option) => (
<Element tag="li" key={option.lead}>
<Typography tag="span">
<Typography
tag="b"
variant="inherit"
className="font-bold"
>
{option.lead}
</Typography>{' '}
{option.text}
</Typography>
</Element>
))}
</FlexBox>
)}
{rest.map((paragraph) => (
<Typography key={paragraph}>{paragraph}</Typography>
))}
{index === last && (
<>
<Typography color="secondary">{labels.hours}</Typography>
<SupportSheet
placement="rows"
baleHref={chats.bale}
telegramHref={chats.telegram}
labels={labels.support}
/>
</>
)}
</FlexBox>
);
})}
</FlexBox>
<SupportSheet
placement="rows"
baleHref={chats.bale}
telegramHref={chats.telegram}
labels={{
title: t('auth:support.title'),
bale: t('auth:support.bale'),
telegram: t('auth:support.telegram'),
close: t('auth:support.close'),
opensNewTab: t('auth:support.opens-new-tab'),
}}
/>
</FlexBox>
</LegalDocumentView>
);
}

View File

@ -1,7 +1,2 @@
export { subscriptionTermsLabels } from './labels';
export { SubscriptionTerms } from './SubscriptionTerms';
export type {
SubscriptionTermsLabels,
SubscriptionTermsProps,
TermsSection,
} from './types';
export type { SubscriptionTermsProps } from './types';

View File

@ -1,54 +0,0 @@
import type { TFunction } from 'i18next';
import type { SubscriptionTermsLabels, TermsSection } from './types';
/** The terms' text, from the server's translations (0020), verbatim from S5. */
export function subscriptionTermsLabels(
t: TFunction<'terms'>,
tAuth: TFunction<'auth'>,
hours: string,
): SubscriptionTermsLabels {
const sections: TermsSection[] = [
{ id: 's1', title: t('s1.title'), paragraphs: [t('s1.p1'), t('s1.p2')] },
{
id: 's2',
title: t('s2.title'),
paragraphs: [t('s2.p1'), t('s2.p2'), t('s2.p3')],
},
{
id: 's3',
title: t('s3.title'),
paragraphs: [t('s3.p1'), t('s3.p2'), t('s3.p3'), t('s3.p4')],
options: [
{ lead: t('s3.refund-lead'), text: t('s3.refund') },
{ lead: t('s3.wait-lead'), text: t('s3.wait') },
],
},
{ id: 's4', title: t('s4.title'), paragraphs: [t('s4.p1'), t('s4.p2')] },
{
id: 's5',
title: t('s5.title'),
paragraphs: [t('s5.p1'), t('s5.p2'), t('s5.p3')],
},
{
id: 's6',
title: t('s6.title'),
paragraphs: [t('s6.p1'), t('s6.p2'), t('s6.p3')],
},
{ id: 's7', title: t('s7.title'), paragraphs: [t('s7.p1'), t('s7.p2')] },
{ id: 's8', title: t('s8.title'), paragraphs: [t('s8.p1')] },
];
return {
title: t('title'),
sections,
hours: t('s8.hours', { hours }),
support: {
title: tAuth('support.title'),
bale: tAuth('support.bale'),
telegram: tAuth('support.telegram'),
close: tAuth('support.close'),
opensNewTab: tAuth('support.opens-new-tab'),
},
};
}

View File

@ -1,29 +1,3 @@
import type { SupportSheetLabels } from '@lumina/island/organisms/support-sheet';
/** One numbered section: its paragraphs, and §۳'s two options after its first paragraph. */
export type TermsSection = {
id: string;
title: string;
paragraphs: string[];
options?: { lead: string; text: string }[];
};
export type SubscriptionTermsLabels = {
/** The page's name: «شرایط اشتراک». */
title: string;
sections: TermsSection[];
/** §۸'s line: «زمان پاسخگویی: …» with the configured hours. */
hours: string;
support: SupportSheetLabels;
};
export type SubscriptionTermsProps = {
/**
* Mobile adds the page's h1 for screen readers, since its bar names the page in plain text;
* desktop's column title (DesktopPageTitle) is the h1.
*/
layout: 'mobile' | 'desktop';
/** The support chats' addresses, from config. */
chats: { bale: string; telegram: string };
labels: SubscriptionTermsLabels;
};

View File

@ -4,11 +4,13 @@ import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { List, ListRow } from '@lumina/island/molecules/list-row';
import { date, version } from '@lumina/tools/format';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAccountOverview } from '../../../../../../features/account';
import { PAYOUT_ACCOUNT_ANCHOR } from '../../../../../../features/finance';
import { useAgreementAcceptance } from '../../../../../../features/legal';
import { useIsStandalone } from '../../../../../navigation/hooks/use-is-standalone';
import { ROUTES } from '../../../../../navigation/navigation';
import { SignOutConfirm } from '../../../../organisms/sign-out-confirm';
@ -21,7 +23,7 @@ import type { AccountOverviewProps } from './types';
* حساب کاربری (J12-1, J12-1b), the member's own page: whose account it is, then اطلاعات کاربری,
* an analyst's اطلاعات تسویه‌حساب (their شبا on داشبورد › مالی, or its empty state), تنظیمات
* اعلان‌ها and نصب اپلیکیشن (hidden in the installed app); then پشتیبانی, which opens the support
* sheet, and قوانین و مقررات; then «خروج از حساب», which asks first (J12-1d), and the version.
* sheet, قوانین و مقررات لومینا and an analyst's توافق‌نامه تحلیلگر; then «خروج از حساب», which asks first (J12-1d), and the version.
*/
export function AccountOverview({ layout }: AccountOverviewProps) {
const { t } = useTranslation('account');
@ -30,6 +32,7 @@ export function AccountOverview({ layout }: AccountOverviewProps) {
const [isSupportOpen, setSupportOpen] = useState(false);
const [isSigningOut, setSigningOut] = useState(false);
const { creator } = model;
const acceptance = useAgreementAcceptance();
return (
<FlexBox
@ -94,6 +97,21 @@ export function AccountOverview({ layout }: AccountOverviewProps) {
title={t('overview.rows.terms')}
href={ROUTES.rules.general}
/>
{creator && (
<ListRow
icon="file"
title={t('overview.rows.agreement')}
subtitle={
acceptance
? t('overview.rows.agreement-record', {
version: version(acceptance.version),
date: date(acceptance.acceptedAt, { time: false }),
})
: undefined
}
href={ROUTES.rules.analystAgreement}
/>
)}
</List>
<Button
variant="danger"

View File

@ -26,6 +26,7 @@ export const NOTIFICATION_ART: Record<NotificationType, NotificationArt> = {
subscription_expired_suspended: { icon: 'ban', tone: 'warning' },
// From the admin panel (J11-7d, J11-7e).
subscription_extended: { icon: 'calendar', tone: 'brand' },
rules_updated: { icon: 'file', tone: 'brand' },
subscription_refunded: { icon: 'receipt', tone: 'neutral' },
// Capacity opened, with the investor's code ready (J06-7e).
waitlist_capacity: { icon: 'tag', tone: 'brand' },

View File

@ -0,0 +1,126 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createInstance } from 'i18next';
import type { ReactNode } from 'react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { legalRepository } from '../../../../features/legal/repositories/legal/legal';
import { resources } from '../../../../shared/locales/resources';
import { useAuthStore } from '../../../../stores/auth';
import { AgreementGate } from './AgreementGate';
vi.mock('../../../../features/legal/repositories/legal/legal', () => ({
legalRepository: {
getDocument: vi.fn(),
accept: vi.fn(),
listAcceptances: vi.fn(),
},
}));
vi.mock('../sign-out-confirm', () => ({
SignOutConfirm: ({ open }: { open: boolean }) =>
open ? <div>sign-out-confirm</div> : null,
}));
const i18n = createInstance();
void i18n.use(initReactI18next).init({
lng: 'fa',
resources,
interpolation: { escapeValue: false },
});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider
client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
>
<I18nextProvider i18n={i18n}>{children}</I18nextProvider>
</QueryClientProvider>
);
const session = (agreementRequired: boolean) =>
useAuthStore.getState().setSession({
account: { id: 'c1', role: 'creator' } as never,
needsProfile: false,
agreementRequired,
});
const acceptButton = () => screen.getByText('پذیرش و ادامه').closest('button')!;
describe('AgreementGate', () => {
beforeEach(() => {
vi.mocked(legalRepository.getDocument).mockResolvedValue({
key: 'analyst_agreement',
version: '2.0',
title: 'توافق‌نامه تحلیلگر',
bodyMd: 'متن کامل توافق‌نامه',
isMajor: true,
changeSummary: 'تغییر کمیسیون',
publishedAt: '2026-11-01T00:00:00Z',
effectiveAt: '2026-11-01T00:00:00Z',
});
vi.mocked(legalRepository.accept).mockResolvedValue({
document: 'analyst_agreement',
version: '2.0',
acceptedAt: '2026-11-02T00:00:00Z',
agreementRequired: false,
});
vi.mocked(legalRepository.listAcceptances).mockResolvedValue([]);
});
it('renders nothing while no major agreement is owed', () => {
session(false);
render(<AgreementGate layout="desktop" />, { wrapper });
expect(screen.queryByText('توافق‌نامه تحلیلگر به‌روزرسانی شد')).toBeNull();
expect(legalRepository.getDocument).not.toHaveBeenCalled();
});
it('unticked: blocks, with no close and «پذیرش و ادامه» frozen with its reason', async () => {
session(true);
render(<AgreementGate layout="desktop" />, { wrapper });
expect(await screen.findByText('تغییرات مهم نسخه 2٫0')).toBeTruthy();
expect(screen.getByText('تغییر کمیسیون')).toBeTruthy();
expect(screen.queryByRole('button', { name: /بستن/ })).toBeNull();
expect(acceptButton().classList.contains('frozen')).toBe(true);
expect(screen.getByText('ابتدا توافق‌نامه را بپذیرید.')).toBeTruthy();
await userEvent.click(acceptButton());
expect(legalRepository.accept).not.toHaveBeenCalled();
});
it('ticked: accepts the version read, and lifts the block', async () => {
session(true);
render(<AgreementGate layout="desktop" />, { wrapper });
await userEvent.click(
await screen.findByLabelText(
'نسخهٔ جدید توافق‌نامه تحلیلگر را خوانده‌ام و می‌پذیرم.',
),
);
expect(acceptButton().classList.contains('frozen')).toBe(false);
await userEvent.click(acceptButton());
await waitFor(() =>
expect(legalRepository.accept).toHaveBeenCalledWith({
document: 'analyst_agreement',
version: '2.0',
}),
);
await waitFor(() =>
expect(useAuthStore.getState().session?.agreementRequired).toBe(false),
);
});
it('shows the whole text inside the dialog and comes back', async () => {
session(true);
render(<AgreementGate layout="mobile" />, { wrapper });
await userEvent.click(await screen.findByText('خواندن متن کامل'));
expect(screen.getByText('متن کامل توافق‌نامه')).toBeTruthy();
await userEvent.click(screen.getByText('بازگشت به خلاصه تغییرات'));
expect(screen.getByText('تغییر کمیسیون')).toBeTruthy();
});
it('asks before signing out', async () => {
session(true);
render(<AgreementGate layout="desktop" />, { wrapper });
await userEvent.click(await screen.findByText('خروج از حساب'));
expect(screen.getByText('sign-out-confirm')).toBeTruthy();
});
});

View File

@ -0,0 +1,54 @@
'use client';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgreementGate } from '../../../../features/legal';
import { SignOutConfirm } from '../sign-out-confirm';
import { GateActions } from './components/GateActions';
import { GateBody } from './components/GateBody';
import type { AgreementGateProps } from './types';
/**
* «توافق‌نامه تحلیلگر به‌روزرسانی شد» (J01-4): over any page while an analyst owes a newer major
* agreement, with no ✕ and no dismissing by Escape or the scrim. It closes by accepting, or by
* signing out, which asks first as it does everywhere. A bottom sheet on mobile, a modal on desktop.
*/
export function AgreementGate({ layout }: AgreementGateProps) {
const { t } = useTranslation('legal');
const model = useAgreementGate();
const [isSigningOut, setSigningOut] = useState(false);
if (!model.isOpen) return null;
const title = t('agreement.gate.title');
const body = <GateBody model={model} />;
const actions = (
<GateActions
model={model}
layout={layout}
onSignOut={() => setSigningOut(true)}
/>
);
return (
<>
{layout === 'mobile' ? (
<Sheet open title={title} dismissible={false} footer={actions}>
{body}
</Sheet>
) : (
<Modal open title={title} dismissible={false} actions={actions}>
{body}
</Modal>
)}
<SignOutConfirm
open={isSigningOut}
onClose={() => setSigningOut(false)}
layout={layout}
/>
</>
);
}

View File

@ -0,0 +1,35 @@
import { Button } from '@lumina/island/atoms/button';
import { useTranslation } from 'react-i18next';
import type { GateActionsProps } from '../types';
/** «پذیرش و ادامه» frozen with its reason until ticked, and the only other way out: signing out. */
export function GateActions({ model, layout, onSignOut }: GateActionsProps) {
const { t } = useTranslation('legal');
const size = layout === 'mobile' ? 'lg' : undefined;
return (
<>
<Button
variant="primary"
size={size}
block
frozen={!model.canAccept}
frozenReason={t('agreement.gate.frozen')}
isLoading={model.isAccepting}
onClick={model.accept}
>
{t('agreement.gate.accept')}
</Button>
<Button
variant="ghost"
size={size}
block
disabled={model.isAccepting}
onClick={onSignOut}
>
{t('agreement.gate.sign-out')}
</Button>
</>
);
}

View File

@ -0,0 +1,80 @@
import { Checkbox } from '@lumina/island/atoms/checkbox';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { LinkButton } from '@lumina/island/atoms/link-button';
import { Skeleton } from '@lumina/island/atoms/skeleton';
import { Typography } from '@lumina/island/atoms/typography';
import { ErrorState } from '@lumina/island/molecules/error-state';
import { version } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import { LegalDocumentBody } from '../../legal-document';
import type { GateBodyProps } from '../types';
/**
* What the analyst reads and ticks: what changed in this version, the way to the whole text, which
* opens inside the dialog so the block never lifts, and the checkbox.
*/
export function GateBody({ model }: GateBodyProps) {
const { t } = useTranslation(['legal', 'errors']);
const { agreement } = model;
const { document } = agreement;
if (agreement.isLoading) return <Skeleton lines={4} />;
if (!document) {
return (
<ErrorState
kind="error"
size="inline"
title={t('document.failed')}
onRetry={() => void agreement.reload()}
retryLabel={t('errors:fallback.retry')}
retryingLabel={t('errors:fallback.retrying')}
retrying={agreement.isReloading}
/>
);
}
if (model.view === 'full') {
return (
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-3">
<LinkButton onClick={model.showSummary}>
{t('agreement.gate.back')}
</LinkButton>
<FlexBox direction="flex-col" className="max-h-[50dvh] overflow-auto">
<LegalDocumentBody bodyMd={document.bodyMd} />
</FlexBox>
</FlexBox>
);
}
return (
<FlexBox direction="flex-col" alignItems="items-start" gap="gap-4">
<Typography color="secondary">{t('agreement.gate.body')}</Typography>
{document.changeSummary && (
<FlexBox
direction="flex-col"
gap="gap-1"
className="w-full rounded-md bg-surface-sunken px-4 py-3"
>
<Typography variant="label">
{t('agreement.gate.changes', {
version: version(document.version),
})}
</Typography>
<Typography variant="body-sm" color="secondary">
{document.changeSummary}
</Typography>
</FlexBox>
)}
<LinkButton onClick={model.showFullText}>
{t('agreement.gate.read')}
</LinkButton>
<Checkbox
checked={model.isTicked}
onChange={(event) => model.setTicked(event.target.checked)}
>
{t('agreement.gate.checkbox')}
</Checkbox>
</FlexBox>
);
}

View File

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

View File

@ -0,0 +1,11 @@
import type { AgreementGateModel } from '../../../../features/legal';
export type AgreementGateProps = { layout: 'mobile' | 'desktop' };
export type GateBodyProps = { model: AgreementGateModel };
export type GateActionsProps = {
model: AgreementGateModel;
layout: AgreementGateProps['layout'];
onSignOut: () => void;
};

View File

@ -1,48 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import type { GeneralRulesProps } from './types';
/**
* «قوانین عمومی» of «قوانین لومینا» (G-2r): seven numbered sections, verbatim, then when they last
* changed. The same for every visitor, so it renders on the server: on its tab, and inside the
* registration form's rules sheet (G-2s), which gets it rendered.
*/
export function GeneralRules({ layout, labels }: GeneralRulesProps) {
return (
<FlexBox
tag="article"
direction="flex-col"
gap={layout === 'desktop' ? 'gap-6' : 'gap-4'}
>
{/* Desktop's column title is the h1; the mobile bar's name is not a heading. */}
{layout === 'mobile' && (
<Typography tag="h1" className="sr-only">
{labels.title}
</Typography>
)}
{labels.sections.map((section) => {
const titleId = `rules-${layout}-${section.id}`;
return (
<FlexBox
key={section.id}
tag="section"
aria-labelledby={titleId}
direction="flex-col"
className="gap-1.5"
>
<Typography tag="h2" id={titleId} variant="heading-sm">
{section.title}
</Typography>
{section.paragraphs.map((paragraph) => (
<Typography key={paragraph}>{paragraph}</Typography>
))}
</FlexBox>
);
})}
<Typography variant="caption" color="secondary">
{labels.updated}
</Typography>
</FlexBox>
);
}

View File

@ -1,7 +0,0 @@
export { GeneralRules } from './GeneralRules';
export { generalRulesLabels } from './labels';
export type {
GeneralRulesLabels,
GeneralRulesProps,
RulesSection,
} from './types';

View File

@ -1,17 +0,0 @@
import type { TFunction } from 'i18next';
import type { GeneralRulesLabels, RulesSection } from './types';
/** «قوانین عمومی»'s text, from the server's translations (0020), verbatim from G-2r. */
export function generalRulesLabels(t: TFunction<'rules'>): GeneralRulesLabels {
const sections: RulesSection[] = [
{ id: 's1', title: t('s1.title'), paragraphs: [t('s1.p1'), t('s1.p2')] },
{ id: 's2', title: t('s2.title'), paragraphs: [t('s2.p1')] },
{ id: 's3', title: t('s3.title'), paragraphs: [t('s3.p1')] },
{ id: 's4', title: t('s4.title'), paragraphs: [t('s4.p1')] },
{ id: 's5', title: t('s5.title'), paragraphs: [t('s5.p1')] },
{ id: 's6', title: t('s6.title'), paragraphs: [t('s6.p1')] },
{ id: 's7', title: t('s7.title'), paragraphs: [t('s7.p1')] },
];
return { title: t('title'), sections, updated: t('updated') };
}

View File

@ -1,23 +0,0 @@
/** One numbered section of the general rules: its title and paragraphs. */
export type RulesSection = {
id: string;
title: string;
paragraphs: string[];
};
export type GeneralRulesLabels = {
/** The page's name: «قوانین لومینا». */
title: string;
sections: RulesSection[];
/** «آخرین به‌روزرسانی: …», the caption last. */
updated: string;
};
export type GeneralRulesProps = {
/**
* mobile: adds the page's h1 for screen readers, since its bar names the page in plain text.
* desktop: the column title is the h1. sheet: the sheet's title names it.
*/
layout: 'mobile' | 'desktop' | 'sheet';
labels: GeneralRulesLabels;
};

View File

@ -6,21 +6,25 @@ import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { useTranslation } from 'react-i18next';
import type { RulesSheetProps } from '../types';
import { LegalDocumentView } from './LegalDocumentView';
import type { LegalDocumentDialogProps } from './types';
/**
* «قوانین لومینا» over the registration form (G-2s): the general rules, rendered on the server and
* passed in, with one «متوجه شدم» that closes it. A bottom sheet on mobile, the 640 modal on
* desktop; Escape and the scrim close it too.
* A legal document over the page, so nothing typed under it is lost (G-2s, G-2u): one «متوجه شدم»
* closes it. A bottom sheet on mobile, the 640 modal on desktop; Escape and the scrim close it too.
* It reads the document only once it opens.
*/
export function RulesSheet({
export function LegalDocumentDialog({
documentKey,
title,
open,
placement,
onClose,
children,
}: RulesSheetProps) {
const { t } = useTranslation('auth');
const title = t('register.rules-title');
}: LegalDocumentDialogProps) {
const { t } = useTranslation('legal');
const body = open && (
<LegalDocumentView documentKey={documentKey} layout="dialog" />
);
const close = (
<Button
variant="primary"
@ -28,14 +32,14 @@ export function RulesSheet({
block
onClick={onClose}
>
{t('register.rules-close')}
{t('dialog.close')}
</Button>
);
if (placement === 'sheet') {
return (
<Sheet open={open} title={title} onClose={onClose} footer={close}>
{children}
{body}
</Sheet>
);
}
@ -46,7 +50,7 @@ export function RulesSheet({
direction="flex-col"
className="min-h-0 flex-1 overflow-auto p-6"
>
{children}
{body}
</FlexBox>
<FlexBox
tag="footer"

View File

@ -0,0 +1,59 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { ErrorState } from '@lumina/island/molecules/error-state';
import { date, version } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import { useLegalDocument } from '../../../../features/legal';
import { LegalDocumentBody } from './components/LegalDocumentBody';
import { LegalDocumentSkeleton } from './components/LegalDocumentSkeleton';
import type { LegalDocumentViewProps } from './types';
/**
* One legal document, its latest version read in the browser (0070), so the text changes without a
* deploy: a skeleton, the error with a retry, or the text with «نسخه … · آخرین به‌روزرسانی: …».
*/
export function LegalDocumentView({
documentKey,
layout,
children,
}: LegalDocumentViewProps) {
const { t } = useTranslation(['legal', 'errors']);
const { document, isLoading, isError, isReloading, reload } =
useLegalDocument(documentKey);
if (isLoading) return <LegalDocumentSkeleton label={t('document.loading')} />;
if (isError || !document) {
return (
<ErrorState
kind="error"
size="section"
title={t('document.failed')}
onRetry={() => void reload()}
retryLabel={t('errors:fallback.retry')}
retryingLabel={t('errors:fallback.retrying')}
retrying={isReloading}
/>
);
}
return (
<FlexBox tag="article" direction="flex-col" gap="gap-6">
{layout === 'mobile' && (
<Typography tag="h1" className="sr-only">
{document.title}
</Typography>
)}
<LegalDocumentBody bodyMd={document.bodyMd} />
{children}
<Typography variant="caption" color="secondary">
{t('document.footer', {
version: version(document.version),
date: date(document.publishedAt, { time: false }),
})}
</Typography>
</FlexBox>
);
}

View File

@ -0,0 +1,94 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { Element } from '@lumina/island/primitives/element';
import { useMemo } from 'react';
import { parseLegalMarkdown } from '../../../../../features/legal';
import type { LegalInline } from '../../../../../features/legal';
import type { LegalDocumentBodyProps } from '../types';
function Inlines({ inlines }: { inlines: LegalInline[] }) {
return inlines.map((inline, index) =>
inline.bold ? (
// The text never changes while it is shown, so its place is its identity.
// oxlint-disable-next-line react/no-array-index-key
<Typography key={index} tag="b" variant="inherit" className="font-bold">
{inline.text}
</Typography>
) : (
inline.text
),
);
}
/** A legal document's text, parsed rather than injected, so it can never carry markup. */
export function LegalDocumentBody({ bodyMd }: LegalDocumentBodyProps) {
const blocks = useMemo(() => parseLegalMarkdown(bodyMd), [bodyMd]);
return (
<FlexBox direction="flex-col" gap="gap-3">
{blocks.map((block, index) => {
// Blocks of one version never reorder, and their text may repeat.
const key = `${block.kind}-${index}`;
switch (block.kind) {
case 'section':
return (
<Typography
key={key}
tag="h2"
variant="heading-sm"
className="mt-3 first:mt-0"
>
<Inlines inlines={block.inlines} />
</Typography>
);
case 'subsection':
return (
<Typography
key={key}
tag="h3"
className="mt-1 font-semibold first:mt-0"
>
<Inlines inlines={block.inlines} />
</Typography>
);
case 'quote':
return (
<Typography
key={key}
color="secondary"
className="rounded-md bg-surface-sunken px-4 py-3"
>
<Inlines inlines={block.inlines} />
</Typography>
);
case 'list':
return (
<FlexBox
key={key}
tag="ol"
direction="flex-col"
gap="gap-2"
className="m-0 list-decimal rounded-md bg-surface-sunken py-3 ps-9 pe-4"
>
{block.items.map((item, itemIndex) => (
// oxlint-disable-next-line react/no-array-index-key
<Element tag="li" key={itemIndex}>
<Typography tag="span">
<Inlines inlines={item} />
</Typography>
</Element>
))}
</FlexBox>
);
default:
return (
<Typography key={key}>
<Inlines inlines={block.inlines} />
</Typography>
);
}
})}
</FlexBox>
);
}

View File

@ -0,0 +1,15 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
/** A document's place while it loads: a few sections' worth of lines. */
export function LegalDocumentSkeleton({ label }: { label: string }) {
return (
<SkeletonRegion label={label}>
<Skeleton width="40%" height="1.25rem" className="mb-3" />
<Skeleton lines={3} />
<Skeleton width="35%" height="1.25rem" className="mt-6 mb-3" />
<Skeleton lines={3} />
<Skeleton width="45%" height="1.25rem" className="mt-6 mb-3" />
<Skeleton lines={4} />
</SkeletonRegion>
);
}

View File

@ -0,0 +1,9 @@
export { LegalDocumentBody } from './components/LegalDocumentBody';
export { LegalDocumentSkeleton } from './components/LegalDocumentSkeleton';
export { LegalDocumentDialog } from './LegalDocumentDialog';
export { LegalDocumentView } from './LegalDocumentView';
export type {
LegalDocumentBodyProps,
LegalDocumentDialogProps,
LegalDocumentViewProps,
} from './types';

View File

@ -0,0 +1,25 @@
import type { ReactNode } from 'react';
import type { LegalDocumentKey } from '../../../../features/legal';
export type LegalDocumentBodyProps = { bodyMd: string };
export type LegalDocumentViewProps = {
documentKey: LegalDocumentKey;
/**
* mobile adds the document's title as an h1 for screen readers, since its bar names the page in
* plain text. desktop's column title and a dialog's title are the heading already.
*/
layout: 'mobile' | 'desktop' | 'dialog';
/** Under the text, such as the analyst's own record or the support chats. */
children?: ReactNode;
};
export type LegalDocumentDialogProps = {
documentKey: LegalDocumentKey;
title: string;
open: boolean;
/** A bottom sheet on mobile, the 640 modal on desktop. */
placement: 'sheet' | 'modal';
onClose: () => void;
};

View File

@ -0,0 +1,19 @@
import { isHttpError } from '@lumina/libs/http';
import { useAuthStore } from '../../../../stores/auth';
const AGREEMENT_REQUIRED = 'agreement_required';
/**
* A 403 `agreement_required` on any call means a newer major agreement came out during the session:
* the shell's blocking modal opens. The 422 of the same code belongs to the sign-up form.
*/
export function noteAgreementRequired(error: unknown): void {
if (
isHttpError(error) &&
error.status === 403 &&
error.code === AGREEMENT_REQUIRED
) {
useAuthStore.getState().setAgreementRequired(true);
}
}

View File

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

View File

@ -37,6 +37,8 @@ export async function registerCreator(
useAuthStore.getState().setSession({
account: registration.account,
needsProfile: registration.profileSetupRequired,
// Registration itself accepted the latest agreement.
agreementRequired: false,
});
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {

View File

@ -29,7 +29,8 @@ export async function restoreSession({
const { setSession, clearSession } = useAuthStore.getState();
let status: ViewerStatus;
try {
const { account, needsProfile } = await authRepository.getSession();
const { account, needsProfile, agreementRequired } =
await authRepository.getSession();
if (account?.status === 'suspended') {
// An API that still answers the session of a suspended account: close it, then halt (J01-3d).
void authRepository
@ -40,7 +41,7 @@ export async function restoreSession({
endSuspendedSession({ role: account.role, reason: null });
status = 'guest';
} else if (account) {
setSession({ account, needsProfile });
setSession({ account, needsProfile, agreementRequired });
status = 'member';
} else {
clearSession();

View File

@ -5,6 +5,7 @@ export {
isSessionSuspended,
suspendedSessionOf,
} from './actions/end-suspended-session';
export { noteAgreementRequired } from './actions/agreement-required';
export { login } from './actions/login';
export type { LoginOutcome } from './actions/login';
export { logout } from './actions/logout';

View File

@ -94,6 +94,17 @@ export type CreatorIdentityPartModel = {
pickImage: (side: IdCardSide, file: File | null) => void;
/** 0–100 while the images upload. */
progress: number | undefined;
/** The analyst agreement, ticked before anything is sent. */
agreement: {
/** The version the tick accepts; null until it has been read. */
version: string | null;
isLoading: boolean;
isError: boolean;
isReloading: boolean;
reload: () => void;
isTicked: boolean;
setTicked: (ticked: boolean) => void;
};
draft: () => RegistrationDraft;
leave: RegisterLeaveModel;
};

View File

@ -1,5 +1,6 @@
import { valibotResolver } from '@hookform/resolvers/valibot';
import { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
@ -16,6 +17,7 @@ import type {
CreatorIdentityFormValues,
} from '../../../../shared/validations';
import { useAuthFlowStore } from '../../../../stores/auth-flow';
import { LEGAL_ERROR_CODES, useLegalDocument } from '../../../legal';
import { registerCreator } from '../../actions/register-creator';
import {
AUTH_ERROR_CODES,
@ -52,13 +54,14 @@ type Submission =
* with progress; repeat taps are ignored while sending. Errors show on blur and on submit, the username's also as
* it is typed. The username stands in for the display name the API wants now; the profile step
* sets the real one. The text fields are saved as a draft on the server (never the images), and
* leaving asks first (J02-3f).
* leaving asks first (J02-3f). The analyst agreement is ticked first and travels with the version
* read, which the API checks is still the latest.
*/
export function useCreatorIdentityPart({
profileHref,
onExpired,
}: UseDetailsPartOptions): CreatorIdentityPartModel {
const { t } = useTranslation('auth');
const { t } = useTranslation(['auth', 'legal']);
const router = useRouter();
const [draft] = useState(() => useAuthFlowStore.getState().draft);
const [submission, setSubmission] = useState<Submission>({ phase: 'idle' });
@ -80,6 +83,9 @@ export function useCreatorIdentityPart({
idCardBack: draft?.idCardBack ?? null,
},
});
const agreementDocument = useLegalDocument('analyst_agreement');
const [agreementTicked, setAgreementTicked] = useState(false);
const agreementVersion = agreementDocument.document?.version;
const username = useUsernameAvailability(form);
const { errors, isSubmitting } = form.formState;
const saveDraft = useRegistrationAutosave(form);
@ -104,6 +110,7 @@ export function useCreatorIdentityPart({
};
const submit = form.handleSubmit(async (values) => {
if (!agreementTicked || agreementVersion === undefined) return;
const { phone, registration } = useAuthFlowStore.getState();
if (!phone || !registration) {
onExpired();
@ -131,6 +138,7 @@ export function useCreatorIdentityPart({
nationalIdNumber: values.nationalId,
nationalIdFrontImage: values.idCardFront,
nationalIdBackImage: values.idCardBack,
agreementVersion,
},
{
signal,
@ -149,6 +157,16 @@ export function useCreatorIdentityPart({
onExpired();
return;
}
// A newer version came out while the form was open: it reads again and asks again.
if (
isHttpError(error) &&
error.code === LEGAL_ERROR_CODES.agreementRequired
) {
setAgreementTicked(false);
void agreementDocument.reload();
showToast({ tone: 'error', message: t('legal:agreement.kyc.changed') });
return;
}
applyServerErrors(form, renameFieldErrors(error, FORM_FIELDS), {
t,
failedMessage: t('register.identity.failed'),
@ -167,5 +185,14 @@ export function useCreatorIdentityPart({
submission.phase === 'uploading' ? submission.progress : undefined,
draft: () => form.getValues(),
leave,
agreement: {
version: agreementVersion ?? null,
isLoading: agreementDocument.isLoading,
isError: agreementDocument.isError,
isReloading: agreementDocument.isReloading,
reload: () => void agreementDocument.reload(),
isTicked: agreementTicked,
setTicked: setAgreementTicked,
},
};
}

View File

@ -58,6 +58,7 @@ export function toRegisterCreatorFormData(args: RegisterCreatorArgs): FormData {
...toRegisterInvestorDto(args),
displayName: args.displayName.trim(),
nationalIdNumber: args.nationalIdNumber.trim(),
agreementVersion: args.agreementVersion,
};
for (const [name, value] of Object.entries(fields)) form.append(name, value);
form.append('nationalIdFrontImage', args.nationalIdFrontImage);
@ -144,6 +145,7 @@ export function toSessionPayload(dto: SessionResponseDto): SessionPayload {
return {
account: toAccountPayload(dto.user),
needsProfile: needsProfileOf(dto),
agreementRequired: dto.agreementRequired ?? false,
};
}
@ -151,8 +153,12 @@ export function toSessionStatePayload(
dto: SessionStateResponseDto,
): SessionStatePayload {
return dto.user
? { account: toAccountPayload(dto.user), needsProfile: needsProfileOf(dto) }
: { account: null, needsProfile: false };
? {
account: toAccountPayload(dto.user),
needsProfile: needsProfileOf(dto),
agreementRequired: dto.agreementRequired ?? false,
}
: { account: null, needsProfile: false, agreementRequired: false };
}
export function toCreatorRegisteredPayload(

View File

@ -108,6 +108,8 @@ export type RegisterCreatorArgs = RegisterInvestorArgs & {
nationalIdNumber: string;
nationalIdFrontImage: File;
nationalIdBackImage: File;
/** The agreement version the creator ticked; the API refuses anything but the latest. */
agreementVersion: string;
};
/** Sign-in and registration set the HttpOnly session cookies; the body carries the account. */
@ -116,18 +118,32 @@ export type SessionResponseDto = {
userType: UserRole;
/** Missing from an older gateway. */
needsProfile?: boolean;
agreementRequired?: boolean;
};
/**
* `needsProfile`: a creator who has not finished registration step 5. `agreementRequired`: a
* creator who owes a newer major agreement. Both always false for an investor.
*/
export type SessionPayload = {
account: AccountPayload;
needsProfile: boolean;
agreementRequired: boolean;
};
/** `needsProfile`: a creator who has not finished registration step 5; always false for an investor. */
export type SessionPayload = { account: AccountPayload; needsProfile: boolean };
/** A guest gets `{ user: null }`, never a 401, so a guest never starts a refresh. */
export type SessionStateResponseDto =
| { user: UserEntity; userType: UserRole; needsProfile?: boolean }
| {
user: UserEntity;
userType: UserRole;
needsProfile?: boolean;
agreementRequired?: boolean;
}
| { user: null };
/** A guest is `{ account: null, needsProfile: false }`. */
/** A guest is `{ account: null, needsProfile: false, agreementRequired: false }`. */
export type SessionStatePayload = {
account: AccountPayload | null;
needsProfile: boolean;
agreementRequired: boolean;
};
export type CreatorRegisteredResponseDto = {

View File

@ -0,0 +1,28 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { LEGAL_EVENTS } from '../../constants';
import { legalRepository } from '../../repositories/legal';
import type {
AcceptDocumentArgs,
AcceptedDocumentPayload,
} from '../../repositories/legal';
/**
* Accepts a version of a document and, when nothing newer is owed, lifts the agreement's block on
* the session. Emits `legal.agreement-accepted`.
*/
export async function acceptAgreement(
args: AcceptDocumentArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<AcceptedDocumentPayload> {
const accepted = await legalRepository.accept(args);
useAuthStore.getState().setAgreementRequired(accepted.agreementRequired);
if (emit) {
eventEmitter.emit(LEGAL_EVENTS.agreementAccepted, {
document: accepted.document,
version: accepted.version,
});
}
return accepted;
}

View File

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

View File

@ -0,0 +1,9 @@
export const LEGAL_EVENTS = {
agreementAccepted: 'legal.agreement-accepted',
} as const;
/** The API's refusal when the agreement version sent isn't the one that counts. */
export const LEGAL_ERROR_CODES = {
agreementRequired: 'agreement_required',
versionOutdated: 'agreement_version_outdated',
} as const;

View File

@ -0,0 +1,5 @@
export type {
LegalAcceptanceEntity,
LegalDocumentEntity,
LegalDocumentKey,
} from './types';

View File

@ -0,0 +1,22 @@
/** The back end's three versioned documents. */
export type LegalDocumentKey =
| 'platform_rules'
| 'analyst_agreement'
| 'subscription_terms';
export type LegalDocumentEntity = {
key: LegalDocumentKey;
version: string;
title: string;
bodyMd: string;
isMajor: boolean;
changeSummary: string | null;
publishedAt: string;
effectiveAt: string;
};
export type LegalAcceptanceEntity = {
document: LegalDocumentKey;
version: string;
acceptedAt: string;
};

View File

@ -0,0 +1,3 @@
import { http } from '@lumina/libs/http';
export const legalHttp = http.extend({});

View File

@ -0,0 +1,26 @@
import './types';
export { acceptAgreement } from './actions/accept-agreement';
export { LEGAL_ERROR_CODES, LEGAL_EVENTS } from './constants';
export type {
LegalAcceptanceEntity,
LegalDocumentEntity,
LegalDocumentKey,
} from './entities/legal-document';
export { useAgreementAcceptance } from './models/agreement-acceptance';
export { useAgreementGate } from './models/agreement-gate';
export type {
AgreementGateModel,
AgreementGateView,
} from './models/agreement-gate';
export { useLegalDocument } from './models/legal-document';
export type { LegalDocumentModel } from './models/legal-document';
export { legalKeys, legalRepository } from './repositories/legal';
export type {
AcceptDocumentArgs,
AcceptedDocumentPayload,
LegalAcceptancePayload,
LegalDocumentPayload,
} from './repositories/legal';
export { parseLegalMarkdown } from './utils/parse-legal-markdown';
export type { LegalBlock, LegalInline } from './utils/parse-legal-markdown';

View File

@ -0,0 +1 @@
export { useAgreementAcceptance } from './use-agreement-acceptance';

View File

@ -0,0 +1,20 @@
import { useQuery } from '@tanstack/react-query';
import { useViewerStatus } from '../../../../stores/auth';
import { legalKeys, legalRepository } from '../../repositories/legal';
import type { LegalAcceptancePayload } from '../../repositories/legal';
/** The newest analyst agreement this analyst accepted; null while unknown or when there is none. */
export function useAgreementAcceptance(): LegalAcceptancePayload | null {
const status = useViewerStatus();
const { data } = useQuery({
queryKey: legalKeys.acceptances(),
queryFn: ({ signal }) => legalRepository.listAcceptances({ signal }),
enabled: status === 'member',
throwOnError: false,
});
return (
data?.find((acceptance) => acceptance.document === 'analyst_agreement') ??
null
);
}

View File

@ -0,0 +1,2 @@
export type { AgreementGateModel, AgreementGateView } from './types';
export { useAgreementGate } from './use-agreement-gate';

Some files were not shown because too many files have changed in this diff Show More