Compare commits

...

3 Commits

Author SHA1 Message Date
Amiram_se aafac927bf refactor(market,apps): drop the session proxy and restore auth in the browser
The server render no longer depends on auth: it reads no session and
forwards only FORWARDED_COOKIES (none today), so every visitor of a URL
gets the same HTML and the Next.js proxy is no longer needed.

- Remove proxy.ts from bull and bear, the app/session module, the
  server auth and role guards, and the server caches that read the
  viewer's own data. Public caches stay: channel, post, prediction stats.
- Add an auth store (status unknown | guest | member) filled by the
  restoreSession action, which reads GET /auth/session once per load
  from the AppShell's useSession hook.
- Login and register actions set the store, logout clears it; the
  AppShell clears the query cache on auth.logout. No router.refresh.
- Add client AuthGuard (fallback, optional role) and GuestGuard, with
  safeReturnPath limiting post-login redirects to same-site paths.
- readOnServer no longer redirects on 401.
- The browser HTTP client refreshes against AUTH_ENDPOINTS.refresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:28:05 +04:00
Amiram_se 9de000f3d2 chore: docs 2026-10-04 22:03:42 +04:00
Amiram_se 2f0e1d12f8 feat: update skill 2026-10-04 21:53:48 +04:00
107 changed files with 771 additions and 4461 deletions

View File

@ -1,6 +1,6 @@
---
name: front-end-architect
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, or when another skill such as a product designer or architect needs front-end input.
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's architecture and design decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, when the user states a lasting project rule or asks to record or change a decision, or when another skill such as a product designer or architect needs front-end input.
---
# Front-end Architect
@ -11,7 +11,8 @@ How you work:
- Explain *why*, not only *what*. Present designs and reviews as checklists.
- When a requirement is ambiguous, state your assumption and continue. Ask only when a wrong guess would be expensive to undo.
- When a request conflicts with a rule here, follow the rule and explain the trade-off. When something isn't covered, reason from these principles and say so.
- When a request conflicts with a rule here, follow the rule and explain the trade-off, unless an accepted project decision overrides it. When something isn't covered, reason from these principles and say so.
- Follow the project's decisions. When `docs/decisions/README.md` exists, read it once per session before any task: each line is one rule. When the user states a lasting rule, or you make a choice that is hard to undo, record it as [references/decisions.md](references/decisions.md) describes.
- Prefer boring, proven technology, fewer re-renders, and the user's time.
## 1. The project
@ -64,7 +65,7 @@ Error handling, patterns, and refactoring have their own references. Read each o
- Error handling (error boundaries EB-W and EB-S, API errors by status for reads and actions, empty states, reporting), before you add a page, a part, a query, an action, or a form, and whenever code catches or shows an error: [references/error-handling.md](references/error-handling.md)
- Design patterns (GoF, JavaScript, and React: which one, where it lives, its shape, and what isn't used), before you add a pattern or a shared abstraction such as a factory, a `Record` map, a state machine, an adapter, a context, or a generic hook: [references/design-patterns.md](references/design-patterns.md)
- Rendering and loading patterns, before you add or move a part of a page or change when its code loads: [references/rendering-patterns.md](references/rendering-patterns.md)
- Rendering and loading patterns, before you add or move a part of a page, or change where it renders or when its code loads: [references/rendering-patterns.md](references/rendering-patterns.md)
- Code smells and refactoring (safe steps, smells mapped to layers, smells that are intended), before you refactor and when you review code, together with design-patterns.md's "Not used here" list: [references/refactoring.md](references/refactoring.md)
**Naming**
@ -96,6 +97,13 @@ Error handling, patterns, and refactoring have their own references. Read each o
- `stores/` sits beside `features/`: zustand + immer, one store per feature or domain, holding `*Payload` data.
- `shared/` holds `constants/`, `utils/`, and `validations/` (valibot: `base-validations.ts` plus one `<feature>-validations.ts` per feature).
**Rendering and auth**
- The server render never depends on auth. It reads no session and sends no auth cookies, so every visitor of a URL gets the same server HTML.
- A page or part whose UI depends on the viewer renders completely in the browser. That covers pages that need a logged-in user, UI that differs for guests, members, and paying members, and the viewer's own data. The server renders only its same-size skeleton, and the skeleton stays until the browser knows who the viewer is. Render in the browser only the smallest piece that differs.
- A page or part that is the same for every visitor renders on the server.
- Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write it in the plan. Details: [references/rendering-patterns.md](references/rendering-patterns.md#auth-dependent-ui).
**Data flow**
- Client side (the parts of a page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`). Every part that loads on its own has its own `<Suspense>` with a same-size skeleton and its own part boundary (EB-S), so one slow or failing part never blocks the others.
@ -105,7 +113,7 @@ Error handling, patterns, and refactoring have their own references. Read each o
- Env (`packages/libs/src/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server only). Other projects read their own values with `getEnv`, filled by the app's bootstrap. Libs never read env; the bootstrap passes their settings through `configure`.
- HTTP (`packages/libs/http`): one root `http` client, configured in the app's bootstrap, and one client per feature made with `http.extend(...)`, so every feature shares one token refresh, the interceptors, and error normalization.
- Auth is cookie-based. On a 401, one refresh runs for the whole app, the waiting requests replay once, and a failed refresh triggers logout. The server side never refreshes.
- Auth is cookie-based. On a 401, one refresh runs for the whole app, the waiting requests replay once, and a failed refresh triggers logout. The server side never refreshes and never sends the auth cookies.
- Retry covers only idempotent requests, with backoff. Every request is abortable, and aborted requests are silent. Uploads report progress.
- Every failure is an `HttpError`: `{ code, message, status, fieldErrors, hint, requestId, retryAfter }`. The error handler lib (`packages/libs/error-handler`) decides what each one shows and reports it.
- Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`.
@ -131,12 +139,12 @@ Error handling, patterns, and refactoring have their own references. Read each o
## 4. Workflow
Follow these steps for any design or implementation task. Write a short plan in the PR description: affected projects and paths, data types, each route's streamed and deferred parts, and each new non-obvious pattern.
Follow these steps for any design or implementation task. Write a short plan in the PR description: affected projects and paths, data types, each route's streamed, deferred, and auth-dependent parts, each rendering override the developer asked for, and each new non-obvious pattern.
1. **Clarify the job.** Who uses it, how often, and what they finish with it. State assumptions.
2. **Read the playbook** ([b2c-b2b.md](references/b2c-b2b.md)), plus [ui-rules.md](references/ui-rules.md) for UI work.
3. **Map the data.** Entities, repository types (`*Args`, `*Dto`, `*ResponseDto`, `*Payload`), caches and how each client part gets its server data, page and part models, actions and their events, query keys, and how the query cache is updated after each mutation.
4. **Place the code.** List the Nx projects and folders that change. Reuse what exists before creating anything. For each part you add or move, decide where it renders and when its code loads ([rendering-patterns.md](references/rendering-patterns.md)), and add a pattern only for a signal you can name ([design-patterns.md](references/design-patterns.md)). When existing code resists the change, refactor it first, in its own commit ([refactoring.md](references/refactoring.md)).
4. **Place the code.** List the Nx projects and folders that change. Reuse what exists before creating anything. For each part you add or move, decide whether it depends on the viewer, where it renders, and when its code loads ([rendering-patterns.md](references/rendering-patterns.md)), and add a pattern only for a signal you can name ([design-patterns.md](references/design-patterns.md)). When existing code resists the change, refactor it first, in its own commit ([refactoring.md](references/refactoring.md)).
5. **Design every state first:** loading, empty (no data, no results, not found, no access), error, in progress, then populated.
6. **Build in layer order,** with island components, adding variants to island when needed:
1. Setup: Nx projects, tags, subpath exports, and new env variables.
@ -180,7 +188,9 @@ Structure
[ ] No tokens or personal data in cookies or local storage; neither is read during render
[ ] Every new pattern answers a named signal and sits where design-patterns.md puts it; none is on its "Not used here" list
[ ] Each new or moved part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR
[ ] The server render is the same for every visitor; every auth-dependent page or part renders in the browser behind a same-size skeleton, unless the developer asked otherwise and the PR says so
[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt
[ ] Code follows every accepted decision in docs/decisions; lasting decisions made in this work are recorded
States and feedback
[ ] Loading, empty, error, and in-progress states exist
@ -204,4 +214,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo
Name a code smell and its technique, with the target layer or file, as [references/refactoring.md](references/refactoring.md#review-comments) does. A smell is a suggestion; when it also breaks a rule on the list below, lead with that rule, mark it blocking, and name the smell in the body. In a feature PR, raise smells only in the code the PR touches. Flag a pattern from the "Not used here" list in [references/design-patterns.md](references/design-patterns.md#not-used-here) with its alternative. Never flag the smells that refactoring.md marks as intended.
Block a merge only for: a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.

View File

@ -33,10 +33,11 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
## Rendering
- Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page.
- The server render never depends on auth: every visitor of a URL gets the same server HTML. A page or part whose UI depends on the viewer (it needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's own data) renders completely in the browser behind a same-size skeleton. What is the same for every visitor renders on the server. An explicit request from the developer overrides either default ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use-<page>-<part>-part.ts`). Don't turn a whole template into a client component to use a page model when only part of it is interactive.
- Keep props passed to client components small and serializable; they are serialized into the page's RSC payload.
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components.
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed parts in the plan.
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan.
- Server code reads data through the features' caches, so `generateMetadata`, the page, and every server component share one request per distinct call (see Data flow).
## Server and client entries
@ -51,13 +52,12 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
## Data flow
A request becomes a page in this order. The server steps run per request and keep nothing afterwards.
A request becomes a page in this order. The server steps run per request, keep nothing afterwards, and never depend on who the viewer is.
1. `proxy.ts` refreshes an expired session before rendering.
2. Every root layout imports `bootstrap.server.ts` first.
3. The page resolves the device, awaits only what the first paint needs through caches or a server page loader, and renders the mobile or the desktop template.
4. Server components that need more data read it through caches. A slow part is an async server component inside `<Suspense>` with a same-size skeleton, so the page streams around it.
5. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions. After a mutation that changes server-rendered content, `router.refresh()` renders the page again.
1. Every root layout imports `bootstrap.server.ts` first.
2. The page resolves the device, awaits only what the first paint needs through caches or a server page loader, and renders the mobile or the desktop template.
3. Server components that need more data read it through caches. A slow part is an async server component inside `<Suspense>` with a same-size skeleton, so the page streams around it. An auth-dependent part renders only its skeleton on the server.
4. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions, and auth-dependent parts render their variant once the auth store knows the viewer. After a mutation that changes server-rendered content, `router.refresh()` renders the page again.
**Caches** (`features/<feature>/caches/`, server-only)
@ -77,14 +77,14 @@ A request becomes a page in this order. The server steps run per request and kee
**Data loaded only in the browser**
- Render on the server what search engines and the first paint need. Load in the browser only what's personal, below the fold, or shown on interaction, through a part model inside `<Suspense>` with a skeleton.
- Render on the server what search engines and the first paint need. Load in the browser only what depends on the viewer, is below the fold, or is shown on interaction, through a part model inside `<Suspense>` with a skeleton.
- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies.
## Errors
The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here:
- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`: the page calls `notFound()` for 404 and 410, renders the `no-access` empty state for 403 with `robots: { index: false }`, and redirects a 401 to login; a part renders its empty state for 404 and 403. Everything else is rethrown to a boundary.
- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`: the page calls `notFound()` for 404 and 410, renders the `no-access` empty state for 403 with `robots: { index: false }`; a part renders its empty state for 404 and 403. Everything else is rethrown to a boundary.
- Boundaries: `app/global-error.tsx` is EB-W; every route group has `error.tsx` (page EB-S) and, when it calls `notFound()`, `not-found.tsx`; each part has a `PartBoundary` built with `catchError`, which lets `notFound()` and `redirect()` through. Error pages render `noindex`.
- A part that must show an empty state awaits its read on the server; an un-awaited prefetch fits only reads that can't answer 404 or 403.
- `instrumentation.ts` configures the error handler for the server and reports what no server code caught; `bootstrap.client.ts` configures it for the browser.
@ -93,9 +93,9 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl
- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), a failed first load throws to its boundary while a failed refetch keeps the data, and pending queries are dehydrated so they can stream.
- zustand stores hold client state only. Never write to a store during server render: on the server a module-level store is shared by every request, so one user's data would leak to another. Pass server data through props or the query cache. If a store must start from server data, create it per request with `createStore` inside a provider.
- Server-side requests forward the incoming request's cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request. That configures the root client, so every feature client forwards cookies too. Never keep a user's cookies in module state.
- Server-side requests forward only the incoming request's cookies that the render needs, such as locale and theme, and never the auth cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request and keeps only the app's forwarded cookie names ([lib-http.md](lib-http.md#server-side)). That configures the root client, so every feature client forwards the same cookies. Never keep a user's cookies in module state.
- On the server, the HTTP lib never refreshes, never calls `abortAll`, and retries at most once with a shorter timeout, so a slow back end doesn't hold up rendering (see [lib-http.md](lib-http.md#server-side)).
- Server Components can't set cookies. Refresh an expired session in `proxy.ts` before rendering, or in a Route Handler or Server Function, never during render.
- The server never reads or refreshes the session. The browser learns who the viewer is once per load through the auth store's `status`, and the browser's HTTP lib refreshes an expired session on a 401 ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- The `cookie` and `storage` libs are browser-only. Never read them during render: client components also render on the server, and the value would differ between server and browser. A value the page needs while rendering (theme, locale) is read on the server with `cookies()` and passed down as a prop.
- Persisted zustand stores set `skipHydration: true` and rehydrate in an effect of the platform's `AppShell`, so the first browser render matches the server's (code in code-patterns.md, Persisted store).
@ -136,6 +136,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par
[ ] global-error.tsx, error.tsx in every route group, and not-found.tsx where notFound() is called; error pages are noindex
[ ] Server reads that can answer 404 or 403 go through readOnServer; every streamed part has a PartBoundary
[ ] Each route's streamed parts are decided and written in the plan
[ ] The server render is the same for every visitor: no session reads, no auth cookies forwarded, no variant picked on the server; auth-dependent parts render their skeleton until the browser knows the viewer, unless the developer asked otherwise
[ ] Page is a thin entrypoint that renders the server-chosen mobile or desktop template
[ ] 'use client' only on interactive leaves; no server-only code reachable from client bundles
[ ] New server-only code is exported through server.ts and starts with import 'server-only'

View File

@ -152,6 +152,7 @@ This is an excerpt. The real file defines every semantic token the components us
```css
@import './theme.css';
@import './fonts.css';
@import './utilities.css';
@source '../';
```
@ -527,7 +528,10 @@ export type Session = {
isFirstLogin: boolean;
};
export type ViewerStatus = 'unknown' | 'guest' | 'member';
export type AuthState = {
status: ViewerStatus;
session: Session | null;
setSession: (session: Session) => void;
clearSession: () => void;
@ -543,23 +547,30 @@ import type { AuthState } from './types';
export const useAuthStore = create<AuthState>()(
immer((set) => ({
status: 'unknown',
session: null,
setSession: (session) =>
set((state) => {
state.status = 'member';
state.session = session;
}),
clearSession: () =>
set((state) => {
state.status = 'guest';
state.session = null;
}),
})),
);
export const useCurrentUser = () => useAuthStore((state) => state.session?.user);
export const useViewerStatus = () => useAuthStore((state) => state.status);
```
Never write to a store during server render (see b2c-b2b.md).
- `status` stays `'unknown'` on the server and in the first browser render, so auth-dependent parts render their skeleton until the browser knows the viewer, and `'unknown'` never reads as a guest.
- The `AppShell` calls the auth feature's `restoreSession` action once in an effect. It reads the session through the auth repository and calls `setSession` or `clearSession` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
## Persisted store
A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`:

View File

@ -0,0 +1,81 @@
# Decisions
How to keep a project's architecture decision records (ADR) and design decision records (DDR) in one log, so a decision made once is followed in every later task. Read this file only when you add, accept, reject, or supersede a decision. To follow decisions, the index is enough ([SKILL.md](../SKILL.md)).
Contents: Layout · When to record · Writing a record · Changing a decision · Precedence
## Layout
`docs/decisions/` at the monorepo root holds one file per decision and one index. Create both with the first decision.
```
docs/decisions/
README.md # the index
0001-zod-instead-of-valibot.md
0002-island-components-over-native-elements.md
```
The index lists only live decisions, one line each. The line is the rule itself, one imperative sentence with its scope, so a task follows it without opening the record. Open a record only to change it, or when a case isn't clear from its line.
```markdown
# Decisions
## Design (DDR)
- 0002 Build UI with island components; never use native interactive elements (`button`, `input`, `select`, `textarea`, `a`) in features or apps.
## Architecture (ADR)
- 0001 Validate with Zod instead of valibot in every project.
## Proposed
- 0003 architecture: Load the reviews part only on interaction, on every product page.
```
- The area is where the rule applies: design for UI, island, tokens, copy, and UX; architecture for everything else.
- Keep a line under about 30 words. A rule that needs more is two decisions, or its detail belongs in the record.
- Rejected and superseded decisions leave the index. Their files stay, with their status, as history.
## When to record
- The user states a lasting rule for the project: "always", "never", "use X instead of Y", "from now on". Write it as `Accepted`, because the user decides, and say so in one line: "Recorded as decision 0004."
- You make a choice that is hard to undo, adds a dependency, deviates from this skill, or sets a pattern beyond the current task. Write it as `Proposed` and list it in the PR's plan. It binds nothing until the user accepts it.
Don't record a one-off instruction for the current task, a rule this skill already states, or detail that one file shows. When you can't tell whether an instruction is lasting, follow it for the task and ask in your final message whether to record it.
Before you propose a decision, search `docs/decisions/` for its topic, so you don't propose again what the user rejected or superseded.
## Writing a record
Number: the highest number in the folder plus 1, four digits. File name: `NNNN-<kebab-title>.md`. Keep a record under about 25 lines.
```markdown
# 0002 Island components over native elements
Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user
## Context
Why the decision came up, in one to three sentences.
## Decision
The rule in the imperative, with its scope and exceptions.
## Alternatives
- The option, and why it lost. "Not discussed" when the user gave none.
## Consequences
What becomes easier or harder, and which existing code doesn't follow it yet.
```
- `Decided by` is `user` or `agent`. Add `Supersedes: NNNN` to the status line when it applies.
- Add the record's line to its area in the index, or to Proposed.
- Existing code that breaks a new decision is debt. List it under Consequences, and fix it only when the user asks or a task touches that code.
## Changing a decision
- Accept: set `Status: Accepted`, and move the line from Proposed to its area.
- Reject: set `Status: Rejected`, add the reason in one line under Decision, and remove the line from the index.
- Supersede: never rewrite the body of an accepted record. Write a new record with `Supersedes: NNNN`, set the old one to `Status: Superseded by MMMM`, and replace the old index line with the new one. A typo fix or clearer wording that keeps the rule is fine in place.
- When the user asks for something an accepted decision forbids, name the decision and ask: supersede it, or make a one-time exception. Record only a supersede.
## Precedence
An accepted decision overrides this skill's rules and your own judgment. A proposed decision overrides nothing. When a decision would break a rule that blocks a merge ([SKILL.md](../SKILL.md#7-review-stance)), such as tokens readable by JavaScript, state the risk once before you record it, and write the risk under Consequences.

View File

@ -121,9 +121,9 @@ export const PartBoundary = catchError(PartFallback);
A part in a template:
```tsx
<PartBoundary name="order-invoice">
<Suspense fallback={<OrderInvoiceSkeleton />}>
<OrderInvoice orderId={order.id} />
<PartBoundary name="seller-ratings">
<Suspense fallback={<SellerRatingsSkeleton />}>
<SellerRatings sellerId={seller.id} />
</Suspense>
</PartBoundary>
```
@ -222,71 +222,59 @@ function makeQueryClient(): QueryClient {
```ts
import 'server-only';
import { classifyError } from '@project/libs/error-handler';
import { isHttpError } from '@project/libs/http';
import { redirect } from 'next/navigation';
import { ROUTES } from '../../navigation';
import type { ServerRead } from './types';
export async function readOnServer<T>(
read: () => Promise<T>,
options: { returnTo?: string } = {},
): Promise<ServerRead<T>> {
export async function readOnServer<T>(read: () => Promise<T>): Promise<ServerRead<T>> {
try {
return { status: 'ok', data: await read() };
} catch (error) {
const outcome = classifyError(error).read;
if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome };
if (options.returnTo && isHttpError(error) && error.status === 401) {
redirect(`${ROUTES.login}?redirect=${encodeURIComponent(options.returnTo)}`);
}
throw error;
}
}
```
`apps/<app>/src/app/(account)/orders/[id]/page.tsx`. `getOrder` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too.
`apps/<app>/src/app/(shop)/seller/[slug]/page.tsx`. A seller page is the same for every visitor, so it reads on the server. A page that depends on the viewer, such as an order page, loads in the browser instead, and its reads reach the fallback as browser errors ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). `getSeller` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too.
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getDevice, getOrder, readOnServer } from '@project/<platform>/server';
import { getDevice, getSeller, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { OrderDesktop } from './templates/order-desktop';
import { OrderMobile } from './templates/order-mobile';
import { SellerDesktop } from './templates/seller-desktop';
import { SellerMobile } from './templates/seller-mobile';
type OrderPageProps = { params: Promise<{ id: string }> };
type SellerPageProps = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: OrderPageProps): Promise<Metadata> {
const { id } = await params;
const order = await readOnServer(() => getOrder(id));
if (order.status !== 'ok') return { robots: { index: false } };
return { title: order.data.title };
export async function generateMetadata({ params }: SellerPageProps): Promise<Metadata> {
const { slug } = await params;
const seller = await readOnServer(() => getSeller(slug));
if (seller.status !== 'ok') return { robots: { index: false } };
return { title: seller.data.name };
}
export default async function OrderPage({ params }: OrderPageProps) {
const { id } = await params;
const [device, order] = await Promise.all([
getDevice(),
readOnServer(() => getOrder(id), { returnTo: `/orders/${id}` }),
]);
if (order.status === 'not-found') notFound();
if (order.status === 'no-access') return <StatusEmptyState variant="no-access" size="page" />;
return device === 'mobile' ? <OrderMobile order={order.data} /> : <OrderDesktop order={order.data} />;
export default async function SellerPage({ params }: SellerPageProps) {
const { slug } = await params;
const [device, seller] = await Promise.all([getDevice(), readOnServer(() => getSeller(slug))]);
if (seller.status === 'not-found') notFound();
if (seller.status === 'no-access') return <StatusEmptyState variant="no-access" size="page" />;
return device === 'mobile' ? <SellerMobile seller={seller.data} /> : <SellerDesktop seller={seller.data} />;
}
```
A server part, `.../orders/[id]/organisms/order-invoice/OrderInvoice.tsx`:
A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`:
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getOrderInvoice, readOnServer } from '@project/<platform>/server';
import { InvoiceSummary } from './components/invoice-summary';
import type { OrderInvoiceProps } from './types';
import { getSellerRatings, readOnServer } from '@project/<platform>/server';
import { RatingsSummary } from './components/ratings-summary';
import type { SellerRatingsProps } from './types';
export async function OrderInvoice({ orderId }: OrderInvoiceProps) {
const invoice = await readOnServer(() => getOrderInvoice(orderId));
if (invoice.status !== 'ok') return <StatusEmptyState variant={invoice.status} size="part" />;
return <InvoiceSummary invoice={invoice.data} />;
export async function SellerRatings({ sellerId }: SellerRatingsProps) {
const ratings = await readOnServer(() => getSellerRatings(sellerId));
if (ratings.status !== 'ok') return <StatusEmptyState variant={ratings.status} size="part" />;
return <RatingsSummary ratings={ratings.data} />;
}
```

View File

@ -108,7 +108,7 @@ Rules:
Server reads classify on the server, because a Server Component error reaches the browser with only its digest.
- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, redirects a 401 to login with a return URL when the page passes `returnTo`, and rethrows the rest to the page's `error.tsx`.
- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, and rethrows the rest to the page's `error.tsx`. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found.
- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)).
- A server part reads through `readOnServer` too: it renders the part-size `StatusEmptyState` for `not-found` and `no-access`, and rethrows the rest to its `PartBoundary`.

View File

@ -39,7 +39,7 @@ type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server';
interface ErrorContext {
where: ErrorWhere; // where the error stopped
name?: string; // the part, action, or route, e.g. 'order-invoice'; never personal data
name?: string; // the part, action, or route, e.g. 'seller-ratings'; never personal data
}
interface ErrorReport extends Partial<ErrorContext> {
@ -90,7 +90,7 @@ The first matching row wins.
| Not an `HttpError`, with a `digest` | network | boundary | toast | again | no |
| Anything else | logic | boundary | toast | none | yes |
- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh, so server code checks for 401 itself and redirects to login ([error-handling.md](error-handling.md#b2cb2b-server)).
- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh and sends no auth cookies, so a server read never expects a 401; `readOnServer` rethrows one to its boundary like any other error ([error-handling.md](error-handling.md#b2cb2b-server)).
- A `digest` without `HttpError` fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server.
- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `fix` offers none, because the user must change the input; `none` offers none.

View File

@ -175,11 +175,11 @@ A feature never sets `refresh`, `credentials`, or `getCookieHeader`: auth works
- Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it.
- Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh.
- On success, every waiting request is replayed once. A replay that gets 401 again fails with `UNAUTHORIZED` without refreshing again, so there are no loops.
- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store and redirects). Later requests try normally, so logging in again works without a reload.
- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user the `AuthGuard` sends the user to login). Later requests try normally, so logging in again works without a reload.
- The refresh request is sent with `skipRefresh: true`, `retry: false`, and the normal timeout, and runs request interceptors like any request.
- Waiting is abortable per request: an aborted waiter rejects with `ABORTED` while the refresh continues for the others.
- In the browser, run the refresh inside `navigator.locks.request('http-refresh', ...)` when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it).
- On the server refresh is disabled. Server Components can't set cookies, so a 401 throws `UNAUTHORIZED`, and `proxy.ts` refreshes an expired session before rendering.
- On the server refresh is disabled. Server requests send no auth cookies (Server side), so the server render never reads or refreshes the session, and a 401 there throws `UNAUTHORIZED` to its boundary.
## Abort
@ -256,11 +256,27 @@ interface DownloadResult {
## Server side
- `bootstrap.server.ts` calls `configureServerHttp({ baseUrl: serverEnv.API_INTERNAL_URL, getCookieHeader: async () => (await cookies()).toString() })` once. It sets the root's server `baseUrl` (from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards cookies too. A feature with its own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address.
- `getCookieHeader` runs on every server request, so each request forwards its own user's cookies. Never keep cookies, users, or tokens in module state.
- `bootstrap.server.ts` calls `configureServerHttp` once (code below). It sets the root's server `baseUrl` (from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards the same cookies. A feature with its own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address.
- `getCookieHeader` runs on every server request and forwards only the names in the app's `FORWARDED_COOKIES`, the cookies the server render needs, such as `LOCALE_COOKIE` and `THEME_COOKIE`. It never forwards the auth cookies, so no back-end response on the server depends on who the viewer is ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Never keep cookies, users, or tokens in module state.
- On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says.
- `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)).
`bootstrap.server.ts`:
```ts
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () =>
(await cookies())
.getAll()
.filter(({ name }) => FORWARDED_COOKIES.has(name))
.map(({ name, value }) => `${name}=${encodeURIComponent(value)}`)
.join('; '),
});
```
`FORWARDED_COOKIES` is a `ReadonlySet<string>` in the app's `constants/`, built from the cookie name constants ([lib-cookie.md](lib-cookie.md)). Adding an auth cookie to it is an override of rendering-patterns.md's Auth-dependent UI rule and needs a recorded decision.
## Usage
`features/catalog/http.ts`. `getEnv` is the owning project's env getter (see [lib-env.md](lib-env.md#project-env)).
@ -358,5 +374,5 @@ For building or changing the lib:
[ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow
[ ] Download returns the blob and the file name from Content-Disposition
[ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles
[ ] On the server, each request forwards its own cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests
[ ] On the server, each request forwards only its own allowed cookies and never the auth cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests
```

View File

@ -49,7 +49,7 @@ export { getProduct, getProductReviews, getRelatedProducts } from './features/ca
export { getDevice } from './shared/utils/get-device';
```
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the order page in [error-handling.md](error-handling-code.md) does.
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does.
```tsx
import { getDevice, getProduct } from '@project/<platform>/server';

View File

@ -21,7 +21,7 @@ Three folders are named `tools`. Keep them apart:
- Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti.
- `packages/tools/`: shared runtime tools that apps and projects import.
- `packages/island/src/tools/`: design-system tools such as `cn`, `icon-sprite-plugin`, and `icon-name-extraction`.
- `packages/island/src/tools/`: design-system tools such as `cn`, `cvx`, `icon-sprite-plugin`, and `icon-name-extraction`.
## App (Next.js)
@ -49,7 +49,6 @@ apps/<app>/src/
│ └── templates/ # optional: this route's mobile and desktop templates
├── styles/
│ ├── app.css # Tailwind entry; imports island.css
│ ├── fonts.ts # next/font/local faces from island fonts/, set as CSS variables on <html>
│ └── index.ts
├── configs/
│ ├── seo.ts
@ -79,7 +78,7 @@ platforms/<app>/src/
│ │ ├── AppShell.tsx
│ │ ├── types.ts
│ │ └── index.ts
│ ├── guards/ # e.g. the route authentication guard
│ ├── guards/ # e.g. AuthGuard for pages that need a logged-in user
│ │ └── <guard-name>/
│ │ ├── <guard-name>.ts or <GuardName>.tsx
│ │ └── index.ts
@ -191,7 +190,7 @@ packages/island/src/
├── templates/ # like organisms
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms
├── tools/
│ └── <tool-name>/ # e.g. cn, icon-sprite-plugin, icon-name-extraction
│ └── <tool-name>/ # e.g. cn, cvx, icon-sprite-plugin, icon-name-extraction
│ ├── <tool-name>.ts or <tool-name>.tsx
│ ├── types.ts
│ ├── constants.ts
@ -199,7 +198,8 @@ packages/island/src/
├── styles/
│ ├── island.css # entry that apps import into their Tailwind v4 CSS
│ ├── theme.css # primitive and semantic tokens
│ └── utilities.css # custom @utility definitions
│ ├── utilities.css # custom @utility definitions
│ └── fonts.css # @font-face rules for fonts/
├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap
│ ├── env.ts
│ ├── types.ts
@ -207,7 +207,7 @@ packages/island/src/
├── icons/
│ ├── symbol-defs.svg # sprite generated by Icomoon
│ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set
├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2; each app loads them with next/font/local
├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2
├── constants.ts # island-level constants
├── index.ts
└── server.ts

View File

@ -141,6 +141,9 @@ The catalog doesn't name these, but this stack has them. Each line gives the sme
- `'use client'` on a page, layout, or template → only on the interactive leaf, driven by its part model ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Business logic in components → the model, action, mapper, or util that owns it ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Viewport checks choosing layouts → the template the server picks ([b2c-b2b.md](b2c-b2b.md#rendering)).
- A server render that depends on auth (a session read, auth cookies forwarded, a variant picked on the server, or a page that needs a logged-in user rendered on the server) → a browser part, or a page behind the `AuthGuard`, that renders its skeleton until the auth store knows the viewer ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Leave it when the developer explicitly asked for it and the plan or a decision records it.
- The guest variant shown while the viewer is still unknown → the same-size skeleton while the auth store's `status` is `'unknown'` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- A `<Suspense>` boundary or `'use client'` added to keep a part out of the server render → a technique from rendering-patterns.md's "What keeps a part out of the server HTML": browser-only state that renders the skeleton, `next/dynamic` with `ssr: false`, or `LoadOnVisible` ([rendering-patterns.md](rendering-patterns.md#choosing-where-a-part-loads)).
- Cookie or storage reads during render → an effect or an event handler, or `cookies()` on the server passed down as a prop ([lib-cookie.md](lib-cookie.md#browser-only), [lib-local-storage.md](lib-local-storage.md#browser-only)).
- Module-scope data on the server → React `cache()`, props, or the per-request `QueryClient` ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- A page, loader, or server component that calls a repository directly → a cache, so every reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)).

View File

@ -2,16 +2,16 @@
This file takes the rendering and performance patterns from patterns.dev and decides whether to use each one and which tool implements it. The playbook, [b2c-b2b.md](b2c-b2b.md), holds the details and wins on any conflict. Code-level patterns are in [design-patterns.md](design-patterns.md), and code smells in [refactoring.md](refactoring.md). Names match the source pages under patterns.dev/react/ and patterns.dev/vanilla/.
Contents: Rendering patterns · Loading patterns · Choosing where a part loads
Contents: Rendering patterns · Auth-dependent UI · Loading patterns · Choosing where a part loads
## Rendering patterns
Apps render every page on the server for each request and stream it.
Apps render every page on the server for each request and stream it. The server render is the same for every visitor: what depends on the viewer renders in the browser (Auth-dependent UI below).
| Pattern | Use | How here |
|---|---|---|
| Client-side rendering | Parts only | A page renders only its browser-only parts in the browser ([b2c-b2b.md](b2c-b2b.md#data-flow)). |
| Server-side rendering | Always | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Client-side rendering | Auth-dependent pages and parts; other browser-only parts | A page or part whose UI depends on the viewer renders completely in the browser (Auth-dependent UI below). Other parts render in the browser only when [b2c-b2b.md](b2c-b2b.md#data-flow) says so. |
| Server-side rendering | Always, for what's the same for every visitor | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). The server render never depends on auth. |
| Static rendering | Never | Nothing renders at build time. Keep each request cheap instead (first note below). |
| Incremental static generation | Never | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Partial prerendering | Never | It needs Cache Components, which stay off. `loading.tsx` and `<Suspense>` give an early first paint instead ([b2c-b2b.md](b2c-b2b.md#rendering)). |
@ -27,6 +27,69 @@ Apps render every page on the server for each request and stream it.
- Experimental APIs, such as `unstable_*` exports, canary-only React features, and Next.js `experimental.*` flags, stay unused until they're stable, unless the repo already enables them. `<ViewTransition>` counts as stable from React 19.3 and Next.js 16.3 (View transitions row). [SKILL.md](../SKILL.md) prefers boring, proven technology.
- Many patterns.dev examples use the Pages Router (`getServerSideProps`, `getStaticProps`, `next/head`), APIs removed in React 19, or libraries such as loadable-components and react-window. Take the idea and write the code with this stack's APIs.
## Auth-dependent UI
The server render never depends on auth. Every visitor of a URL gets the same server HTML, whether they are a guest, a logged-in member, or a paying member.
A page or part is auth-dependent when what it shows changes with who the viewer is: it needs a logged-in user (orders, addresses, settings), it shows a different UI per user type (a guest, a member without a subscription, a member with one), or it shows the viewer's own data (the cart count, a wishlist, recommendations, a member price). Locale, theme, device, and URL parameters aren't auth, so the server may render by them.
- Same for every visitor → render it on the server, through "Choosing where a part loads" below.
- Depends on the viewer → render it completely in the browser. The server renders only its same-size skeleton: it never reads the session, sends auth cookies, or picks a variant. In the browser, the part's model reads the viewer and the viewer's data, and the part renders its variant.
- Render in the browser only the smallest piece that differs. A product page stays on the server and only its membership offer is a browser part. A page renders in the browser as a whole only when all of it depends on the viewer, such as an account page.
- Both are defaults. When the developer explicitly asks for a page or part to render on the server or in the browser, follow the request, state the trade-off, and write the override in the plan. When they make it a lasting rule, record it as a decision ([decisions.md](decisions.md#when-to-record)). Auth-dependent UI rendered on the server needs the auth cookies forwarded and the session refreshed in `proxy.ts` for the whole app, so record that override as a decision even for one page.
Why:
- The server renders the same thing for millions of mostly logged-out visitors, with no per-user back-end calls, so TTFB stays flat.
- The server can't refresh an expired session, because Server Components can't set cookies. A server render that read the session would show a member the guest UI, or fail, whenever the access token expired. In the browser, the HTTP lib refreshes and replays.
- One user's data can never reach another user's HTML through a misconfigured CDN or module state.
- Search engines crawl as guests, so they never saw auth-dependent UI. SEO loses nothing.
How:
- Server requests forward only the cookies the render needs, never the auth cookies ([b2c-b2b.md](b2c-b2b.md#state-and-auth)), so the back end can't personalize a server response by accident.
- The browser learns who the viewer is once per load. The `AppShell` calls the auth feature's `restoreSession` action in an effect, and the action moves the auth store's `status` from `'unknown'` to `'guest'` or `'member'` ([code-patterns.md](code-patterns.md#store)). The session endpoint answers a guest with an empty session, not 401, so a guest never starts a refresh or a logout. When the read still fails after the HTTP lib's retries, the action clears the session, so the status becomes `'guest'`, and rethrows; the `AppShell`'s effect passes the error to `handleError`.
- An auth-dependent part renders its same-size skeleton while the status is `'unknown'`. That covers the server render and the first browser render, so hydration matches. Never render the guest variant as the placeholder: a member would see it flash, and the layout would shift.
- When the part needs the viewer's own data, its model reads it with `useQuery`, enabled only when the status is `'member'`. Never use a server prefetch or `useSuspenseQuery` for it.
- Every variant ships in the route's bundle. Make a heavy variant, such as a subscriber's video player, a `next/dynamic` component with a same-size `loading` skeleton, so each visitor downloads only their own.
- A page that needs a logged-in user, such as every `(account)` page: the route group's layout wraps its children in the platform's `AuthGuard` (`app/guards/auth-guard/`). This client component renders the page skeleton while the status is `'unknown'`, sends a guest to login with a return URL, and renders the page for a member. The page stays a thin Server Component that resolves the device and passes only URL parameters to its template, and the template's parts load in the browser. `generateMetadata` reads no data: it returns a generic title and `robots: { index: false }`.
- An action that changes the viewer, such as login, logout, or a payment, updates the auth store, so every auth-dependent part renders its new variant. It doesn't call `router.refresh()`, because no server-rendered content changed.
`platforms/<app>/src/features/membership/models/product/use-membership-offer-part.ts`. A guest sees an invitation to log in, a member without a subscription sees the subscription offer, and a subscriber (`user.hasSubscription`) sees their benefit. `types.ts` declares `MembershipOfferVariant = 'pending' | 'guest' | 'member' | 'subscriber'`.
```ts
import { useCurrentUser, useViewerStatus } from '../../../../stores/auth';
import type { MembershipOfferVariant } from './types';
export function useMembershipOfferPart(): MembershipOfferVariant {
const status = useViewerStatus();
const user = useCurrentUser();
if (status === 'unknown') return 'pending';
if (status === 'guest') return 'guest';
return user?.hasSubscription ? 'subscriber' : 'member';
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/membership-offer/MembershipOffer.tsx`. The product template, a Server Component, renders `<MembershipOffer />` beside the server-rendered product summary. The server and the first browser render both show the skeleton. The part reads no data of its own, so it needs no `PartBoundary`; a variant that queries data gets one.
```tsx
'use client';
import { useMembershipOfferPart } from '@project/<platform>/features/membership';
import { GuestOffer } from './components/guest-offer';
import { MemberOffer } from './components/member-offer';
import { MembershipOfferSkeleton } from './components/membership-offer-skeleton';
import { SubscriberOffer } from './components/subscriber-offer';
export function MembershipOffer() {
const variant = useMembershipOfferPart();
if (variant === 'pending') return <MembershipOfferSkeleton />;
if (variant === 'guest') return <GuestOffer />;
if (variant === 'member') return <MemberOffer />;
return <SubscriberOffer />;
}
```
## Loading patterns
The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Record each route's deferred parts and what triggers them in the plan (the PR description).
@ -144,9 +207,22 @@ export function ProductVideo({ video }: ProductVideoProps) {
## Choosing where a part loads
Ask about each part of a page in this order. Every match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (1), makes its thumbnails a small client leaf (2), and loads its zoom viewer only when the user opens it (3 and 4). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow).
Ask about each part of a page in this order. Step 1 decides first, and every later match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (2), makes its thumbnails a small client leaf (3), and loads its zoom viewer only when the user opens it (4 and 5). These are defaults: an explicit request from the developer to render a part on the server or in the browser wins (Auth-dependent UI). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow).
1. Search engines or the first paint need it → a Server Component that reads caches, inside `<Suspense>` with a same-size skeleton when it's slow.
2. The user interacts with it → only the interactive piece becomes a client leaf, driven by its part model, with server data as props or through query hydration.
3. It's personal, below the fold, or shown only on interaction, and search engines don't need it → a browser-only part: `useQuery` with a skeleton, or `next/dynamic`: with `ssr: false` when it renders unconditionally, without it inside `LoadOnVisible` or behind an interaction (see the `PriceHistory` note).
4. Its code is heavy, or it's a third party → a dynamic import that starts on visibility or interaction, behind a same-size skeleton or a facade. Third-party scripts use `next/script` with `afterInteractive` or `lazyOnload`.
1. It depends on the viewer → it renders completely in the browser behind a same-size skeleton, even when search engines or the first paint would want it (Auth-dependent UI). Split off what is the same for every visitor, and ask about that piece from step 2.
2. Search engines or the first paint need it → a Server Component that reads caches, inside `<Suspense>` with a same-size skeleton when it's slow.
3. The user interacts with it → only the interactive piece becomes a client leaf, driven by its part model, with server data as props or through query hydration.
4. It's below the fold or shown only on interaction, and search engines don't need it → a browser-only part: `useQuery` with a skeleton, or `next/dynamic`: with `ssr: false` when it renders unconditionally, without it inside `LoadOnVisible` or behind an interaction (see the `PriceHistory` note).
5. Its code is heavy, or it's a third party → a dynamic import that starts on visibility or interaction, behind a same-size skeleton or a facade. Third-party scripts use `next/script` with `afterInteractive` or `lazyOnload`.
**What keeps a part out of the server HTML.** `'use client'` doesn't, and neither does `<Suspense>`. Client components render to HTML on the server and then hydrate. `<Suspense>` only decides what shows while its children wait: the server streams the fallback, then the children's HTML when they're ready. A child that never suspends renders on the server as if the boundary weren't there, and a `useSuspenseQuery` inside it sends its request from the server. Only these keep a part's real UI out of the server HTML:
| Technique | The server HTML holds | Use it for |
|---|---|---|
| Output that depends on browser-only state: the auth store's `status` while it's `'unknown'`, or a `useQuery` while it's pending | The skeleton the component returns | Auth-dependent parts (step 1) and data loaded only in the browser (step 4) |
| `next/dynamic` with `ssr: false` and a same-size `loading` skeleton | The `loading` skeleton | Heavy code that renders at once but the first paint doesn't need (steps 4 and 5) |
| `LoadOnVisible`, or rendering only after an interaction | The fallback or the facade | Parts below the fold or shown on interaction (steps 4 and 5) |
- `ssr: false` throws a bail-out during the server render, so the nearest Suspense boundary sends its fallback. Suspense is how the skip happens, not what causes it.
- React also falls back to client rendering when a child throws during the server render. That's an error path: never use it to keep a part off the server.
- Decide what the server HTML must hold, the real UI or a skeleton, then pick the technique. Add `<Suspense>` for streaming and selective hydration, never to move a part to the browser.

View File

@ -2,9 +2,8 @@ import { configureErrorHandler } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import { http } from '@lumina/libs/http';
import { mapApiErrorBody } from '@lumina/market/app/http';
import { SESSION_REFRESH_ENDPOINT } from '@lumina/market/app/session';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { AUTH_EVENTS } from '@lumina/market/features/auth';
import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
@ -23,7 +22,7 @@ setMarketEnv({
http.configure({
baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`,
refresh: {
endpoint: SESSION_REFRESH_ENDPOINT,
endpoint: AUTH_ENDPOINTS.refresh,
onFailure: () =>
eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'session-ended' }),
},

View File

@ -7,7 +7,7 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { cookies } from 'next/headers';
import { API_VERSION_PATH } from '../constants';
import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
@ -19,11 +19,17 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
// Each server request forwards its own user's session cookies; nothing per user is kept in module
// state. The server never refreshes: proxy.ts already did, before rendering.
// Server requests forward only the allowlisted cookies, never the session: the server render is
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each
// request; nothing per visitor is kept in module state.
configureServerHttp({
baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`,
getCookieHeader: async () => (await cookies()).toString(),
getCookieHeader: async () =>
(await cookies())
.getAll()
.filter(({ name }) => FORWARDED_COOKIES.has(name))
.map(({ name, value }) => `${name}=${encodeURIComponent(value)}`)
.join('; '),
});
http.configure({ mapErrorBody: mapApiErrorBody });
configureErrorHandler(ERROR_HANDLER_CONFIG);

View File

@ -0,0 +1,6 @@
/**
* Cookies the server render may read, forwarded on every server-side API request. Only values
* every visitor can have, such as locale and theme; never the session cookies, so no server
* response depends on who the viewer is. Adding an auth cookie here needs a recorded decision.
*/
export const FORWARDED_COOKIES: ReadonlySet<string> = new Set<string>([]);

View File

@ -1 +1,2 @@
export { API_VERSION_PATH } from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,17 +0,0 @@
import { refreshSessionInProxy } from '@lumina/market/server';
import type { NextRequest } from 'next/server';
import { API_VERSION_PATH } from './constants';
import { serverEnv } from './env/server';
/** Refreshes an expired session before the page renders (see refreshSessionInProxy). */
export function proxy(request: NextRequest) {
return refreshSessionInProxy(request, {
apiUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`,
});
}
export const config = {
// Pages and their data requests only: not build assets, images or files with an extension.
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.[a-zA-Z0-9]+$).*)'],
};

View File

@ -2,9 +2,8 @@ import { configureErrorHandler } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import { http } from '@lumina/libs/http';
import { mapApiErrorBody } from '@lumina/market/app/http';
import { SESSION_REFRESH_ENDPOINT } from '@lumina/market/app/session';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { AUTH_EVENTS } from '@lumina/market/features/auth';
import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth';
import { API_VERSION_PATH } from '../constants';
import { clientEnv } from '../env';
@ -23,7 +22,7 @@ setMarketEnv({
http.configure({
baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`,
refresh: {
endpoint: SESSION_REFRESH_ENDPOINT,
endpoint: AUTH_ENDPOINTS.refresh,
onFailure: () =>
eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'session-ended' }),
},

View File

@ -7,7 +7,7 @@ import { mapApiErrorBody } from '@lumina/market/app/http';
import { setEnv as setMarketEnv } from '@lumina/market/env';
import { cookies } from 'next/headers';
import { API_VERSION_PATH } from '../constants';
import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
import { ERROR_HANDLER_CONFIG } from './error-reporting';
@ -19,11 +19,17 @@ setMarketEnv({
telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE,
supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS,
});
// Each server request forwards its own user's session cookies; nothing per user is kept in module
// state. The server never refreshes: proxy.ts already did, before rendering.
// Server requests forward only the allowlisted cookies, never the session: the server render is
// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each
// request; nothing per visitor is kept in module state.
configureServerHttp({
baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`,
getCookieHeader: async () => (await cookies()).toString(),
getCookieHeader: async () =>
(await cookies())
.getAll()
.filter(({ name }) => FORWARDED_COOKIES.has(name))
.map(({ name, value }) => `${name}=${encodeURIComponent(value)}`)
.join('; '),
});
http.configure({ mapErrorBody: mapApiErrorBody });
configureErrorHandler(ERROR_HANDLER_CONFIG);

View File

@ -0,0 +1,6 @@
/**
* Cookies the server render may read, forwarded on every server-side API request. Only values
* every visitor can have, such as locale and theme; never the session cookies, so no server
* response depends on who the viewer is. Adding an auth cookie here needs a recorded decision.
*/
export const FORWARDED_COOKIES: ReadonlySet<string> = new Set<string>([]);

View File

@ -1 +1,2 @@
export { API_VERSION_PATH } from './api';
export { FORWARDED_COOKIES } from './cookies';

View File

@ -1,17 +0,0 @@
import { refreshSessionInProxy } from '@lumina/market/server';
import type { NextRequest } from 'next/server';
import { API_VERSION_PATH } from './constants';
import { serverEnv } from './env/server';
/** Refreshes an expired session before the page renders (see refreshSessionInProxy). */
export function proxy(request: NextRequest) {
return refreshSessionInProxy(request, {
apiUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`,
});
}
export const config = {
// Pages and their data requests only: not build assets, images or files with an extension.
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.[a-zA-Z0-9]+$).*)'],
};

View File

@ -0,0 +1,17 @@
# 0001 One platform shared by mobile and desktop apps
Status: Accepted · Area: architecture · Date: 2026-10-04 · Decided by: user
## Context
The product ships two Next.js apps, `bull` (mobile) and `bear` (desktop), that serve the same Lumina product. Both apps serve under one domain; nginx proxies each request to the mobile or desktop app based on its user agent. The default rule gives each app its own platform.
## Decision
Both `apps/bull` and `apps/bear` depend on one platform, `platforms/market`. Each app keeps only its routes, templates, bootstrap, and env; features, stores, models, and shared logic live in `platforms/market`.
## Alternatives
- One platform per app (`platforms/bull`, `platforms/bear`): duplicates the same business logic in two places.
## Consequences
- Nx tags: both apps and the platform use `scope:market`, so each app may import `platforms/market`, and neither app imports the other.
- Models and actions must stay viewport-agnostic; device-specific UI belongs in each app's templates and organisms.
- One URL serves two apps (dynamic serving): both apps keep the same route paths, and nginx sends `Vary: User-Agent` so caches and search engines don't mix the two versions.

View File

@ -0,0 +1,22 @@
# 0002 Island Element, FlexBox, and GridBox over native tags
Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user
## Context
Island has three typed atoms, `Element`, `FlexBox`, and `GridBox`, that render tags and layouts. The user set them as the only way to render tags and layouts.
## Decision
- Render every HTML or SVG tag through island `Element` (`<Element tag="section">`), never as native JSX (`<a>`, `<div>`, `<button>`).
- Build every flex layout with `FlexBox` and every grid layout with `GridBox`; never put `flex`, `inline-flex`, `grid`, or `inline-grid` in a `className`.
- Applies to apps, platforms, integrations, and island itself. Only `Element` renders a native tag, except the island `Link` below.
- Once island has a `Link` component built on `next/link`, render every link with `Link`, never `<Element tag="a">`. `Link` renders `next/link` directly, which renders its own `<a>`.
- Responsive or one-off layout classes that the props don't type (for example `md:flex-row`) go in `className` on the same `FlexBox` or `GridBox`.
## Alternatives
- Not discussed.
## Consequences
- One typed place per tag: attributes narrow per `tag`, and layout values are typed Tailwind classes.
- All three are server components with no client JavaScript.
- Next.js `<html>` and `<body>` in layouts and `global-error.tsx` use `<Element tag="html">` and `<Element tag="body">`.
- No existing UI code yet, so no debt.

View File

@ -0,0 +1,21 @@
# 0003 Semantic tokens only in the Tailwind theme
Status: Proposed · Area: design · Date: 2026-10-04 · Decided by: agent
## Context
The Lumina Design System (tokens.json v5) defines primitives (indigo, saffron, slate, green, red, amber) and semantic roles (`surface`, `text-primary`, `action-primary`, `premium`, status shades). If primitives become utilities, components can bypass the roles and theming breaks.
## Decision
- In island `styles/theme.css`, keep three layers: primitives (`--indigo-600`) and semantic variables (`--surface`, `--text-primary`) as plain `:root` custom properties, and utilities only in `@theme inline`, each mapping `--color-<role>` to its semantic variable.
- Put the scales in `@theme`: type (`--text-body-md`), radii (`--radius-md`), shadows (`--shadow-1` to `--shadow-3`), spacing, containers, and the `desktop` and `wide` breakpoints.
- Name every semantic token exactly as the design system does. Remove Tailwind's default palette, fonts, type scale, radii, shadows, breakpoints, and containers (`--color-*: initial` and so on), so only Lumina tokens produce utilities.
- A value the design system uses that has no token gets a semantic token first, with a comment saying so; raw hex values never appear in components.
## Alternatives
- Primitives in `@theme` too: they become utilities (`bg-indigo-600`) and leak into components.
- Semantic values written straight into `@theme`: a theme can't switch them under its own selector.
## Consequences
- Utilities read as `bg-surface`, `text-text-primary`, `border-border-subtle`, `text-body-md`, `desktop:`; `bg-white`, `text-sm`, and `md:` don't exist.
- A theme overrides only the semantic `:root` block under its own selector. Shadows built from roles (`--shadow-focus-ring`, `--shadow-focus-field`) sit in `@theme inline`, so they follow the theme.
- Added beyond the design system: `--action-primary-pressed`, because the design system paints pressed states from primitives.

View File

@ -0,0 +1,20 @@
# 0004 Self-hosted Yekan Bakh variable font
Status: Superseded by 0007 · Area: design · Date: 2026-10-04 · Decided by: user
## Context
The Lumina Design System replaced Vazirmatn with Yekan Bakh, a licensed variable font (weights 100–1000) that ships with the app, plus Yekan Bakh FaNum, which draws Latin digits as Persian.
## Decision
- Serve both faces from island: `packages/island/src/fonts/yekan-bakh-vf.woff2` and `yekan-bakh-fa-num-vf.woff2`. Never load them from a public CDN.
- Each app loads them with `next/font/local` (`weight: '100 1000'`, `display: 'swap'`, a Tahoma fallback), with `variable: '--font-yekan-bakh'` and `'--font-yekan-bakh-fa-num'`, on `<html lang="fa" dir="rtl">`, never `<body>`: island's `--font-sans` and `--font-fanum` resolve on `:root`, so variables set lower fall back to Tahoma silently.
- Use `font-sans` everywhere and write Persian digits. Use `font-fanum` only where typed Latin digits can't be reformatted.
## Alternatives
- Vazirmatn from Google Fonts (the design system's first choice): a third-party request on the critical path.
- Static weight files: the design system ships only the variable files, and one file per weight means more requests.
## Consequences
- No third-party font request; one preloaded file covers every weight.
- The font is licensed: keep the repo private, and check that the licence covers web embedding in every app before release.
- Upgrading the font is a file swap in island.

View File

@ -0,0 +1,22 @@
# 0005 Island product components take their text as props
Status: Proposed · Area: design · Date: 2026-10-04 · Decided by: agent
## Context
The Lumina Design System draws product components (post, prediction, and subscription cards, creator stats, tier options, the support sheet) and a status vocabulary that pairs each status with one tone and icon. Both apps use them, and every one shows Persian copy, but island can't read the platform's translations.
## Decision
- Island holds Lumina's product components (`PostCard`, `PredictionCard`, `SubscriptionCard`, `CreatorStats`, `TierOption`, `SupportSheet`) and the status vocabulary: `StatusKey` maps to a tone and icon in `StatusBadge`'s `STATUS_STYLES`.
- They take every text as props: `children`, or one `labels` object per component that the platform fills from i18next. Island never imports i18next and never hard-codes copy, defaults included.
- Their data props are island's own types with the API's values (`PredictionData`, `SubscriptionStatus`). Island never imports from `platforms/` or a feature's entities; the platform's models map each `*Payload` to these props.
- Page composition (which sections a page has, and where each card goes) stays in the platform and app templates.
## Alternatives
- Product components as `platforms/market` organisms: island stays domain-free, but the design system splits across two projects, away from the atoms and tokens it builds on.
- i18next inside island: island would depend on the platform's locale files and i18n setup.
## Consequences
- Island is Lumina's design system, not a product-neutral one.
- A new status needs a `StatusKey` and a `STATUS_STYLES` entry in island, and its label in the platform's translations.
- The platform builds each `labels` object once per list, not once per card.
- Debt: `StepProgress` joins its `aria-valuetext` with a hard-coded «،».

View File

@ -0,0 +1,17 @@
# 0006 pnpm workspaces with package.json exports
Status: Proposed · Area: architecture · Date: 2026-10-04 · Decided by: agent
## Context
The workspace had no TypeScript or package wiring. The skill allows either package.json `exports` with workspaces or `tsconfig.base.json` path aliases.
## Decision
- Every non-app project is a pnpm workspace package (`pnpm-workspace.yaml`) named `@lumina/<name>` with subpath `exports` that point at its TypeScript sources (`@lumina/island/atoms/button`).
- Third-party dependencies stay in the root package.json (one version policy); each package lists only the `@lumina/*` packages it imports, as `workspace:*`. `tsconfig.base.json` holds the shared compiler options, and each project's `tsconfig.json` extends it.
## Alternatives
- Path aliases: CSS `@import` can't resolve them, so apps would import `island.css` by relative path.
## Consequences
- Apps import `@lumina/island/styles/island.css` by package name, and Node, Next.js, and TypeScript resolve the same subpaths.
- Each new package needs a package.json with `exports` and `sideEffects`.

View File

@ -0,0 +1,22 @@
# 0007 Yekan Bakh served from the app's public folder or a CDN
Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user · Supersedes: 0004
## Context
Lumina uses two variable faces from `packages/island/src/fonts/`: Yekan Bakh FaNum (`yekan-bakh-fa-num-vf.woff2`), which draws Latin digits as Persian, and Yekan Bakh (`yekan-bakh-vf.woff2`), which keeps Latin digits. 0004 loaded them with `next/font/local`, which serves them only from `/_next/static/media`. The user wants fonts served as plain files from each app's `public/` or from a CDN, put there by a plugin (0008).
## Decision
- `font-sans` is Yekan Bakh FaNum, for every UI text. Formatters output Latin digits, which the font draws as Persian, and insert `٬` and `٫` themselves, because the font doesn't map `,` and `.`.
- `font-latin` is Yekan Bakh, only for text that must show Latin digits: شبا and other codes banks print in Latin digits.
- Serve both as content-hashed files from the app's `public/fonts/`, or from a CDN under the same paths. Never use `next/font`, and never use a public third-party font CDN.
- Declare them with `@font-face` (`font-display: swap`, weight 100–950, width 62.5–150%) and a size-adjusted fallback face over local Arial. island's `FontFaces` primitive renders these rules from the URLs in island env.
- Preload only the FaNum face with `ReactDOM.preload(url, { as: 'font', type: 'font/woff2' })`, which adds `crossorigin`. The Latin face loads only where it's used.
- A CDN on another origin must send `Access-Control-Allow-Origin`, because browsers fetch `@font-face` URLs in CORS mode.
## Alternatives
- `next/font/local` with `assetPrefix` for the CDN (0004): it gives hashing, preload, and fallback metrics for free, but fonts can't live in `public/`.
## Consequences
- We now own what `next/font` did: hashed names and immutable `Cache-Control` (the asset plugin), the preload (`FontFaces`), and the fallback metrics (`FONT_FALLBACK` in island `constants.ts`, measured on Persian text).
- The font is licensed. "Never a public CDN" means only the company's own CDN. Confirm the licence covers web embedding from that CDN.
- Debt: both apps still load the faces with `next/font/local` in `src/styles/fonts.ts`, and `island.css` says so. `FontFaces`, island env, `FONT_FALLBACK`, and the asset plugin don't exist yet.

View File

@ -0,0 +1,27 @@
# 0008 Island asset plugin in each app's next.config
Status: Accepted · Area: architecture · Date: 2026-10-04 · Decided by: user
## Context
Fonts (0007) and the icon sprite live in island, but browsers load them from each app's `public/` or a CDN. Something must put them there in dev and in build.
## Decision
- Island ships one build-time plugin, `withIslandAssets` in `tools/asset-plugin` (it replaces the planned `icon-sprite-plugin`). Each app wraps its `next.config.ts` export with it.
- On `next dev` and `next build` (gated on `PHASE_DEVELOPMENT_SERVER` and `PHASE_PRODUCTION_BUILD`), it writes into the app's `public/`:
- the fonts, under content-hashed names;
- `symbol-defs.svg`, optimized with svgo, under a content-hashed name.
- It adds the hashed paths, prefixed with the app's `basePath`, to the app's `env` (`NEXT_PUBLIC_ISLAND_*`) and an immutable `Cache-Control` header per file. The app's `env/` reads them, and its bootstraps pass them to island's `setEnv` (`iconSpritePath`, `fontUrls`, with the app's CDN base prepended to the font paths).
- The writes are idempotent and atomic (write a temp file, then rename), because Next can evaluate the config more than once per command.
- The generated files are gitignored.
- It is build-time only: import it from `next.config.ts` as `@lumina/island/tools/asset-plugin`. island's root `index.ts` leaves it out, an exception to re-exporting every module.
- The sprite always loads from a root-relative, same-origin URL (`/icons/symbol-defs.<hash>.svg#icon-x`). `<use href>` is same-origin only in every engine, and CORS can't change that. To serve it through a CDN, put the CDN in front of the app's own domain, or add a `beforeFiles` rewrite. Never use an absolute CDN URL or `assetPrefix`.
## Alternatives
- An Nx target or `predev`/`prebuild` script: runs exactly once per command, but the user chose the next.config plugin.
- Inlining the sprite in the root layout: no request, but it adds weight to every HTML response.
## Consequences
- Every app gets fonts and icons by registering one plugin; island stays the single source.
- In dev, edits to island assets need a dev-server restart (Next watches only next.config), unless the plugin adds a watcher.
- Other phases, `next start` included, get the config back unchanged: the build already inlined `env` and wrote the headers into its routes manifest, so production needs neither island's sources nor svgo. `next typegen` and other build-phase commands still run it.
- Standalone and Docker builds must copy `public/`.

14
docs/decisions/README.md Normal file
View File

@ -0,0 +1,14 @@
# Decisions
## Design (DDR)
- 0002 Render every tag through island `Element`, flex layouts through `FlexBox`, grid layouts through `GridBox`; never native JSX tags or `flex`/`grid` classes, island included.
- 0007 Serve Yekan Bakh FaNum (`font-sans`, all UI text) and Yekan Bakh (`font-latin`, شبا and bank codes only) as hashed `@font-face` files from the app's `public/fonts/` or our CDN, never `next/font`.
## Architecture (ADR)
- 0001 Share one platform, `platforms/market`, between `apps/bull` and `apps/bear`; tag all three `scope:market`.
- 0008 Register island's asset plugin in each app's `next.config`; on dev and build it writes hashed fonts and the svgo sprite into `public/`; the sprite stays same-origin.
## Proposed
- 0003 design: Only semantic tokens, named as in the Lumina Design System, produce Tailwind utilities (`@theme inline`); primitives stay plain `:root` variables and Tailwind's defaults are removed.
- 0005 design: Island holds Lumina's product components and status-to-tone map; they take every text as props (`children` or `labels`) and never import i18next or platform code.
- 0006 architecture: Make every non-app project a pnpm workspace package `@lumina/<name>` with subpath `exports`; third-party dependencies stay in the root package.json.

View File

@ -1,426 +0,0 @@
# Design Brief — Lumina (لومینا) · Verified Financial Creator Platform · MVP Phase 0
> Sources: PRD MVP Phase 0 v3.1 + ClickUp stories (23 tasks) + back-end codebase (`trading-platform` @ `3553719`).
> **Precedence:** ClickUp story > PRD for *behaviour*. The back end is used for *data shapes* and wherever a story is silent. Where a story and the back end conflict, **design to the story** and treat the conflict as an open decision (§9).
> Full acceptance criteria and exact Farsi copy for each story are in the `round-*.md` files. Attach the matching round file with this brief.
---
## 1. Product in one paragraph
Lumina is a platform for Iranian financial creators (analysts, signal providers) and the investors who follow them. Creators get a verified professional profile, a channel with free and premium posts, invite-only paid subscriptions, and **structured, immutable predictions** that the system tracks automatically. Investors can judge a creator by a **verifiable track record** before paying.
The core positioning is **performance proof over social proof**. The product must feel credible and professional, not like another Telegram channel. Because of this, follower counts are never shown publicly, and prediction outcomes are never hidden behind the paywall.
Phase 0 is a **closed beta**: 5–10 hand-picked creators and about 50 paying subscribers.
---
## 2. Platform and locale (confirmed)
| Topic | Decision |
|---|---|
| Stack | NX monorepo + Next.js, one responsive web app for **mobile and desktop** |
| Priority | **Mobile-first** for investor and creator surfaces; **desktop-first** for the admin panel (mobile = simplified card list) |
| Direction | **RTL** throughout. LTR exceptions: شبا field, URLs, usernames, tickers, signed amounts (§4.4) |
| Language | Persian. Persian digits (۰–۹) in UI, `٬` as thousands separator |
| Currency | تومان, whole numbers only |
| Dates | Shamsi (Jalali), e.g. `۱۵ خرداد ۱۴۰۴، ساعت ۱۴:۳۰`. Relative for recent items: همین الان · ۵ دقیقه پیش · ۲ ساعت پیش · دیروز. Timezone Asia/Tehran |
| Auth | Iranian mobile number (09XXXXXXXXX) + 5-digit SMS OTP. One entry screen for login and registration. Investor and creator accounts are separate (one number = one role) |
| Notifications | SMS + in-app only (push is deferred to Phase 1) |
| Payment | ZarinPal only |
| URLs | Channel `lumina.ir/@{username}`, post `lumina.ir/@{username}/posts/{post_id}`, finance `lumina.ir/dashboard/finance` |
---
## 3. Navigation and information architecture
### 3.1 Investor
- **Top bar:** notification bell with unread badge (99+). It opens a slide-in panel from the right on mobile.
- **Bottom nav:** خانه (feed + creator search) · داشبورد
- **داشبورد sub-sections:** اشتراک‌ها · تراکنش‌ها · دنبال‌شده‌ها
- **Reached from links:** creator channel, standalone post, checkout, track record page
- **Logged-out visitors** can browse channels and free posts via shared links. Every gated action leads to one CTA, **ورود/ثبت‌نام**, and the user returns to the same page after auth.
### 3.2 Creator
- **Top bar:** avatar opens **اطلاعات کاربری** (profile edit + verification status, C3). The notification bell is assumed to be shared with investors.
- **Bottom nav:** داشبورد · کانال, plus a center **FAB `+ انتشار`** that opens a mini menu with **پست جدید** and **پیشبینی جدید**.
- **داشبورد contents:** overview stats (C9, not yet specced) · **قیمت‌گذاری اشتراک** (C7) · **مالی** (C19 + C20).
- **First-run onboarding** (C1 then C2) is mandatory and can't be exited. There is no back button, and the Android back gesture is suppressed.
### 3.3 Admin (desktop)
- **Sidebar:** احراز هویت کریتورها (with a red pending-count badge) · مدیریت کریتورها · then the other sections from PRD Epic 3/11 (not yet specced).
---
## 4. Design system ("Stripe-inspired")
> Only the tokens referenced in the stories are listed here. **If you have the full design-system file, attach it.** It fills in the values marked "?".
### 4.1 Tokens
| Token | Value | Used for |
|---|---|---|
| `colors.primary` | `#533afd` | Primary CTA, verified, active, success, selected |
| `colors.primary-deep` | ? | Text on soft tags |
| `colors.primary-bg-subdued-hover` | `#b9b9f9` | Soft tag background, unread notification border |
| `colors.brand-dark-900` | `#1c1e54` | **پریمیوم** badge, primary financial figure |
| `colors.ink` | ? | Body text |
| `colors.ink-mute` | `#64748d` | Secondary text, pending, neutral and expired badges, icons |
| `colors.canvas` | `#ffffff` | Cards, sheets |
| `colors.canvas-soft` | `#f6f9fc` | Page backgrounds, locked placeholders, highlighted blocks |
| `colors.hairline` / `hairline-input` | ? | Borders, dividers, input borders |
| `colors.ruby` | `#ea2261` | Errors, critical/urgent, destructive, rejected, suspended, negative balance, **and the تخفیف badge** (its only affirmative use) |
| `colors.warning` | `#f59e0b` | Time-sensitive warnings, pending payment, non-blocking cautions, preview-mode banner |
| Typography | `heading-md`, `heading-sm`, `body-md`, `caption`, `micro` | Font **Yekan Bakh** for all Farsi |
| Radius | `rounded.md`, `rounded.lg`, `rounded.xl`, pill | |
| Shadow | Level 1 (cards), Level 2 (menus, popovers, sheets) | |
### 4.2 Components
`button-primary-pill` · `button-secondary` (outline, primary text; **ruby variant** for destructive admin actions) · `pill-tag-soft` · `card-feature-light` (canvas, hairline border, rounded.lg, Level 1) · `text-input` (focus border = primary) · `link-on-light` · snackbar/toast · modal · bottom sheet (mobile) / popover or side panel (desktop) · full-screen image lightbox (black background, swipe, pinch-zoom, `۱ / ۳` counter) · status badge · countdown.
### 4.3 Global rules
- **Tabular figures** (`font-feature-settings: "tnum"`) on every number: prices, dates, OTP, stats, reference numbers, countdowns. This is non-negotiable and part of the brand's financial look.
- **Frozen controls** stay visible at `opacity: 0.4` with `cursor: not-allowed`, and show an explanatory tooltip or message on tap. Controls are never hidden just because they're unavailable.
- **Dimmed or unavailable items** (for example a suspended creator) use `opacity: 0.5` with a lock icon. Any action that still works inside the item renders at full opacity.
- **Touch targets** are at least 44×44px.
- **Desktop column widths:** forms 560px · content and post pages 640px · checkout 480px.
- **Data safety:** on any network failure the entered data is kept. Errors appear inline under fields, and an error banner appears at the top for submit failures.
### 4.4 Numbers and RTL
- Signed amounts are wrapped in an LTR isolate, so the minus sign stays left of the digits: `−۱۲۰٬۰۰۰ تومان`. The word تومان sits outside the isolate.
- شبا renders LTR in groups of four: `IR62 0120 0000 0010 1234 5678 90`.
---
## 5. Cross-cutting patterns
### 5.1 Viewer states (channel, post page, feed)
| Viewer | Content | Follow | Subscribe |
|---|---|---|---|
| Logged-out | Free posts in full, premium as locked teasers | Shown; leads to auth | Shown; leads to auth |
| Logged in, not following | Same | دنبال کردن | اشتراک |
| Following, not subscribed | Same | دنبال نکردن | اشتراک |
| Waitlisted | Same | As applicable | **اشتراک stays live**, with a quiet note underneath and a لغو اطلاع‌رسانی link |
| Payment pending | Same | As applicable | Frozen indicator «پرداخت در حال بررسی» with a clock icon |
| Active subscriber | Everything unlocked, پریمیوم badge still shown | **Frozen** (can't unfollow while subscribed) | Replaced by the indicator «مشترک هستید ✓» |
| Creator (own channel) | Everything, plus share/edit/delete | Hidden | Hidden |
| Creator in "view as visitor" preview | Locked teaser, with an amber banner and «خروج از پیش‌نمایش» | n/a | n/a |
### 5.2 Locked premium post (one shared component everywhere: channel, post page, feed)
- The header row (avatar, username, timestamp, **پریمیوم** badge) is always visible.
- **Text:** only the first 2 lines are shown, fading into the canvas color with a centered lock icon. Two lines is a hard limit, so no analysis leaks.
- **Images:** never shown and never blurred. A generic lock placeholder on canvas-soft replaces them, with an optional «۳ تصویر» count badge.
- **Premium prediction:** asset, direction, entry, targets, stop loss and horizon are all hidden. Only the card frame, the پریمیوم badge and the status remain.
- **Data note:** the API sends `captionPreview` (first 140 characters) and `mediaPreview` with a `blurHash`. **Clamp the preview visually to 2 lines and never render the blurHash.** The rule against blurred images comes first.
- Below the locked content: one message and one CTA, depending on auth state. Logged-out users see «ورود/ثبت‌نام». Logged-in users see «اشتراک در کانال». The two are never shown together.
- There is no "you used to have access" variant after a subscription lapses.
### 5.3 Creator verification gating
- **States:** در انتظار احراز هویت (ink-mute, clock icon) · تأییدشده ✓ (primary, check icon) · رد شده (ruby, warning icon). Suspended is a separate admin state that can coexist with these.
- **For a creator who isn't yet Verified:**
- A persistent, non-dismissible banner sits on the کانال tab. It's informational when Pending. When Rejected, it shows the reason and is tappable to C3.
- A compact badge shows on داشبورد.
- The FAB and the channel share icon are frozen.
- Pricing and profile can still be edited.
- Payout details (شبا) are locked.
- **Identity fields** lock at first submission and reopen only on rejection. The username can never be changed. The national ID card image field is always empty when the form opens.
### 5.4 Time-based states
- **Post edit window:** 15 minutes after publishing. After that the edit icon is frozen and shows a tooltip. Edited posts show a «ویرایش‌شده» label in micro type. Posts can be deleted at any time; predictions can't (per the PRD).
- **Subscription remaining time:**
| Remaining | Label | Color | Warning under card |
|---|---|---|---|
| More than 7 days | {n} روز مانده | ink-mute | — |
| 4–7 days | {n} روز مانده | warning | — |
| 3 days or less | کمتر از {n} روز مانده | ruby | Yes |
- **Promotion countdown:** a plain date when more than 48 hours remain, a live «{n} ساعت باقی مانده» in warning color at 48 hours or less, and nothing at all for an indefinite promotion. There is no fake urgency.
- **OTP:** a 2-minute countdown that turns ruby in the last 30 seconds. Resend is available only after expiry. After 3 failed attempts the user is blocked for 10 minutes.
### 5.5 Status vocabulary
| Domain | States (Farsi label · color) |
|---|---|
| Subscription | فعال · primary — منقضی‌شده · ink-mute (neutral, not an error) — suspended creator: card dimmed + «درخواست بازگشت وجه» action — refund requested: «درخواست بازگشت وجه در حال بررسی» |
| Transaction | موفق · primary — ناموفق · ruby (ruby start border on row) — در حال بررسی · warning (warning start border, pinned to top) |
| Transaction type | اشتراک جدید · تمدید اشتراک · فعال‌سازی مجدد |
| Tier | ماهانه · سه‌ماهه · شش‌ماهه · سالانه |
| Payout | در حال انجام · ink-mute pill — انجام شده · no pill — لغو شده · ruby pill + struck-through amount |
| Ledger entry | درآمد اشتراک (+) · واریز به حساب (−) · کسر بازگشت وجه (−) · اصلاحیه (±). Amounts in ink color; the sign carries the meaning |
| Creator account (admin) | Active · primary + check — Suspended · ruby + ban icon, row tinted `rgba(234,34,97,0.05)` |
### 5.6 Prediction card (no ClickUp story yet; fields from the back end, rules from the PRD)
**Fields as the API returns them:**
| Field | Shape | Display |
|---|---|---|
| `symbol` | free text, uppercased (`XAUUSD`, `BTCUSDT`, `TEDPIX`) | LTR, prominent |
| `market` | one of the market keys (§10.2) | soft tag with its Farsi label |
| `direction` | `long` / `short` | Labels خرید / فروش (Long / Short) with an arrow icon. Never rely on color alone |
| `entryPrice` | number | tabular |
| `targetPrices[]` | **1 or more** numbers | Design for 1–3 targets (T1, T2, T3) |
| `stopLoss` | number, optional | Show when present; hide the row when absent |
| `horizon` | free label, for example `2w`, `45d` | Shown as a label. Show time remaining only when `expiresAt` exists |
| `caption` | text | Acts as the creator's note / rationale |
| `publishedAt` | system timestamp | **Prominent**; it is the trust signal |
| `status` | `open` / `closed` | |
| `outcome` | `win` / `loss` / **`breakeven`** | Three closed states |
| `closedPrice`, `closedAt` | on close | Show with the outcome |
| ROI | computed: (closed − entry) / entry, reversed for short | Signed percent, LTR-isolated |
- **States to design:** open · closed-win · closed-loss · closed-breakeven · premium-locked (§5.2) · owner view (with a «بستن پیشبینی» action that asks for the closing price, since closing is currently done by the creator).
- **Immutability:** prediction fields can't be edited after publishing. Show a lock cue and the timestamp. The PRD's 15-minute window and edit history don't exist yet (§9).
- **Variants:** compact (feed, channel) and expanded (post page). It also appears on the track record page, the creator dashboard and admin screens.
- **No market snapshot image for now:** a prediction post can't carry media in the API.
**Creator stats block** (U6, channel header):
- **Metrics:** نرخ موفقیت (`winRate`, already a percent such as `62.86` → `۶۲٫۹٪`) · کل پیشبینی‌ها · پیشبینی‌های فعال · بازدهی (`avgRoiPercent`) · روند دقت · and a CTA «مشاهده کارنامه کامل».
- **روند دقت is the last 10 outcomes** (`["win","loss","win",…]`). Design it as a row of 10 small outcome markers (win / loss / breakeven), not a line chart. A wins / losses / breakeven split is also available.
- **When the block shows:** the U6 rule is all or nothing. It's absent until the activation threshold is met or when the creator hides it. No zeros, no placeholder.
---
## 6. Screen inventory
Status key: ✅ fully specced in ClickUp · 📄 PRD only (design at lower fidelity, expect changes).
### 6.1 Auth and onboarding
| # | Screen | Story | Key states |
|---|---|---|---|
| 1 | ورود یا ثبت‌نام (mobile number) | U1, C1 | Invalid format · number belongs to the other role · network error |
| 2 | OTP | U1, C1 | Countdown · wrong code · expired · blocked 10 min (full screen) · resend |
| 3 | Investor تکمیل پروفایل (first and last name in Persian, username) | U1 | Live username check (available ✓, taken, invalid) · immutability note · step indicator without a total count |
| 4 | Login success modal / suspended-account screen | U1, A2 | |
| 5 | Creator KYC form (username, first and last name, national ID, ID card image) | C1 | Field validation · upload errors · no exit |
| 6 | Creator تکمیل پروفایل (bio, avatar crop, links, market tags, T&C) | C2 | Toast on load · 8-link limit (frozen add button) · drag reorder · quick-add (Telegram, Instagram, X, YouTube) · success screen «پروفایل ذخیره شد» |
| 7 | اطلاعات کاربری (creator profile edit) | C3 | Verified/Pending (identity locked) · Rejected (banner + editable identity + «ارسال مجدد اطلاعات هویتی») · two independent save actions · unsaved-changes dialog |
### 6.2 Investor
| # | Screen | Story | Key states |
|---|---|---|---|
| 8 | **Creator channel** `/@username` (header + post list) | U6, C4 §12, U8 | All viewer states (§5.1) · stats present or absent · empty channel · suspended channel |
| 9 | **Standalone post page** | C4b | Free · locked · subscriber · owner · visitor preview · deleted (404) · channel suspended · desktop share popover / mobile native share |
| 10 | خانه feed + creator search | 📄 Epic 7, U7 | Empty state «follow someone» + CTA · locked cards inline in chronological order |
| 11 | **Checkout** «خرید اشتراک» (one screen) | U9 | Tier cards with total, per-month and strike-through · promotion badge and countdown · referral code (valid ✓ / invalid) · frozen CTA · no code · price-changed modal · waitlist offer modal · already-waitlisted modal · pay CTA pinned to the bottom · link to «شرایط اشتراک» |
| 12 | Payment return | U10 | Non-dismissible «در حال تأیید پرداخت...» · success toast on the channel · pending · failure (back to checkout with selections kept) |
| 13 | شرایط اشتراک (terms page) | U9 comment | Static long-form text |
| 14 | داشبورد → اشتراک‌ها | U2, U3, A2 | Summary line «{n} اشتراک فعال» · active cards sorted by soonest expiry · expiry escalation · expired section · suspended-creator card with refund action · empty state |
| 15 | Renew / reactivate bottom sheet | U3 | Tier selector · date preview block (renew: from current expiry; reactivate: from today) · price-changed note · promotion · success checkmark animation · failure |
| 16 | داشبورد → تراکنش‌ها + detail sheet | U4 | Filter chips (همه · موفق · ناموفق · در حال بررسی) · pending rows pinned · tap-to-copy reference number · support CTA · pagination of 20 |
| 17 | داشبورد → دنبال‌شده‌ها | U8 | Unfollow with confirmation · frozen unfollow for subscribed creators · suspended row · empty state |
| 18 | Notification center | U5 | Unread (start border) / read · CTA chips · relative timestamps · empty state |
| 19 | Track record page | 📄 Epic 10 | Public · not yet available · hidden |
| 20 | Refund request + status | 📄 U21 (only the suspension case is specced, in A2 §6) | |
### 6.3 Creator
| # | Screen | Story | Key states |
|---|---|---|---|
| 21 | کانال tab (own channel) | C4, C5 | Verification banner · post cards with share/edit/delete (+ preview icon on premium posts) · empty state |
| 22 | FAB + mini menu | C4 | Frozen when not Verified, with a blocking message per state |
| 23 | Post composer (full-screen modal) | C4, C5 | Free/premium toggle · 2,000-character counter · up to 4 images (thumbnail strip, frozen add button) · empty error · discard dialog · publishing state · failed image |
| 24 | Prediction composer | 📄 C12–C15 | Structured form · free/premium · preview · warning that it locks after 15 min |
| 25 | Share channel | C6 | Mobile bottom sheet / desktop popover · editable caption (150 characters, default «من را در لومینا دنبال کن 👇») · copy link |
| 26 | داشبورد overview | 📄 C9–C11, C16 | Subscribers · revenue (label gross or net) · prediction summary · open predictions · compact verification badge |
| 27 | **قیمت‌گذاری اشتراک** | C7 | 4 tier cards (monthly always on) · per-month equivalent · floors · suggestions · validation that per-month cost can't increase with duration · promotion section per tier · cooldown lock (standing prices dimmed, promotions still live) · confirmation dialog |
| 28 | **مالی** — schedule notice · balance · next payout · شبا · ledger | C19, C20 | See §7 |
### 6.4 Admin (desktop-first)
| # | Screen | Story |
|---|---|---|
| 29 | Verification queue (tabs: در انتظار بررسی · تأییدشده · رد شده, search, sort, pagination of 20) | A1 |
| 30 | Verification detail (ID image lightbox and download, previous/next request, submission history, audit log, approve, reject with reason templates) | A1 |
| 31 | Creator management list and detail (suspend dialog showing subscriber impact, reinstate dialog showing extension summary, audit log) | A2 |
| 32 | Users · subscriptions · transactions · reconciliation · refunds · payout run (amount + receipt upload) · predictions moderation · feature flags | 📄 Epic 3/11 |
---
## 7. Creator finance model (from C19/C20, which replace the PRD's Epic 11 numbers)
- **Payouts are weekly on Thursday** (`{payout_day}` is configurable). A static notice explains bank cycles and holidays.
- **There is no minimum payout threshold, and income is available immediately** on payment confirmation. There is no 7-day pending state.
- **Balance summary:**
- **قابل واریز** is the primary figure in brand-dark-900.
- **مجموع واریزشده** is a secondary line.
- **در حال واریز** appears only while a transfer is in flight.
- A negative balance shows in ruby with an explanation underneath.
- **Next payout line** has several states: date · «register شبا first» · «nothing to pay» · suspended/frozen.
- **شبا:**
- The field is LTR with a fixed `IR` prefix, auto-grouped into fours, and normalizes Persian/Arabic digits.
- The bank name is detected and shown underneath.
- It's checked with a mod-97 checksum.
- A responsibility checkbox is mandatory.
- A read-back confirmation dialog appears before saving.
- A duplicate شبا shows an amber warning; it doesn't block.
- **No admin approval.** Every edit sends an SMS alert.
- Saved state shows the شبا, bank and last-updated date, with an edit action.
- **Ledger «گردش حساب»:**
- Tabs همه · واریزها, 20 rows plus «نمایش بیشتر».
- Two-line rows.
- A detail view opens as a bottom sheet on mobile and a side panel on desktop. Income detail shows price → discount → amount paid → commission → «سهم شما». Payout detail shows a masked شبا and the receipt (view/download).
- **Subscriber privacy:** creators only ever see `@username`. Phone numbers and real names are never shown.
---
## 8. Sample data (for realistic mockups)
Keys follow the real API (§10). Raw dates are ISO UTC and money is Toman where shown. Display everything per §2 (Shamsi, Persian digits, `٬`).
```json
{
"creator": {
"username": "ali_gold",
"displayName": "تحلیل‌گر طلا",
"bio": "تحلیل تکنیکال طلا و دلار، ۸ سال سابقه",
"markets": ["gold", "forex", "crypto"],
"socialLinks": [{ "label": "کانال تلگرام", "url": "https://t.me/ali_gold" }, { "label": "اینستاگرام", "url": "https://instagram.com/ali_gold" }],
"stats": { "totalPredictions": 42, "activePredictions": 7, "pastPredictions": 35, "wins": 22, "losses": 12, "breakeven": 1,
"winRate": 62.86, "avgRoiPercent": 8.7,
"accuracyTrend": ["win", "loss", "win", "win", "breakeven", "win", "loss", "win", "win", "win"] },
"tiers": [
{ "billingPeriod": "monthly", "priceToman": 490000, "perMonthToman": 490000 },
{ "billingPeriod": "quarterly", "priceToman": 1161000, "standingPriceToman": 1290000, "perMonthToman": 387000,
"promotion": { "percent": 10, "endsAt": "2026-10-12T20:30:00Z" } },
{ "billingPeriod": "semi_annual", "priceToman": 2352000, "perMonthToman": 392000 },
{ "billingPeriod": "yearly", "priceToman": 4116000, "perMonthToman": 343000 }
]
},
"posts": [
{ "type": "text", "accessLevel": "free", "publishedAt": "2026-10-01T11:00:00Z", "caption": "دلار در محدوده حمایتی؛ منتظر تأیید باشید." },
{ "type": "image", "accessLevel": "premium", "locked": true, "captionPreview": "تحلیل هفتگی انس جهانی و دلار آزاد؛ سطوح کلیدی…", "mediaCount": 3 },
{ "type": "prediction", "accessLevel": "free", "caption": "شکست مقاومت ۲۴۰۰ دلار",
"prediction": { "symbol": "XAUUSD", "market": "gold", "direction": "long", "entryPrice": 2310, "targetPrices": [2400, 2450],
"stopLoss": 2280, "horizon": "2w", "status": "closed", "outcome": "win", "closedPrice": 2402 } },
{ "type": "prediction", "accessLevel": "free",
"prediction": { "symbol": "BTCUSDT", "market": "crypto", "direction": "short", "entryPrice": 68000, "targetPrices": [61000],
"horizon": "45d", "status": "open" } },
{ "type": "prediction", "accessLevel": "premium", "locked": true, "prediction": { "status": "open" } }
],
"investorSubscriptions": [
{ "creator": "ali_gold", "tier": "quarterly", "status": "active", "daysRemaining": 2 },
{ "creator": "gold_signal", "tier": "monthly", "status": "active", "daysRemaining": 5 },
{ "creator": "crypto_mina", "tier": "monthly", "status": "active", "creatorSuspended": true },
{ "creator": "bourse_pro", "tier": "yearly", "status": "expired", "expiryDate": "2026-09-21T08:00:00Z" }
],
"transactions": [
{ "type": "subscribe", "tier": "quarterly", "toman": 1161000, "status": "pending", "reference": "201234567" },
{ "type": "renew", "tier": "monthly", "toman": 490000, "status": "successful", "reference": "201230011" },
{ "type": "subscribe", "tier": "yearly", "toman": 4116000, "status": "failed", "reference": null }
],
"creatorFinance (C20 target shape; no API yet)": {
"available": 3420000, "inTransfer": 1250000, "totalPaidOut": 14300000,
"nextPayout": "پنجشنبه ۱۶ مهر ۱۴۰۵",
"sheba": "IR620120000000101234567890", "bank": "بانک ملت",
"ledger": [
{ "type": "income", "amount": 203150, "subscriber": "@reza_inv", "tier": "quarterly", "date": "2026-09-27" },
{ "type": "payout", "amount": -1250000, "status": "in_progress", "date": "2026-10-01" },
{ "type": "refund_deduction", "amount": -600000, "date": "2026-09-30" },
{ "type": "payout", "amount": -900000, "status": "cancelled", "date": "2026-09-19" }
]
}
}
```
---
## 9. Decisions and open points
**Story decisions that override the PRD**
- Subscriptions are **invite-only**. A referral code from the creator is required, and capacity is limited. When capacity is full, users with a valid code can join a waitlist (a notification subscription with opt-out). Following stays free.
- Creator payouts are weekly, with no threshold, no clearing period and no شبا approval (see §7).
- There is no public follower count anywhere.
- Prediction stats show in full or not at all.
- Pricing uses 4 fixed tiers with per-month floors (ماهانه ۲۹۹٬۰۰۰ · سه‌ماهه ۲۶۵٬۰۰۰ · شش‌ماهه ۲۳۰٬۰۰۰ · سالانه ۱۹۹٬۰۰۰ per month), promotions, and a 7-day cooldown.
- Suspension is a full blackout. Subscribers choose between a pro-rated refund and extension by the paused time.
**Inconsistencies to resolve (design with the first option until told otherwise)**
1. **Brand name:** «لومینا / lumina.ir» appears in C4, C6, C19 and C20, while other stories use the placeholder `[نام پلتفرم]`. Use **Lumina**.
2. **Pending label:** C1 uses «در انتظار تأیید», while C3 and the PRD use «در انتظار احراز هویت». Use the latter.
3. **Thousands separator:** C7 examples use `,`, while C20 specifies `٬`. Use `٬`.
4. **Push notifications:** C20 §8.1 mentions push, but push is deferred to Phase 1. Design for SMS + in-app.
5. **Prediction outcome:** the back end has `win` / `loss` / `breakeven`, closed by the creator. Design those three states.
**Story vs back-end conflicts (design to the story; the team must decide)**
| # | Topic | Story | Back end today |
|---|---|---|---|
| 6 | OTP | 5 digits, 2-minute expiry | 6 digits, 10-minute expiry, 60 s resend cooldown |
| 7 | National ID images | Front only | Front **and back** required |
| 8 | Public name | `@username` only (no nickname in C2) | Also a required `displayName` (max 80) |
| 9 | Post edit window | 15 minutes, then frozen; «ویرایش‌شده» label | Caption/media/access editable forever; no edited flag; predictions frozen at publish |
| 10 | Drafts | None (local draft only) | Server drafts, soft delete, purge |
| 11 | Locked prediction teaser | Everything hidden | Leaks `symbol` + `direction` |
| 12 | Locked image teaser | Never blurred | Sends `blurHash` |
| 13 | Follower count | Never public | Public endpoint exists |
| 14 | Promotions | Apply to new, renew and reactivate | New subscriptions only |
| 15 | Pending payment | Stays «در حال بررسی» until resolved | Auto-expires after 30 min and shows as **failed** |
| 16 | Creator profile field | — | Extra `tradingStyle` (not in stories, don't design it) |
| 17 | Brand | Lumina | `OnlyT` in SMS and config |
---
## 10. Back-end data model (design-relevant summary)
> The full analysis is in `backend-context.md` (for engineering). This section only keeps what changes how a screen looks or what content it shows.
### 10.1 Formats
- **Money:** stored in Rial, but every response has a Toman field (`toman`, `priceToman`, `perMonthToman`). The UI always shows Toman.
- **Dates:** ISO UTC. Server-made Farsi labels look like `۱۴۰۵/۳/۶` (no zero padding, no time). Designs use the §2 format; the front end formats dates itself.
- **Percentages:** `winRate` and `avgRoiPercent` are already percentages (`62.86`), not fractions.
- **Server copy:** many subscription, pricing, checkout and notification responses carry ready Farsi strings (`*Fa`) and color hints that match the tokens in §4.1. They agree with the story copy, so the round files stay the copy source.
### 10.2 Enums (exact keys)
| Enum | Keys |
|---|---|
| Market | `crypto` کریپتو · `gold` طلا و سکه · `equities` بورس · `forex` فارکس · `funds` صندوق‌های سرمایه‌گذاری · `real_estate` مسکن · `automotive` خودرو · `USDT` تتر |
| Billing period | `monthly` · `quarterly` · `semi_annual` · `yearly` |
| Post | type `text` / `image` / `prediction` · access `free` / `premium` |
| Prediction | status `open` / `closed` · outcome `win` / `loss` / `breakeven` · direction `long` / `short` |
| Subscription | `active` / `expired`. "Expiring" is computed: amber at 4–7 days, ruby with warning at ≤3 days |
| Payment (UI) | `successful` / `pending` / `failed` · type `subscribe` / `renew` / `reactivate` |
| Checkout CTA | `subscribe` · `active` (مشترک هستید ✓) · `pending_review` (frozen) · `own` (hidden) |
| Payment return | `processing` → `granted` (land on channel) / `pending_review` / `failed` (back to checkout) |
| Verification | `pending` / `approved` / `rejected` (+ account `suspended`) |
### 10.3 Limits that affect layouts
- Bio 300 characters, max 3 line breaks.
- Links: max 8, label max 30 characters.
- Display name max 80 characters (if used, §9 #8).
- Avatar and ID images: JPG/PNG, max 5 MB.
- Post text: the story limit of 2,000 applies (the API accepts 5,000). Max 4 images per post (the API has no limit).
- Pagination: 20 per page for feed, posts and transactions. Notifications: latest 100, no paging.
### 10.4 Back-end support by screen
Designs still follow the stories for every screen. This list only shows what can be built against real data now.
| Supported | Not implemented yet |
|---|---|
| Auth, investor registration, creator registration + profile setup/edit | Verification approve/reject, resubmit, rejection reason (creators stay `pending`) |
| Channel, posts, post page, follow/unfollow (frozen while subscribed, auto-follow on subscribe) | Creator search · track record gate/history/hide · prediction auto-tracking (manual close only) |
| Pricing (floors, suggestions, promotions, cooldown, validation) | Earnings ledger, شبا, payouts, receipts, commission (C19/C20) |
| Checkout with invite code, waitlist, price-change guard, ZarinPal return | Refunds · reconciliation · subscription cancel |
| اشتراک‌ها, renew/reactivate, تراکنش‌ها, notification center | Whole admin panel · audit log · feature flags |
| Creator dashboard: active subscribers, gross revenue, recent payments | Net revenue (only gross exists, so label it «درآمد ناخالص») |
---
## 11. Design rounds
| Round | File | Goal |
|---|---|---|
| 1 | `round-1-channel-and-posts.md` | **Visual language.** Channel header, post card (free / locked / subscriber / owner), standalone post page, composer, share, follow, prediction card (from §5.6) |
| 2 | `round-2-auth-and-onboarding.md` | Entry, OTP, investor profile, creator KYC, profile setup, اطلاعات کاربری |
| 3 | `round-3-investor-subscriptions.md` | Checkout, payment return, waitlist, اشتراک‌ها, renew/reactivate, تراکنش‌ها, notifications |
| 4 | `round-4-creator-money.md` | Pricing, مالی (شبا + ledger) |
| 5 | `round-5-admin.md` | Verification queue and detail, suspend/reinstate |
| 6 | (PRD only) | Feed + search, track record, creator dashboard overview, prediction composer, other admin screens |
**For each round:** mobile (390px) and desktop, RTL, real Farsi copy from the stories, and every listed state (loading, empty, error, success, frozen, edge).

View File

@ -1,944 +0,0 @@
# Round 1 — Channel, posts & visual language
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Establish the visual language that every later round reuses.
## Deliver in this round
- Creator channel page `/@username`: header (U6) with all viewer states (brief §5.1), stats block present and absent, empty channel, suspended channel
- Post card: free text, free image (1 and 3 images), locked premium, unlocked premium (subscriber), owner view with actions, edit window active vs frozen, «ویرایش‌شده» label
- Prediction card (brief §5.6, no story yet): compact and expanded, all states including premium-locked
- Standalone post page: free, locked (logged-out and logged-in), owner, visitor-preview banner, deleted, suspended
- Creator کانال tab: Pending and Rejected banners, FAB + mini menu (live and frozen)
- Post composer (full-screen modal): free/premium toggle, images, counter, errors, discard dialog
- Share: creator caption sheet (mobile) and popover (desktop); plain share for visitors
- Image lightbox
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **C4** — Creator Post Publishing (Free Content) _(ClickUp status: ready for development)_
- **C4b** — Standalone Post Page _(ClickUp status: ready for development)_
- **C5** — Premium Post Publishing _(ClickUp status: ready for development)_
- **U6** — Investor: Creator Profile Header _(ClickUp status: ready for development)_
- **U7** — Investor: Premium Content Lock Indication (Cross-Surface) _(ClickUp status: ready for development)_
- **U8** — Investor: Follow a Creator _(ClickUp status: ready for development)_
- **C6** — Creator Channel Sharing (External Promotion) _(ClickUp status: ready for development)_
---
## C4 — Creator Post Publishing (Free Content)
C4 — Creator Post Publishing (Free Content)
Story:
As a creator, I want to publish free text and image posts to my channel so that I can attract new followers with publicly visible content.
Note: This story covers free text and image posts only. Premium posts are covered in C5. Prediction posts are covered in C8. Posts in this story are always publicly visible to all users — logged in or not.
⚠️ Forward dependency note: The creator channel public URL structure (lumina.ir/@{username}) and post URL structure (lumina.ir/@{username}/posts/{post_id}) are introduced in this story. Standalone post page behaviour is covered in C4b.
⚠️ Phase 1 backlog item: Text truncation on long posts is intentionally not implemented in Phase 0 — full post text is always shown in every context.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
The post composer is accessed via the FAB (Floating Action Button) labeled + انتشار in the bottom navigation bar — visible to creators from all tabs at all times
Tapping + انتشار expands a mini menu with two options:
پست جدید → opens the post composer (this story)
پیشبینی جدید → opens the prediction composer (C8)
The creator's published posts are managed from the کانال tab in the bottom navigation bar — posts appear chronologically and share/edit/delete actions are accessible inline on each post card
Only Verified creators can publish posts
Edge Cases:
If a creator's account is Pending Verification, the FAB is visible but frozen (opacity: 0.4, cursor: not-allowed) — tapping it shows a context-appropriate blocking message
If a creator's account is Rejected, the FAB is also frozen — tapping it shows a message directing the creator to resubmit their identity verification via C3
If a creator's account is Suspended, the FAB is also frozen — tapping it shows a different context-appropriate blocking message. (In practice, per A2, a Suspended creator cannot log in at all, so this state is largely theoretical within the app itself — kept here for completeness/defense-in-depth)
Tapping anywhere outside the expanded FAB mini menu collapses it without any action
Error States:
Pending verification: blocking message shown on FAB tap
Rejected: blocking message shown on FAB tap
Suspended: blocking message shown on FAB tap
Farsi copy:
FAB label: + انتشار
FAB menu option 1: پست جدید
FAB menu option 2: پیشبینی جدید
Pending verification blocking message: برای انتشار پست، ابتدا باید احراز هویت شما تأیید شود.
Rejected blocking message: احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.
Suspended blocking message: حساب شما تعلیق شده است. امکان انتشار پست وجود ندارد.
2. Persistent Verification Status Banner (کانال tab)
⚠️ This section fulfills the forward reference established in C1 Section 7.
Happy Path:
A banner is shown at the top of the کانال tab, directly beneath the top navigation bar, for any creator who is Pending or Rejected
The banner does not appear for Verified creators — it disappears entirely and permanently once verification succeeds
Banner content and tap behavior differ by state:
State Message Tappable? Tap Destination
Pending حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید. No — informational only —
Rejected احراز هویت شما تأیید نشد. دلیل: {admin_reason} Yes Navigates to C3 (اطلاعات کاربری), landing at the top of اطلاعات هویتی, per C1 Section 7
Edge Cases:
This banner is scoped to the creator's own view of their own کانال tab — entirely separate from what other users see on the creator's public channel page (Section 12)
The banner is non-dismissible — the creator cannot close or hide it; it remains until their verification state changes
If the creator has no posts yet (empty کانال), the banner still renders above the empty state
Error States: None specific — this is a display-only state, no user input involved
Farsi copy:
Pending banner message: حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید.
Rejected banner message: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
3. Post Composer
Happy Path:
The composer opens as a full-screen modal on mobile
The composer contains:
A free-text input area for the post body
An image attachment area supporting up to 4 images
A visibility toggle: Free (رایگان) / Premium (پریمیوم) — defaults to Free in C4; Premium behaviour is covered in C5
A Publish CTA button
A Discard option to cancel without publishing
Creator can write text only, attach images only, or combine both — the post cannot be empty (at least one of text or image must be present)
Edge Cases:
If the creator closes the composer with unsaved content, a confirmation dialog appears before discarding
Composer preserves draft content if the app is backgrounded or the device locks — content is not lost on accidental exit
If the creator switches the visibility toggle to Premium during composition, the flow transitions to C5 — text and images already entered are preserved
Error States:
If the post is empty (no text, no images) and the creator taps Publish, an inline error appears
If the network fails during publish, an error banner appears and the draft is preserved — creator can retry
Farsi copy:
Composer heading: پست جدید
Text input placeholder: تحلیل یا دیدگاه خود را بنویسید...
Visibility toggle — free: رایگان
Visibility toggle — premium: پریمیوم
Publish CTA: انتشار
Discard CTA: انصراف
Discard confirmation dialog: پست شما ذخیره نشده است. آیا می‌خواهید خارج شوید؟
Discard confirm CTA: خروج
Discard cancel CTA: ادامه ویرایش
Empty post error: پست نمی‌تواند خالی باشد. متن یا تصویر اضافه کنید.
Network error banner: انتشار پست ناموفق بود. اتصال اینترنت خود را بررسی کنید.
4. Text Content
Happy Path:
Creator enters post text of up to 2000 characters
Persian, English, or mixed text accepted
Line breaks accepted
A live character counter is shown as the creator types
Edge Cases:
Input stops accepting new characters at 2000
URLs typed into the text are displayed as plain text in Phase 0 — not hyperlinked
Hashtags and mentions typed into the text are displayed as plain text in Phase 0
Error States:
Counter turns {colors.ruby} (#ea2261) at 0 remaining characters
Farsi copy:
Character counter: {n}/۲۰۰۰
Counter at limit: به حداکثر تعداد کاراکتر رسیدید.
5. Image Attachments
Happy Path:
Creator can attach up to 4 images per post
Accepted formats: JPG, PNG, WebP
Maximum size per image: 5 MB
A helper text note is shown below the image upload area informing creators of the file specs
After selecting images, thumbnails are shown in a horizontal strip beneath the text input
Creator can remove any individual image before publishing by tapping a remove icon on the thumbnail
Images are displayed in the published post in the order they were attached
Images are displayed at their original aspect ratio — no cropping or forced ratio applied
A maximum height cap of 400px is applied in the feed — images taller than this are letterboxed; the full image is viewable in the lightbox
Edge Cases:
Creator can attach images without any text — image-only posts are valid
If the creator attempts to attach a 5th image, the add image button is frozen/disabled with a message
If an image fails to upload during publish, the entire post publish is blocked — the creator is shown which image failed and can remove or replace it
Image compression is deferred to Phase 1
Error States:
Wrong format: inline error shown, upload rejected
File too large: inline error shown, upload rejected
5th image attempted: add button frozen with message shown
Image upload failure on publish: specific error identifying the failed image
Farsi copy:
Add image CTA: افزودن تصویر
File specs helper text: فرمت‌های مجاز: JPG، PNG، WebP — حداکثر حجم هر تصویر: ۵ مگابایت
Remove image tooltip: حذف تصویر
Wrong format error: فقط فایل‌های JPG، PNG و WebP مجاز هستند.
Too large error: حجم هر تصویر نباید بیشتر از ۵ مگابایت باشد.
Max images reached (frozen button message): امکان افزودن بیش از ۴ تصویر وجود ندارد.
Image upload failure: آپلود تصویر {n} ناموفق بود. تصویر را حذف یا جایگزین کنید.
6. Publishing & Post State
Happy Path:
Creator taps انتشار
System validates content
Post is published immediately and appears at the top of the creator's channel feed
Post is visible to all users — logged in or logged out — immediately upon publishing
A success toast message appears briefly after publishing
Creator is returned to the کانال tab where the new post is visible at the top
Edge Cases:
Post publish timestamp is system-generated — not editable by the creator
If the creator is on a slow connection, a loading indicator is shown on the Publish button during upload — button is disabled to prevent double submission
Published post appears immediately on the خانه feed of all investors who follow the creator
Error States:
If publish fails due to network error, draft is preserved and error banner shown with retry option
Farsi copy:
Publishing loading state: در حال انتشار...
Publish success toast: پست شما با موفقیت منتشر شد.
7. Image Display in Feed & Channel
Happy Path:
Images are displayed at their original aspect ratio in the feed and channel
A maximum height cap of 400px is applied — images taller than this are letterboxed; full image viewable in lightbox
Multi-image display uses a swipe carousel:
1 image: Full width, original aspect ratio
2–4 images: Swipe carousel — each image displayed full width at its original ratio, with a dot indicator showing current position
Tapping any image opens the full-screen lightbox viewer
Full-Screen Lightbox:
Image fills the screen at full resolution
Swipe left/right to navigate between images in the same post
Swipe down to close the lightbox
A back button (←) in the top corner serves as a secondary close option
Image position indicator shown (e.g., ۱ / ۳)
Pinch to zoom supported
Edge Cases:
If the post has only 1 image, no dot indicator or swipe gesture is shown
If the creator attaches images of mixed aspect ratios, each displays at its own ratio within the carousel
Dot indicator uses filled/unfilled dots — maximum 4 dots
Farsi copy:
Image position indicator in lightbox: {current} / {total}
8. Post Display on Channel (Scrollable List)
Happy Path:
The کانال tab shows all published posts as a scrollable chronological list — most recent at the top
Each post card in the list displays:
Creator avatar and username
Post timestamp — Shamsi calendar, relative format for recent posts, absolute for older ones
Full post text — no truncation
Image carousel (if images attached) — as defined in Section 7
Visibility badge: shown only if the post is پریمیوم — free posts carry no badge
Three inline action icons below each post card: share, edit, delete — no labels
Tapping the post body or images navigates to the standalone post page (C4b)
Edge Cases:
If the post has no text, no text area is rendered on the card
If the post has no images, no carousel area is rendered
Action icons (share, edit, delete) are visible only to the creator on their own channel — investors see only the share icon
On the creator's own کانال tab, all of the creator's own posts (free and premium) are shown with full content — no lock or teaser applies
For premium posts specifically, a fourth action icon (مشاهده به عنوان کاربر) is also shown to the creator, alongside share/edit/delete — full behavior defined in C5 Section 6. This icon does not appear on free posts, since there is nothing to preview
The persistent verification banner (Section 2), when applicable, is shown above this list
Farsi copy:
Visibility badge (premium only): پریمیوم
Timestamp examples: همین الان · {n} دقیقه پیش · {n} ساعت پیش · دیروز · {date}
9. Share Action
Happy Path:
Creator or investor taps the share icon on a post card (in the list or on the standalone post page)
The native share sheet opens on mobile — shows whichever apps are already installed on the user's device, plus a copy link option
The shared link is the post's standalone permalink: lumina.ir/@{username}/posts/{post_id}
Copying the link via the share sheet shows a brief confirmation toast
Edge Cases:
Share is available to all users — creators and investors alike
Share is available on both the scrollable list and the standalone post page
If the post is deleted after a link is shared, the permalink returns a پست یافت نشد page
Farsi copy:
Copy link confirmation toast: لینک پست کپی شد.
Deleted post permalink page: این پست حذف شده یا وجود ندارد.
10. Edit Action
Happy Path:
Creator taps the edit icon on a post card within 15 minutes of publishing
Composer reopens with existing content pre-populated
Saving updates the post immediately; a subtle ویرایش‌شده label appears on the post
Post retains its original publish timestamp after editing
Edge Cases:
After 15 minutes, the edit icon remains visible but is frozen (opacity: 0.4) — tapping it shows a tooltip explaining editing is no longer possible
Edit is available on both the scrollable list and the standalone post page
If edit save fails due to network error, error banner shown and original content preserved
Error States:
Edit window expired: frozen icon with tooltip on tap
Network error on save: error banner shown
Farsi copy:
Edit icon tooltip (within window): ویرایش پست
Edit icon tooltip (frozen, after 15 min): مهلت ویرایش این پست به پایان رسیده است.
Edited label: ویرایش‌شده
Edit network error: خطا در ذخیره تغییرات. دوباره تلاش کنید.
11. Delete Action
Happy Path:
Creator taps the delete icon on a post card at any time
A confirmation dialog appears before permanent removal
On confirm, post is permanently removed from the channel and all feeds
Deleted posts disappear from investors' feeds on next refresh — no message shown to investors
Edge Cases:
Delete is available at any time — no time restriction
Delete is available on both the scrollable list and the standalone post page
Deleted posts are permanently removed — no soft delete or recovery in Phase 0
If delete fails due to network error, error banner shown and post remains
Farsi copy:
Delete icon tooltip: حذف پست
Delete confirmation dialog: آیا از حذف این پست اطمینان دارید؟ این عملیات غیرقابل بازگشت است.
Delete confirm CTA: بله، حذف کن
Delete cancel CTA: انصراف
Delete network error: خطا در حذف پست. دوباره تلاش کنید.
12. Channel Page & Creator Public URL
Creator's public channel is accessible at lumina.ir/@{username}
The channel page displays:
Creator profile header: avatar, username, bio, market specialization tags, social links, verified badge
Prediction stats summary — pulled from Epic 9; shown as placeholder zeros until prediction data exists
Follow / unfollow button — available to any investor regardless of subscription status; no referral code required to follow
Subscribe button — referral-code-gated (links to Epic 5 paid access flow)
Scrollable post list — as defined in Section 8, with locked-teaser rendering for premium posts as defined in C5
The channel URL is shareable externally — opens correctly for logged-out users
Share button on the channel page copies the channel URL to clipboard
This public-facing view is distinct from the creator's own کانال tab (Section 2 and Section 8) — external visitors never see the persistent verification banner
Edge Cases:
If a creator has no posts yet, a contextual empty state is shown
If the creator's account is suspended, the channel page shows a suspended message
If a logged-out user taps Follow or Subscribe, they are redirected to the unified auth entry flow with the channel URL preserved as the return destination
Following a creator never requires a referral code; only subscription is referral-gated
Farsi copy:
Channel empty state: این کریتور هنوز پستی منتشر نکرده است.
Suspended channel message: این کانال در حال حاضر در دسترس نیست.
Share channel CTA: اشتراک‌گذاری کانال
Channel URL copied toast: لینک کانال کپی شد.
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Subscribe CTA: اشتراک
13. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
FAB uses button-primary-pill style (#533afd, pill radius); frozen state uses opacity: 0.4
FAB expanded mini menu uses card-feature-light style with {rounded.lg} radius and Level 2 shadow
Persistent verification banner spans full width, sits directly beneath the top nav bar on the کانال tab: Pending — {colors.ink-mute} (#64748d) background tint with clock icon; Rejected — {colors.ruby} (#ea2261) background tint with warning icon and chevron
Post composer opens as a full-screen modal with {colors.canvas} (#ffffff) background
Post cards use card-feature-light style
Only the پریمیوم badge is ever rendered — {colors.brand-dark-900} (#1c1e54) background with white text — free posts carry no badge
Character counter uses {colors.ink-mute} (#64748d), switches to {colors.ruby} (#ea2261) at 0 remaining
Carousel dot indicator uses {colors.primary} for active dot, {colors.hairline} for inactive dots
Full-screen lightbox uses a pure black (#000000) background
Action icons use {colors.ink-mute} (#64748d) — frozen edit icon uses opacity: 0.4
ویرایش‌شده label uses {colors.ink-mute} in {typography.micro} size
Minimum touch target for all interactive elements: 44×44px
Channel page and post composer are mobile-first
---
## C4b — Standalone Post Page
C4b — Standalone Post Page
Story: As a user, I want to view a post on its own dedicated page so that I can access it directly via a shared link and see its full content.
Note: The standalone post page is the canonical destination for any shared post link. It serves both internal navigation (tapping a post from the channel or feed) and external deep linking (shared permalink on Telegram, WhatsApp, etc.). This story applies to all post types — free text/image posts (C4), premium posts (C5), and prediction posts (C8) — with access rules per post type applying as defined in their respective stories.
⚠️ Forward reference: Creator referral code visibility and sharing (needed for the subscription-gated referral system defined in U1 Section 7) is addressed in C9 (Creator Dashboard) — not in this story.
Acceptance Criteria:
1. URL Structure & Access
Happy Path:
Every post has a unique, permanent permalink: lumina.ir/@{username}/posts/{post_id}
The standalone post page is accessible to:
Logged-out users — can view free content in full; premium content shown as locked teaser
Logged-in investors (non-subscribers) — can view free content in full; premium content shown as locked teaser with subscribe prompt
Logged-in subscribers — can view all content including premium
The creator themselves — can view all content plus edit/delete actions, and can toggle a visitor-view preview on their own premium posts (see Section 6)
The page loads correctly when accessed via external link — no login required to view free content
Edge Cases:
If the post has been deleted, the permalink returns a not found page — clean and informative, with a CTA to visit the creator's channel
If the creator's account has been suspended, the permalink returns a channel unavailable page — post content is not shown
If a logged-out user taps a locked premium content prompt, they are redirected to the unified auth entry flow with the post URL preserved as the return destination (as defined in U1 Section 5)
Farsi copy:
Deleted post page heading: این پست حذف شده است.
Deleted post page body: پست مورد نظر حذف شده یا وجود ندارد.
Deleted post page CTA: مشاهده کانال {username}
Suspended channel page: این کانال در حال حاضر در دسترس نیست.
2. Page Structure & Content
Happy Path:
The standalone post page displays the following sections in order from top to bottom:
Section A — Creator Mini Profile Header:
Creator avatar (circular)
Creator username (tappable — navigates to lumina.ir/@{username})
Verified badge (if applicable)
Follow / Unfollow button (for investors — no referral code required)
Subscribe button (for non-subscribers) — see Section 4 for exact CTA logic by auth state
Section B — Post Content:
Badge placement: The پریمیوم badge sits at the top of the content area, alongside the timestamp — same placement rule as C5
Post timestamp — Shamsi calendar, absolute format (e.g., ۱۵ خرداد ۱۴۰۴، ساعت ۱۴:۳۰) — shown prominently near the top, directly beneath the creator header. Deliberate placement: timestamp is a trust signal central to the platform's Proof-of-Performance positioning, not incidental metadata
ویرایش‌شده label if the post was edited within the 15-minute window
Full post text — no truncation, full content shown (for free posts; premium post teaser rules in Section 4)
Image carousel (if images attached) — same display rules as C4 Section 7 apply
For prediction posts: structured prediction fields — covered in C8
Section C — Action Bar:
Share, edit (creator only), delete (creator only) icons — same rules as C4 Sections 9, 10, 11 apply
مشاهده به عنوان کاربر (View as Visitor) icon — shown only to the creator, only on their own premium posts — see Section 6
No labels under any icon in this bar
Section D — Comments:
Not implemented in Phase 0 — this section is omitted entirely, no placeholder shown
Edge Cases:
If the post has no images, Section B renders text only — no empty carousel
If the post is text-only, the image area is not rendered at all
If the post is image-only, the text area is not rendered
The creator mini profile header is always shown — even if the post is premium and locked
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Subscribe CTA: اشتراک
Visibility badge (premium only): پریمیوم
3. Navigation & Back Behaviour
Happy Path:
If the user arrived at the standalone post page from within the app (tapping a post in the channel list or feed), the back button returns them to the previous screen they came from — channel tab, خانه tab, or search results
If the user arrived via an external link (shared permalink), the back button navigates to the creator's channel page (lumina.ir/@{username}) — not to a blank previous state
Edge Cases:
If the user arrived via external link and has no browsing history within the app, the back button always falls back to the creator's channel page
If the creator's channel is suspended when the user attempts to navigate back from a shared link, the back button navigates to the خانه tab instead
4. Locked Premium Content (Non-Subscribers)
Happy Path:
If the post is premium and the user is not a subscriber, the same locked teaser pattern defined in C5 Section 3 applies here — unified across every surface where a premium post can appear:
Text teaser: First 2 lines of the post text, then gradient blur fade with a lock icon overlay
Image teaser: Images not shown — generic locked placeholder with an optional count badge (e.g., ۳ تصویر)
The پریمیوم badge, timestamp, and creator mini profile header remain fully visible — only the content body is restricted
Directly beneath the locked content, a contextual message and a single CTA are shown, determined by auth state
Message & CTA Logic by Auth State (single message + single CTA — never both states shown simultaneously):
User State Message Shown CTA Shown
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
The creator (own post) — No lock — full content always shown by default (see Section 6 for the visitor-preview toggle)
Edge Cases:
A logged-out user never sees a Subscribe CTA — authentication must happen first, subscription is a separate step after
If the user subscribes and returns to the same permalink, content is immediately accessible without needing to refresh
Arriving at a locked premium post via a shared link vs. tapping into it from a feed/channel list produces identical locked-teaser behavior — no distinction by entry path
Farsi copy:
Locked teaser image badge: {n} تصویر
Lock overlay small label (optional): محتوای پریمیوم
Message (logged-in, not subscribed): برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.
Subscribe CTA (logged-in, not subscribed): اشتراک در کانال
Message (logged-out): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA (logged-out): ورود/ثبت‌نام
5. Share Action on Standalone Post Page
Happy Path — Mobile:
Share icon is visible to all users on the standalone post page
Tapping share opens the native OS share sheet — shows whichever apps are already installed on the user's device, plus a copy link option
The platform does not construct or call any specific third-party share URL — it hands the permalink to the OS and lets the user's own device decide the available destinations
The shared link is the current page's permalink: lumina.ir/@{username}/posts/{post_id}
Happy Path — Desktop:
Clicking share opens a minimal popover containing a single action: کپی لینک (copy link)
No direct-share buttons to specific third-party platforms are included on desktop
Clicking outside the popover closes it without action
Edge Cases:
Share is available for both free and premium posts — sharing a premium post link will show the locked teaser (Section 4) to non-subscribers who open it, which is a deliberate conversion mechanic, not a gap
Copy link action shows a brief confirmation toast on both mobile and desktop
This is precisely the moment the "View as Visitor" preview (Section 6) is most useful — a creator preparing to share their own premium post externally can check exactly what a stranger clicking that link will see, without leaving this page
Farsi copy:
Copy link confirmation toast: لینک پست کپی شد.
Desktop popover — copy link option: کپی لینک
6. Creator Preview — "View as Visitor" (مشاهده به عنوان کاربر)
Happy Path:
On the standalone page of any premium post the creator owns, the مشاهده به عنوان کاربر icon appears in the Action Bar (Section 2, Section C), alongside share/edit/delete
Tapping it renders the exact same locked-teaser view defined in Section 4 — the identical component/template a non-subscriber would see, not a separate mock
This is the same feature introduced in C5 Section 6, scoped there to the کانال tab list view — this section extends its availability to the standalone post page as well, since a creator is often on this exact page (about to share the link, per Section 5) when the need to check the visitor's view is highest
A visible banner while active: شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
A dismissible خروج از پیش‌نمایش action returns the creator to their normal full-access view
Edge Cases:
This action is not shown for free posts — there is nothing to preview, since free posts render identically for everyone
This action is not shown to anyone other than the post's owning creator — investors, subscribers, and logged-out users never see this icon
No actual impersonation or session-switching occurs — it is a conditional render of the visitor-facing template within the creator's own authenticated session
Toggling this preview does not affect what the URL shows to anyone else — it is a local, client-side view state for the creator only
Farsi copy:
Action icon label (tooltip): مشاهده به عنوان کاربر
Preview mode banner (shown while active): شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
Exit preview CTA: خروج از پیش‌نمایش
7. Edit & Delete on Standalone Post Page
Edit and delete icons are visible only to the creator on the standalone post page
All edit/delete rules from C4 Sections 10 and 11 apply identically here
After a successful delete from the standalone post page, the creator is navigated back to their کانال tab — the deleted post is no longer visible
Farsi copy: Same as C4 Sections 10 and 11.
8. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Page background uses {colors.canvas-soft} (#f6f9fc) — slightly off-white to distinguish the page from the post card content area
Post content area uses card-feature-light style — {colors.canvas} background, {colors.hairline} border, {rounded.lg} radius, Level 1 shadow
Creator mini profile header is separated from post content by a {colors.hairline} divider
Timestamp rendered directly beneath the creator header in {colors.ink-mute} (#64748d), {typography.caption} size
پریمیوم badge uses {colors.brand-dark-900} (#1c1e54) background with white text, positioned at the top of the content area alongside the timestamp — shown only when applicable, no badge for free posts
Locked text teaser fade uses a linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Locked image placeholder uses {colors.canvas-soft} background, lock icon in {colors.ink-mute}, image count badge in pill-tag-soft style
Contextual message (logged-out or not-subscribed) renders in {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Subscribe CTA and auth CTA both use button-primary-pill style (#533afd, pill radius)
Action icons (share, edit, delete, view-as-visitor) use {colors.ink-mute} (#64748d) — consistent with C4
ویرایش‌شده label uses {colors.ink-mute} in {typography.micro} size
View-as-visitor preview banner uses {colors.warning} (#f59e0b) background with dark text — signals a temporary/altered viewing mode without implying an error, consistent with the same treatment in C5 Section 7
Desktop share popover is minimal — single row, card-feature-light style with Level 2 shadow, {rounded.md} radius
Image carousel and lightbox behaviour identical to C4 Section 7
Minimum touch target for all interactive elements: 44×44px
Page is mobile-first; on desktop, content is centered in a single column with max-width of 640px
---
## C5 — Premium Post Publishing
C5 — Premium Post Publishing
Story:
As a creator, I want to publish premium posts visible only to subscribers so that I can provide exclusive value that justifies the subscription price.
Note: This story extends the composer introduced in C4 — the visibility toggle (رایگان / پریمیوم) is shared infrastructure between both stories. C5 owns the premium-specific behavior: access control, locked teaser rendering, and the paywall logic. Standalone post page behavior is defined in C4b Section 4, using the identical teaser pattern specified here.
⚠️ Forward dependency note: Premium access in Phase 0 is gated purely by active channel subscription — there is no per-post pricing (PPV). One subscription unlocks all premium content on that creator's channel. PPV is explicitly deferred to Phase 1 per the PRD. Subscription itself is referral-code-gated (Epic 5); following a creator is free and requires no referral code.
Acceptance Criteria:
1. Marking a Post as Premium
Happy Path:
In the post composer (C4 Section 3), the creator switches the visibility toggle from رایگان to پریمیوم
All composition rules (text limit, image limits, formats) remain identical to C4 — only the visibility and access control differ
On publish, the post is immediately locked for all non-subscribers and fully visible to subscribers and the creator
Edge Cases:
A creator with zero subscribers can still publish premium posts — content accumulates for whenever their first subscriber joins
The visibility toggle (رایگان ⇄ پریمیوم) can be changed in either direction within the same 15-minute edit window established in C4 — consistent with all other post edits
After the 15-minute window closes, visibility is locked along with the rest of the post content — a creator cannot convert a free post to premium (or vice versa) after this window
Error States:
Same network/validation error states as C4 apply — no additional error states specific to the toggle itself
Farsi copy: Same visibility toggle copy as C4 Section 3 (رایگان / پریمیوم).
2. Access Control Logic
Viewer Access
The creator (post owner), viewing their own کانال tab Full content, always — no lock, no teaser
Active subscriber to this creator Full content
Logged-in investor, not subscribed Locked teaser (Section 3)
Logged-out user Locked teaser (Section 3)
Edge Cases:
If a subscriber's subscription expires, premium posts immediately revert to locked teaser state for that user on next load — no grace period
If a non-subscriber subscribes, previously locked posts become immediately accessible without needing to refresh the app
If the creator's account is suspended, all content (free and premium) becomes inaccessible per the suspension rules already defined in A2 and C4 — premium-specific access control is irrelevant in this state
Following a creator does not grant premium access — following is free and ungated; only an active, referral-code-originated subscription unlocks premium content
3. Locked Teaser Display (Investor-Facing Surfaces)
Scope clarification: This locked teaser applies exclusively to investor-facing surfaces — the public channel page (lumina.ir/@{username}) and the خانه feed (Epic 7). It does not apply to the creator's own کانال tab, where the creator always sees full content for their own posts (per Section 2).
Happy Path:
Badge placement: The پریمیوم badge sits at the top of the post card, in the header area alongside the creator avatar, username, and timestamp — identical placement whether the post is locked or unlocked
Text teaser: The first 2 lines of the post text are shown, then fade into a gradient blur with a lock icon overlay centered on the fade. Kept intentionally short — even a longer excerpt risks revealing directional analysis, which undermines the platform's core value proposition
Image teaser: Images are not shown at all — replaced with a generic locked placeholder (a branded lock icon on {colors.canvas-soft} background), not a blurred version of the actual image, to avoid any risk of leaking directional information. If multiple images, a count badge indicates richness (e.g., ۳ تصویر)
Directly beneath the locked content, a contextual message and a single CTA are shown, determined by auth state (see table below)
Tapping the card body (text or image placeholder area) navigates to the standalone post page (C4b), where the identical locked-teaser pattern is shown
Edge Cases:
If the premium post has no text (image-only), only the image placeholder is shown
If the premium post has no images (text-only), only the text teaser is shown
Post timestamp, creator info, and the پریمیوم badge remain fully visible on locked cards — only the content body is restricted
Message & CTA Logic by Auth State (single message + single CTA — never both states shown simultaneously):
User State Message Shown CTA Shown
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
Error States: None specific — this is a display-only state, no user input involved
Farsi copy:
Locked teaser image badge: {n} تصویر
Lock overlay small label (optional): محتوای پریمیوم
Message (logged-in, not subscribed): برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.
Subscribe CTA (logged-in, not subscribed): اشتراک در کانال
Message (logged-out): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA (logged-out): ورود/ثبت‌نام
4. Standalone Post Page Behavior
Full lock behavior — including badge placement, the 2-line text teaser, image placeholder, contextual message, and auth-state CTA logic — is fully specified in C4b Section 4, using the exact same pattern defined in Section 3 above. No divergence between list/feed teasers and standalone page teasers
Arriving at a premium post's standalone page from a locked teaser tap vs. a direct shared link produces identical behavior — the lock does not differentiate by entry path
5. Subscriber View
Happy Path:
An active subscriber sees premium posts identically to free posts — full text, full image carousel, no visual distinction in content rendering
The پریمیوم badge remains visible at the top of the post, as a status indicator, even to subscribers who have full access — this reinforces the perceived value of their subscription
Edge Cases:
If a subscriber's subscription expires while they are actively viewing a premium post, the content does not disappear mid-session — the lock takes effect on the next page load or refresh, not retroactively within an open session
6. Creator Preview — "View as Visitor"
Happy Path:
On every premium post the creator owns (visible from their کانال tab), a "مشاهده به عنوان کاربر" action is available alongside the standard share/edit/delete icons
Tapping it opens a read-only preview rendering the exact locked-teaser view a non-subscriber would see — using the identical component/template defined in Section 3, not a separate mock
This gives creators direct visibility into what their non-subscribing audience actually sees, closing the trust gap of publishing premium content on faith
This same action is also available on the standalone post page for the identical premium post — fully specified in C4b Section 6. Both surfaces use the same underlying preview template; a creator can trigger it from wherever they happen to be reviewing that specific post
Edge Cases:
This preview is available only to the creator, only on their own premium posts
No actual impersonation or session-switching occurs — it is a conditional render of the visitor-facing template within the creator's own authenticated session
The preview is dismissible via a clear "خروج از پیش‌نمایش" action, returning the creator to their normal full-access view
Farsi copy:
Preview action label: مشاهده به عنوان کاربر
Preview mode banner (shown while active): شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
Exit preview CTA: خروج از پیش‌نمایش
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Locked teaser text fade uses a linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Image placeholder uses {colors.canvas-soft} (#f6f9fc) background, lock icon in {colors.ink-mute}, with the image count badge in pill-tag-soft style
پریمیوم badge uses {colors.brand-dark-900} (#1c1e54) background with white text, positioned at the top of the post card in the header row — consistent with C4/C4b; no badge is ever shown for free posts
Contextual message (logged-out or not-subscribed) renders in {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Subscribe CTA and auth CTA both use button-primary-pill style (#533afd, pill radius) for visual consistency
"View as Visitor" preview banner uses {colors.warning} (#f59e0b) background with dark text — signals a temporary/altered viewing mode without implying an error
Minimum touch target for all interactive elements: 44×44px
Locked card layout is otherwise identical in structure to a free post card (avatar, username, timestamp, badge) — only the content body area differs
---
## U6 — Investor: Creator Profile Header
U6 — Investor: Creator Profile Header
Story: As an investor, I want to view a creator's public profile including their prediction stats (win rate, ROI, accuracy trend) so that I can evaluate a creator's credibility before subscribing.
Scope note: This story owns the investor-facing profile header on the public channel page (lumina.ir/@{username}) — the block above the post feed. The page itself, its URL structure, and the post list below are defined in C4 Section 12; the locked-teaser rendering of premium posts within that feed is defined in C5. U6 does not re-specify those.
⚠️ Forward dependency note: Prediction statistics originate from Epic 9 (Prediction Tracking Engine) and the visibility gate from Epic 10 (Public Track Record Page). Until Epic 9 exists, the entire statistics block is hidden per Section 3 — the header renders without it, not with placeholder values.
Acceptance Criteria:
1. Access & Context
Happy Path:
The profile header is the first block on a creator's public channel page (lumina.ir/@{username}), directly above the post feed
Accessible to all viewer types — logged-out visitors, logged-in non-subscribers, active subscribers, and the creator themselves
Reached by navigating from any surface where the creator's identity appears as a link — a shared channel link (external), a shared post permalink, tapping a creator's avatar or username on a post card (in the خانه feed or a channel's post list), or in-app creator search (Epic 7). The خانه feed itself never displays this header directly — it shows only posts from followed creators; it is simply one of several starting points an investor navigates from on their way to a creator's channel
Edge Cases:
If the creator's account is suspended, the header is not rendered at all — the page shows the channel-unavailable message instead (per C4 Section 12)
If the creator is Pending Verification or Rejected, their channel is not publicly discoverable and this header is not reachable by investors — the creator's own persistent status banner (C4 Section 2) is a separate, creator-only surface and never appears here
2. Header Content — Always Visible
Happy Path:
The header displays, in order:
Avatar — circular; falls back to the default placeholder (initials on {colors.primary} background) if the creator uploaded none (per C2 Section 3)
Username — @{username}, the creator's permanent public identifier
Verified badge — shown only for Verified creators
Bio — full text as entered in C2/C3; up to 300 characters
Market specialization tags — rendered as pill-tag-soft chips, in the order the creator selected them
Social & web links — as icons/labels, in the creator's saved order, opening in a new tab
Prediction statistics block — conditional, see Section 3
Follow / Unfollow button — see Section 4
Subscribe button — see Section 5
Edge Cases:
If the creator left bio empty (optional per C2), the bio area is not rendered — no empty placeholder
If the creator added no social links (optional per C2), that row is not rendered
Market specializations are always present — at least one tag is mandatory in C2, so this block always renders
Long bios render in full — no truncation, consistent with the no-truncation decision in C4
Farsi copy:
Verified badge label/tooltip: تأییدشده
3. Prediction Statistics Block (Conditional)
This block is governed by a strict two-state rule — it is either fully absent or fully present. There is no partial, placeholder, or zero-value rendering at any point.
Condition Rendering
Creator has not met the Epic 10 activation threshold (no predictions at all, or predictions exist but the threshold is unmet) Block entirely hidden. No heading, no empty state, no zeros, no "coming soon" text — the header renders as though the block does not exist
Creator has met the Epic 10 activation threshold Full summary displayed (see below)
Rationale (documented so this isn't later mistaken for an oversight): showing zeros would make a creator with no prediction history visually near-identical to one with a genuinely poor record — directly undermining the platform's credibility thesis. Showing partial activity counts below the threshold was considered and rejected in favour of a simpler two-state model: statistics appear only once they are aggregated enough to be meaningful.
Full summary contents (threshold met):
Win rate — wins ÷ total closed predictions, as a percentage
Total predictions — count of all predictions published
Active predictions — count currently open
ROI — average return across closed predictions
Accuracy trend — directional indicator over time
A CTA linking through to the creator's full public track record page (Epic 10 / U19)
Edge Cases:
The activation threshold itself is owned by Epic 10 — U6 only consumes the resulting boolean (threshold met: yes/no) and must not reimplement or hardcode the threshold logic. The exact minimum-closed-predictions value remains an Open Question in the PRD
If a creator has opted to hide their public track record page (C18), the statistics block is hidden here as well, and no CTA is shown — a creator's choice to stay private must be honoured consistently across surfaces, not just on the track record page itself
All statistics are read-only on this header — no filtering, sorting, or interaction beyond the CTA
Statistics reflect all of the creator's predictions, free and premium alike — the paywall governs access to prediction content and reasoning, never to their recorded outcomes. Hiding losing outcomes behind a paywall would defeat the entire proof-of-performance model
Farsi copy:
Section heading: عملکرد پیشبینی‌ها
Win rate label: نرخ موفقیت
Total predictions label: کل پیشبینی‌ها
Active predictions label: پیشبینی‌های فعال
ROI label: بازدهی
Accuracy trend label: روند دقت
Track record CTA: مشاهده کارنامه کامل
4. Follow / Unfollow
Happy Path:
Following is free and ungated — no referral code, no payment, no subscription required
Button reflects current state: دنبال کردن when not following, دنبال نکردن when already following
Tapping toggles the state immediately with optimistic UI update
Edge Cases:
Logged-out visitor tapping Follow → redirected to the unified auth entry flow, with the channel URL preserved as the return destination (U1 Sections 5–6). A single ورود/ثبت‌نام CTA is shown — never separate Register and Login options
Following does not grant access to premium content — that requires an active subscription (C5 Section 2)
Full follow-interaction mechanics (state persistence, effect on the خانه feed, notification behaviour) are owned by U8 — U6 owns only the button's presence and appearance within this header
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
5. Subscribe
Happy Path:
Subscribe button is displayed in the header for any viewer who is not an active subscriber
Tapping initiates the subscription flow (Epic 5), which is referral-code-gated in Phase 0
Edge Cases:
Logged-out visitor tapping Subscribe → same unified auth redirect as Follow (Section 4), with the channel URL preserved. Authentication happens first; subscription is a separate subsequent step
Active subscriber → the Subscribe button is replaced with a subscription status indicator rather than shown as a redundant action
If the creator's referral code is at capacity, the investor enters the waitlist flow (specified in Epic 5, referenced in U1 Section 7) — U6 does not own that behaviour
Farsi copy:
Subscribe CTA: اشتراک
Active subscriber status indicator: مشترک هستید ✓
6. Viewer-State Summary
Viewer Header Content Follow Subscribe
Logged-out Full header (stats per Section 3) Shown — tap → auth flow Shown — tap → auth flow
Logged-in, not following, not subscribed Full header دنبال کردن اشتراک
Logged-in, following, not subscribed Full header دنبال نکردن اشتراک
Active subscriber Full header Follow state as applicable Replaced with مشترک هستید ✓
The creator themselves Full header Not shown Not shown
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Header sits on {colors.canvas} with a {colors.hairline} divider separating it from the post feed below
Avatar rendered circular; default placeholder uses {colors.primary} background with white initials
Username in {typography.heading-md}; bio in {typography.body-md}, {colors.ink}
Verified badge uses {colors.primary} (#533afd) with a checkmark icon, positioned inline beside the username
Market specialization tags use pill-tag-soft — {colors.primary-bg-subdued-hover} background, {colors.primary-deep} text
Social link icons use {colors.ink-mute} (#64748d), shifting to {colors.primary} on hover/press
All prediction statistics use font-feature-settings: "tnum" — non-negotiable per the design system's tabular-figures rule for any numeric or performance value, and is the brand's quiet financial-data signature
Statistics block sits within a card-feature-light container to visually distinguish it as a distinct credibility artifact rather than ordinary profile text
Track record CTA uses link-on-light style — {colors.primary} text, no underline by default
Subscribe CTA uses button-primary-pill (#533afd, pill radius); Follow uses button-secondary (outline, {colors.primary} text) so the paid action stays visually dominant
Active subscriber indicator uses {colors.primary} text with checkmark — not a button, no press state
Minimum touch target for all interactive elements: 44×44px
Header is mobile-first; on desktop it centers in a single column matching the post feed's max-width
---
## U7 — Investor: Premium Content Lock Indication (Cross-Surface)
Good — writing U7 as the cross-surface consistency spec. It owns the principle and the currently-orphaned feed case; C5 and C4b remain the source of truth for the pattern's visual details.
U7 — Investor: Premium Content Lock Indication (Cross-Surface)
Story: As an investor, I want to see a clear visual indicator when a post is premium and locked so that I understand what I'm missing and can decide whether to subscribe.
Scope note: This story owns the consistency principle for how locked premium content is presented to investors across every surface where it can appear, and fully specifies the one surface not yet owned by any other story: the خانه feed. The locked-teaser pattern itself (badge placement, 2-line text fade, image placeholder, message/CTA logic) is defined in C5 Section 3 and applied identically on the standalone post page in C4b Section 4 — U7 references that pattern rather than redefining it.
⚠️ Forward dependency note: The خانه feed as a container — its composition, ordering, empty states, pagination, and refresh behaviour — is owned by Epic 7 (User Feed), which is not yet written. U7 specifies only how a locked premium post renders and behaves once it appears within that feed. Epic 7 must not redefine locked-post rendering; it inherits it from here.
Acceptance Criteria:
1. The Consistency Principle
Happy Path:
A locked premium post presents identically to the investor on every surface where it can appear. There is exactly one locked-post pattern platform-wide, implemented as a single shared component — not re-created per surface
The pattern is defined in C5 Section 3 and consists of:
پریمیوم badge at the top of the card/content area, in the header row alongside avatar, username, and timestamp
Text teaser — first 2 lines only, fading into a gradient blur with a lock icon overlay
Image treatment — images are not shown at all; replaced by a generic locked placeholder (branded lock icon), never a blurred version of the real image. An optional count badge indicates how many images are behind the lock
Contextual message + single CTA, determined by the viewer's auth state (Section 3)
Creator identity, timestamp, and the پریمیوم badge always remain fully visible — only the content body is restricted
Surfaces this applies to:
Surface Owning Story Status
Public channel page (lumina.ir/@{username}) post list C5 Section 3 Specified
Standalone post page (lumina.ir/@{username}/posts/{post_id}) C4b Section 4 Specified
خانه feed U7 (this story), Section 2 Specified here
Edge Cases:
If any future surface renders posts (search results, discovery, notifications), it inherits this same pattern by default — new surfaces do not get to invent their own locked-post treatment
The pattern does not vary by how the investor arrived — tapping a locked card from the feed, opening a shared permalink, or browsing a channel all produce identical rendering
2. Locked Posts in the خانه Feed
Happy Path:
Premium posts from creators the investor follows but is not subscribed to appear in the خانه feed as locked cards, using the pattern from Section 1
They are not filtered out or hidden — an investor should see that a creator they follow is actively publishing premium analysis, since that awareness is the primary conversion trigger
Locked cards sit inline in normal chronological order alongside free posts — no separate section, no grouping, no reordering
The اشتراک در کانال CTA appears directly on the locked card, allowing subscription to be initiated without leaving the feed
Edge Cases:
If an investor follows a creator and is subscribed to them, that creator's premium posts appear fully unlocked in the feed — identical to free posts apart from the retained پریمیوم badge
If an investor's subscription expires, previously unlocked posts already in their feed revert to locked cards on next feed load or refresh — no grace period, consistent with C5 Section 2
If a creator is suspended, none of their posts (free or premium) appear in the feed at all — suspension is a full blackout per A2, and takes precedence over any locked/unlocked logic
A locked card is fully tappable — tapping the card body navigates to the standalone post page (C4b), where the same locked pattern is shown with its own CTA
Locked and free posts are counted identically for feed pagination purposes — locking affects presentation only, never feed composition or ordering
Error States:
No error states specific to locking — this is a display state derived from subscription status, involving no user input
3. Message & CTA Logic by Auth State
Identical across all three surfaces. A single message and a single CTA are shown — never two competing calls to action.
Viewer State Message CTA
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
Edge Cases:
A logged-out visitor never sees a Subscribe CTA — authentication must complete first; subscription is a separate subsequent step (consistent with U1 Section 6)
Tapping the logged-out CTA preserves the current page as the post-auth return destination (U1 Section 5)
On successful subscription, locked content unlocks immediately without requiring a manual refresh
The logged-out message deliberately reads "وارد شوید یا ثبت‌نام کنید" — never assuming the visitor is a new user, since the platform's auth entry screen silently handles both cases
4. What the Lock Must Never Reveal
Happy Path:
The 2-line text limit is a hard ceiling, not a guideline. It exists because a longer excerpt risks revealing the directional substance of an analysis — which would let a non-subscriber extract the value without subscribing, defeating the entire monetization model
Images are never blurred versions of the real image. A blurred chart can still leak directional information (e.g. red vs. green candle patterns, an obvious trend line), so a generic placeholder is used instead — this is a deliberate content-security decision, not a visual style choice
Edge Cases:
For prediction posts (C8) marked premium, the structured prediction fields (asset, direction, entry, target, horizon) are treated as locked content and are not shown in the teaser — direction and target are precisely the values a non-subscriber must not obtain for free
The prediction's recorded outcome, however, is never hidden — aggregate statistics on the creator's profile header (U6 Section 3) and public track record page (Epic 10) reflect all predictions regardless of their free/premium status. The paywall governs access to reasoning and calls, never to results
5. Creator-Side Verification
A creator can confirm exactly what an investor sees on a locked post via مشاهده به عنوان کاربر, available on their own premium posts — specified in C5 Section 6 (کانال tab) and C4b Section 6 (standalone post page)
Because U7 mandates a single shared component, this preview is accurate for every surface — what the creator previews is what an investor sees in the feed, on the channel page, and on the standalone page alike
6. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
پریمیوم badge: {colors.brand-dark-900} (#1c1e54) background with white text, pill-tag-soft style — positioned at the top of the card in the header row. No badge is ever rendered for free posts; only the exception is marked
Locked text fade: linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Locked image placeholder: {colors.canvas-soft} (#f6f9fc) background, lock icon in {colors.ink-mute}, optional image count badge in pill-tag-soft style
Contextual message: {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Both the subscribe CTA and the logged-out auth CTA use button-primary-pill (#533afd, pill radius) — visually consistent, since both are the primary conversion action in their respective states
Locked card structure is otherwise identical to a free post card (avatar, username, timestamp, badge row) — only the content body area differs, so locking never disrupts the feed's visual rhythm
Minimum touch target for all interactive elements: 44×44px
All surfaces are mobile-first
---
## U8 — Investor: Follow a Creator
U8 — Investor: Follow a Creator
Story:
As an investor, I want to follow a creator for free to see their public content so that I can track their quality before committing to a paid subscription.
Scope note: This story owns the follow mechanic end-to-end — the action itself, what it does, and the دنبال‌شده‌ها management surface. The Follow button's presence and appearance within the creator profile header is defined in U6 Section 4; this story defines what happens when it's tapped.
⚠️ Forward dependency note: The خانه feed as a container is owned by Epic 7 (User Feed). U8 defines only that following is what populates it — feed composition, ordering, and pagination belong to Epic 7.
Acceptance Criteria:
1. What Following Is (and Isn't)
Happy Path:
Following is free and completely ungated — no referral code, no payment, no subscription, no capacity limit. Any registered investor can follow any Verified creator
Following a creator causes that creator's posts to appear in the investor's خانه feed
There is no limit on how many creators an investor can follow
What following explicitly does NOT do:
Does not grant access to premium content — that requires an active, referral-code-originated subscription (C5 Section 2). A follower sees premium posts as locked cards in their feed (U7 Section 2)
Does not notify the creator (Section 6)
Does not affect the creator's public profile in any visible way (Section 6)
Edge Cases:
Follow and subscription are related but distinct states — see Section 2 for how they interact
Follow state is per-account, not per-device — it syncs across any device the investor logs into
2. Follow ↔ Subscription Relationship
Subscription is treated as a strict superset of following. An investor who pays for a creator's premium content necessarily wants that creator's posts in their feed.
Happy Path:
Subscribing auto-follows. On successful subscription, if the investor is not already following that creator, the follow relationship is created automatically as part of the same transaction — no separate action required
While a subscription is active, the investor cannot unfollow that creator — the unfollow control is frozen everywhere it appears (profile header, post page mini-header, دنبال‌شده‌ها list), with a tooltip explaining why
When the subscription expires, the follow relationship persists but becomes a normal, unfollowable follow — the control unfreezes automatically with no action needed from the investor
Rationale: without auto-follow, the fastest-converting investors — those who land via a shared link and subscribe immediately without following first — would pay for content and then see none of it in their feed, and reasonably conclude the product is broken. Freezing unfollow while subscribed prevents that same nonsensical state from being reached deliberately.
Edge Cases:
If the investor was already following before subscribing, nothing changes on subscribe except that the unfollow control freezes
Unfollowing does not cancel a subscription — but since unfollow is unavailable while subscribed, this combination cannot arise in Phase 0
Reactivating an expired subscription (U3) re-freezes the unfollow control; if the investor unfollowed during the expired window, reactivation re-applies the auto-follow
Auto-follow applies to new subscriptions, renewals, and reactivations alike
Phase 1+ consideration: allowing subscribers to unfollow (treating follow purely as a feed-delivery preference, useful for an investor subscribed to many creators who wants to mute one) was considered and deliberately deferred. Phase 0 prioritizes eliminating a confusing state over granting that flexibility.
Farsi copy:
Frozen unfollow tooltip: تا زمانی که اشتراک این کانال فعال است، امکان لغو دنبال‌کردن وجود ندارد.
3. Following — Entry Points & Behaviour
Happy Path:
Follow/Unfollow is available from:
The creator profile header on the public channel page (U6 Section 4)
The creator mini profile header on a standalone post page (C4b Section 2)
The دنبال‌شده‌ها list in داشبورد — unfollow only (Section 5)
Tapping دنبال کردن applies immediately with an optimistic UI update — the button switches to دنبال نکردن without waiting for server confirmation
The creator's subsequent posts begin appearing in the investor's خانه feed
Edge Cases:
Logged-out visitor tapping Follow → redirected to the unified auth entry flow with the current page preserved as the return destination (U1 Sections 5–6). A single ورود/ثبت‌نام CTA is shown. The follow action is not auto-applied on return — the investor lands back on the channel page with the Follow button in its normal untapped state and taps it deliberately. Silently performing an action the user initiated before authenticating is surprising; the redirect exists to enable the action, not to complete it on their behalf
If the creator is suspended after being followed, their posts disappear from the investor's feed (full blackout per A2) but the follow relationship is preserved — if the creator is reinstated, their posts reappear without the investor needing to re-follow
Error States:
If the follow action fails server-side after the optimistic update, the button reverts to its previous state and a brief error toast is shown
Network unavailable: same revert-and-notify behaviour
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Follow failure toast: عملیات ناموفق بود. دوباره تلاش کنید.
4. Unfollowing from a Channel or Post Page
Happy Path:
Tapping دنبال نکردن from the profile header or post page mini-header unfollows immediately, with no confirmation dialog
The creator's posts stop appearing in the investor's خانه feed
The button reverts to دنبال کردن — re-following is a single tap away
Edge Cases:
No confirmation is required here because the creator's identity is directly visible on screen, making an accidental unfollow immediately obvious and trivially reversible. This deliberately differs from the list-based unfollow in Section 5
If the investor has an active subscription, the unfollow control is frozen here per Section 2 — tapping it shows the explanatory tooltip and takes no action
Unfollowing does not delete any history — transaction records (U4) and subscription records (U2/U3) are unaffected
5. دنبال‌شده‌ها — Followed Creators List
Happy Path:
A third sub-section is added to the داشبورد tab, alongside اشتراک‌ها and تراکنش‌ها:
داشبورد
├── اشتراک‌ها
├── تراکنش‌ها
└── دنبال‌شده‌ها
Displays a simple list of every creator the investor currently follows
Each row shows: creator avatar, username, verified badge, and an inline unfollow action
Tapping a row (anywhere except the unfollow action) navigates to that creator's channel page
Sorted by most recently followed first — no sorting controls, no search, no filters. Deliberately minimal for Phase 0
Unfollowing from the list — with confirmation:
Tapping the unfollow action opens a confirmation dialog naming the specific creator
On confirm: creator unfollowed, row removed, posts stop appearing in خانه
On cancel: dialog closes, nothing changes
Confirmation is required only here — a list of avatars makes mistaps easy and less immediately noticeable than on a channel page, so the friction is placed where the actual risk is
Edge Cases:
If the investor follows no one, an empty state is shown with a CTA to the خانه tab
If a followed creator is suspended, their row is visually dimmed and non-navigable (tapping the row body does nothing, since the channel is unavailable) — but the unfollow action remains fully functional, with the same confirmation dialog. A creator being suspended is a plausible moment for an investor to want to clean up their list, so the action must stay available
If the investor has an active subscription to a listed creator, the unfollow action on that row is frozen per Section 2, with the explanatory tooltip
The list has no pagination in Phase 0 — with 5–10 creators platform-wide, the maximum possible list length is trivially short
Error States:
If the list fails to load, an error message is shown with a retry option
If the unfollow fails, the row remains in the list and an error toast is shown
Farsi copy:
Sub-section label: دنبال‌شده‌ها
Empty state message: هنوز کریتوری را دنبال نکرده‌اید.
Empty state CTA: رفتن به خانه
Suspended creator note: کانال این کریتور موقتاً در دسترس نیست.
Unfollow action tooltip: دنبال نکردن
Confirmation dialog heading: دنبال نکردن {username}
Confirmation dialog body: با این کار، پست‌های این کریتور دیگر در خانه شما نمایش داده نمی‌شود. آیا مطمئن هستید؟
Confirm CTA: بله، دنبال نکن
Cancel CTA: انصراف
List load error: خطا در بارگذاری لیست. دوباره تلاش کنید.
Unfollow failure toast: عملیات ناموفق بود. دوباره تلاش کنید.
6. Follower Visibility — Deliberate Omissions
Two decisions here are intentional and should not be mistaken for oversights:
No follow notification to the creator.
Creators receive no notification when someone follows them. Notifications are reserved for events that carry real signal — chiefly paid subscriptions
Rationale: a founding creator driving their existing Telegram or Instagram audience onto the platform could receive dozens of follow events in a single day. That is noise, and it would train creators to ignore notifications entirely — devaluing the subscription notifications that actually matter
The creator's own follower count is available privately on their dashboard (C9), which serves the same informational need without the interruption
No public follower count on the creator profile.
The follower count is not displayed to investors anywhere — not on the profile header (U6), not on post cards, not in search results
Rationale: the platform's entire positioning is credibility earned through verified performance, not follower counts — performance proof over social proof. Displaying a follower count would partially reimport the vanity metric the product is built to replace
This matters acutely in Phase 0: every founding creator would display a number close to zero, which reads as "nobody trusts this person" when the actual situation is "the platform launched last week." The absence of the metric is more honest than the presence of a misleading one
Revisit in Phase 1+, once counts are meaningful and the reputation layer exists to contextualize them
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Follow button uses button-secondary style (outline, {colors.primary} text) so the paid Subscribe action remains visually dominant — consistent with U6 Section 7
Followed state (دنبال نکردن) uses the same button-secondary geometry with {colors.ink-mute} text, signalling an already-completed action rather than a call to action
Frozen unfollow control (active subscriber) uses opacity: 0.4 with cursor: not-allowed, consistent with the frozen-control pattern established for the FAB in C4 and the edit icon in C4 Section 10 — visible but non-interactive, with an explanatory tooltip on tap
دنبال‌شده‌ها list rows use card-feature-light style — {colors.canvas} background, {colors.hairline} border, {rounded.lg} radius, Level 1 shadow
Creator avatar in list rows rendered circular, falling back to the default initials placeholder on {colors.primary} where no avatar was uploaded
Verified badge in list rows uses {colors.primary} (#533afd) with a checkmark icon
Inline unfollow action uses {colors.ink-mute} (#64748d) — deliberately understated, not a {colors.ruby} destructive treatment, since unfollowing is low-stakes and fully reversible
Suspended creator rows use opacity: 0.5 with a lock icon (consistent with U2 Section 7) — but the unfollow action within the row renders at full opacity, since it remains functional
Confirmation dialog uses the standard modal pattern; confirm CTA uses button-primary-pill
Minimum touch target for all interactive elements: 44×44px
All surfaces mobile-first; دنبال‌شده‌ها list stacks in a single column
---
## C6 — Creator Channel Sharing (External Promotion)
C6 — Creator Channel Sharing (External Promotion)
Story: As a creator, I want to share my channel link externally (Telegram, Instagram, X, etc.) so that I can drive my existing audience to the platform.
Note: This story defines the enhanced, creator-specific share behavior — a pre-filled, editable promotional caption combined with the channel link. It extends the same share icon already defined in C4 Section 12, which remains unchanged for non-creator viewers (investors, logged-out visitors get a plain link-only share with no caption). The icon is one control; its behavior branches by who is viewing. There is only one entry point for the enhanced flow — the کانال tab is the creator's own rendering of their channel page, not a separate screen.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
The enhanced share action is available to the creator (channel owner) via a dedicated share icon in the header of the creator's own کانال tab
Tapping/clicking the icon opens the enhanced share flow (Sections 2–3)
Only Verified creators can access this enhanced flow
Edge Cases:
If the creator's account is Pending Verification, the share icon is frozen (opacity: 0.4) — tapping shows a contextual blocking message, consistent with the FAB pattern in C4 Section 1
If the creator's account is Suspended, the share icon is also frozen with a different contextual message
For any user other than the channel owner (investors, logged-out visitors) viewing the same channel page, tapping the share icon triggers the simple share behavior already defined in C4 Section 12 — unchanged, no caption
Error States:
Pending verification: blocking message shown on tap
Suspended: blocking message shown on tap
Farsi copy:
Share icon tooltip (creator, own channel): اشتراک‌گذاری کانال
Pending verification blocking message: برای اشتراک‌گذاری کانال، ابتدا باید احراز هویت شما تأیید شود.
Suspended blocking message: حساب شما تعلیق شده است. امکان اشتراک‌گذاری کانال وجود ندارد.
2. Caption Composition
Happy Path:
On first use, a default suggested caption is pre-filled: من را در لومینا دنبال کن 👇
The caption is fully editable — the creator can rewrite it entirely or adjust the default
Maximum caption length: 150 characters — a live counter is shown
On subsequent uses, the field is pre-filled with the creator's last-used caption (not the default) — the system remembers their most recent edit
The channel link (lumina.ir/@{username}) is appended automatically below the caption when shared — the creator does not type or edit the link itself
Edge Cases:
If the creator clears the caption field entirely (empty string), sharing proceeds with link only — this is a valid state, not an error
If saving the "last-used caption" fails due to a network error, this fails silently — it does not block the share action itself; the next attempt simply falls back to the default suggestion
The default suggested caption is a fixed, hardcoded string in Phase 0 — not admin-configurable (flagged as a potential Phase 1 enhancement)
Error States:
Input stops accepting new characters at 150 — counter turning {colors.ruby} (#ea2261) communicates the limit
Farsi copy:
Default suggested caption: من را در لومینا دنبال کن 👇
Caption field label: پیام اشتراک‌گذاری کانال
Character counter: {n}/۱۵۰
Counter at limit: به حداکثر تعداد کاراکتر رسیدید.
3. Sharing Mechanics — Mobile
Happy Path:
Tapping the share icon opens a bottom sheet containing:
The editable caption field (Section 2)
A primary CTA: اشتراک‌گذاری — closes the bottom sheet immediately, then invokes the native OS share sheet, passing the caption and link combined as the shared text (caption on one line, link below it)
A secondary action: کپی لینک — copies the bare channel link only (bypassing the caption), shows a confirmation toast, and closes the bottom sheet
Tapping the dimmed overlay behind the bottom sheet dismisses it without action — consistent with other dismissible overlays in the product (e.g., the FAB mini-menu in C4)
Edge Cases:
The native OS share sheet shows whichever apps are installed on the creator's device — the platform does not construct or call any specific third-party URL directly, consistent with the approach in C4/C4b
If the creator dismisses the native share sheet without selecting an app, no caption is saved as "last-used" — only a confirmed share (an app was actually selected) updates the remembered caption
Tapping کپی لینک does not update the "last-used caption" — since no caption was actually used in that action
Error States:
None specific to this mechanism — native share sheet failures are handled at the OS level, outside the platform's control
Farsi copy:
Bottom sheet heading: اشتراک‌گذاری کانال
Primary CTA: اشتراک‌گذاری
Secondary CTA: کپی لینک
Copy link confirmation toast: لینک کانال کپی شد.
4. Sharing Mechanics — Desktop
Happy Path:
Clicking the share icon opens a popover containing:
The editable caption field (Section 2)
A primary CTA: کپی همه — copies the caption and link together as a single combined text block, shows a confirmation toast, and closes the popover
A secondary CTA: کپی لینک — copies the bare channel link only, shows a confirmation toast, and closes the popover
Clicking outside the popover closes it without action
Edge Cases:
Only a successful کپی همه action updates the "last-used caption" for next time — کپی لینک does not, consistent with the mobile behavior in Section 3
Error States:
If the clipboard write fails (rare browser permission issue), an inline error is shown with a retry option — the popover remains open in this case so the creator can retry
Farsi copy:
Popover heading: اشتراک‌گذاری کانال
Primary CTA: کپی همه
Secondary CTA: کپی لینک
Copy all confirmation toast: متن و لینک کپی شد.
Copy link confirmation toast: لینک کانال کپی شد.
Clipboard error: کپی ناموفق بود. دوباره تلاش کنید.
5. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Mobile bottom sheet uses {colors.canvas} (#ffffff) background, {rounded.xl} radius on top corners, Level 2 shadow, with a dimmed scrim overlay behind it
Desktop popover uses card-feature-light style with Level 2 shadow, {rounded.md} radius
Caption input field uses standard text-input style — {colors.hairline-input} border, focus state swaps to {colors.primary}
Character counter uses {colors.ink-mute} (#64748d), switches to {colors.ruby} (#ea2261) at 0 remaining
Primary CTA (اشتراک‌گذاری / کپی همه) uses button-primary-pill style (#533afd, pill radius)
Secondary CTA (کپی لینک) uses button-secondary style — outline, {colors.primary} text
Frozen share icon (Pending/Suspended states) uses opacity: 0.4, consistent with the FAB pattern in C4
Minimum touch target for all interactive elements: 44×44px
Mobile bottom sheet and desktop popover are both compact, single-purpose, no unnecessary scrolling

View File

@ -1,680 +0,0 @@
# Round 2 — Auth & onboarding
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Reuse round-1 components. Mobile-first forms; desktop single column, 560px max (C3: 640px).
## Deliver in this round
- Entry screen (shared login/registration), OTP with countdown, blocked state, login success modal, suspended-account screen
- Investor تکمیل پروفایل with live username check and step indicator
- Creator KYC form (no exit), ID card upload
- Creator تکمیل پروفایل: bio, avatar crop, links (quick-add, reorder, 8-link limit), market tags, T&C, success screen
- اطلاعات کاربری (C3) in Verified, Pending and Rejected states, with the unsaved-changes dialog
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **U1** — Investor Registration & Login _(ClickUp status: in review)_
- **C1** — Creator Registration & Identity Verification _(ClickUp status: in review)_
- **C2** — Creator Profile Setup _(ClickUp status: in review)_
- **C3** — Creator Profile Edit _(ClickUp status: in review)_
---
## U1 — Investor Registration & Login
Story:
As an investor, I want to register and log in with my mobile number so that I can access the platform securely.
Acceptance Criteria:
1. Entry Screen — Mobile Number Input
Happy Path:
A single entry screen handles both registration and login — the user does not need to explicitly choose between the two
The screen accepts Iranian mobile numbers only (format: 09XXXXXXXXX — 11 digits starting with 09)
Input field triggers numeric keyboard on mobile
On submission, the system checks whether the number is already registered:
Number not registered → moves to OTP step → then profile setup → then redirect (context-aware, see Section 5)
Number already registered as investor → moves to OTP step → then redirect (context-aware, see Section 5)
Number already registered as creator → inline error, no redirect
Edge Cases:
The user does not know whether they are registering or logging in — the system handles this silently after number submission
A creator cannot register as an investor using the same mobile number in Phase 0
Error States:
Invalid format: inline error shown, no OTP sent
Number belongs to a creator account: specific inline error shown
Farsi copy:
Screen heading: ورود یا ثبت‌نام
Field label: شماره موبایل
Placeholder: ۰۹۱۲ ۳۴۵ ۶۷۸۹
Invalid format error: شماره موبایل وارد‌شده معتبر نیست.
Creator account error: این شماره به یک حساب کریتور تعلق دارد و امکان ثبت‌نام به عنوان سرمایه‌گذار را ندارد.
CTA button: ادامه
2. OTP Verification
Happy Path:
A 5-digit OTP is sent via SMS immediately after a valid number is submitted
OTP expires after 2 minutes
A visible countdown timer shows remaining time
On correct OTP entry:
New user → proceeds to profile setup (Section 3)
Returning user → login success modal shown → redirected based on context (Section 5)
Edge Cases:
User can request a resend only after the countdown expires — not before
After 3 consecutive failed OTP attempts, the session is blocked for 10 minutes
If the user navigates back to change their mobile number, the current OTP is invalidated — a new one is sent after re-submission
Error States:
Wrong OTP: inline error shown, remaining attempts decremented
Expired OTP: inline error with resend prompt
Blocked session: full-screen message with countdown to unblock
Network error on OTP send: inline error with retry option
Farsi copy:
Screen heading: کد تأیید را وارد کنید
Screen subheading: کد ۵ رقمی ارسال‌شده به {mobile_number} را وارد کنید.
SMS body: کد تأیید شما: ۴۵۲۱۸ — این کد تا ۲ دقیقه معتبر است.
Countdown label: انقضای کد: {mm:ss}
Wrong OTP error: کد وارد‌شده اشتباه است. لطفاً دوباره تلاش کنید.
Expired OTP error: کد منقضی شده. یک کد جدید دریافت کنید.
Resend CTA: ارسال مجدد کد
Blocked state: تعداد تلاش‌های مجاز به پایان رسید. ۱۰ دقیقه دیگر تلاش کنید.
Network error: ارسال کد تأیید ناموفق بود. دوباره تلاش کنید.
Returning user login success modal: شما وارد حساب کاربری خود شدید.
3. Registration — Profile Setup
This step is shown to new users only, immediately after OTP verification. It is mandatory and cannot be skipped — the user cannot access the platform without completing it.
3.1 Full Name
Happy Path:
Two separate fields: first name (نام) and last name (نام خانوادگی)
Persian characters only — Latin characters are not accepted
Both fields are mandatory
Full name is stored for payment reconciliation with ZarinPal — not publicly displayed in Phase 0
Full name can be edited later from the user's profile settings
Edge Cases:
Full name does not need to be unique across the platform
Error States:
Empty first name field: inline error shown
Empty last name field: inline error shown
Latin characters entered: inline error shown on that specific field
Farsi copy:
First name field label: نام
First name placeholder: مثال: علی
Last name field label: نام خانوادگی
Last name placeholder: مثال: رضایی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام را به فارسی وارد کنید.
3.2 Username
Happy Path:
User chooses a unique username that serves as their public identifier on the platform
Username rules:
3–30 characters
Allowed characters: Latin letters (a–z, A–Z), digits (0–9), and underscores (_)
No spaces, no special characters other than underscore
Case-insensitive — Ali and ali are treated as the same username
Must be unique across both investor and creator accounts
Real-time availability check fires after the user stops typing for 500ms (debounced)
Username is immutable after submission — a clear note is shown before submission
Edge Cases:
A user cannot take a username already held by a creator, and vice versa
Real-time availability check is debounced to avoid excessive API calls
Error States:
Taken username: inline error with availability indicator turning red
Invalid characters: inline error shown
Too short: inline error shown
Too long: input stops accepting characters at 30
Empty field on submission: inline error shown
Farsi copy:
Field label: نام کاربری
Field hint: نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت قابل تغییر نیست.
Placeholder: مثال: ali_investor
Taken error: این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.
Invalid characters error: نام کاربری فقط می‌تواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.
Too short error: نام کاربری باید حداقل ۳ کاراکتر باشد.
Available confirmation: این نام کاربری در دسترس است. ✓
Immutability note: نام کاربری پس از ثبت قابل تغییر نیست.
Empty error: وارد کردن نام کاربری الزامی است.
3.3 Form Submission
Happy Path:
All fields are valid and filled
User taps the submit CTA
Account is fully created
User is redirected based on context (Section 5)
Edge Cases:
If the network fails on submission, an error banner appears at the top and all entered data is preserved — not lost
Error States:
Any invalid or empty mandatory field is highlighted with an inline error on submission attempt
Network error: error banner at top of screen with retry option
Farsi copy:
Screen heading: تکمیل پروفایل
Screen subheading: برای ورود به پلتفرم، اطلاعات زیر را تکمیل کنید.
Submit CTA: ورود به پلتفرم
Network error banner: خطا در ثبت اطلاعات. اتصال اینترنت خود را بررسی کنید.
4. Login — Returning User
Happy Path:
Returning investor enters their registered mobile number on the entry screen
System silently detects the number is registered and sends an OTP
On correct OTP entry, login success modal is shown and user is redirected based on context (Section 5)
Edge Cases:
If a returning user's account has been suspended, they are shown a suspended account screen after OTP verification — no redirect occurs
The entry screen is identical for new and returning users — no distinction is made until after number submission
Error States:
Same OTP error states as Section 2 apply
Suspended account: full-screen suspended message shown after OTP verification
Farsi copy:
Login success modal: شما وارد حساب کاربری خود شدید.
Suspended account screen heading: حساب شما تعلیق شده است.
Suspended account screen body: برای اطلاعات بیشتر با پشتیبانی تماس بگیرید.
Support CTA: تماس با پشتیبانی
5. Post-Authentication Redirect (Context-Aware)
⚠️ Forward dependency note: Full implementation of context-aware redirect — including creator profile URL structure, deep link handling, and locked content rendering — is fully specified in Epic 4 (Creator Channel: C4, C4b, C5). The principle is stated here so the authentication flow is built with this behaviour in mind from day one.
Principle:
After successful registration or login, the redirect destination is context-aware:
If the user entered the auth flow from a creator's public channel or a specific post → redirect back to that exact page after completing registration or login
If the user entered the auth flow directly (no creator channel context) → redirect to خانه tab
The originating context must be preserved throughout all registration steps so it is available at the moment of redirect
Farsi copy:
Welcome message for new users: به [نام پلتفرم] خوش آمدید.
6. Logged-Out User Access
⚠️ Forward dependency note: Full specification of the locked content teaser rendering (what is shown vs. hidden, exact layout) is defined in C4, C4b, and C5. This section states only the authentication-related principle: what happens when a logged-out user attempts to act on locked content.
Principle:
Unauthenticated users can browse creator public channels and view free content via a shared link or direct visit — no registration required
Premium content is shown to logged-out users as a locked teaser (full rendering specified in C5)
Any action requiring authentication — subscribing, following, interacting — shows a single unified prompt directing the user to the entry screen (Section 1)
There is only one CTA shown to logged-out users in any locked-content context — the platform never shows separate "Register" and "Login" buttons, since the entry screen itself silently determines which flow applies
After completing registration or login, the user is redirected back to the exact page they were on — as defined in Section 5
Farsi copy:
Locked content prompt (logged-out, shown across all locked-content contexts): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA: ورود/ثبت‌نام
7. Subscription Access & Waitlist
⚠️ Forward dependency note: Full specification of referral code validation, subscription access control, waitlist entry, and waitlist notification mechanics are deferred to Epic 5 (Paid Access Infrastructure). The following principles are stated here for awareness only.
Principles:
Subscription access to a creator's premium content is controlled via a referral code tied to that creator
Each referral code has a configurable maximum number of uses — set and adjusted manually by the admin in the database
If a referral code has reached its maximum use limit at the time an investor attempts to subscribe, the investor is placed on a waitlist for that creator's channel
When the admin increases the max_uses of a referral code, all waitlisted users for that creator are notified simultaneously via in-app notification and SMS — first to act gets the available slot
Existing subscribers can renew their subscriptions freely regardless of referral code capacity — capacity limits apply to new subscriptions only
8. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text
Numeric fields (mobile number, OTP) use font-feature-settings: "tnum" per design system
Primary CTA buttons use button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Username availability confirmation renders in {colors.primary} (#533afd) with a checkmark
OTP countdown timer renders in {colors.ink-mute} (#64748d), switching to {colors.ruby} in the last 30 seconds
Progress through registration steps is communicated via a simple step indicator at the top — current step highlighted, no total step count shown to avoid overwhelming new users
Minimum touch target for all interactive elements: 44×44px
All registration and login screens are mobile-first
---
## C1 — Creator Registration & Identity Verification
C1 — Creator Registration & Identity Verification
Story: As a creator, I want to register with my mobile number and complete identity verification so that I have a verified, credible identity on the platform.
Acceptance Criteria:
1. Mobile Number Entry
The registration screen accepts Iranian mobile numbers only (format: 09XXXXXXXXX — 11 digits starting with 09)
Input field triggers numeric keyboard on mobile
If the number is already registered, the system shows an error and directs the user to the login flow
If the format is invalid, an inline error appears before the OTP is sent
On correct OTP entry:
New user → proceeds directly to profile & KYC step (no modal)
Returning user (login flow) → a confirmation modal appears before redirecting to the داشبورد tab
Farsi copy:
Field label: شماره موبایل
Placeholder: ۰۹۱۲ ۳۴۵ ۶۷۸۹
Invalid format error: شماره موبایل وارد‌شده معتبر نیست.
Already registered error: این شماره قبلاً ثبت شده. وارد شوید.
CTA button: ارسال کد تأیید
Login success modal: شما وارد حساب کاربری خود شدید.
2. OTP Verification
A 5-digit OTP is sent via SMS immediately after the creator submits their number
OTP expires after 2 minutes
A visible countdown timer shows remaining time
Creator can request a resend only after the countdown expires
After 3 consecutive failed OTP attempts, the session is blocked for 10 minutes
On correct OTP entry, behaviour follows Section 1 (new vs. returning user)
On expired OTP entry, system rejects it and prompts a resend
Farsi copy:
SMS body: کد تأیید شما: ۴۵۲۱۸ — این کد تا ۲ دقیقه معتبر است.
Countdown label: انقضای کد: {mm:ss}
Wrong OTP error: کد وارد‌شده اشتباه است. لطفاً دوباره تلاش کنید.
Expired OTP error: کد منقضی شده. یک کد جدید دریافت کنید.
Resend CTA: ارسال مجدد کد
Blocked state: تعداد تلاش‌های مجاز به پایان رسید. ۱۰ دقیقه دیگر تلاش کنید.
3. Profile Setup & KYC Submission
After OTP is verified, the creator fills in a single form with the following fields before submitting for admin review.
3.1 Username
Creator must choose a unique username serving as their public identifier (channel, profile URL, all public-facing surfaces)
Rules: 3–30 characters, Latin letters/digits/underscore only, case-insensitive, unique across the platform (checked against both investor and creator accounts), checked in real time (debounced)
Locked immediately upon first submission — this is permanent. Once a creator submits their KYC form for the first time, the username is reserved and can never be changed again through any later edit or resubmission flow, including after a rejection
Farsi copy:
Field label: نام کاربری
Field hint: نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت اولیه قابل تغییر نیست.
Placeholder: مثال: ali_trader
Taken error: این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.
Invalid characters error: نام کاربری فقط می‌تواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.
Too short error: نام کاربری باید حداقل ۳ کاراکتر باشد.
Available confirmation: این نام کاربری در دسترس است. ✓
3.2 First Name
Persian characters only — matches the format of the national ID card
Mandatory
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: نام
Placeholder: مثال: علی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام را به فارسی وارد کنید.
3.3 Last Name
Persian characters only — matches the format of the national ID card
Mandatory
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: نام خانوادگی
Placeholder: مثال: رضایی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام خانوادگی را به فارسی وارد کنید.
3.4 National ID Number
Exactly 10 digits, numeric only — used by admin for verification, never publicly displayed
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: کد ملی
Invalid format error: کد ملی باید ۱۰ رقم باشد.
3.5 National ID Card Image Upload
Clear photo of the front side of the national ID card — stored securely, visible only to admins, never displayed publicly
Format: JPG, PNG, or PDF; max 5 MB; mandatory
This field always starts empty and requires a fresh selection every time the creator reaches it — on first submission, after any interrupted/resumed session, and on any resubmission following rejection. No previously selected or submitted image is ever pre-filled or restored, under any circumstance (see Section 8 for full rationale)
Farsi copy:
Upload field label: تصویر کارت ملی (رو)
Upload hint: یک تصویر واضح از روی کارت ملی خود آپلود کنید.
Upload error – wrong format: فقط فایل‌های JPG، PNG یا PDF مجاز هستند.
Upload error – too large: حجم فایل نباید بیشتر از ۵ مگابایت باشد.
3.6 Form Submission & Transition to Channel Setup
All fields mandatory
Creator taps ادامه
On successful submission, creator status is set to Pending Verification; username and all identity fields (first name, last name, national ID) are now locked
The creator is moved directly and seamlessly into channel/profile setup (C2 — تکمیل پروفایل) — no intermediate screen, no wizard, no separate confirmation page
A toast message confirming receipt is shown overlaid on top of the تکمیل پروفایل screen as it loads
Creator cannot publish content, set up payments, or be discovered while Pending — but can complete their channel/profile info immediately, since C2 explicitly allows this in Pending state
Farsi copy:
Submit CTA: ادامه
Toast (shown on the تکمیل پروفایل screen): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
4. Admin Review
Admin receives a new verification request notification in the Admin Panel
For each pending request, admin can view: first name, last name, username, phone number, uploaded national ID card image (full-size, zoomable) — first and last name displayed together as a single combined field in the Admin Panel UI, even though stored as two separate fields
Admin can Approve (→ Verified, notified) or Reject (→ must provide written reason → Rejected, notified with reason)
All admin actions timestamped and logged with admin's account ID
Farsi copy (Admin Panel):
Pending requests section heading: درخواست‌های احراز هویت
Approve CTA: تأیید
Reject CTA: رد کردن
Rejection reason field label: دلیل رد درخواست
Rejection reason placeholder: دلیل رد را بنویسید...
Rejection reason empty error: وارد کردن دلیل رد الزامی است.
5. Verification States
State Trigger Creator Access Identity Fields (name, national ID, username)
Pending Verification KYC form submitted; awaiting admin review Can complete/edit channel & profile via C3 (اطلاعات کاربری); cannot publish or monetize; can browse platform Fully locked — no self-service edits
Verified Admin approved Full creator access unlocked Fully locked, permanently
Rejected Admin rejected Can view rejection reason and resubmit — resubmission happens via the same C3 screen, not a separate form First name, last name, national ID reopen for editing; username remains permanently locked
Account state is visible to the creator across three surfaces (see Section 7)
On rejection, the admin-provided reason is shown both in-app and via SMS
Creator can resubmit — resubmission creates a new pending request in the Admin Panel
There is intentionally no self-service way to correct identity fields while Pending (e.g., a typo the creator spots before admin reviews it) — this is an accepted tradeoff for Phase 0, handled operationally via direct creator contact through the founding-creator support channel, with admin rejecting-with-reason to reopen the fields if needed
Farsi copy:
Pending label: در انتظار تأیید
Verified label: تأییدشده ✓
Rejected label: رد شده
Rejected message: احراز هویت شما تأیید نشد. دلیل: {admin_reason} — اطلاعات را اصلاح و مجدداً ارسال کنید.
Resubmit CTA: ارسال مجدد
6. Notifications
OTP sent: SMS with OTP code
KYC submitted: In-app notification confirming receipt
Admin approved: In-app notification + SMS
Admin rejected: In-app notification + SMS with rejection reason
Farsi copy:
KYC submitted in-app: اطلاعات شما دریافت شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
Approval SMS: حساب کریتور شما در [نام پلتفرم] تأیید شد. اکنون می‌توانید کانال خود را راه‌اندازی کنید.
Rejection SMS: احراز هویت شما در [نام پلتفرم] تأیید نشد. دلیل: {admin_reason} — برای اصلاح و ارسال مجدد وارد حساب خود شوید.
7. Persistent Verification Status Visibility & Resubmission Access (Principle)
⚠️ Forward dependency note: This section states the principle only. Full specification of placement, layout, copy, and interaction is owned by the following stories. C3 (اطلاعات کاربری) is the single, canonical, ongoing surface for viewing verification status, editing profile/channel info, and resubmitting KYC after rejection — کانال and داشبورد only ever navigate to C3, they never host a duplicate form themselves. C2's تکمیل پروفایل screen is a one-time, first-run screen only and is never a recurring destination.
Surface Treatment Tap Destination Full Spec Owned By
کانال tab Full banner with contextual message Navigates to C3, landing target per state below C4
اطلاعات کاربری (C3) Status badge under name/username — تأییدشده ✓ / در انتظار احراز هویت / رد شده (this is the destination itself) C3
داشبورد tab Compact status badge, visually consistent with the C3 badge Navigates to C3, landing target per state below C9 (Epic 6 — Creator Dashboard, not yet written)
Landing target within C3, by state:
Creator State Lands At Why
Rejected Top of screen — اطلاعات هویتی (identity block) Text identity fields (first name, last name, national ID) pre-fill with previously submitted values — creator only fixes what's wrong. The ID card image field always starts empty (Section 8)
Pending (Not applicable — under the mandatory onboarding sequence in Section 8, a Pending creator's profile is always complete) —
Pending, informational only Not tappable Nothing actionable left for the creator to do but wait
Principle (applies to all three surfaces):
The signal is persistent and non-dismissible for any creator not yet Verified
Once Verified, all three signals disappear entirely and do not reappear
This signal does not appear on the standalone post page (C4b)
C2 is a one-time, first-run screen only — reached exactly once via Section 3.6. It is not a recurring destination from کانال or داشبورد; C3 is
8. Onboarding Completeness & Draft Persistence (Cross-Story Principle)
⚠️ Forward dependency note: This principle applies to C1 (this story), C2 (channel/profile setup), and C3 (Rejected resubmission editing). It is documented once here as the shared source of truth.
Mandatory, uninterruptible first-run sequence:
KYC (C1) and channel/profile setup (C2) together form a single mandatory onboarding sequence for first-time creators — there is no in-app exit or back-navigation available until C2 is submitted
This means a Pending creator's profile is always complete by definition — the "incomplete profile" state does not exist for first-run onboarding
Fields that are optional within C2 (bio, avatar, social links) remain optional as content, but the screen itself cannot be abandoned mid-flow
Resumption after OS-level interruption (app killed, backgrounded, call received, etc.) — this is outside our control and must be handled regardless of the "no exit" rule above:
After submission (server-committed state): if KYC has been successfully submitted, re-authenticating (even on a different device) always routes the creator to the correct next step — C2 if channel setup is still pending, or C3 if Verified/Rejected
Before submission (client-side draft only): all text field values (username, first name, last name, national ID digits) are persisted locally as the creator types (e.g., on field blur) and restored if the app is reopened on the same device
Different device, pre-submission: no draft carries over; the form starts blank — acceptable, since nothing has been submitted yet
Resumption is step-level, not field-position-level — the creator returns to the top of whichever screen (C1 or C2) they were on, with text fields pre-filled; no attempt is made to restore exact scroll position or cursor location
No special "welcome back" screen or messaging — resumption happens silently, as if the creator had simply navigated away and returned
National ID card image — never persisted, under any circumstance:
The ID card image field always starts empty and requires a fresh selection, in every scenario without exception: first submission, a resumed draft after interruption, or a Rejected resubmission via C3
This is a deliberate policy, not just a technical limitation: since the image itself is a common source of rejection, silently carrying forward a previously selected (possibly flawed) file risks a creator unknowingly resubmitting the same bad image. Requiring a fresh, conscious selection every time closes that gap entirely
This also removes the need for any fragile "best-effort" file-handle restoration logic across app kills
Rejected resubmission via C3, specifically:
On a fresh (non-interrupted) visit, text identity fields (first name, last name, national ID) pre-fill with the creator's previously submitted values — they edit only what needs correcting
Username is not editable at this stage — it was permanently reserved at first submission (Section 3.1)
The ID card image field is empty and requires fresh selection (see above)
Once resubmitted, the flow is functionally identical to the original C1 submission: status flips to Pending, a new entry appears in the Admin Panel review queue, and all identity fields lock again immediately
9. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Numeric fields (OTP, national ID, phone) use font-feature-settings: "tnum" per design system
Primary CTA buttons use button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Verified badge/state uses {colors.primary} (#533afd) with a checkmark icon
Pending badge/state uses {colors.ink-mute} (#64748d) with a clock/hourglass icon
Rejected badge/state uses {colors.ruby} (#ea2261) with a warning icon
Toast on the تکمیل پروفایل screen uses the standard snackbar component style, auto-dismissing after a few seconds
Minimum touch target for all interactive elements: 44×44px
All screens in this story are mobile-first
Design note for Figma handoff: the existing locked-field captions in the C3 mockups currently read این اطلاعات پس از تأیید هویت قابل تغییر نیست ("cannot be changed after verification"). Per the rule above, fields actually lock at submission, not verification, and reopen only on rejection. Recommend updating the caption to: این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست.
---
## C2 — Creator Profile Setup
C2 — Creator Profile Setup
Story:
As a creator, I want to set up my channel's public profile — bio, avatar, social links, and market specializations — as part of onboarding, so that investors can evaluate my expertise before subscribing.
Acceptance Criteria:
1. Screen Context & Onboarding Flow
Happy Path:
This screen (تکمیل پروفایل) is reached directly and automatically immediately after KYC submission in C1 Section 3.6 — there is no separate navigation step
This is a one-time, first-run screen only. Once submitted, the creator will never see this exact screen again — all future edits to this same data (bio, avatar, links, specializations) happen exclusively through C3 (اطلاعات کاربری)
On load, a toast is shown (triggered by the KYC submission in C1, not owned by this screen): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
All fields are presented as a single continuous scrolling form — not paginated, not a multi-step wizard
The creator's account status is Pending Verification throughout this screen — admin has not yet reviewed their KYC submission
This screen is part of the mandatory onboarding sequence established in C1 Section 8: there is no back button, no in-app exit, and no way to skip or defer this screen
Edge Cases:
If the app is interrupted (backgrounded, killed, call received) while filling this screen, resumption is governed entirely by C1 Section 8 — text field values restore on the same device; a different device starts the screen blank; no special "welcome back" messaging is shown
If the network fails on final submission, an error banner appears and all entered data is preserved — the creator can retry (see Section 6)
Farsi copy:
Screen heading: تکمیل پروفایل
Toast on load (inherited from C1 Section 3.6): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
2. Bio
Happy Path:
Creator enters a free-text bio of up to 300 characters
Persian, English, or mixed text accepted
Bio is displayed on the creator's public profile page below their username
A live character counter is shown as the creator types
Edge Cases:
Bio is optional — creator can submit the form without a bio
Line breaks are allowed (max 3 line breaks to prevent abuse)
URLs typed into the bio are displayed as plain text — not hyperlinked in Phase 0
Error States:
If the character count exceeds 300, the input stops accepting new characters, the counter turns red, and an inline message appears
Farsi copy:
Field label: بیو
Field hint: خود و حوزه تخصصی‌تان را معرفی کنید.
Placeholder: تحلیلگر بازار کریپتو و طلا با ۵ سال سابقه...
Character counter: {n}/۳۰۰
Max length indicator: به حداکثر تعداد کاراکتر رسیدید.
3. Avatar
Happy Path:
Creator uploads a square profile image
Accepted formats: JPG, PNG; maximum size: 5 MB
After upload, a circular crop preview is shown before the form is submitted
Avatar is displayed on the profile page, channel header, post cards, feed, and search results
Edge Cases:
Avatar is optional — if no avatar is uploaded, a default placeholder is shown (initials of the username on a {colors.primary} background)
Non-square images are accepted but the system applies a centered circular crop — a preview is shown so the creator can re-upload if unhappy
Creator can remove an uploaded avatar and revert to the default placeholder at any time
Error States:
Wrong format: inline error shown, upload rejected
File too large: inline error shown, upload rejected
Upload fails due to network error: inline error shown with a retry option
Farsi copy:
Field label: تصویر پروفایل
Field hint: تصویر مربعی با کیفیت بالا توصیه می‌شود.
Upload CTA: انتخاب تصویر
Remove CTA: حذف تصویر
Wrong format error: فقط فایل‌های JPG و PNG مجاز هستند.
Too large error: حجم فایل نباید بیشتر از ۵ مگابایت باشد.
Network error: آپلود ناموفق بود. دوباره تلاش کنید.
4. Social & Web Links
Happy Path:
Creator adds links using a dynamic list — each entry has two fields:
Label — free text, max 30 characters (e.g., کانال تلگرام, لینک‌تری, وب‌سایت شخصی)
URL — the full link
Four quick-add shortcut buttons are shown at the top of this section for the most common platforms: Telegram, Instagram, X, YouTube — tapping one adds a new entry with the label pre-filled, cursor lands on the URL field
For any other platform or link type (Linktree, personal website, etc.), creator taps "افزودن لینک" and fills both fields manually
Links are displayed on the public profile page in the order the creator added them
Creator can reorder links via drag-and-drop
Links go live on the public profile immediately upon saving — no moderation step
If no protocol is entered (i.e., the URL does not start with http:// or https://), the system automatically prepends https:// before saving and displaying the link
Constraints:
Maximum 8 links total
URL must contain at least a domain and a top-level domain (e.g., t.me/ali, linktr.ee/ali) — plain text with no dot is rejected
Label is mandatory for each entry — a link cannot be saved without a label
URL is mandatory for each entry — a label cannot be saved without a URL
T&C Agreement:
A one-time T&C checkbox is shown at the bottom of this form (Section 6) — since this is the creator's first-ever encounter with this data, the checkbox is always shown here, unconditionally
The checkbox must be ticked before the form can be submitted
The T&C text explicitly states that the creator is solely responsible for any links they add — including compliance with Iranian law and platform content policy
Edge Cases:
All link fields are optional — creator can submit the form with no links added
Quick-add shortcuts can be used multiple times (e.g., a creator could add two Telegram links)
If a creator deletes all entries, the section shows an empty state with the shortcut buttons and the add button visible
Creator can delete any individual link entry at any time via a remove icon on that entry
If the creator enters a URL without a protocol (e.g., t.me/ali_trader), https:// is silently prepended on save — no notification needed
Error States:
If a URL field contains plain text with no dot (e.g., alitrader), an inline error appears beneath that entry on submission
If a label is filled but URL is empty (or vice versa), an inline error appears on that entry on submission
Once 8 links are added, the add button is frozen/disabled — it remains visible but non-interactive, with a message shown beneath it
If the network fails on save, the error banner from Section 6 applies — no link data is lost
Farsi copy:
Section label: لینک‌ها
Section hint: لینک کانال‌ها، صفحات یا وب‌سایت خود را اضافه کنید.
Quick-add buttons: تلگرام · اینستاگرام · ایکس · یوتیوب
Label field placeholder: نام لینک (مثال: کانال تلگرام)
URL field placeholder: آدرس لینک (مثال: t.me/alitrader)
Add link CTA: + افزودن لینک
Remove link icon tooltip: حذف لینک
Max links reached (shown beneath frozen button): امکان افزودن بیش از ۸ لینک وجود ندارد!
Invalid URL error: آدرس وارد‌شده معتبر نیست.
Missing label error: وارد کردن نام برای این لینک الزامی است.
Missing URL error: وارد کردن آدرس لینک الزامی است.
T&C checkbox label: مسئولیت تمامی لینک‌های افزوده‌شده، از جمله انطباق آن‌ها با قوانین جمهوری اسلامی ایران و قوانین پلتفرم، به‌عهده من است.
T&C not checked error: برای ادامه، باید شرایط فوق را بپذیرید.
5. Market Specializations
Happy Path:
Creator selects one or more market specialization tags from a predefined list
Available tags in Phase 0:
Tag (Farsi) Tag (English key)
کریپتو crypto
طلا و سکه gold
بورس equities
فارکس forex
صندوق‌های سرمایه‌گذاری funds
مسکن real_estate
خودرو automotive
تتر (دلار و ارز) USDT
Selected tags are displayed as pill-tag-soft chips on the public profile
At least 1 tag must be selected — this is the only mandatory field in this form
Creator can select all tags if applicable (e.g., an institute covering all markets)
Edge Cases:
There is no maximum tag selection limit — creator can select all available tags
Tags are displayed in the same order as selected by the creator
Tags are stored and used internally in Phase 1+ for discovery and filtering — not exposed in Phase 0 discovery UI but must be stored correctly from day one
Error States:
If no tag is selected and the creator attempts to submit, an inline error appears beneath the section
Farsi copy:
Section label: تخصص بازارها
Section hint: بازارهایی که در آن‌ها تحلیل ارائه می‌دهید را انتخاب کنید.
Empty selection error: انتخاب حداقل یک تخصص الزامی است.
6. Form Submission & Transition to Channel
Happy Path:
At least 1 market specialization tag is selected and the T&C checkbox is ticked — these are the only two hard requirements to submit
Creator taps the submit CTA
On successful submission:
A success confirmation is shown: heading پروفایل ذخیره شد with a primary CTA رفتن به کانال
Tapping رفتن به کانال navigates the creator to the کانال tab
Since the creator is still Pending Verification at this moment (admin has not yet reviewed their KYC), the persistent verification banner (fully specified in C4) is visible on the کانال tab — this screen does not duplicate that messaging
This is the only forward path out of this screen — there is no discard, skip, or "complete later" option
Edge Cases:
Bio, avatar, and links remain optional as content — the creator can submit with all three left empty — but the screen itself cannot be abandoned without submitting
If the creator is already Verified by the time they reach this point (extremely unlikely given admin review timing, but technically possible), the same success flow applies — no special-casing needed
Error States:
If the mandatory market specialization field is empty on submission, it is highlighted with an inline error
If the T&C checkbox is not ticked, an inline error appears beneath it
If the network fails on submission, an error banner appears at the top of the form and all entered data is preserved — not lost, and no partial submission occurs
Farsi copy:
Submit CTA: ذخیره و تکمیل
Success screen heading: پروفایل ذخیره شد
Success screen CTA: رفتن به کانال
Network error banner: خطا در ذخیره‌سازی. اتصال اینترنت خود را بررسی کنید.
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
No back arrow or close icon is shown in the top bar on this screen — since no legitimate exit exists, a visible-but-non-functional control would be confusing. The Android hardware back gesture is intercepted and suppressed for the same reason
Market specialization tags use pill-tag-soft style ({colors.primary-bg-subdued-hover} background, {colors.primary-deep} text) when unselected
Selected tags use {colors.primary} fill with white text
Primary CTA uses button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Character counter for bio uses {colors.ink-mute} and switches to {colors.ruby} when limit is reached
Avatar upload area is a circular dashed-border zone — tappable on mobile
Platform quick-add shortcut buttons use button-secondary style with their respective platform icon
Frozen add link button renders at reduced opacity (0.4) with cursor: not-allowed
Success screen (Section 6) uses a calm, celebratory layout — checkmark or similar affirming visual, generous whitespace, consistent with card-feature-light styling
Minimum touch target for all interactive elements: 44×44px
Form is mobile-first; on desktop, fields are in a single column with a max-width of 560px
---
## C3 — Creator Profile Edit
C3 — Creator Profile Edit (اطلاعات کاربری)
Story:
As a creator, I want to edit my profile information and, if rejected, resubmit my identity verification, so that my profile stays current and I can correct issues that blocked my approval.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
Accessed by tapping the avatar icon from the top bar — available on both داشبورد and کانال tabs, for any creator regardless of verification state
The screen's top-bar title is اطلاعات کاربری — this is the screen-level label, distinct from the section-level heading introduced in Section 5 below
The screen renders as a single continuous scroll, structured in two independently functioning blocks: اطلاعات هویتی (identity — top) and اطلاعات پروفایل (profile info — below it)
Landing scroll position on entry depends on verification state, per C1 Section 7: Rejected creators land at the top of اطلاعات هویتی; Verified/Pending creators land at the top of the screen normally (no forced scroll)
Edge Cases:
Unlike C2, this screen is exitable — a standard back button is shown, since this is an ongoing edit surface, not mandatory onboarding
If the creator has unsaved changes in either block and attempts to exit, a confirmation dialog appears (Section 8)
2. Verification Status Badge
Happy Path:
Displayed directly beneath the creator's name and username, at the top of the screen
Three states:
State Label Tappable?
Verified تأییدشده ✓ No
Pending در انتظار احراز هویت No — informational only
Rejected رد شده No — the rejection reason and resubmission action are already visible inline in اطلاعات هویتی below; no separate tap action needed since the creator is already on this screen
Edge Cases:
Since C3 is itself the canonical destination referenced by کانال/داشبورد banners (per C1 Section 7), the badge here doesn't need its own navigation — it's a status display, not a link
Farsi copy:
Verified: تأییدشده ✓
Pending: در انتظار احراز هویت
Rejected: رد شده
3. اطلاعات هویتی (Identity Block) — Display by State
Verified state:
Username, first name, last name, national ID — all shown read-only, each with a lock icon and the caption: این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست
No action button — nothing to do here
Pending state:
Identical read-only rendering to Verified — locked, same caption
No action button — per C1 Section 5, there is intentionally no self-service edit while Pending
Rejected state:
A rejection banner is shown at the top of this block: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
First name, last name, national ID unlock and become editable — pre-filled with the creator's previously submitted values (per C1 Section 8) so they only correct what's wrong
National ID card image field is shown empty — always requires a fresh selection, never pre-filled, regardless of prior submissions (per C1 Section 8)
Username remains permanently locked and read-only, even here — it was reserved at first submission and never reopens
A dedicated CTA appears directly beneath this block: ارسال مجدد اطلاعات هویتی
A helper caption sits beneath that CTA: این عملیات فقط اطلاعات هویتی شما را برای بررسی مجدد ارسال می‌کند.
Edge Cases:
The resubmit CTA is disabled until all four identity fields (first name, last name, national ID, ID card image) are validly filled — same validation rules as C1 Sections 3.2–3.5
If the creator edits identity fields but does not tap ارسال مجدد اطلاعات هویتی, and instead only interacts with اطلاعات پروفایل below, the identity edits are not saved — they remain as unsaved local state until that specific CTA is tapped, and trigger the exit-confirmation dialog if the creator tries to leave
Error States:
Same field-level validation errors as C1 Sections 3.2–3.5 (empty fields, Latin characters, invalid national ID format, wrong image format/size)
If resubmission fails due to network error: error banner shown, all entered data preserved, creator can retry
Farsi copy:
Rejection banner: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
Resubmit CTA: ارسال مجدد اطلاعات هویتی
Helper caption: این عملیات فقط اطلاعات هویتی شما را برای بررسی مجدد ارسال می‌کند.
Locked field caption (Verified/Pending): این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست
Username locked caption (all states): نام کاربری پس از ثبت اولیه قابل تغییر نیست.
4. اطلاعات هویتی — Resubmission Success
Happy Path:
On successful resubmission, the creator stays on C3 — no navigation away
A success toast appears: اطلاعات شما مجدداً ارسال شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
The identity block immediately re-locks (read-only again) and the badge flips to در انتظار احراز هویت
This creates a new Pending entry in the Admin Panel review queue, identical in structure to the original C1 submission (per C1 Section 8)
Standard notifications apply per C1 Section 6 (in-app confirmation; later, SMS + in-app on the next admin decision)
Farsi copy:
Resubmission success toast: اطلاعات شما مجدداً ارسال شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
5. اطلاعات پروفایل (Profile Info Block) — Always Editable
This block is functionally identical to C2 Sections 2–5 (Bio, Avatar, Social & Web Links, Market Specializations) — same fields, same validation rules, same limits. It is fully independent of verification state: editable and savable whether the creator is Pending, Verified, or Rejected.
Key difference from C2: the T&C checkbox does not appear here. Since C2's mandatory onboarding sequence already requires T&C agreement before a creator can ever reach C3 for the first time, re-showing it on every edit would be redundant. The creator's original agreement, given once in C2, covers all future edits made through this screen.
Happy Path:
Existing values (bio, avatar, links, specialization tags) are pre-populated from what was saved in C2 or any prior C3 edit
Creator edits any combination of fields and taps the dedicated CTA: ذخیره اطلاعات پروفایل
On success: toast confirmation, values update immediately, and — if the creator is Verified — the public profile reflects changes instantly
Edge Cases:
If the creator is Pending or Rejected, changes save normally but remain not publicly visible until the account reaches Verified status
All field-level rules (bio 300-char limit, avatar format/size, max 8 links, market specialization minimum 1 tag) carry over unchanged from C2
Error States:
Same as C2 Sections 2, 3, 4, 5 respectively (bio overflow, avatar format/size errors, link validation errors, empty specialization error)
Network failure on save: error banner, entered data preserved, retry available
Farsi copy:
Section header: اطلاعات پروفایل
Section CTA: ذخیره اطلاعات پروفایل
Success toast: اطلاعات پروفایل با موفقیت ذخیره شد.
All field-level copy: identical to C2 Sections 2–5 (bio, avatar, links, specializations)
6. Two Independent Save Actions — Rationale & Behavior
اطلاعات هویتی and اطلاعات پروفایل are deliberately decoupled, each with its own CTA, its own validation, and its own success/error handling
The top-bar **ذخیره** button present in the original design is removed entirely — it created ambiguity about scope once the screen had two genuinely independent save actions; removing it avoids that ambiguity rather than trying to define what a combined "save everything" would even mean
A creator can save either block without needing to touch or complete the other
This decoupling is reinforced by distinct CTA language (ارسال مجدد اطلاعات هویتی vs. ذخیره اطلاعات پروفایل) specifically to prevent a Rejected creator from mistakenly believing an edit to their identity fields was saved by tapping the profile-info button, or vice versa
7. Field Editability Summary
Field Verified Pending Rejected
Username Locked Locked Locked
First name Locked Locked Editable (pre-filled)
Last name Locked Locked Editable (pre-filled)
National ID Locked Locked Editable (pre-filled)
National ID card image Locked (n/a — no re-upload) Locked (n/a) Editable (always empty)
Bio Editable Editable Editable
Avatar Editable Editable Editable
Social & web links Editable Editable Editable
Market specializations Editable Editable Editable
8. Exit & Unsaved Changes
Happy Path:
If the creator has no unsaved changes in either block and taps back, they exit immediately — no dialog
If the creator has unsaved changes in either block (identity edits not yet resubmitted, or profile info edits not yet saved), a confirmation dialog appears on exit attempt
Edge Cases:
The dialog checks both blocks independently — if only one block has unsaved changes, the dialog still appears, since any unsaved data would be lost
Dialog options: save-and-exit (triggers whichever block(s) have pending changes) or discard-and-exit
Farsi copy:
Exit confirmation dialog: تغییرات ذخیره‌نشده دارید. آیا می‌خواهید خارج شوید؟
Save-and-exit CTA: ذخیره و خروج
Discard-and-exit CTA: خروج بدون ذخیره
9. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Screen top-bar title: اطلاعات کاربری — do not confuse with the اطلاعات پروفایل section header within the page; the two operate at different scopes (screen-level vs. section-level)
Locked fields use {colors.ink-mute} (#64748d) text with a lock icon, background tinted {colors.canvas-soft} to visually read as non-interactive
Verification badge colors: Verified — {colors.primary} (#533afd) with checkmark; Pending — {colors.ink-mute} (#64748d) with clock icon; Rejected — {colors.ruby} (#ea2261) with warning icon
Rejection banner uses {colors.ruby} (#ea2261) background tint, positioned directly above the now-unlocked identity fields to draw immediate attention
Resubmit CTA (ارسال مجدد اطلاعات هویتی) uses button-primary-pill style (#533afd, pill radius) — visually distinct from the profile-info save CTA through label alone, not color, to avoid implying one action is "more correct" than the other
Profile info save CTA (ذخیره اطلاعات پروفایل) also uses button-primary-pill style, positioned at the bottom of that block, separated from the identity block by a clear divider/section break
Helper caption beneath the resubmit CTA uses {colors.ink-mute} (#64748d), smaller type size, non-bold
Minimum touch target for all interactive elements: 44×44px
Screen is mobile-first; on desktop, content is centered in a single column with max-width of 640px

File diff suppressed because one or more lines are too long

View File

@ -1,543 +0,0 @@
# Round 4 — Creator pricing & finance
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Keep amounts in ink color; the sign carries meaning. Ruby only for negative balance and cancelled payouts.
## Deliver in this round
- قیمت‌گذاری اشتراک: first-time setup with suggestions, edit mode, validation errors, promotion section, cooldown-locked state, confirmation dialog
- مالی: schedule notice, balance summary (normal, in-transfer, negative, suspended), next-payout line states
- شبا: empty state, form with live grouping and bank name, errors, duplicate warning, read-back dialog, saved state
- گردش حساب ledger (همه / واریزها) and detail views for each entry type and payout status, receipt viewer, empty and error states
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **C7** — Creator: Subscription Pricing & Tier Configuration _(ClickUp status: ready for development)_
- **C19** — Payout Details _(ClickUp status: in design)_
- **C20** — Earnings & Payouts _(ClickUp status: in design)_
---
## C7 — Creator: Subscription Pricing & Tier Configuration
C7 — Creator: Subscription Pricing & Tier Configuration
Story:
As a creator, I want to set my own subscription price and available billing periods so that I have full control over my monetization model.
Scope note: This story owns everything the creator configures about subscription pricing — tier availability, standing prices, promotional discounts, and validation. The investor-facing checkout flow is owned by U9; renewal and reactivation pricing behaviour is owned by U3; revenue reporting is owned by C9.
⚠️ Forward dependency note: Subscription purchase requires ZarinPal integration (U9) and referral-code gating (Epic 5). A creator can fully configure pricing while Pending Verification, but no subscription can be purchased until they are Verified.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
Pricing configuration is accessed from the creator's داشبورد tab
Available to creators in Pending Verification and Verified states — a Pending creator can configure pricing while awaiting admin review, consistent with how C2/C3 allow profile completion while Pending
Configuration is a single scrolling form covering all tiers
Edge Cases:
A Pending creator can save pricing, but their channel cannot be subscribed to until Verified — an informational note explains this
A Rejected creator can still view and edit pricing — the block is on monetization, not configuration
A Suspended creator cannot access the app at all (A2), so this screen is unreachable in that state
Farsi copy:
Screen heading: قیمت‌گذاری اشتراک
Pending verification note: پس از تأیید احراز هویت، کاربران می‌توانند در کانال شما مشترک شوند.
2. Tier Availability
Happy Path:
Four fixed tiers: ماهانه (1 month), سه‌ماهه (3 months), شش‌ماهه (6 months), سالانه (12 months)
ماهانه is mandatory and always enabled — it cannot be toggled off. It is the baseline every creator must offer and the reference point all other tiers are validated against
The three longer tiers are individually toggleable and default to ON — combined with pre-filled suggestions (Section 4), a creator entering a single monthly price arrives at a complete, valid four-tier structure with no further input. Longer tiers create commitment and retention for both sides, so the default favours offering them
A creator may toggle any longer tier off; offering only ماهانه is a complete, valid configuration
Enabling a tier reveals its price field; disabling hides it and removes it from investor-facing checkout
Edge Cases:
Disabling a tier with active subscribers does not affect them — existing subscriptions run to natural expiry at the price paid. The tier simply stops being offered to new subscribers; a note informs the creator
Custom durations (e.g. 4 or 8 months) are not supported in Phase 0 — fixed tiers only
Phase 1 candidate: custom tier durations. Deliberately deferred — every surface displaying a tier label (U2 cards, U3 date previews, U4 transaction history, C9 dashboard) currently assumes four known labels, and no founding creator has yet indicated the fixed tiers are insufficient. Add to founding-creator interview questions to gather evidence before building.
Farsi copy:
Tier labels: ماهانه · سه‌ماهه · شش‌ماهه · سالانه
Monthly mandatory note: اشتراک ماهانه همیشه فعال است و قابل غیرفعال‌سازی نیست.
Disabling with active subscribers note: {n} مشترک فعال روی این دوره دارید. با غیرفعال کردن، اشتراک آن‌ها تا پایان دوره ادامه می‌یابد و فقط این دوره برای کاربران جدید نمایش داده نمی‌شود.
3. Standing Prices — Entry & Floors
Happy Path:
The creator enters a total price for each enabled tier (not a percentage, not a per-month figure) — the full amount an investor pays for that duration
Beneath each field, the system displays the computed per-month equivalent — how the creator sanity-checks their structure
Each tier has a minimum per-month standing price, declining with duration so long-tier discounting remains possible:
Tier Minimum standing price (per month)
ماهانه ۲۹۹,۰۰۰ تومان
سه‌ماهه ۲۶۵,۰۰۰ تومان
شش‌ماهه ۲۳۰,۰۰۰ تومان
سالانه ۱۹۹,۰۰۰ تومان
Floors are hardcoded in Phase 0; admin configurability is a Phase 1 item
There is no maximum price — premium positioning for a smaller, higher-value audience is a legitimate strategy the platform does not constrain
Edge Cases:
Prices entered in تومان, whole numbers only — no decimals
Per-month equivalent displayed rounded to the nearest تومان; the stored total price is exact
Typo protection comes from the confirmation dialog (Section 7), not from a price ceiling
Error States:
Price below the tier's floor → inline error naming that tier's specific minimum
Empty price on an enabled tier → inline error; the tier cannot be saved without a price
Non-numeric input → rejected at the input layer
Farsi copy:
Price field label: قیمت کل دوره
Per-month equivalent display: معادل {amount} تومان در ماه
Floor helper text (beneath each tier's field): حداقل قیمت این دوره {amount} تومان در ماه است.
Below-floor error: قیمت این دوره نمی‌تواند کمتر از {amount} تومان در ماه باشد.
Empty price error: وارد کردن قیمت برای دوره‌های فعال الزامی است.
4. Price Suggestions
Happy Path:
When the creator enters their monthly price, the system computes suggested prices for the three longer tiers using platform-standard discounts:
Tier Suggested discount off monthly × duration
سه‌ماهه 10%
شش‌ماهه 20%
سالانه 30%
Suggested prices are rounded down to the nearest ۱,۰۰۰ تومان, consistent with promotional rounding (Section 6)
First-time setup (no tier prices saved yet): suggestions are pre-filled directly into the price fields — fastest path for the common case, fully editable
Subsequent edits (tier prices already exist): suggestions appear as hint text beneath the field only — existing values are never overwritten, since a creator who deliberately set a price should not have it silently replaced
Worked example at ۴۰۰,۰۰۰ monthly:
Tier Full (monthly × duration) Suggested Per month
سه‌ماهه ۱,۲۰۰,۰۰۰ ۱,۰۸۰,۰۰۰ ۳۶۰,۰۰۰
شش‌ماهه ۲,۴۰۰,۰۰۰ ۱,۹۲۰,۰۰۰ ۳۲۰,۰۰۰
سالانه ۴,۸۰۰,۰۰۰ ۳,۳۶۰,۰۰۰ ۲۸۰,۰۰۰
Edge Cases:
Because the tier floors decline faster than the suggested discounts deepen, a suggested price can never fall below its tier floor at any monthly price. At the lowest legal monthly price (۲۹۹,۰۰۰): سه‌ماهه ۲۶۹,۰۰۰/mo (floor ۲۶۵,۰۰۰), شش‌ماهه ۲۳۹,۰۰۰/mo (floor ۲۳۰,۰۰۰), سالانه ۲۰۹,۰۰۰/mo (floor ۱۹۹,۰۰۰). No clamping logic is required
Changing the monthly price later does not overwrite existing longer-tier prices — it only re-computes hint text, and flags any tier that now violates validation (Section 5)
Suggestions are guidance only — a creator may ignore them entirely, provided validation passes
Farsi copy:
Suggestion hint text: پیشنهاد: {amount} تومان
5. Validation — Per-Month Cost Must Not Increase With Duration
Happy Path:
Core rule: a longer tier's per-month cost must be less than or equal to that of every shorter enabled tier, guaranteeing longer commitment never costs more per month
Validation runs live as the creator types and again on save
Edge Cases:
Validation compares against enabled tiers only — disabled tiers are ignored
Equal per-month cost is permitted (a longer tier at no discount — unusual, not invalid)
If the creator raises their monthly price such that an existing longer tier now costs more per month, that tier is flagged immediately
Violating prices cannot be saved — save is blocked until every enabled tier passes. There is no "save anyway" override
Error States:
Per-month cost higher than a shorter tier → inline error naming the conflict explicitly
Multiple violations → all flagged simultaneously, not one at a time
Farsi copy:
Validation error: قیمت ماهانه این دوره ({amount} تومان) نباید بیشتر از دوره {shorter_tier} ({amount} تومان) باشد.
Blocked save message: برای ذخیره، ابتدا خطاهای قیمت‌گذاری را برطرف کنید.
6. Promotional Discounts
Promotions are a separate mechanic from standing prices. A standing price is the creator's permanent, normal price; a promotion is a temporary reduction off it.
Happy Path:
A promotion can be applied to any enabled tier, including ماهانه
The creator enters a percentage (whole numbers, 1–99) — percentages are how discounts are conventionally communicated, and the تخفیف badge reads naturally from them
Each promotion has a start date and time and an end date and time (Shamsi calendar). The end may be set to indefinite — the promotion runs until the creator ends it
The system computes the effective price and rounds down to the nearest ۱,۰۰۰ تومان — rounding down ensures the investor always receives at least the advertised discount, never slightly less
Promotions are per-tier and independent — a creator may run 30% off سالانه while offering nothing on ماهانه; multiple tiers may run promotions simultaneously
Both the total promotional price and its per-month equivalent are displayed to the creator alongside the standing price and its per-month equivalent, so the full before/after comparison is visible while deciding
Promotion controls are always available, including during the standing-price cooldown (Section 8) — the cooldown governs permanent pricing only, never temporary offers
Worked example: standing price ۲۹۹,۰۰۰ with 30% off = ۲۰۹,۳۰۰ → displayed as ۲۰۹,۰۰۰
Promotional floor:
The effective promotional price may not fall below ۹۹,۰۰۰ تومان per month — a single flat floor across all tiers, regardless of duration
Deliberately far below the standing-price floors, allowing genuinely aggressive acquisition pricing while preventing fee-negative transactions
Scope of application — all purchase moments:
Purchase type Promotion applies?
New subscription ✅ Yes
Reactivation (expired subscription, buying again) ✅ Yes
Renewal (active subscription, extending early) ✅ Yes
A promotion applies at every moment an investor pays, with no exceptions
Rationale: a lapsed subscriber is someone the creator is re-acquiring — precisely who a win-back promotion targets. And for early renewal, a discount is the only thing that makes renewing early rational: the extension runs from the current expiry date either way (U3 Section 3), so without a promotion the investor gains nothing by paying sooner. Early renewal is a retention win — revenue arrives earlier, and the subscriber removes themselves from churn risk at the expiry moment
What a promotion never does: retroactively alter an already-purchased subscription. Someone who paid ۴۰۰,۰۰۰ last week receives no partial refund when a 30% promotion launches today — they receive the promotional price only if they choose to renew or reactivate during the promotional window
Ending a promotion:
A creator ends a promotion by toggling it off or deleting it, then saving — the change takes effect on save, not on toggle
Ending early affects only purchases made after that moment
Edge Cases:
The 7-day pricing cooldown (Section 8) does not apply to promotions — promos are inherently temporary and explicitly marked as such to investors; a Nowruz promo followed by an Eid promo two weeks later is normal behaviour, not thrash. A creator locked out of their main acquisition lever because they adjusted a standing price five days earlier would be a genuine handicap
A promotion ending mid-subscription has no effect on that subscriber — they paid the promotional price for a full term and keep it. At renewal they see whatever pricing is current at that moment
Promotions may be scheduled with a future start date and time
One active promotion per tier in Phase 0 — multiple scheduled promotions with different date ranges on the same tier is deferred to a later phase
No validation on discount depth beyond the floor — any percentage is permitted subject to the ۹۹,۰۰۰ minimum, with confirmation on save (Section 7)
Error States:
Effective price below ۹۹,۰۰۰/month → inline error showing the computed price and the floor
End date/time before or equal to start date/time → inline error
Percentage outside 1–99 → inline error
Farsi copy:
Section label: تخفیف دوره‌ای
Percentage field label: درصد تخفیف
Start/end labels: تاریخ و ساعت شروع / تاریخ و ساعت پایان
Indefinite end option: بدون تاریخ پایان
Computed price display: قیمت با تخفیف: {amount} تومان (معادل {amount} تومان در ماه)
Promotional floor error: قیمت با تخفیف ({amount} تومان در ماه) نمی‌تواند کمتر از ۹۹,۰۰۰ تومان در ماه باشد.
Invalid date range error: تاریخ و ساعت پایان باید بعد از شروع باشد.
Invalid percentage error: درصد تخفیف باید بین ۱ تا ۹۹ باشد.
Scope note: تخفیف برای خرید جدید، تمدید و خرید مجدد اعمال می‌شود، اما روی اشتراک‌های خریداری‌شده قبلی تأثیری ندارد.
7. Save & Confirmation Dialog
Happy Path:
On tapping save, a confirmation dialog summarises the full pricing structure before anything is committed
Every enabled tier is listed with its total price and per-month equivalent. Where a promotion is active, the dialog additionally shows the promotional price in both total and per-month terms, alongside the discount percentage and end date — the complete before/after picture in one view
The dialog also carries the cooldown warning and the safety-valve explanation (Section 8), so the creator understands the consequences of committing at the moment of committing
Confirming saves; cancelling returns to the form with all values intact
Example dialog content:
تأیید قیمت‌گذاری
ماهانه ۴۰۰,۰۰۰ تومان (۴۰۰,۰۰۰ در ماه)
سه‌ماهه ۱,۰۸۰,۰۰۰ تومان (۳۶۰,۰۰۰ در ماه)
سالانه ۳,۶۰۰,۰۰۰ تومان (۳۰۰,۰۰۰ در ماه)
تخفیف ۲۵٪ تا ۱۵ تیر ۱۴۰۴
معادل ۲,۷۰۰,۰۰۰ تومان (۲۲۵,۰۰۰ در ماه)
پس از اولین خرید با این قیمت‌ها، تا ۷ روز امکان تغییر قیمت وجود ندارد.
تا زمانی که خریدی انجام نشده، می‌توانید قیمت‌ها را آزادانه ویرایش کنید.
تنظیم تخفیف در هر زمان امکان‌پذیر است.
[تأیید و ذخیره] [انصراف]
Edge Cases:
The dialog appears on every save, not only the first — it is the platform's primary typo protection at any price level, replacing the need for a maximum price
If validation fails, the dialog does not appear — errors are surfaced inline first (Section 5)
Saving with no changes still shows the dialog; harmless, and keeps behaviour predictable
Error States:
Network failure on save: error banner, all entered values preserved, retry available
Farsi copy:
Dialog heading: تأیید قیمت‌گذاری
Per-month suffix: ({amount} در ماه)
Promotion lines: تخفیف {n}٪ تا {end_date} / معادل {amount} تومان ({amount} در ماه)
Indefinite promotion line: تخفیف {n}٪ (بدون تاریخ پایان)
Cooldown warning: پس از اولین خرید با این قیمت‌ها، تا ۷ روز امکان تغییر قیمت وجود ندارد.
Safety valve note: تا زمانی که خریدی انجام نشده، می‌توانید قیمت‌ها را آزادانه ویرایش کنید.
Promotion exemption note: تنظیم تخفیف در هر زمان امکان‌پذیر است.
Confirm CTA: تأیید و ذخیره
Cancel CTA: انصراف
Save success toast: قیمت‌گذاری با موفقیت ذخیره شد.
Network error banner: خطا در ذخیره‌سازی. اتصال اینترنت خود را بررسی کنید.
8. Changing Prices After Launch — Cooldown & Safety Valve
Happy Path:
A creator may change standing prices at any time, subject to a 7-day cooldown between changes
The cooldown does not begin at save — it begins at the first subscription purchased at the new price. Until someone actually buys, the creator can edit freely and as often as they like
Existing subscribers are unaffected by any price change — they keep the price they purchased at until expiry. At renewal they see the current standing price (or promotional price, if one is active), with U3's price-change note explaining any difference
The cooldown is per-creator, not per-tier — one change resets it for the entire standing-price configuration
Rationale for the safety valve: the scenario a cooldown must not punish is a creator saving a typo and discovering it minutes later. Tying the cooldown to first purchase rather than to save eliminates that entirely, without ever creating a subscriber who paid a price the creator immediately revoked. A fixed post-save edit window was considered and rejected: unlike editing a post (C4's 15-minute window), pricing is immediately purchasable, so a timed window would allow real money to change hands at a price still being edited.
Edge Cases:
The cooldown applies to standing prices and tier toggles only. Promotion controls — creating, editing, and ending — remain fully available at all times, including during cooldown (Section 6). The cooldown governs permanent pricing, never temporary offers
Toggling a tier on or off counts as a standing-price change and is subject to the same cooldown rules
During cooldown, only standing-price fields and tier toggles are read-only — the promotion section of each tier remains fully interactive
The cooldown notice is shown in two places: persistently on the form whenever it is locked (so the creator knows before typing, not after), and in the confirmation dialog at save time (so they know the clock is about to start). In both places the notice explicitly states that promotions remain editable, so a creator seeing a locked form doesn't assume promotions are locked too
Error States:
Attempting to edit standing prices during cooldown → those fields are not editable; notice shows when editing becomes available again
Phase 0 tuning note: 7 days is a starting value, not a fixed constraint. If founding creators report it as too restrictive during interviews, shortening it is a trivial configuration change — gather that evidence before adjusting.
Farsi copy:
Cooldown notice (on locked form): قیمت‌ها را هر ۷ روز یک‌بار می‌توانید تغییر دهید. امکان ویرایش بعدی: {date} — تنظیم تخفیف در هر زمان امکان‌پذیر است.
Pre-purchase editable note (on form, before first sale at current prices): هنوز خریدی با این قیمت‌ها انجام نشده — می‌توانید آزادانه ویرایش کنید.
Existing subscribers note (shown when editing prices): تغییر قیمت روی مشترکان فعلی تأثیری ندارد. قیمت جدید از زمان تمدید اشتراک آن‌ها اعمال می‌شود.
9. Investor-Facing Display (Reference)
How configured prices appear in checkout is owned by U9, but the display rules originate here:
When a longer tier's total is less than monthly × duration, checkout shows the higher figure struck through alongside the actual price — making the saving visible without the creator configuring anything
When a promotion is active, the strike-through shows the standing tier price (not the monthly-derived comparison), the live price shows the promotional price, and a تخفیف badge marks it. The monthly-derived comparison recedes in this state — one clear "before" figure, never two competing ones
Promotional time remaining is displayed as a plain date beyond 48 hours and switches to a live hourly countdown within 48 hours (U9 Section 3) — urgency appears only when it is real
Because promotions apply to renewals and reactivations as well as new subscriptions, these same display rules apply in U3's renewal and reactivation flows, not only in U9's first-purchase checkout
Disabled tiers do not appear in checkout at all
10. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
All prices and per-month equivalents use font-feature-settings: "tnum" — non-negotiable per the design system's tabular-figures rule for monetary values
Each tier renders as a card-feature-light block containing its toggle, price field, per-month equivalent, floor helper text, and promotion controls
The mandatory ماهانه tier renders without a toggle — its permanence is visually evident, not an interaction the creator can attempt
Disabled tiers collapse to just their toggle row — price fields and promotion controls hidden, not merely greyed
Price input fields use text-input style with a تومان suffix; numeric keyboard on mobile
Per-month equivalent renders in {colors.ink-mute} (#64748d), {typography.caption} — supporting information, not the primary figure
Floor helper text renders in {colors.ink-mute}; on violation, the same line switches to {colors.ruby} (#ea2261) with the specific error
Suggestion hint text renders in {colors.ink-mute}, visually distinct from both entered values and error states
Promotion section within each tier sits on {colors.canvas-soft} (#f6f9fc) to distinguish it from standing-price configuration — and remains at full opacity during cooldown, while standing-price fields above it dim, making the distinction visually obvious
تخفیف badge uses {colors.ruby} (#ea2261) background with white text, pill-tag-soft style — the one place ruby is used affirmatively rather than as an error, since a discount badge is conventionally red in Iranian e-commerce
Save CTA uses button-primary-pill (#533afd); blocked state uses opacity: 0.4 with cursor: not-allowed
Cooldown read-only state renders standing-price fields and tier toggles at opacity: 0.5, with the cooldown notice prominently above the form
Confirmation dialog uses the standard modal pattern; confirm CTA button-primary-pill
Minimum touch target for all interactive elements: 44×44px
Form is mobile-first; desktop single column, max-width 560px
---
## C19 — Payout Details
C19 — Payout Details
Story: As a Creator, I want to register my bank payout details (شماره شبا), so that the platform can transfer the money I have earned.
Acceptance Criteria
Section 1 — Access & Entry Point
1.1 Payout details live under داشبورد → مالی. The section holds these blocks in order: the payout schedule notice, موجودی (C20), اطلاعات تسویه‌حساب (this story), تاریخچه واریز (C20).
Still a proposal until Epic 6 fixes the creator dashboard's sub-navigation.
1.2 Only the authenticated creator can see it, and only for their own account.
1.3 Gated on identity verification. While C1 verification is pending or rejected, the block shows locked:
پس از تأیید احراز هویت، می‌توانید اطلاعات تسویه‌حساب خود را ثبت کنید.
Section 2 — Payout Schedule Notice
2.1 A static notice sits at the top of the مالی section and is always visible:
واریز درآمد هر هفته، روزهای پنجشنبه انجام می‌شود. زمان نشستن مبلغ در حساب شما به چرخه‌های بانکی بستگی دارد. در صورت تعطیلی، واریز در اولین روز کاری بعد انجام خواهد شد.
2.2 The payout day is a config value ({payout_day}), not hard-coded copy, so changing the cadence doesn't need a release.
Section 3 — Empty State
3.1 With no شبا on file:
اطلاعات تسویه‌حساب
هنوز شماره شبای خود را ثبت نکرده‌اید. تا زمان ثبت آن، امکان واریز درآمد شما وجود ندارد.
3.2 CTA (button-primary-pill):
ثبت شماره شبا
3.3 If the creator has a balance above zero, a {colors.warning} note appears above the CTA:
درآمد شما در لومینا محفوظ است، اما تا ثبت شماره شبا قابل واریز نیست.
Section 4 — The Form
4.1 One field and one checkbox.
4.2 شماره شبا: text-input, dir="ltr", left-aligned, font-feature-settings: "tnum". IR is a fixed, non-editable prefix, and the 24 digits are grouped in fours as they're typed: IR## #### #### #### #### #### ##.
4.3 Helper text:
شماره شبای ۲۴ رقمی خود را وارد کنید. می‌توانید شبا را به‌صورت کامل کپی و اینجا جای‌گذاری کنید.
4.4 Normalization on type or paste, applied silently:
A leading IR / ir is stripped
Spaces, dashes and dots are stripped
Persian (۰–۹) and Arabic (٠–٩) digits are converted to Latin
4.5 Bank name, shown only once the bank code is present and recognised, in {colors.ink-mute} below the field:
بانک: بانک ملت
If the code isn't recognised, nothing is shown: no error, no placeholder.
4.6 Mandatory responsibility checkbox:
تأیید می‌کنم که این شماره شبا متعلق به من است. مسئولیت صحت آن، از جمله ثبت شبای متعلق به شخص یا نهاد دیگر، به‌طور کامل بر عهده من است و لومینا در قبال واریز به حساب اشتباه مسئولیتی ندارد.
4.7 Submit CTA, disabled until validation passes and the checkbox is ticked:
ثبت شماره شبا
Section 5 — Validation
5.1 Validation runs on blur and again on submit. Errors appear in {colors.ruby} below the field.
Condition Message
Empty شماره شبا را وارد کنید.
Not 24 digits after normalization شماره شبا باید ۲۴ رقم باشد.
Non-numeric characters شماره شبا فقط شامل عدد است.
Mod-97 checksum fails شماره شبای واردشده معتبر نیست. لطفاً آن را بررسی کنید.
Checkbox unticked برای ثبت، تأیید مسئولیت صحت اطلاعات الزامی است.
5.2 The checksum is the only real guard against typos. It catches every single-digit error and almost every transposition.
Section 6 — Duplicate شبا Warning
6.1 If the شبا already exists on another Lumina account, a {colors.warning} notice shows under the field. It's a warning, not a blocker:
این شماره شبا قبلاً در حساب کاربری دیگری در لومینا ثبت شده است. در صورت اطمینان از صحت آن، می‌توانید ادامه دهید.
6.2 The warning never says which account holds it.
6.3 Legitimate cases are an organisation running two channels, or a family sharing an account. That's why it doesn't block.
Token note: this uses {colors.warning} for a non-blocking caution rather than a time-sensitive one, which is wider than the scope we documented for that token. I think it's the right meaning for amber, but the token's description should be updated to say so.
Section 7 — Confirmation & Save
7.1 Submitting opens a read-back dialog:
ثبت شماره شبا
درآمد شما به این حساب واریز خواهد شد:
شماره شبا: IR62 0120 0000 0010 1234 5678 90
بانک: بانک ملت
لطفاً شماره را با اطلاعات بانک خود تطبیق دهید. واریز به حساب اشتباه قابل بازگشت نیست.
7.2 The بانک line is omitted if the code wasn't recognised. The شبا renders LTR, in groups of four, with tabular figures.
7.3 CTAs: ثبت نهایی (button-primary-pill) and ویرایش (button-secondary, which returns to the form with the value kept).
7.4 On success, the form collapses into the saved state and a toast confirms:
شماره شبا با موفقیت ثبت شد.
7.5 No admin approval. The شبا is used from the next payout onward.
Section 8 — Saved State & Editing
8.1 The saved card shows the full شبا (LTR, grouped), the bank name if recognised, and the last-updated date in Shamsi:
آخرین به‌روزرسانی: ۵ مهر ۱۴۰۵
8.2 An inline ویرایش action opens the same form, pre-filled, with the same validation, checkbox and read-back dialog. The checkbox must be ticked again on every edit.
8.3 An edit takes effect immediately, including for the next Thursday payout. There's no approval and no hold.
8.4 Every version is kept with a timestamp. Records are never overwritten, so the شبا used for any past payout can always be traced.
Section 9 — Change Notification
9.1 Each edit (not the first registration) triggers an SMS to the creator's registered mobile number:
شماره شبای حساب شما در لومینا تغییر کرد. اگر این تغییر توسط شما انجام نشده، فوراً با پشتیبانی تماس بگیرید.
lumina.ir/dashboard/finance
لومینا
9.2 An in-app notification mirrors the SMS.
9.3 With admin approval gone, this is what stops a hijacked account from silently redirecting a payout. It costs one SMS per edit.
Section 10 — Admin Visibility (hand-off to A15)
10.1 C19 has no admin approval step. The admin sees payout details in the A15 payout screen, next to each creator's balance:
Current شبا and bank name
Last-updated timestamp
Flag: شبای تکراری if it's shared with another account
Flag: تغییر در ۷ روز اخیر if it was edited within 7 days before the payout
10.2 The ownership check happens manually at transfer time. Before confirming a پایا or ساتنا, the admin compares the holder name shown by the bank against the creator's C1-verified name. The exact steps belong in A15.
Section 11 — Edge Cases
# Case Behavior
11.1 Creator suspended (A2) Block is read-only: حساب شما معلق است و امکان ویرایش شماره شبا وجود ندارد.
11.2 Edit saved on Thursday while the admin is paying The admin uses whichever شبا is shown at the moment of transfer, and A15 records it on the payout. The تغییر در ۷ روز اخیر flag makes the change visible
11.3 Balance exists but no شبا on payout day Creator is skipped and the balance carries over. The prompt in 3.3 stays visible
11.4 Browser autofill puts a 16-digit card number in the field Caught by length and checksum validation
11.5 Form abandoned mid-entry Nothing is saved. No drafts
11.6 Creator re-enters the same شبا already on file Saves normally, updates the timestamp, no SMS (nothing changed)
Section 12 — Error States
Condition Message
Save fails (network) ثبت انجام نشد. لطفاً دوباره تلاش کنید.
Save fails (server) خطایی رخ داد. لطفاً چند لحظه دیگر تلاش کنید.
Session expired جلسه شما منقضی شده است. لطفاً دوباره وارد شوید.
12.1 On any failure the typed شبا is kept, so the creator never has to re-type 24 digits.
Section 13 — Design Notes
Block: card-feature-light on {colors.canvas-soft}
Field: text-input, the only LTR element on an RTL page, with tabular figures
Primary CTA: button-primary-pill; secondary: button-secondary
Warnings: {colors.warning}; errors: {colors.ruby}; bank name and timestamp: {colors.ink-mute}
Touch targets ≥ 44×44px; Yekan Bakh throughout
---
## C20 — Earnings & Payouts
C20 — Earnings & Payouts
Story: As a Creator, I want to see my payable balance and a record of every earning and payout, so that I know exactly what I am owed and what has reached me.
Acceptance Criteria
Section 1 — Access & Layout
1.1 Location: داشبورد → مالی. Order, top to bottom:
Payout schedule notice (C19 §2)
Balance summary (§2)
Next payout line (§3)
اطلاعات تسویه‌حساب (C19)
گردش حساب (§4)
1.2 Only the authenticated creator can see it, and only for their own account.
1.3 Subscriber privacy, platform-wide: anywhere in this section, a subscriber is identified by username only. Their phone number and full name never appear in the UI, in notifications, in receipts, or in any creator-facing export or API response. The rule is enforced on the server: those fields never leave the backend in any creator-scoped response.
1.4 All amounts are whole تومان, Persian digits, ٬ separators, font-feature-settings: "tnum".
Section 2 — Balance Summary
2.1 Two figures:
Label Meaning Tooltip (ⓘ)
قابل واریز Confirmed earnings not yet paid out or in transfer این مبلغ در واریز بعدی به حساب شما منتقل می‌شود.
مجموع واریزشده Lifetime total of payouts with status انجام شده مجموع مبالغی که تاکنون به حساب شما واریز شده است.
2.2 Hierarchy: قابل واریز is the primary figure: larger, in {colors.brand-dark-900}. مجموع واریزشده sits beneath it as a secondary line.
2.3 In-transfer line, shown only when one or more payouts are در حال انجام, directly under the primary figure in {colors.ink-mute}:
در حال واریز: ۱٬۲۵۰٬۰۰۰ تومان
2.4 Negative balance. The label stays قابل واریز. The figure shows the negative amount in {colors.ruby}, with this explanation directly below:
قابل واریز: −۱۲۰٬۰۰۰ تومان
این مبلغ بابت بازگشت وجه به مشترکان است و از درآمدهای بعدی شما کسر می‌شود.
2.5 Rendering note (dev): every signed amount, whether in this figure or in ledger rows, is wrapped in an LTR isolate (<bdi dir="ltr"> or unicode-bidi: isolate; direction: ltr) so the sign stays attached to the left of the digits. The word تومان sits outside the isolate.
Section 3 — Next Payout Line
3.1 One line, depending on state:
State Copy
Available > 0 and a شبا on file واریز بعدی: پنجشنبه ۱۰ مهر ۱۴۰۵
Available > 0, no شبا برای دریافت واریز، ابتدا شماره شبای خود را ثبت کنید. (anchor link to the C19 block)
Available ≤ 0 and nothing in transfer در حال حاضر مبلغی برای واریز وجود ندارد.
Available ≤ 0, a payout in transfer Line hidden: the in-transfer line (§2.3) is enough
Account suspended See §9.1
3.2 The date comes from {payout_day} in Asia/Tehran time. Holidays aren't computed; C19 §2's copy covers them.
3.3 No minimum payout threshold in Phase 0. Any positive available amount is eligible.
Section 4 — The Ledger (گردش حساب)
4.1 One reverse-chronological list with two tabs: همه and واریزها.
4.2 Entry types:
Type Label Sign Created by
Subscription income درآمد اشتراک + U10 (successful payment) or A13 (reconciled payment)
Payout واریز به حساب − A15
Refund deduction کسر بازگشت وجه − A16, exceptional cases only
Correction اصلاحیه ± Admin, mandatory reason
4.3 Row anatomy:
Line 1: type label, with the signed amount on the opposite edge
Line 2 in {colors.ink-mute}: context, then the Shamsi date
Type Line 2 example
درآمد اشتراک @username · اشتراک ۳ ماهه · ۵ مهر ۱۴۰۵
واریز به حساب شبای …۵۶۷۸۹۰ · ۱۰ مهر ۱۴۰۵
کسر بازگشت وجه @username · بازگشت وجه اشتراک ۱۲ ماهه · ۸ مهر ۱۴۰۵
اصلاحیه {reason, one line} · ۱۱ مهر ۱۴۰۵
4.4 Payout status pills. Only non-final states are marked:
Status Pill Amount display
در حال انجام pill-tag-soft, {colors.ink-mute} Normal
انجام شده None, the default Normal
لغو شده pill-tag-soft, {colors.ruby} Struck through, {colors.ink-mute}
4.5 Amounts are in ink, and the sign carries the meaning. Red appears only on the negative balance and the لغو شده pill.
4.6 20 rows per page, with نمایش بیشتر. No filters, date ranges or search in Phase 0.
4.7 Each row opens a detail view: a bottom sheet on mobile, a side panel on desktop.
Section 5 — Entry Detail
5.1 درآمد اشتراک:
جزئیات درآمد
قیمت طرح: ۲۹۹٬۰۰۰ تومان
تخفیف: ۲۰٪ (only if a promotion applied)
مبلغ پرداختی مشترک: ۲۳۹٬۰۰۰ تومان
کارمزد لومینا ({commission_rate}٪): −۳۵٬۸۵۰ تومان
سهم شما: ۲۰۳٬۱۵۰ تومان
مشترک: @username
طرح: ۳ ماهه
تاریخ پرداخت: ۵ مهر ۱۴۰۵، ۱۴:۲۲
5.2 The rate shown is the rate stored with that payment, not the current one.
5.3 واریز به حساب:
جزئیات واریز
مبلغ: ۱٬۲۵۰٬۰۰۰ تومان
وضعیت: در حال انجام
تاریخ ثبت: ۱۰ مهر ۱۴۰۵، ۱۱:۰۵
شبای مقصد: IR62 •••• •••• •••• •••• 5678 90
[مشاهده رسید] [دانلود رسید]
5.4 While the status is در حال انجام, the detail view adds a note in {colors.ink-mute}:
بسته به چرخه‌های بانکی، مبلغ معمولاً طی ۱ تا ۲ روز کاری به حساب شما می‌نشیند.
5.5 Once the status is انجام شده, the view adds the completion date:
تاریخ انجام: ۱۳ مهر ۱۴۰۵
The creator is not told whether completion was automatic or manual. That distinction is visible to the admin only.
5.6 The destination شبا is the one recorded when the payout was created, not the creator's current شبا.
5.7 The receipt buttons are always present. A payout can't exist without a receipt, because A15 requires one at creation.
5.8 For لغو شده, the view adds:
تاریخ لغو: ۱۲ مهر ۱۴۰۵
دلیل: {reason}
این مبلغ به موجودی قابل واریز شما بازگشت داده شد.
5.9 کسر بازگشت وجه: the refunded subscription (plan, subscriber username, original payment date), the total refunded to the investor, and the creator's portion deducted.
5.10 اصلاحیه: the amount, the full reason, and the date. The admin's identity is never shown.
Section 6 — How Balances Move
6.1 Auditable history. Income, refund and correction entries are never edited or deleted. A payout's status can change, but every transition is logged with a timestamp, the actor (admin or system), and a reason where one is required. Balances are always derived from these records, never stored as editable numbers.
6.2 Income. Commission = {commission_rate} × amount actually paid (after any promotion), rounded down to a whole تومان. Creator share = amount paid − commission.
6.3 The rate is stored with each income entry at payment time. {commission_rate} is a single global config value that only the tech team changes. There is no admin UI and no per-creator rate in Phase 0.
6.4 Availability. Income is added to قابل واریز immediately on payment confirmation. For a payment resolved later through A13, it becomes available at the moment of resolution.
6.5 Payout lifecycle:
From To Triggered by Effect
— در حال انجام Admin records the payout with amount + receipt (A15) Amount leaves قابل واریز and appears in the in-transfer line (§2.3)
در حال انجام انجام شده Automatically, {auto_complete_hours} after creation, or earlier by an admin Amount moves from in-transfer to مجموع واریزشده. قابل واریز unchanged
در حال انجام لغو شده Admin, mandatory reason Amount returns to قابل واریز
انجام شده لغو شده Admin, mandatory reason (e.g. a bounced transfer) Amount leaves مجموع واریزشده and returns to قابل واریز
6.6 No other transitions exist, and لغو شده is final. The system never cancels on its own: every cancellation is a human decision with a reason.
6.7 {auto_complete_hours} defaults to 72. Payouts go out on Thursday, Friday is a holiday, and a Thursday transfer often lands on Saturday. 24 hours would mark payouts complete before the money arrives. 72 hours covers the normal weekend. Long holidays (نوروز and similar) are handled manually by the admin.
6.8 Automatic completion doesn't depend on any creator action. A creator who hasn't received a payout reports it through the creator support channel. If the report is confirmed, the admin cancels the payout from whichever state it's in.
6.9 The completion job is idempotent. If it runs late, the payout completes on the next run, and the recorded completion time is the actual transition time, not the scheduled time.
6.10 A payout amount can't exceed قابل واریز at the moment it's created. Enforced in A15.
6.11 A refund deduction comes out of قابل واریز and may take it below zero. New income offsets the negative balance first, and no payout can be created while قابل واریز ≤ 0.
Section 7 — Receipts
7.1 Receipts are uploaded by the admin when the payout is created (A15), as an image (JPG/PNG) or a PDF.
7.2 An image receipt opens in C4's full-screen lightbox (close with ✕ or the back gesture). A PDF opens in a new browser tab.
7.3 دانلود رسید saves the original file, uncompressed.
7.4 Receipts are private to their creator, served through signed, expiring URLs, so a copied link never becomes a public document.
Section 8 — Notifications
All mandatory, none can be turned off.
8.1 Payout created (در حال انجام), SMS plus in-app plus push. This is the creator's main payout notification:
مبلغ ۱٬۲۵۰٬۰۰۰ تومان بابت درآمد شما در لومینا به حساب با شبای …۵۶۷۸۹۰ ارسال شد و بسته به چرخه‌های بانکی، معمولاً طی ۱ تا ۲ روز کاری به حساب شما می‌نشیند. رسید واریز در بخش مالی داشبورد قابل مشاهده است.
lumina.ir/dashboard/finance
لومینا
8.2 Payout completed (انجام شده): no notification. Automatic completion comes from a timer, not a confirmation from the bank. Telling the creator «واریز شد» at that moment would be asserting something we haven't checked. The status change shows in the ledger only.
8.3 Payout cancelled (لغو شده), SMS plus in-app:
واریز مبلغ ۱٬۲۵۰٬۰۰۰ تومان به حساب شما لغو شد و این مبلغ به موجودی قابل واریز شما بازگشت. دلیل و جزئیات در بخش مالی داشبورد قابل مشاهده است.
lumina.ir/dashboard/finance
لومینا
The reason stays out of the SMS because it's free text from an admin.
8.4 Refund deduction, SMS plus in-app:
مبلغ ۶۰۰٬۰۰۰ تومان بابت بازگشت وجه اشتراک یکی از مشترکان، از موجودی شما در لومینا کسر شد. جزئیات در بخش مالی داشبورد قابل مشاهده است.
lumina.ir/dashboard/finance
لومینا
The SMS never names the subscriber.
8.5 Correction, in-app only:
یک اصلاحیه به مبلغ {amount} تومان در حساب مالی شما ثبت شد.
8.6 No notification for individual income entries. Whether creators get a "new subscriber" notification is an Epic 6 question.
Section 9 — Edge Cases
# Case Behavior
9.1 Creator suspended (A2) Figures stay visible. The next payout line becomes: به دلیل تعلیق حساب، موجودی شما تا زمان رسیدگی مسدود است و واریزی انجام نمی‌شود. Income from existing subscriptions still records; no new payout can be created. A payout already در حال انجام still auto-completes, because that money has already left
9.2 Payment stuck in در حال بررسی No entry until A13 resolves it. A payment that fails reconciliation never appears
9.3 Creator reports non-receipt while the payout is در حال انجام No in-app action. The admin investigates, and either cancels or lets automatic completion run
9.4 Transfer bounces after automatic completion Admin moves انجام شده → لغو شده with a reason; amount returns; SMS 8.3 corrects the earlier SMS 8.1
9.5 Admin marks a payout انجام شده before the timer Allowed; the timer is cancelled for that payout
9.6 Completion job runs late (outage, deploy) Completes on the next run (§6.9); no notification either way
9.7 Creator edits شبا while a payout is در حال انجام The payout keeps the شبا recorded at creation
9.8 Commission rate changes Past entries unchanged; new entries use the new rate
9.9 Subscriber deletes or loses their account Rows keep the username captured at payment time
9.10 Page open while a status changes No live update; the next load shows the new state
9.11 Two entries with the same timestamp Ordered by entry ID
Section 10 — Empty States
10.1 No entries at all:
هنوز درآمدی ثبت نشده است. پس از اولین اشتراک در کانال شما، جزئیات درآمد اینجا نمایش داده می‌شود.
Both figures show ۰ تومان, and the layout stays intact.
10.2 واریزها tab with no payouts:
هنوز واریزی به حساب شما انجام نشده است.
Section 11 — Error States
Condition Message
Section fails to load بارگذاری اطلاعات مالی انجام نشد. لطفاً دوباره تلاش کنید. (with a تلاش مجدد button)
More rows fail to load بارگذاری ادامه تراکنش‌ها انجام نشد. (inline, with retry)
Receipt fails to open نمایش رسید امکان‌پذیر نیست. لطفاً دوباره تلاش کنید.
Receipt link expired Regenerated silently on tap
11.1 The balance summary and the ledger fail independently, so one failure never blanks the whole section.
Section 12 — Design Notes
Summary: card-feature-light on {colors.canvas-soft}; primary figure in {colors.brand-dark-900}, labels in {colors.ink-mute}
Status pills: pill-tag-soft
{colors.ruby} only for the negative balance and لغو شده
{colors.hairline} dividers between rows
Signed amounts are LTR-isolated (§2.5); tabular figures everywhere; Yekan Bakh throughout
Touch targets ≥ 44×44px, including each full ledger row

View File

@ -1,347 +0,0 @@
# Round 5 — Admin panel
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Desktop-first with full tables; mobile is a simplified card list. Reuse the status badges from earlier rounds.
## Deliver in this round
- Admin shell: sidebar with pending-count badge
- Verification queue: tabs, search, sort, pagination, empty state
- Verification detail: ID image lightbox, previous/next, submission history, audit log, approve dialog (normal and suspended), reject panel with templates
- Creator management list (suspended row tint) and detail: suspend dialog (subscriber impact), reinstate dialog (extension summary)
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **A1** — Admin: Creator Verification Review _(ClickUp status: backlog)_
- **A2** — Admin: Creator Account Suspension & Reinstatement _(ClickUp status: backlog)_
---
## A1 — Admin: Creator Verification Review
A1 — Admin: Creator Verification Review
Story:
As an admin, I want to view and manually approve or reject creator verification requests so that I can ensure platform quality and manage onboarding.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
Admin accesses the verification requests section from the main Admin Panel navigation
The section displays a list of all Pending Verification requests sorted by submission date — oldest first
A badge on the navigation item shows the count of pending requests at all times
Edge Cases:
If there are no pending requests, an empty state is shown with a clear message
Admin can also access Verified and Rejected creator lists as separate filtered views within the same section
Farsi copy:
Navigation item label: احراز هویت کریتورها
Pending badge tooltip: {n} درخواست در انتظار بررسی
Empty state: هیچ درخواست جدیدی برای بررسی وجود ندارد.
Filter tabs: در انتظار بررسی · تأییدشده · رد شده
2. Verification Request List
Happy Path:
Each row in the list shows the following summary information:
Name — first name and last name displayed together as a single combined string (e.g., رضا احمدی), even though the underlying data is stored as two separate fields (per C1 Sections 3.2–3.3)
Username
Phone number
Submission date and time
Current status (Pending / Verified / Rejected)
Admin can click any row to open the full verification detail view
Edge Cases:
List is paginated — maximum 20 rows per page
Admin can search by name (matches either first name, last name, or the combined string), username, or phone number
Admin can sort by submission date (ascending / descending)
Error States:
If the list fails to load due to a network error, an error message is shown with a retry option
Farsi copy:
Table column headers: نام و نام خانوادگی · نام کاربری · شماره موبایل · تاریخ ارسال · وضعیت
Search placeholder: جستجو بر اساس نام، نام کاربری یا شماره موبایل
Load error: خطا در بارگذاری لیست. دوباره تلاش کنید.
3. Verification Detail View
Happy Path:
Clicking a request row opens a detail view showing all of the following:
Name — first name and last name shown together as a single combined label (same display rule as Section 2), though stored and independently editable as two separate fields — this matters specifically during a Rejected resubmission, where a creator may correct only one of the two (per C3 Section 3)
Username
Phone number
Submission date and time
Uploaded national ID card image — displayed at a readable size, with a zoom/full-screen option and a download option
Two action buttons are shown: Approve and Reject
Admin can navigate to the previous or next pending request without returning to the list
Edge Cases:
If the creator has resubmitted after a previous rejection, the detail view shows the full history of all past submissions for that creator — each with its date, the admin action taken, and the rejection reason if applicable
The national ID card image opens in a lightbox/full-screen viewer for clarity — the admin must be able to read the card details clearly
If the creator's account has been suspended (via A2) between submission and admin review, a warning banner is shown in the detail view — the admin can still approve or reject; approval on a suspended account does not automatically reinstate it (A2 suspension must be lifted separately)
Error States:
If the national ID card image fails to load, a retry option is shown — the admin cannot take an action without being able to view the image
If the national ID card image fails to download, an error message is shown with a retry option
If the detail view fails to load, an error message with a retry option is shown
Farsi copy:
Detail view heading: بررسی درخواست احراز هویت
Name label: نام و نام خانوادگی
Username label: نام کاربری
Phone label: شماره موبایل
Submission date label: تاریخ ارسال
ID image label: تصویر کارت ملی
Image zoom CTA: مشاهده تصویر کامل
Image download CTA: دانلود تصویر
Image load error: بارگذاری تصویر ناموفق بود. دوباره تلاش کنید.
Image download error: دانلود تصویر ناموفق بود. دوباره تلاش کنید.
Previous request CTA: درخواست قبلی
Next request CTA: درخواست بعدی
Submission history heading: تاریخچه ارسال‌های قبلی
Suspended account warning: این حساب در حال حاضر توسط ادمین تعلیق شده است. تأیید هویت، تعلیق را لغو نمی‌کند.
4. Approve Action
Happy Path:
Admin clicks the Approve CTA
A confirmation dialog appears asking the admin to confirm the approval
Admin confirms — creator status is set to Verified immediately
The request is removed from the Pending list and moved to the Verified list
Creator receives an in-app notification and SMS (as defined in C1 Section 6)
The approval action is logged with a timestamp and the admin's account ID
Edge Cases:
If the creator's account is currently suspended, approval sets the verification status to Verified but does not lift the suspension — the account remains suspended until an admin explicitly reinstates it via A2. A note in the confirmation dialog informs the admin of this.
Error States:
If the approval action fails due to a network error, an error message is shown and the creator's status remains Pending — the admin can retry
Farsi copy:
Approve CTA: تأیید
Confirmation dialog heading: تأیید درخواست
Confirmation dialog body (normal): آیا از تأیید هویت این کریتور اطمینان دارید؟
Confirmation dialog body (suspended account): این حساب در حال حاضر تعلیق شده است. تأیید هویت، تعلیق را لغو نمی‌کند و حساب تا رفع تعلیق غیرفعال می‌ماند. آیا ادامه می‌دهید؟
Confirm CTA: بله، تأیید کن
Cancel CTA: انصراف
Success message: حساب کریتور با موفقیت تأیید شد.
Network error: خطا در انجام عملیات. دوباره تلاش کنید.
5. Reject Action
Happy Path:
Admin clicks the Reject CTA
A rejection panel/dialog opens with a mandatory free-text field for the rejection reason
Admin enters the rejection reason and confirms
Creator status is set to Rejected
The request is removed from the Pending list and moved to the Rejected list
Creator receives an in-app notification and SMS with the rejection reason (as defined in C1 Section 6)
The rejection action is logged with a timestamp, the admin's account ID, and the rejection reason
The creator resubmits exclusively through C3 (اطلاعات کاربری) — first name, last name, and national ID unlock there (pre-filled with prior values), the ID card image field is always empty and requires a fresh selection, and username remains permanently locked. There is no separate resubmission form or admin-side re-entry mechanism; the resubmitted request appears back in this same Pending queue, indistinguishable in structure from a first-time submission
Edge Cases:
Rejection reason field is mandatory — the reject confirmation button is disabled until text is entered
Admin can use predefined reason templates (see below) to speed up the process — selecting a template pre-fills the field, which the admin can then edit
Rejection reason is visible to the creator in their profile area and in the SMS notification
Predefined Rejection Reason Templates:
Template label (Farsi) Pre-filled text (Farsi)
عدم تطابق اطلاعات اطلاعات وارد‌شده با مدارک ارسالی مطابقت ندارد.
تصویر ناخوانا تصویر کارت ملی ارسال‌شده واضح نیست. لطفاً تصویر با کیفیت بالاتر ارسال کنید.
مدرک ناقص مدارک ارسالی ناقص است. لطفاً اطلاعات را تکمیل و مجدداً ارسال کنید.
سایر — (admin writes manually)
Error States:
If rejection reason is empty and admin attempts to confirm, the confirm button remains disabled
If the rejection action fails due to a network error, an error message is shown and the creator's status remains Pending — admin can retry
Farsi copy:
Reject CTA: رد کردن
Rejection panel heading: رد درخواست احراز هویت
Rejection reason field label: دلیل رد درخواست
Rejection reason placeholder: دلیل رد را بنویسید یا از پیش‌فرض‌های زیر انتخاب کنید...
Template selector label: انتخاب دلیل پیش‌فرض
Confirm reject CTA (disabled until reason entered): رد کردن و اطلاع‌رسانی
Cancel CTA: انصراف
Success message: درخواست رد شد و کریتور مطلع گردید.
Network error: خطا در انجام عملیات. دوباره تلاش کنید.
6. Audit Log
Every admin action (approval or rejection) is permanently logged with:
Admin account ID and name
Action taken (Approved / Rejected)
Timestamp (date and time)
Rejection reason (if applicable)
The audit log is viewable within the creator's detail view under a collapsible "تاریخچه اقدامات" section
Audit log entries are immutable — no admin can edit or delete them
Farsi copy:
Audit log section heading: تاریخچه اقدامات
Log entry format: {admin_name} — {action} — {date} — {reason if rejected}
Approved action label: تأیید شد
Rejected action label: رد شد
7. Notifications Triggered by Admin Actions
Admin Action Creator Notification
Approve In-app + SMS — account approved
Reject In-app + SMS — account rejected with reason
Notifications are sent automatically by the system upon admin confirmation — no manual step required from the admin
8. UI / UX
Admin Panel layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text
Pending status badge on navigation item uses {colors.ruby} (#ea2261) background with white text
Status labels use consistent color coding: Pending — {colors.ink-mute} (#64748d) with clock icon; Verified — {colors.primary} (#533afd) with checkmark icon; Rejected — {colors.ruby} (#ea2261) with warning icon
Approve button uses button-primary-pill style (#533afd)
Reject button uses button-secondary style, overridden to {colors.ruby} text and border instead of the component's default {colors.primary} — a deliberate semantic deviation (danger action), not an error
Confirm reject button is visually disabled (opacity: 0.4, cursor: not-allowed) until rejection reason is entered
National ID card image viewer is a full-screen lightbox with zoom and download support — minimum display size 600px on desktop
Predefined rejection reason templates displayed as pill-tag-soft chips
Admin Panel is desktop-first — optimized for desktop use with full table layout; mobile view is a simplified card list
---
## A2 — Admin: Creator Account Suspension & Reinstatement
A2 — Admin: Creator Account Suspension & Reinstatement
Story:
As an admin, I want to suspend or reinstate a creator account so that I can respond to policy violations or errors quickly.
Product decision (Option A adopted): Suspension is a full blackout — the creator's profile and all content are hidden from everyone; existing subscribers lose access for the duration of the suspension.
⚠️ Forward dependency note: Sections 4–6 introduce subscriber notification, a suspension pause clock, and a refund/extension choice. The refund mechanism itself (pro-rated calculation, ZarinPal card return, admin execution) is owned by Epic 11 — Financial Operations. The investor-facing action surface lives on the U2 subscription card and must be added there.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
Admin can suspend/reinstate from two entry points: the creator list (context menu or action button per row) and the creator detail view (action button in the header)
Available at all times for any creator regardless of verification state
The suspend action appears only for Active creators; reinstate only for Suspended creators — never both simultaneously
Farsi copy:
Navigation item label: مدیریت کریتورها
Suspend CTA (list row): تعلیق حساب
Reinstate CTA (list row): رفع تعلیق
2. Suspension Action
Happy Path:
The suspension dialog requires a free-text reason, with optional predefined templates
On confirm: status set to Suspended immediately; action logged (timestamp + admin ID); creator notified in-app + SMS
All active subscribers are notified simultaneously (Section 4)
The suspension pause clock starts for every active subscription (Section 5)
Edge Cases:
A Pending Verification creator can be suspended — the states coexist (Pending AND Suspended)
A Rejected creator can also be suspended
An already-suspended account cannot be suspended again — the CTA is hidden in that state
The dialog shows the number of active subscribers who will be affected, so the admin understands the blast radius before confirming
Predefined Suspension Reason Templates:
Template label (Farsi) Pre-filled text (Farsi)
نقض قوانین پلتفرم حساب شما به دلیل نقض قوانین پلتفرم تعلیق شده است.
محتوای نامناسب حساب شما به دلیل انتشار محتوای نامناسب یا غیرمجاز تعلیق شده است.
گزارش تخلف حساب شما به دلیل دریافت گزارش تخلف در حال بررسی است.
خطای اداری این تعلیق به دلیل خطای اداری بوده و به زودی رفع خواهد شد.
سایر — (admin writes manually)
Farsi copy:
Suspension dialog heading: تعلیق حساب کریتور
Affected subscribers note: این کریتور در حال حاضر {n} مشترک فعال دارد. با تعلیق حساب، دسترسی آن‌ها قطع می‌شود و امکان درخواست بازگشت وجه یا تمدید اشتراک به آن‌ها اطلاع داده خواهد شد.
Reason field label: دلیل تعلیق
Reason placeholder: دلیل تعلیق را بنویسید یا از پیش‌فرض‌های زیر انتخاب کنید...
Confirm CTA: تعلیق و اطلاع‌رسانی
Cancel CTA: انصراف
Success message: حساب کریتور تعلیق شد و {n} مشترک فعال مطلع شدند.
Network error: خطا در انجام عملیات. دوباره تلاش کنید.
3. Effects of Suspension
Take effect immediately:
Area Effect
Creator login Cannot log in — shown suspended message
Creator profile Hidden from all public-facing surfaces
Creator content All posts, predictions, channel content hidden
New subscriptions Blocked — channel undiscoverable and unsubscribable
Active subscriber access Revoked for the suspension duration
Payments No new payments; no renewals or reactivations processed
Creator dashboard Inaccessible
Subscription pause clock Starts for every active subscription (Section 5)
Waitlist notifications Suppressed for this creator until reinstatement; entries preserved (U9 Section 6)
Follow relationships Preserved — posts simply disappear from followers' feeds (U8 Section 3)
Content that was free and public before suspension is also hidden — full blackout applies
A subscription expiring during suspension still expires on schedule, but the subscriber retains their refund right with no deadline (Section 6)
Farsi copy (creator login attempt while suspended):
Heading: حساب شما تعلیق شده است.
Body: دلیل: {suspension_reason} — برای اطلاعات بیشتر با پشتیبانی تماس بگیرید.
Support contact CTA: تماس با پشتیبانی
4. Subscriber Notification (New)
This section fulfils the commitment made in the platform's Subscription Terms, Section 3. Without it, an investor who paid for a year would lose access in month two with no explanation and no recourse — which the platform has explicitly undertaken not to do.
Happy Path:
At the moment of suspension, every investor with an active subscription to that creator is notified via in-app notification and SMS
The notification states plainly that access has paused, and presents the two options:
Request a pro-rated refund for the unused period
Wait — if the creator returns, the paused duration is added to their subscription
Taking no action defaults to option 2 (extension) — the option that preserves the relationship
The notification links to the investor's اشتراک‌ها section, where the affected subscription card carries the refund-request action
Edge Cases:
The reason for suspension is not disclosed to subscribers — only that access has paused. The reason is between the platform and the creator; sharing it would expose a creator to reputational damage before any appeal or reinstatement
Investors whose subscription to that creator has already expired are not notified — they have nothing paused
Investors merely following (not subscribed) are not notified — they lost no paid access
SMS follows the same retry policy as other transactional messages (up to 3 attempts, 10-minute intervals, per U5 Section 3)
Farsi copy:
In-app notification title: دسترسی به کانال {creator_username} موقتاً متوقف شد
In-app notification body: دسترسی شما به محتوای این کانال موقتاً متوقف شده است. می‌توانید مبلغ دوره استفاده‌نشده را به‌صورت نسبی درخواست کنید، یا منتظر بمانید تا در صورت بازگشت کانال، مدت توقف به اشتراک شما اضافه شود.
In-app notification CTA: مشاهده اشتراک
SMS: دسترسی شما به کانال {creator_username} در [نام پلتفرم] موقتاً متوقف شد. برای مشاهده گزینه‌های خود (بازگشت وجه یا تمدید اشتراک): [لینک به بخش اشتراک‌ها]
5. Suspension Pause Clock (New)
Happy Path:
On suspension, a pause clock starts for every active subscription to that creator, recording the exact suspension timestamp
On reinstatement, the clock stops and the elapsed suspended duration is computed
For every subscriber who did not request a refund, that duration is added to their expiry date automatically
Each affected subscriber is notified of their new expiry date (Section 7)
Edge Cases:
The pause clock is tracked per subscription, not per creator — subscriptions purchased at different times all pause and resume together, but each carries its own adjusted expiry
Duration is measured to the minute, not the day — a 3-day-4-hour suspension extends by exactly that
If a creator is suspended and reinstated multiple times, each pause accumulates onto the same subscription
A subscriber who requested a refund during suspension is excluded from extension entirely — the two are mutually exclusive (Section 6)
If a subscription expired during suspension and no refund was requested, it remains expired on reinstatement. Extension applies only to subscriptions still within their term. The refund right persists regardless (Section 6)
6. Refund Requests During Suspension (New)
⚠️ The refund mechanism — pro-rated calculation, admin execution, ZarinPal card return — is owned by Epic 11 — Financial Operations. This section specifies only the trigger and its consequences within A2.
Happy Path:
While a creator is suspended, each affected subscriber sees a refund-request action on that creator's subscription card in اشتراک‌ها
Requesting a refund marks the subscription for admin review; the admin processes it per Epic 11
On refund completion, the subscription terminates — the subscriber forfeits any extension
Edge Cases:
Refund and extension are mutually exclusive — requesting one forfeits the other, and this is stated clearly at the point of request
There is no deadline for requesting a refund in Phase 0, including after a subscription would have expired naturally. A creator never reinstated leaves subscribers with an indefinite refund right
If a refund is requested and the creator is reinstated before it is processed, the request stands unless the investor cancels it — the platform does not silently void a request because circumstances changed
Requesting a refund does not unfollow the creator (U8) — those are independent
Forward dependency — U2 amendment required: the suspended-creator subscription card (U2 Section 2) currently dims and disables interaction entirely. It must gain a functional refund-request action while retaining the dimmed, non-navigable treatment for the rest of the card. This mirrors the precedent set in U8 Section 5, where a suspended creator's row stays dimmed but its unfollow action remains fully functional.
Farsi copy:
Refund action on subscription card: درخواست بازگشت وجه
Confirmation dialog heading: درخواست بازگشت وجه
Confirmation dialog body: مبلغ دوره استفاده‌نشده به‌صورت نسبی محاسبه و به کارت شما بازگردانده می‌شود. با ثبت این درخواست، اشتراک شما پایان می‌یابد و در صورت بازگشت کانال، تمدید نخواهد شد.
Confirm CTA: ثبت درخواست
Cancel CTA: انصراف
Request submitted toast: درخواست شما ثبت شد و به‌زودی بررسی می‌شود.
Card state after request: درخواست بازگشت وجه در حال بررسی
7. Reinstatement Action
Happy Path:
Admin taps رفع تعلیق; a confirmation dialog appears — no reason required
On confirm: status set to Active immediately; all suspended access restored (profile visible, content accessible, login enabled); action logged; creator notified in-app + SMS
The pause clock stops and extensions are applied automatically to every eligible subscription (Section 5)
Every extended subscriber is notified of their new expiry date
Edge Cases:
Reinstatement restores account access only — it does not affect verification state. A creator Pending before suspension remains Pending after
Subscribers who requested a refund are not extended and are not notified of any new expiry
Subscriptions that expired during suspension are not revived — they appear in اشتراک‌های منقضی‌شده (U3 Section 2) and can be reactivated normally
Waitlist notifications for this creator resume on reinstatement
The confirmation dialog shows how many subscriptions will be extended and by how long, so the admin sees the consequence before confirming
Farsi copy:
Reinstate CTA: رفع تعلیق
Confirmation dialog heading: رفع تعلیق حساب
Confirmation dialog body: با رفع تعلیق، دسترسی کریتور و مشترکان بازیابی می‌شود. {n} اشتراک فعال به مدت {duration} تمدید خواهد شد.
Confirm CTA: بله، رفع تعلیق
Cancel CTA: انصراف
Success message: تعلیق رفع شد و {n} اشتراک تمدید گردید.
Subscriber extension in-app notification: دسترسی شما به کانال {creator_username} بازیابی شد. اشتراک شما به مدت {duration} تمدید شد — تاریخ انقضای جدید: {new_expiry_date}
Subscriber extension SMS: دسترسی شما به کانال {creator_username} در [نام پلتفرم] بازیابی شد. اشتراک شما تا {new_expiry_date} تمدید شد.
8. Notifications Summary
Event Creator Active Subscribers
Suspension In-app + SMS, with reason In-app + SMS, without reason, with refund/extension choice
Reinstatement In-app + SMS In-app + SMS with new expiry date (extended subscribers only)
All notifications are sent automatically by the system on admin confirmation — no manual step required
Farsi copy:
Suspension SMS (creator): حساب کریتور شما در [نام پلتفرم] تعلیق شده است. دلیل: {suspension_reason} — برای اطلاعات بیشتر با پشتیبانی تماس بگیرید.
Suspension in-app (creator): حساب شما تعلیق شده است. دلیل: {suspension_reason}
Reinstatement SMS (creator): تعلیق حساب کریتور شما در [نام پلتفرم] رفع شد. اکنون می‌توانید وارد حساب خود شوید.
Reinstatement in-app (creator): تعلیق حساب شما رفع شد. خوش آمدید.
9. Audit Log
Every suspension and reinstatement is logged permanently with: admin ID and name, action, timestamp, suspension reason (suspensions only), number of subscribers affected, and total extension duration applied (reinstatements only)
Viewable in the creator's detail view under "تاریخچه اقدامات" — the shared log introduced in A1
Entries are immutable; full history shown chronologically across multiple suspension cycles
Farsi copy:
Suspended action label: تعلیق شد
Reinstated action label: رفع تعلیق شد
Log entry format: {admin_name} — {action} — {date} — {reason if suspended} — {n} مشترک متأثر
10. UI / UX
Admin Panel is RTL throughout; Yekan Bakh typeface
Status colours: Active — {colors.primary} (#533afd) with checkmark; Suspended — {colors.ruby} (#ea2261) with a ban icon
Suspend button uses button-secondary with {colors.ruby} text and border — a deliberate semantic deviation for a destructive action
Reinstate button uses button-primary-pill (#533afd)
Confirm-suspend button disabled (opacity: 0.4, cursor: not-allowed) until a reason is entered
Suspension reason templates render as pill-tag-soft chips
The affected-subscribers note in the suspension dialog and the extension summary in the reinstatement dialog both use {colors.ruby} — these are the consequence lines the admin most needs to register before confirming
Suspended creator rows in the list use a soft red tint (rgba(234, 34, 97, 0.05)) with a ban icon beside the status label
Admin Panel is desktop-first; mobile renders as a simplified card list
All prices, durations, and subscriber counts use font-feature-settings: "tnum"

View File

@ -5,16 +5,16 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { I18nextProvider } from 'react-i18next';
import { NetworkBoundary } from './components/NetworkBoundary';
import { useSessionEvents } from './hooks/use-session-events';
import { useSession } from './hooks/use-session';
import type { AppShellProps } from './types';
/**
* The provider shell shared by bull and bear: the query client, i18n, the connection bar, the
* one toast region, and the reactions to sign-in and sign-out. The app's root client component renders it after running the client
* one toast region, and the viewer's session (read once per load in the browser). The app's root client component renders it after running the client
* bootstrap.
*/
export function AppShell({ queryClient, i18n, children }: AppShellProps) {
useSessionEvents(queryClient);
useSession(queryClient);
return (
<QueryClientProvider client={queryClient}>

View File

@ -1,28 +0,0 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import type { QueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { AUTH_EVENTS } from '../../../features/auth';
/**
* Keeps the page in step with the session. Signing in or up re-renders the server components for
* the new account; signing out, or a refresh that failed, drops every cached query (they belonged
* to the old account) and re-renders as a guest.
*/
export function useSessionEvents(queryClient: QueryClient): void {
const router = useRouter();
useEffect(() => {
const refresh = () => router.refresh();
const unsubscribers = [
eventEmitter.on(AUTH_EVENTS.login, refresh),
eventEmitter.on(AUTH_EVENTS.register, refresh),
eventEmitter.on(AUTH_EVENTS.logout, () => {
queryClient.clear();
router.refresh();
}),
];
return () => unsubscribers.forEach((unsubscribe) => unsubscribe());
}, [router, queryClient]);
}

View File

@ -0,0 +1,24 @@
import { handleError } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import type { QueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
import { AUTH_EVENTS, restoreSession } from '../../../features/auth';
import { useAuthStore } from '../../../stores/auth';
/**
* The browser learns who the viewer is once per page load; auth-dependent parts wait in their
* skeleton until then. When the session ends (sign-out, or a refresh that failed), the store goes
* back to guest and every cached query is dropped: it belonged to the old account.
*/
export function useSession(queryClient: QueryClient): void {
useEffect(() => {
restoreSession().catch((error: unknown) =>
handleError(error, { where: 'app', name: 'restore-session' }),
);
return eventEmitter.on(AUTH_EVENTS.logout, () => {
useAuthStore.getState().clearSession();
queryClient.clear();
});
}, [queryClient]);
}

View File

@ -1,21 +1,17 @@
import 'server-only';
import { classifyError } from '@lumina/libs/error-handler';
import { isHttpError } from '@lumina/libs/http';
import { redirect } from 'next/navigation';
import { loginRoute } from '../../navigation';
import type { ReadOnServerOptions, ServerRead } from './types';
import type { ServerRead } from './types';
/**
* Every server read of a page or a server part goes through it. A Server Component error reaches
* the browser with only its digest, so the expected answers are classified here: 404 and 410 are
* `not-found`, 403 `no-access`, 401 redirects to login with `returnTo`, and the rest is rethrown
* to the nearest boundary.
* `not-found`, 403 `no-access`, and the rest is rethrown to the nearest boundary. Server reads
* carry no session, so only reads that are the same for every visitor happen here.
*/
export async function readOnServer<T>(
read: () => Promise<T>,
{ returnTo }: ReadOnServerOptions = {},
): Promise<ServerRead<T>> {
try {
return { status: 'ok', data: await read() };
@ -24,9 +20,6 @@ export async function readOnServer<T>(
if (outcome === 'not-found' || outcome === 'no-access') {
return { status: outcome };
}
if (returnTo && isHttpError(error) && error.status === 401) {
redirect(loginRoute(returnTo));
}
throw error;
}
}

View File

@ -1,4 +1,4 @@
import 'server-only';
export { readOnServer } from './read-on-server';
export type { ReadOnServerOptions, ServerRead } from './types';
export type { ServerRead } from './types';

View File

@ -2,8 +2,3 @@
export type ServerRead<T> =
| { status: 'ok'; data: T }
| { status: 'not-found' | 'no-access' };
export type ReadOnServerOptions = {
/** The page's own path: a 401 redirects to login and comes back here. */
returnTo?: string;
};

View File

@ -1,4 +1,4 @@
import 'server-only';
export { readOnServer } from './read-on-server/server';
export type { ReadOnServerOptions, ServerRead } from './read-on-server/server';
export type { ServerRead } from './read-on-server/server';

View File

@ -0,0 +1,33 @@
'use client';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { useCurrentAccount, useViewerStatus } from '../../../stores/auth';
import { StatusEmptyState } from '../../error-boundaries';
import { loginRoute } from '../../navigation';
import type { AuthGuardProps } from './types';
/**
* Wraps every page that needs a signed-in visitor (the route group's layout renders it). The
* server render and the first browser render show the page skeleton, because the server never
* knows the viewer. Then a guest goes to login with a return path, the other role sees the
* page-size no-access state, and a member sees the page.
*/
export function AuthGuard({ fallback, role, children }: AuthGuardProps) {
const status = useViewerStatus();
const account = useCurrentAccount();
const router = useRouter();
useEffect(() => {
if (status !== 'guest') return;
const { pathname, search } = window.location;
router.replace(loginRoute(`${pathname}${search}`));
}, [status, router]);
if (status !== 'member' || !account) return fallback;
if (role && account.role !== role) {
return <StatusEmptyState variant="no-access" size="page" />;
}
return children;
}

View File

@ -1,27 +0,0 @@
import 'server-only';
import { redirect } from 'next/navigation';
import { getSessionAccount } from '../../../features/auth/caches/server';
import type { AccountPayload } from '../../../features/auth';
import { loginRoute, ROUTES } from '../../navigation';
import type { RequireAccountOptions } from './types';
/**
* For pages that need a signed-in visitor: the account, or a redirect to login that comes back to
* `returnTo`. proxy.ts has already refreshed an expired session, so `null` here means a guest.
*/
export async function requireAccount({
returnTo,
}: RequireAccountOptions): Promise<AccountPayload> {
const account = await getSessionAccount();
if (!account) redirect(loginRoute(returnTo));
return account;
}
/** For login and registration: a signed-in visitor goes straight to `to` (home by default). */
export async function redirectIfSignedIn(
to: string = ROUTES.home,
): Promise<void> {
if (await getSessionAccount()) redirect(to);
}

View File

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

View File

@ -1,4 +0,0 @@
import 'server-only';
export { redirectIfSignedIn, requireAccount } from './auth-guard';
export type { RequireAccountOptions } from './types';

View File

@ -1,4 +1,11 @@
export type RequireAccountOptions = {
/** The page's own path: login sends the visitor back here afterwards. */
returnTo: string;
import type { ReactNode } from 'react';
import type { UserRole } from '../../../features/auth';
export type AuthGuardProps = {
/** The page's same-size skeleton, shown until the browser knows the viewer. */
fallback: ReactNode;
/** Only this role may see the page; the other role gets the no-access state. */
role?: UserRole;
children: ReactNode;
};

View File

@ -0,0 +1,27 @@
'use client';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { useViewerStatus } from '../../../stores/auth';
import { safeReturnPath } from '../../navigation';
import type { GuestGuardProps } from './types';
/**
* Wraps login and registration. A signed-in visitor goes on to `?redirect=` (a path on this site
* only) or home; a guest sees the page. The skeleton covers the moment before the viewer is known.
*/
export function GuestGuard({ fallback, children }: GuestGuardProps) {
const status = useViewerStatus();
const router = useRouter();
useEffect(() => {
if (status !== 'member') return;
const redirect = new URLSearchParams(window.location.search).get(
'redirect',
);
router.replace(safeReturnPath(redirect));
}, [status, router]);
return status === 'guest' ? children : fallback;
}

View File

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

View File

@ -0,0 +1,7 @@
import type { ReactNode } from 'react';
export type GuestGuardProps = {
/** The page's same-size skeleton, shown until the browser knows the viewer. */
fallback: ReactNode;
children: ReactNode;
};

View File

@ -1,19 +0,0 @@
import 'server-only';
import { requireAccount } from '../auth-guard/server';
import type { RequireRoleOptions, RoleCheck } from './types';
/**
* For pages of one role (the creator dashboard, the investor's subscriptions). A guest is sent to
* login; the other role gets `no-access`, which the page renders as its page-size
* StatusEmptyState (a 403, never a redirect loop).
*/
export async function requireRole({
role,
returnTo,
}: RequireRoleOptions): Promise<RoleCheck> {
const account = await requireAccount({ returnTo });
return account.role === role
? { status: 'ok', account }
: { status: 'no-access' };
}

View File

@ -1,4 +0,0 @@
import 'server-only';
export { requireRole } from './role-guard';
export type { RequireRoleOptions, RoleCheck } from './types';

View File

@ -1,12 +0,0 @@
import type { AccountPayload, UserRole } from '../../../features/auth';
export type RequireRoleOptions = {
role: UserRole;
/** The page's own path, for the login redirect. */
returnTo: string;
};
/** The account when it has the role, `no-access` when it is the other role. */
export type RoleCheck =
| { status: 'ok'; account: AccountPayload }
| { status: 'no-access' };

View File

@ -1,2 +1,3 @@
export { CHANNEL_PREFIX } from './constants';
export { loginRoute, ROUTES } from './navigation';
export { safeReturnPath } from './return-path';

View File

@ -0,0 +1,17 @@
import { ROUTES } from './navigation';
/**
* A `?redirect=` value is only followed when it is a path on this site: `/dashboard`, never
* `https://evil.example` or `//evil.example`, so login can't be turned into an open redirect.
*/
export function safeReturnPath(value: string | null | undefined): string {
if (
!value ||
!value.startsWith('/') ||
value.startsWith('//') ||
value.startsWith('/\\')
) {
return ROUTES.home;
}
return value;
}

View File

@ -1,11 +0,0 @@
/** The gateway's HttpOnly session cookies; JavaScript never reads their values. */
export const SESSION_COOKIES = {
access: 'access_token',
refresh: 'refresh_token',
} as const;
/** Rotates the session from the refresh cookie; relative to the API base URL (`…/v1`). */
export const SESSION_REFRESH_ENDPOINT = '/auth/refresh';
/** A refresh before rendering must never hold the page up for long. */
export const PROXY_REFRESH_TIMEOUT_MS = 3000;

View File

@ -1 +0,0 @@
export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './constants';

View File

@ -1,77 +0,0 @@
import { createHttpClient } from '@lumina/libs/http';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import {
PROXY_REFRESH_TIMEOUT_MS,
SESSION_COOKIES,
SESSION_REFRESH_ENDPOINT,
} from './constants';
import type { ProxySessionOptions, RefreshResponseDto } from './types';
/** `name=value; Path=/; …` → [name, value]. */
function cookiePair(setCookie: string): [string, string] | undefined {
const pair = setCookie.split(';', 1)[0] ?? '';
const index = pair.indexOf('=');
return index > 0 ? [pair.slice(0, index), pair.slice(index + 1)] : undefined;
}
/** Copies the gateway's Set-Cookie headers to the browser's response. */
function forwardCookies(
response: NextResponse,
setCookies: string[],
): NextResponse {
for (const setCookie of setCookies)
response.headers.append('set-cookie', setCookie);
return response;
}
/**
* Refreshes an expired session before the page renders, so server components never render a
* signed-in visitor as a guest. It runs only when the access cookie is gone (it lives 15 minutes)
* and the refresh cookie is still there. The new cookies go to the browser, and into this
* request's Cookie header so this render's API calls already use them.
*
* A superseded refresh (a tab refreshed at the same moment) changes nothing. On any failure the
* page renders as a guest and the cookies stay as they are: the browser's next API call refreshes
* against the gateway itself, which clears a dead session's cookies on its own domain. Never
* throws: rendering goes on either way.
*/
export async function refreshSessionInProxy(
request: NextRequest,
{ apiUrl }: ProxySessionOptions,
): Promise<NextResponse> {
const refreshToken = request.cookies.get(SESSION_COOKIES.refresh)?.value;
if (!refreshToken || request.cookies.has(SESSION_COOKIES.access)) {
return NextResponse.next();
}
// A client of its own: the proxy runs before any bootstrap has configured the root client.
const client = createHttpClient({
baseUrl: apiUrl,
retry: false,
timeout: PROXY_REFRESH_TIMEOUT_MS,
});
try {
const response = await client.request<RefreshResponseDto>({
method: 'POST',
url: SESSION_REFRESH_ENDPOINT,
headers: {
cookie: `${SESSION_COOKIES.refresh}=${refreshToken}`,
'user-agent': request.headers.get('user-agent') ?? '',
},
skipRefresh: true,
});
const setCookies = response.headers.getSetCookie();
for (const setCookie of setCookies) {
const pair = cookiePair(setCookie);
if (pair) request.cookies.set(pair[0], pair[1]);
}
return forwardCookies(
NextResponse.next({ request: { headers: request.headers } }),
setCookies,
);
} catch {
return NextResponse.next();
}
}

View File

@ -1,4 +0,0 @@
import 'server-only';
export { refreshSessionInProxy } from './refresh-in-proxy';
export type { ProxySessionOptions } from './types';

View File

@ -1,7 +0,0 @@
export type ProxySessionOptions = {
/** The API base URL as the server reaches it, with the version: `http://gateway:3000/v1`. */
apiUrl: string;
};
/** `POST /auth/refresh` body: the user after a rotation, or `superseded` when another refresh won. */
export type RefreshResponseDto = { superseded: true } | { user: unknown };

View File

@ -1,15 +1,20 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth';
/** Verifies the login code; the gateway sets the session cookies. Emits `auth.login`. */
/**
* Verifies the login code; the gateway sets the session cookies and the auth store learns the
* account, so every auth-dependent part renders its member variant. Emits `auth.login`.
*/
export async function login(
args: VerifyOtpArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<SessionPayload> {
const session = await authRepository.verifyLoginOtp(args);
useAuthStore.getState().setSession({ account: session.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.login, {
userId: session.account.id,

View File

@ -1,13 +1,15 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
/** Revokes the session and clears its cookies. Emits `auth.logout`. */
/** Revokes the session, clears its cookies and the auth store. Emits `auth.logout`. */
export async function logout({
emit = true,
}: { emit?: boolean } = {}): Promise<'ok'> {
await authRepository.logout();
useAuthStore.getState().clearSession();
if (emit) eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'signed-out' });
return 'ok';
}

View File

@ -1,5 +1,6 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
@ -7,12 +8,13 @@ import type {
RegisterCreatorArgs,
} from '../../repositories/auth';
/** Creates a creator account with lite KYC and signs it in. Emits `auth.register`. */
/** Creates a creator account with lite KYC and signs it in (cookies and auth store). Emits `auth.register`. */
export async function registerCreator(
args: RegisterCreatorArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<CreatorRegisteredPayload> {
const registration = await authRepository.registerCreator(args);
useAuthStore.getState().setSession({ account: registration.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
userId: registration.account.id,

View File

@ -1,5 +1,6 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
@ -7,12 +8,13 @@ import type {
SessionPayload,
} from '../../repositories/auth';
/** Creates an investor account and signs it in. Emits `auth.register`. */
/** Creates an investor account and signs it in (cookies and auth store). Emits `auth.register`. */
export async function registerInvestor(
args: RegisterInvestorArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<SessionPayload> {
const session = await authRepository.registerInvestor(args);
useAuthStore.getState().setSession({ account: session.account });
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
userId: session.account.id,

View File

@ -0,0 +1,30 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth';
import type { ViewerStatus } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
/**
* Learns who the viewer is, once per page load (the AppShell calls it). A guest is an empty
* session, not an error. An expired access cookie is refreshed by the HTTP client on the way. When
* the read still fails, the viewer is treated as a guest and the error is rethrown for reporting.
* Emits `auth.restore`.
*/
export async function restoreSession({
emit = true,
}: { emit?: boolean } = {}): Promise<ViewerStatus> {
const { setSession, clearSession } = useAuthStore.getState();
let status: ViewerStatus;
try {
const { account } = await authRepository.getSession();
if (account) setSession({ account });
else clearSession();
status = account ? 'member' : 'guest';
} catch (error) {
clearSession();
throw error;
}
if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status });
return status;
}

View File

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

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getSessionAccount } from './session-account';

View File

@ -1,22 +0,0 @@
import 'server-only';
import { isHttpError } from '@lumina/libs/http';
import { cache } from 'react';
import { accountRepository } from '../repositories/account';
import type { AccountPayload } from '../repositories/account';
/**
* The signed-in account for this request, or `null` for a guest. One request per render however
* many server components ask; the cookies are forwarded by the server HTTP configuration.
*/
export const getSessionAccount = cache(
async (): Promise<AccountPayload | null> => {
try {
return await accountRepository.getCurrent();
} catch (error) {
if (isHttpError(error) && error.status === 401) return null;
throw error;
}
},
);

View File

@ -1,5 +1,6 @@
/** Events auth actions emit when they succeed; the AppShell reacts to them. */
export const AUTH_EVENTS = {
restore: 'auth.restore',
login: 'auth.login',
register: 'auth.register',
logout: 'auth.logout',

View File

@ -4,6 +4,7 @@ export { login } from './actions/login';
export { logout } from './actions/logout';
export { registerCreator } from './actions/register-creator';
export { registerInvestor } from './actions/register-investor';
export { restoreSession } from './actions/restore-session';
export { AUTH_EVENTS } from './constants';
export type { UserRole, UserStatus } from './entities/user';
export { accountKeys, accountRepository } from './repositories/account';
@ -17,6 +18,7 @@ export type {
RegistrationVerifiedPayload,
SendOtpArgs,
SessionPayload,
SessionStatePayload,
VerifyOtpArgs,
} from './repositories/auth';
export type { LogoutReason } from './types';

View File

@ -9,6 +9,7 @@ import {
toRegisterInvestorDto,
toRegistrationVerifiedPayload,
toSessionPayload,
toSessionStatePayload,
toVerifyOtpDto,
} from './mappers';
import type {
@ -23,6 +24,8 @@ import type {
SendOtpArgs,
SessionPayload,
SessionResponseDto,
SessionStatePayload,
SessionStateResponseDto,
VerifyOtpArgs,
} from './types';
@ -122,6 +125,20 @@ export const authRepository = {
return toSessionPayload(response);
},
/**
* The viewer's session, read in the browser once per page load. No `skipRefresh`: an expired
* access cookie answers 401, the HTTP client refreshes, and this read replays.
*/
async getSession({
signal,
}: { signal?: AbortSignal } = {}): Promise<SessionStatePayload> {
const response = await authHttp.get<SessionStateResponseDto>(
AUTH_ENDPOINTS.session,
{ signal },
);
return toSessionStatePayload(response);
},
/** Revokes the session and clears its cookies; succeeds even without one. */
async logout(): Promise<void> {
await authHttp.post(AUTH_ENDPOINTS.logout, undefined, {

View File

@ -6,6 +6,10 @@ export const AUTH_ENDPOINTS = {
registerCreator: '/auth/register/creator',
requestLoginOtp: '/auth/login',
verifyLoginOtp: '/auth/login/verify',
/** The viewer's session: the account, or `{ user: null }` for a guest. */
session: '/auth/session',
/** Rotates the session from the refresh cookie; the HTTP client calls it on a 401. */
refresh: '/auth/refresh',
logout: '/auth/logout',
} as const;

View File

@ -8,5 +8,6 @@ export type {
RegistrationVerifiedPayload,
SendOtpArgs,
SessionPayload,
SessionStatePayload,
VerifyOtpArgs,
} from './types';

View File

@ -14,6 +14,8 @@ import type {
SendOtpArgs,
SessionPayload,
SessionResponseDto,
SessionStatePayload,
SessionStateResponseDto,
VerifyOtpArgs,
VerifyOtpDto,
} from './types';
@ -69,6 +71,12 @@ export function toSessionPayload(dto: SessionResponseDto): SessionPayload {
return { account: toAccountPayload(dto.user) };
}
export function toSessionStatePayload(
dto: SessionStateResponseDto,
): SessionStatePayload {
return { account: dto.user ? toAccountPayload(dto.user) : null };
}
export function toCreatorRegisteredPayload(
dto: CreatorRegisteredResponseDto,
): CreatorRegisteredPayload {

View File

@ -49,6 +49,12 @@ export type RegisterCreatorArgs = RegisterInvestorArgs & {
export type SessionResponseDto = { user: UserEntity; userType: UserRole };
export type SessionPayload = { account: AccountPayload };
/** A guest gets `{ user: null }`, never a 401, so a guest never starts a refresh. */
export type SessionStateResponseDto =
| { user: UserEntity; userType: UserRole }
| { user: null };
export type SessionStatePayload = { account: AccountPayload | null };
export type CreatorRegisteredResponseDto = {
account: UserEntity;
onboarding: { nextStep: string; profileSetupRequired: boolean };

View File

@ -1,3 +1,4 @@
import type { ViewerStatus } from '../../stores/auth';
import type { UserRole } from './entities/user';
/** Why the session ended: the user signed out, or the refresh token was dead. */
@ -5,6 +6,7 @@ export type LogoutReason = 'signed-out' | 'session-ended';
declare module '@lumina/libs/event-emitter' {
interface EventMap {
'auth.restore': { status: ViewerStatus };
'auth.login': { userId: string; role: UserRole };
'auth.register': { userId: string; role: UserRole };
'auth.logout': { reason: LogoutReason };

View File

@ -1,15 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { checkoutRepository } from '../repositories/checkout';
import type { CheckoutPayload } from '../repositories/checkout';
/**
* The signed-in investor's U9 checkout for a creator, once per render. Throws the API's error as
* is: 401 without a session, 403 for a non-investor or a creator who is not approved or suspended.
*/
export const getCheckoutScreen = cache(
(creatorId: string): Promise<CheckoutPayload> =>
checkoutRepository.getScreen(creatorId),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getCheckoutScreen } from './checkout-screen';

View File

@ -1,15 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { FEED_PAGE_LIMIT, feedRepository } from '../repositories/feed';
import type { FeedPayload } from '../repositories/feed';
/**
* The signed-in investor's first feed page. Rejects with 401 for a guest and 403 for a creator;
* later pages load on the client with the same `FEED_PAGE_LIMIT`.
*/
export const getFeed = cache(
async (): Promise<FeedPayload> =>
feedRepository.list({ page: 1, limit: FEED_PAGE_LIMIT }),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getFeed } from './feed';

View File

@ -1,11 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { creatorPaymentRepository } from '../repositories/creator-payment';
import type { CreatorPaymentPayload } from '../repositories/creator-payment';
/** Payments the signed-in creator received, once per render. */
export const getCreatorPayments = cache(
async (): Promise<CreatorPaymentPayload[]> => creatorPaymentRepository.list(),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getCreatorPayments } from './creator-payments';

View File

@ -1,15 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { followRepository } from '../repositories/follow';
import type { FollowStatusPayload } from '../repositories/follow';
/**
* The signed-in investor's follow state for a creator, once per render per id. Ask only for an
* investor session: guests get 401 and creators 403.
*/
export const getFollowStatus = cache(
(creatorId: string): Promise<FollowStatusPayload> =>
followRepository.getStatus({ creatorId }),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getFollowStatus } from './follow-status';

View File

@ -1,11 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { notificationRepository } from '../repositories/notification';
import type { InboxPayload } from '../repositories/notification';
/** The signed-in user's inbox, one request per render. 401 reaches the caller. */
export const getNotificationInbox = cache(
(): Promise<InboxPayload> => notificationRepository.listInbox(),
);

View File

@ -1,4 +0,0 @@
import 'server-only';
export { getNotificationInbox } from './inbox';
export { getUnreadNotificationCount } from './unread-count';

View File

@ -1,11 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { notificationRepository } from '../repositories/notification';
import type { UnreadCountPayload } from '../repositories/notification';
/** The signed-in user's unread badge count, one request per render. 401 reaches the caller. */
export const getUnreadNotificationCount = cache(
(): Promise<UnreadCountPayload> => notificationRepository.getUnreadCount(),
);

View File

@ -1,12 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { creatorDashboardRepository } from '../repositories/creator-dashboard';
import type { CreatorDashboardPayload } from '../repositories/creator-dashboard';
/** The signed-in creator's dashboard figures, once per render. */
export const getCreatorDashboard = cache(
async (): Promise<CreatorDashboardPayload> =>
creatorDashboardRepository.get(),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getCreatorDashboard } from './creator-dashboard';

View File

@ -1,14 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { pricingRepository } from '../repositories/pricing';
import type { PricingFormPayload } from '../repositories/pricing';
/**
* The signed-in creator's C7 pricing form, once per render. Throws the API's error as is: 401
* without a session, 403 for a non-creator or an incomplete creator profile.
*/
export const getPricingForm = cache(
(): Promise<PricingFormPayload> => pricingRepository.getForm(),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getPricingForm } from './pricing-form';

View File

@ -1,14 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { profileRepository } from '../repositories/profile';
import type { CreatorProfilePayload } from '../repositories/profile';
/**
* The signed-in creator's own profile for this request, one request per render. 401 and 403 reach
* the caller (`readOnServer` turns them into login and no-access).
*/
export const getMyCreatorProfile = cache(
(): Promise<CreatorProfilePayload> => profileRepository.getMine(),
);

View File

@ -1,3 +0,0 @@
import 'server-only';
export { getMyCreatorProfile } from './my-profile';

View File

@ -1,4 +0,0 @@
import 'server-only';
export { getSubscriptionDashboard } from './subscription-dashboard';
export { getSubscriptionDetail } from './subscription-detail';

View File

@ -1,12 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { subscriptionRepository } from '../repositories/subscription';
import type { SubscriptionDashboardPayload } from '../repositories/subscription';
/** The signed-in investor's اشتراک‌ها, once per render. Errors reach the page's `readOnServer`. */
export const getSubscriptionDashboard = cache(
async (): Promise<SubscriptionDashboardPayload> =>
subscriptionRepository.getDashboard(),
);

View File

@ -1,12 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { subscriptionRepository } from '../repositories/subscription';
import type { SubscriptionDetailPayload } from '../repositories/subscription';
/** One subscription of the signed-in investor, once per render; someone else's is a 404. */
export const getSubscriptionDetail = cache(
async (id: string): Promise<SubscriptionDetailPayload> =>
subscriptionRepository.getDetail(id),
);

View File

@ -1,15 +0,0 @@
import 'server-only';
import { cache } from 'react';
import { transactionRepository } from '../repositories/transaction';
import type { TransactionDetailPayload } from '../repositories/transaction';
/**
* One payment of the signed-in investor (جزئیات تراکنش, and the U10 result after the bank return),
* once per render; someone else's is a 404.
*/
export const getPaymentDetail = cache(
async (id: string): Promise<TransactionDetailPayload> =>
transactionRepository.getDetail(id),
);

View File

@ -1,4 +0,0 @@
import 'server-only';
export { getPaymentDetail } from './payment-detail';
export { getTransactionsFirstPage } from './transactions-first-page';

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