feat(signals): add exact or range entry and required stop-loss to the composer

The composer asks for the entry as «قیمت دقیق», prefilled from the live
quote until edited, or «بازه», plus a required stop-loss, and checks the
levels against that entry on blur, on a direction change and on every
quote refresh. The confirm step sends what it showed. The signal card
shows a range with «بازه» and «ورود (بازه)», measures from its middle,
and shows «ریسک به ریوارد» as lower to higher ratio.

Every UI string now says «سیگنال» in place of «پیش‌بینی». Code identifiers
and routes stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-11-02 01:40:31 +04:00
parent 01c838e869
commit cac4f8e229
110 changed files with 1792 additions and 508 deletions

View File

@ -13,7 +13,7 @@ export const metadata: Metadata = {
};
/**
* «پیش‌بینی جدید» on a direct load (J09-1-D): the 960px composer under the header, in the browser
* «سیگنال جدید» on a direct load (J09-1-D): the 960px composer under the header, in the browser
* only. From a page, the `@modal` slot opens it as a dialog over that page instead (0023).
*/
export default function ComposePredictionPage() {

View File

@ -5,7 +5,7 @@ import {
} from '@lumina/market/app/screens/(flow)/compose/prediction/organisms/prediction-composer';
/**
* «پیش‌بینی جدید» opened from a main page (J09-1-D, 0023): the 960px composer dialog over that
* «سیگنال جدید» opened from a main page (J09-1-D, 0023): the 960px composer dialog over that
* page, the URL /compose/prediction; a direct load of that URL gets the full page instead. In the
* browser only: the dialog's skeleton until the viewer is known, then the composer for a creator
* who may publish, why not for one who may not, or the no-access state for anyone else.

View File

@ -8,7 +8,7 @@ import { i18n } from '../../../../i18n';
/**
* The creator's داشبورد on desktop (Creator Dashboard ۵.۱): the 640 column under the header, with
* the «داشبورد» heading, the three tabs «طرح‌های اشتراک» · «پیش‌بینی‌ها» · «مالی», then the tab. Each tab is its own
* the «داشبورد» heading, the three tabs «طرح‌های اشتراک» · «سیگنال‌ها» · «مالی», then the tab. Each tab is its own
* route with its own loading, so the heading and the tabs stay while one loads. Locked until
* registration step 5 is done (0016).
*/

View File

@ -2,7 +2,7 @@ import { PredictionsTabSkeleton } from '@lumina/market/app/screens/(main)/dashbo
import { i18n } from '../../../../../i18n';
/** پیش‌بینی‌ها before it arrives, block for block; the layout keeps the bar and the tabs. */
/** سیگنال‌ها before it arrives, block for block; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<PredictionsTabSkeleton label={i18n.t('predictions:tab.loading')} delayed />

View File

@ -13,7 +13,7 @@ export const metadata: Metadata = {
};
/**
* داشبورد › پیش‌بینی‌ها (J10-3): the creator's record, open and recently closed predictions, in the
* داشبورد › سیگنال‌ها (J10-3): the creator's record, open and recently closed predictions, in the
* browser only. Each block loads and fails on its own; the tabs stay.
*/
export default function PredictionsPage() {

View File

@ -4,7 +4,7 @@ import { PredictionListSkeleton } from '@lumina/market/app/screens/(main)/dashbo
import { i18n } from '../../../../../i18n';
/** «همه پیش‌بینی‌ها» before it arrives, under its real title. */
/** «همه سیگنال‌ها» before it arrives, under its real title. */
export default function Loading() {
return (
<FlexBox tag="main" justifyContent="justify-center" className="px-8 py-10">

View File

@ -17,8 +17,8 @@ export const metadata: Metadata = {
};
/**
* «همه پیش‌بینی‌ها» on desktop (J10-3f): the same list in the 640 column, «بازگشت» over its title
* back to the پیش‌بینی‌ها tab. The creator's own, in the browser only.
* «همه سیگنال‌ها» on desktop (J10-3f): the same list in the 640 column, «بازگشت» over its title
* back to the سیگنال‌ها tab. The creator's own, in the browser only.
*/
export default function PredictionListPage() {
const skeleton = (

View File

@ -10,7 +10,7 @@ export const metadata: Metadata = {
robots: { index: false },
};
/** «پیش‌بینی جدید» (J09-1): the creator's own task flow, in the browser only, with no bottom nav. */
/** «سیگنال جدید» (J09-1): the creator's own task flow, in the browser only, with no bottom nav. */
export default function ComposePredictionPage() {
return (
<AuthGuard

View File

@ -8,7 +8,7 @@ import { i18n } from '../../../../i18n';
/**
* The creator's داشبورد on mobile (Creator Dashboard ۱.۱, 0034): the tab bar «داشبورد», the three
* tabs «طرح‌های اشتراک» · «پیش‌بینی‌ها» · «مالی», then the tab. Each tab is its own route with its own loading, so the
* tabs «طرح‌های اشتراک» · «سیگنال‌ها» · «مالی», then the tab. Each tab is its own route with its own loading, so the
* bar and the tabs stay while one loads. Locked until registration step 5 is done (0016).
*/
export default function CreatorDashboardLayout({

View File

@ -2,7 +2,7 @@ import { PredictionsTabSkeleton } from '@lumina/market/app/screens/(main)/dashbo
import { i18n } from '../../../../../i18n';
/** پیش‌بینی‌ها before it arrives, block for block; the layout keeps the bar and the tabs. */
/** سیگنال‌ها before it arrives, block for block; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<PredictionsTabSkeleton label={i18n.t('predictions:tab.loading')} delayed />

View File

@ -13,7 +13,7 @@ export const metadata: Metadata = {
};
/**
* داشبورد › پیش‌بینی‌ها (J10-3): the creator's record, open and recently closed predictions, in the
* داشبورد › سیگنال‌ها (J10-3): the creator's record, open and recently closed predictions, in the
* browser only. Each block loads and fails on its own; the tabs stay.
*/
export default function PredictionsPage() {

View File

@ -4,7 +4,7 @@ import { PredictionListSkeleton } from '@lumina/market/app/screens/(main)/dashbo
import { i18n } from '../../../../../i18n';
/** «همه پیش‌بینی‌ها» before it arrives, under its real bar. */
/** «همه سیگنال‌ها» before it arrives, under its real bar. */
export default function Loading() {
return (
<>

View File

@ -17,8 +17,8 @@ export const metadata: Metadata = {
};
/**
* «همه پیش‌بینی‌ها» on mobile (J10-3f, J10-3g): a page pushed from the پیش‌بینی‌ها tab, back ·
* «پیش‌بینی‌ها» · support, with the nav kept on داشبورد. The creator's own, in the browser only;
* «همه سیگنال‌ها» on mobile (J10-3f, J10-3g): a page pushed from the سیگنال‌ها tab, back ·
* «سیگنال‌ها» · support, with the nav kept on داشبورد. The creator's own, in the browser only;
* opened on its own, back goes to the tab.
*/
export default function PredictionListPage() {

View File

@ -19,7 +19,7 @@ import { QuoteHealth } from './components/QuoteHealth';
import { QuoteHealthSkeleton } from './components/QuoteHealthSkeleton';
/**
* پیش‌بینی‌ها (J11-8): the quote sources' health, refreshed every minute, then the queue tabs
* سیگنال‌ها (J11-8): the quote sources' health, refreshed every minute, then the queue tabs
* (نیاز به تأیید with its count) in the URL. Each part loads and fails on its own; a queue change
* remounts the rows behind the table skeleton. The detail opens beside the table and the dialogs
* over it.

View File

@ -28,7 +28,7 @@ import { OutcomeValue } from './OutcomeValue';
import { PredictionCardView } from './PredictionCardView';
/**
* «تأیید بستن پیش‌بینی» (J11-8b): the card, what the system detected at what price, from where and
* «تأیید بستن سیگنال» (J11-8b): the card, what the system detected at what price, from where and
* when, and the outcome it would record. «اصلاح قیمت» turns it into J11-8g: a corrected price from
* the same source with a reason (the analyst's correction notice carries it), the outcome following
* the typed price, and «لغو اصلاح» back.

View File

@ -20,7 +20,7 @@ import { useRetained } from '../use-retained';
import { DialogSubject } from './DialogSubject';
/**
* «پرچم‌گذاری پیش‌بینی» (J11-8e): one reason chip and an optional note («سایر» needs one). Flags
* «پرچم‌گذاری سیگنال» (J11-8e): one reason chip and an optional note («سایر» needs one). Flags
* are internal: they change nothing on the card, the track record or the outcome.
*/
export function FlagDialog({ actions }: ActionsProps) {

View File

@ -4,7 +4,7 @@ import type { PredictionPayload } from '@lumina/garden-roof/features/predictions
import { Button } from '@lumina/island/atoms/button';
import { useTranslation } from 'react-i18next';
/** The row's keyboard way into «جزئیات پیش‌بینی»; a pointer can click anywhere on the row. */
/** The row's keyboard way into «جزئیات سیگنال»; a pointer can click anywhere on the row. */
export function OpenRowButton({
prediction,
href,

View File

@ -42,9 +42,9 @@ function Change({ from, to }: { from: ReactNode; to: ReactNode | null }) {
}
/**
* «اصلاح نتیجه پیش‌بینی» (J11-8d): a closed prediction's new close price from the same source,
* «اصلاح نتیجه سیگنال» (J11-8d): a closed prediction's new close price from the same source,
* with what changes (price, outcome, ROI), a «دلیل», and what investors and the analyst's track
* record will show. On an open prediction it is «بستن پیش‌بینی با قیمت ادمین»: the close price and
* record will show. On an open prediction it is «بستن سیگنال با قیمت ادمین»: the close price and
* outcome it would record, closing now (a symbol with no quote is never proposed). Either way the
* analyst's correction notice carries the reason. The win-rate change shows when the track record
* is known (opened from the detail).

View File

@ -10,7 +10,7 @@ import type { PageModelProps } from '../types';
import { PredictionDetail } from './PredictionDetail';
/**
* «جزئیات پیش‌بینی» (J11-8c) beside the table, open while the URL has `?id=`. Its content loads
* «جزئیات سیگنال» (J11-8c) beside the table, open while the URL has `?id=`. Its content loads
* on its own: a failed read errors inside the panel and leaves the queue as it was.
*/
export function PredictionSheet({ model }: PageModelProps) {

View File

@ -37,10 +37,14 @@ export function predictionCardLabels(
toFinalTarget: t('card.to-final-target'),
toStop: t('card.to-stop'),
riskReward: t('card.risk-reward'),
riskRewardRange: (worst, best) =>
t('card.risk-reward-range', { worst, best }),
levels: {
stop: t('card.levels.stop'),
entry: t('card.levels.entry'),
base: t('card.levels.base'),
range: t('card.levels.range'),
entryRange: t('card.levels.entry-range'),
target,
finalTarget: t('card.levels.final-target'),
close: t('card.levels.close'),

View File

@ -14,7 +14,7 @@ export const metadata: Metadata = {
};
/**
* پیش‌بینی‌ها (J11-8): the title and the rule that nothing closes without ops on the server; the
* سیگنال‌ها (J11-8): the title and the rule that nothing closes without ops on the server; the
* queues in the browser once the admin is known (0062).
*/
export default function PredictionsPage() {

View File

@ -17,16 +17,17 @@
In bull's document order. `compose/layout.tsx` is only `OnboardingGuard` (0016): it renders nothing, and sends a creator who hasn't finished step 5 to the creator profile.
| Section | Data | HTML | JS | Index | Notes |
| ------------------------------- | ------ | ----------- | ----------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| DesktopHeader (bear) | viewer | first flush | hydrate | no | the page renders it itself; rows as in [layout-main.md](layout-main.md) |
| PredictionComposer | viewer | skeleton | hydrate | no | `AuthGuard role="creator"`, fallback `SkeletonPreset form`; `usePublishAccess`: pending keeps the skeleton, blocked sends the creator to their channel (J09-1e, 0060) |
| ↳ ComposerPage | viewer | skeleton | hydrate | no | bull: `MobileTopBar`, the «انصراف» row, the fields, the preview, and «انتشار پیش‌بینی» pinned; bear: a 960 card drawn as the dialog, with its `h1`, the fields beside the preview; published, it replaces itself with the creator's channel |
| ↳ SymbolPicker | query | none | hydrate | no | «انتخاب نماد»: bull: a sheet; bear: a modal; mounts on open, then searches symbols in the browser |
| ↳ ConfirmPublish, LeaveConfirm | — | none | hydrate | no | mount on publish and on leaving with something to lose |
| PredictionComposerDialog (bear) | viewer | none | interaction | no | the `@modal` intercept (J09-1-D, 0023), on a soft navigation from a main page: the 960 dialog over that page; fallback `PredictionComposerDialogSkeleton`; anyone but a creator gets no-access inside the dialog |
| Section | Data | HTML | JS | Index | Notes |
| ------------------------------- | ------ | ----------- | ----------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| DesktopHeader (bear) | viewer | first flush | hydrate | no | the page renders it itself; rows as in [layout-main.md](layout-main.md) |
| PredictionComposer | viewer | skeleton | hydrate | no | `AuthGuard role="creator"`, fallback `SkeletonPreset form`; `usePublishAccess`: pending keeps the skeleton, blocked sends the creator to their channel (J09-1e, 0060) |
| ↳ ComposerPage | viewer | skeleton | hydrate | no | bull: `MobileTopBar`, the «انصراف» row, the fields, the preview, and «انتشار سیگنال» pinned; bear: a 960 card drawn as the dialog, with its `h1`, the fields beside the preview; published, it replaces itself with the creator's channel |
| ↳ SymbolPicker | query | none | hydrate | no | «انتخاب نماد»: bull: a sheet; bear: a modal; mounts on open, then searches symbols in the browser |
| ↳ ConfirmPublish, LeaveConfirm | — | none | hydrate | no | mount on publish and on leaving with something to lose |
| PredictionComposerDialog (bear) | viewer | none | interaction | no | the `@modal` intercept (J09-1-D, 0023), on a soft navigation from a main page: the 960 dialog over that page; fallback `PredictionComposerDialogSkeleton`; anyone but a creator gets no-access inside the dialog |
## Notes
- The analyst states the entry: «قیمت دقیق» (prefilled from the live quote, following it until edited) or «بازه», and a required stop-loss. Levels are checked against that entry in the browser and again by the API (`docs/plans/pre-launch-tasks.md`, Task 2). The confirm step sends what it showed, even if the quote has moved since.
- A hard load or refresh gets the full page; a soft navigation from a `(main)` page gets the dialog over it (see [compose-post.md](compose-post.md)).
- Debt: different H1 per app. bull has no `h1`; add a screen-reader `h1` to `ComposerPage`'s mobile branch (`platforms/market/src/app/screens/(flow)/compose/prediction/organisms/prediction-composer/components/ComposerPage.tsx:57`).

View File

@ -9,7 +9,7 @@
| loading.tsx | `dashboard/predictions/all/loading.tsx`: the real top bar (bull) or page title (bear) over `PredictionListSkeleton`, `delayed` |
| First flush | none |
| Canonical | none: `noindex` |
| H1 | bull: none, the bar's «همه پیش‌بینی‌ها» is a `<span>`; bear: «همه پیش‌بینی‌ها» in `DesktopPageTitle` |
| H1 | bull: none, the bar's «همه سیگنال‌ها» is a `<span>`; bear: «همه سیگنال‌ها» in `DesktopPageTitle` |
| JSON-LD | none |
| Scripts | none beyond the layout's |

View File

@ -19,11 +19,11 @@ In bull's document order. Everything sits in `AuthGuard role="creator"`, whose f
| Section | Data | HTML | JS | Index | Notes |
| --------------------------------------- | ------ | -------- | ----------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| PredictionsTab | viewer | skeleton | hydrate | no | `useQuery` for open and closed; before the first prediction, only the empty state with «پیش‌بینی جدید» to `/compose/prediction` (J10-3c) |
| PredictionsTab | viewer | skeleton | hydrate | no | `useQuery` for open and closed; before the first prediction, only the empty state with «سیگنال جدید» to `/compose/prediction` (J10-3c) |
| ↳ TrackRecord | viewer | skeleton | hydrate | no | the record or its progress to public; own `PartBoundary` and `<Suspense>` |
| ↳ PredictionSection «باز» | viewer | skeleton | hydrate | no | every open prediction as `OwnPredictionCard`; not drawn when empty; loads and fails on its own |
| ↳↳ ClosePredictionSheet | viewer | none | interaction | no | `next/dynamic`, rendered on the first «بستن زودهنگام» tap; its price poll loads with it |
| ↳ PredictionSection «بسته‌شده‌های اخیر» | viewer | skeleton | hydrate | no | the two closed most recently; then «همه پیش‌بینی‌ها», an `<a href>` to `/dashboard/predictions/all` |
| ↳ PredictionSection «بسته‌شده‌های اخیر» | viewer | skeleton | hydrate | no | the two closed most recently; then «همه سیگنال‌ها», an `<a href>` to `/dashboard/predictions/all` |
## Notes

View File

@ -8,7 +8,7 @@
| MobileTopBar (bull) | config | first flush | hydrate | no | `isTab`: the brand and «داشبورد» centred, in a `<span>`; support entry; the connection bar under it (0040) |
| ↳ NotificationBell and account avatar (bull) | viewer | none | hydrate | no | member only; while the viewer is unknown, the guest's «ورود/ثبت‌نام» holds the end of the bar, invisible |
| «داشبورد» `<h1>` (bear) | config | first flush | none | no | at the top of the 640 column |
| DashboardTabs | config | first flush | hydrate | no | `role="creator"`: island `TabLinks`, an `<a href>` per tab «طرح‌های اشتراک» · «پیش‌بینی‌ها» · «مالی» (0034); the active tab comes from `usePathname`, so the server HTML already marks it |
| DashboardTabs | config | first flush | hydrate | no | `role="creator"`: island `TabLinks`, an `<a href>` per tab «طرح‌های اشتراک» · «سیگنال‌ها» · «مالی» (0034); the active tab comes from `usePathname`, so the server HTML already marks it |
Scripts: none beyond the root layout's.

View File

@ -8,7 +8,7 @@
| ↳ Brand link (bear) | viewer | first flush | hydrate | no | `useHomeHref`: `/feed` while the viewer is unknown (so in the server HTML), `/` for a guest, `homeRoute` for a member |
| ↳ Nav: خانه or کانال, داشبورد (bear) | viewer | none | hydrate | no | members only; `HeaderNavLink` is `next/link` |
| ↳ SearchField (bear) | viewer | none | hydrate | no | investors only, not on `/search`; Enter calls `router.push('/search?q=…')` |
| ↳ PublishMenu (bear) | viewer | none | hydrate | no | creators only; «پست جدید» and «پیش‌بینی جدید» open the `@modal` intercepts (0023) |
| ↳ PublishMenu (bear) | viewer | none | hydrate | no | creators only; «پست جدید» and «سیگنال جدید» open the `@modal` intercepts (0023) |
| ↳ SupportEntry (bear) | config | first flush | hydrate | no | the icon trigger; its `SupportDialog` popover renders only while open |
| ↳ NotificationBell (bear) | viewer | none | hydrate | no | members only; the unread count is a browser `useQuery` |
| ↳ NotificationPanel (bear) | query | none | interaction | no | the bell's side panel: `next/dynamic` with `ssr: false`, mounted on the bell's first click |

View File

@ -23,7 +23,7 @@ In bull's document order.
| ↳ Title or login link (bull) | viewer | skeleton | hydrate | no | |
| DesktopPageTitle (bear) | config | first flush | hydrate | no | «بازگشت» and the H1 |
| NotificationCentre | viewer, query | skeleton | hydrate | no | `AuthGuard`, then `<Suspense>` and `PartBoundary name="notification-centre"`; `useSuspenseQuery` of the inbox; opening clears the bell (0058); bear: `framed` |
| ↳ FilterChips | viewer | skeleton | hydrate | no | creators only: «همه · پیش‌بینی‌ها · مالی · حساب», filtered in place (0058) |
| ↳ FilterChips | viewer | skeleton | hydrate | no | creators only: «همه · سیگنال‌ها · مالی · حساب», filtered in place (0058) |
| ↳ NotificationItem list | query | skeleton | hydrate | no | each row leads to its target; a row stays unread until tapped |
## Notes

View File

@ -12,7 +12,7 @@ import { actionMenuVariants } from './variants';
/**
* A short list of destinations or actions anchored to its trigger, such as «انتشار» → «پست جدید»
* / «پیش‌بینی جدید», a post's share → «کپی لینک», or the desktop account menu with its identity
* / «سیگنال جدید», a post's share → «کپی لینک», or the desktop account menu with its identity
* `header`, links and a danger «خروج از حساب» after a separator. Put it in a positioned container
* that holds only the trigger and the menu, and give the trigger `aria-haspopup="menu"`. It takes focus when
* it opens; ↑ ↓ move, and the trigger keeps its own press. Escape or a choice closes it and puts

View File

@ -38,7 +38,7 @@ export type AnalystCardLabels = {
verified: string;
/** The market list's accessible name: «بازارهای تخصصی». */
markets: string;
/** The stat tiles: «نرخ موفقیت», «پیش‌بینی», «میانگین بازده». */
/** The stat tiles: «نرخ موفقیت», «سیگنال», «میانگین بازده». */
winRate: ReactNode;
predictions: ReactNode;
avgRoi: ReactNode;

View File

@ -32,13 +32,13 @@ export type CreatorStatsData = {
* formatted (`1٬234`, `62٫9٪`), so the translation only places them.
*/
export type CreatorStatsLabels = {
/** «عملکرد پیش‌بینی‌ها». */
/** «عملکرد سیگنال‌ها». */
title: ReactNode;
/** «مشاهده کارنامه کامل». */
viewRecord: ReactNode;
/** «نرخ موفقیت». */
winRate: ReactNode;
/** Under the rate, once the split is known: `(count) => \`از ${count} پیش‌بینی بسته‌شده\``. */
/** Under the rate, once the split is known: `(count) => \`از ${count} سیگنال بسته‌شده\``. */
closedCount: (count: string) => ReactNode;
/** Each outcome in words, for the legend, the key, the tooltips and the curve's sentence: «موفق», «ناموفق», «سربه‌سر». */
outcomes: Record<TrendOutcome, string>;
@ -48,19 +48,19 @@ export type CreatorStatsLabels = {
splitSentence: (counts: Record<TrendOutcome, string>) => string;
/** «بازدهی میانگین». */
avgRoi: ReactNode;
/** «کل پیش‌بینی‌ها». */
/** «کل سیگنال‌ها». */
total: ReactNode;
/** «پیش‌بینی‌های فعال». */
/** «سیگنال‌های فعال». */
active: ReactNode;
/** «روند دقت». */
trendTitle: ReactNode;
/** Beside the trend title: `(count) => \`${count} پیش‌بینی اخیر\``. */
/** Beside the trend title: `(count) => \`${count} سیگنال اخیر\``. */
trendWindow: (count: string) => ReactNode;
/** `(wins, total) => \`${wins} از ${total} موفق\`` → «۷ از ۱۰ موفق». */
tally: (wins: string, total: string) => ReactNode;
/**
* The curve's one image label, every outcome in order plus how to read it:
* `(count, outcomes) => \`منحنی نتیجه ${count} پیش‌بینی اخیر، از قدیمی‌ترین به جدیدترین: ${outcomes.join('، ')}. هر موفق یک پله بالا، هر ناموفق یک پله پایین.\``.
* `(count, outcomes) => \`منحنی نتیجه ${count} سیگنال اخیر، از قدیمی‌ترین به جدیدترین: ${outcomes.join('، ')}. هر موفق یک پله بالا، هر ناموفق یک پله پایین.\``.
*/
curveLabel: (count: string, outcomes: string[]) => string;
/** The newest point's tooltip: `(outcome) => \`${outcome} (جدیدترین)\``. */

View File

@ -37,11 +37,11 @@ export type PostCardOwner = {
onDelete?: () => void;
/** «مشاهده به عنوان کاربر», on premium posts only. */
onPreview?: () => void;
/** The embedded open prediction's «بستن پیش‌بینی». */
/** The embedded open prediction's «بستن سیگنال». */
onClosePrediction?: () => void;
/**
* The embedded open prediction's close waiting for ops (J09-5): PredictionCard's `pendingClose`
* detail, which freezes «بستن پیش‌بینی».
* detail, which freezes «بستن سیگنال».
*/
pendingClose?: ReactNode;
/** 15 minutes after publishing: the edit icon stays, frozen, and explains itself. */

View File

@ -0,0 +1,117 @@
import { render, screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { PredictionCard } from './PredictionCard';
import type { PredictionCardLabels, PredictionData } from './types';
const labels = {
status: { open: 'فعال', win: 'موفق', loss: 'ناموفق', breakeven: 'سربه‌سر' },
direction: { long: 'خرید', short: 'فروش' },
horizon: (horizon: string) => horizon,
timeLeft: { daysLeft: (n: string) => n, underDays: (n: string) => n },
roi: 'بازدهی',
closedPrice: (price: unknown) => price,
heldFor: (duration: string) => duration,
toTarget: 'تا هدف',
toFinalTarget: 'تا هدف نهایی',
toStop: 'تا حد ضرر',
riskReward: 'ریسک به ریوارد',
riskRewardRange: (worst: string, best: string) => `${worst} تا ${best}`,
levels: {
stop: 'حد ضرر',
entry: 'ورود',
base: 'مبنا',
range: 'بازه',
entryRange: 'ورود (بازه)',
target: () => 'هدف',
finalTarget: 'هدف نهایی',
close: 'بسته‌شدن',
horizon: 'افق',
},
ladder: {
level: 'سطح',
price: 'قیمت',
change: 'تغییر از ورود',
state: 'وضعیت',
reached: 'رسید',
missed: 'نرسید',
triggered: 'فعال شد',
notTriggered: 'فعال نشد',
},
rangeLabel: ({ entry }: { entry: string }) => `محدوده ${entry}`,
horizonElapsed: (duration: string) => duration,
horizonEnd: (end: string) => end,
horizonProgress: 'زمان',
seal: (at: unknown) => at,
immutable: 'غیرقابل ویرایش',
locked: { title: 't', description: 'd', hidden: 'h' },
} as unknown as PredictionCardLabels;
const exact: PredictionData = {
symbol: 'XAUUSD',
direction: 'long',
entryPrice: 100,
targetPrices: [120],
stopLoss: 90,
horizon: '1w',
status: 'open',
};
const range: PredictionData = {
...exact,
entryPrice: 68000,
entryLow: 67500,
entryHigh: 68500,
targetPrices: [70000],
stopLoss: 67000,
};
const card = (prediction: PredictionData, variant?: 'expanded') =>
render(
<PredictionCard
prediction={prediction}
variant={variant}
publishedAt="2026-01-01T00:00:00Z"
now="2026-01-02T00:00:00Z"
labels={labels}
/>,
);
const riskRewardText = () =>
screen.getByText('ریسک به ریوارد').parentElement!.textContent ?? '';
describe('PredictionCard entry', () => {
it('shows an exact entry with «مبنا» and one ratio', () => {
card(exact);
expect(screen.getByText('مبنا')).toBeTruthy();
expect(screen.queryByText('بازه')).toBeNull();
expect(riskRewardText()).not.toContain('تا ');
});
it('shows a range with both ends, «بازه» instead of «مبنا», and worst to best', () => {
card(range);
expect(screen.getByText('67٬500 – 68٬500')).toBeTruthy();
expect(screen.getByText('بازه')).toBeTruthy();
expect(screen.queryByText('مبنا')).toBeNull();
const text = riskRewardText();
expect(text.indexOf('1٫0')).toBeLessThan(text.indexOf('5٫0'));
expect(text).toContain(' تا ');
});
it('names the range in the bar, measured from its middle', () => {
card(range);
expect(
screen.getByRole('img', { name: 'محدوده 67٬500 – 68٬500' }),
).toBeTruthy();
});
it('calls the ladder row «ورود (بازه)» on an expanded card', () => {
card(range, 'expanded');
const row = screen.getByText('ورود (بازه)').closest('tr')!;
expect(within(row).getByText('67٬500 – 68٬500')).toBeTruthy();
expect(within(row).getByText('بازه')).toBeTruthy();
});
it('keeps «ورود» and «مبنا» in an exact ladder row', () => {
card(exact, 'expanded');
const row = screen.getByText('مبنا').closest('tr')!;
expect(within(row).getByText('ورود')).toBeTruthy();
});
});

View File

@ -37,7 +37,12 @@ export function OpenKpis({ prediction, math, labels }: PredictionPartProps) {
)}
{riskReward != null && (
<Kpi label={labels.riskReward} color="primary">
{ratio(1, riskReward)}
{riskReward.worst === riskReward.best
? ratio(1, riskReward.worst)
: labels.riskRewardRange(
ratio(1, riskReward.worst),
ratio(1, riskReward.best),
)}
</Kpi>
)}
</GridBox>

View File

@ -6,7 +6,7 @@ import { Element } from '../../../primitives/element';
import { cn } from '../../../tools/cn';
import { CLOSE_SORT_NUDGE, EMPTY_VALUE, TREND_COLORS } from '../constants';
import type { LadderRow, PredictionPartProps } from '../types';
import { trendOf } from '../utils';
import { entryText, isRangeEntry, trendOf } from '../utils';
import { ladderCellVariants, ladderHeadVariants } from '../variants';
import { LevelGlyph } from './LevelGlyph';
@ -24,6 +24,7 @@ export function PredictionLadder({
const { closed, closeFav, risk, hits, targetsFav, stopHit } = math;
const { levels, ladder } = labels;
const many = targetPrices.length > 1;
const isRange = isRangeEntry(prediction);
const rows: LadderRow[] = targetPrices.map((target, index) => ({
key: `t${index}`,
@ -44,9 +45,10 @@ export function PredictionLadder({
order: 0,
change: null,
glyph: <LevelGlyph kind="entry" />,
label: levels.entry,
label: isRange ? levels.entryRange : levels.entry,
price: entryPrice,
state: levels.base,
priceText: isRange ? entryText(prediction) : undefined,
state: isRange ? levels.range : levels.base,
});
if (stopLoss != null && risk != null) {
rows.push({
@ -145,7 +147,7 @@ export function PredictionLadder({
variant="body-sm"
className={cn(cell, 'text-end font-bold')}
>
{price(row.price)}
{row.priceText ?? price(row.price)}
</Typography>
<Typography
tag="td"

View File

@ -4,12 +4,15 @@ import { GridBox } from '../../../atoms/grid-box';
import { Typography } from '../../../atoms/typography';
import { TREND_COLORS } from '../constants';
import type { PredictionPartProps } from '../types';
import { hasLongPrice, trendOf } from '../utils';
import { entryText, hasLongPrice, isRangeEntry, trendOf } from '../utils';
import { levelsVariants } from '../variants';
import { LevelGlyph } from './LevelGlyph';
import { LevelTile } from './LevelTile';
/** Compact: the exact prices on sunken tiles, stop loss → entry → targets, each with its % from entry. */
/**
* Compact: the exact prices on sunken tiles, stop loss → entry → targets, each with its % from entry.
* A range entry shows both ends, marked «بازه» instead of «مبنا», on wider tiles.
*/
export function PredictionLevels({
prediction,
math,
@ -17,8 +20,9 @@ export function PredictionLevels({
}: PredictionPartProps) {
const { entryPrice, targetPrices, stopLoss } = prediction;
const many = targetPrices.length > 1;
const isRange = isRangeEntry(prediction);
const value = (level: number, change: number | null) => (
const value = (level: string, change: number | null) => (
<>
<Typography
tag="span"
@ -26,11 +30,11 @@ export function PredictionLevels({
variant="body-sm"
className="truncate text-end font-bold"
>
{price(level)}
{level}
</Typography>
{change == null ? (
<Typography tag="span" variant="micro" color="tertiary">
{labels.levels.base}
{isRange ? labels.levels.range : labels.levels.base}
</Typography>
) : (
<Typography
@ -52,6 +56,7 @@ export function PredictionLevels({
gap="gap-2"
className={levelsVariants({
wide: hasLongPrice([entryPrice, stopLoss, ...targetPrices]),
range: isRange,
})}
>
{stopLoss != null && (
@ -59,14 +64,14 @@ export function PredictionLevels({
glyph={<LevelGlyph kind="stop" />}
label={labels.levels.stop}
>
{value(stopLoss, math.risk)}
{value(price(stopLoss), math.risk)}
</LevelTile>
)}
<LevelTile
glyph={<LevelGlyph kind="entry" />}
label={labels.levels.entry}
>
{value(entryPrice, null)}
{value(entryText(prediction), null)}
</LevelTile>
{targetPrices.map((target, index) => (
<LevelTile
@ -80,7 +85,7 @@ export function PredictionLevels({
}
label={labels.levels.target(many ? number(index + 1) : undefined)}
>
{value(target, math.targetsFav[index])}
{value(price(target), math.targetsFav[index])}
</LevelTile>
))}
</GridBox>

View File

@ -6,7 +6,7 @@ import { Typography } from '../../../atoms/typography';
import { Element } from '../../../primitives/element';
import { OUTCOME_TRENDS } from '../constants';
import type { PredictionRangeProps } from '../types';
import { atPosition, bandBetween, trendOf } from '../utils';
import { atPosition, bandBetween, entryText, trendOf } from '../utils';
import { markerVariants, rangeBandVariants, rangeVariants } from '../variants';
import { ClosePin } from './ClosePin';
@ -14,7 +14,7 @@ import { ClosePin } from './ClosePin';
* Where the prediction stands between its stop loss (inline start, the right in RTL) and its final
* target (inline end): the risk and reward zones, entry, numbered targets that fill once reached,
* and on a closed card a fill from entry with a pin at the close. Without a stop loss the bar
* starts at entry.
* starts at entry. A range entry is drawn at its middle.
*/
export function PredictionRange({
prediction,
@ -22,8 +22,7 @@ export function PredictionRange({
labels,
expanded,
}: PredictionRangeProps) {
const { entryPrice, targetPrices, stopLoss, closedPrice, outcome } =
prediction;
const { targetPrices, stopLoss, closedPrice, outcome } = prediction;
const { position, risk, reward, closed, closeFav, targetsFav, hits } = math;
const hasStop = risk != null;
const entry = position(0);
@ -38,7 +37,7 @@ export function PredictionRange({
const label = labels.rangeLabel({
stop: hasStop ? price(stopLoss) : undefined,
entry: price(entryPrice),
entry: entryText(prediction),
targets: targetPrices.map(price),
close: closed ? price(closedPrice) : undefined,
});

View File

@ -1,4 +1,5 @@
export { PredictionCard } from './PredictionCard';
export { entryText, isRangeEntry } from './utils';
export type {
PredictionCardLabels,
PredictionCardProps,

View File

@ -28,7 +28,11 @@ export type PredictionData = {
/** The market's label from the translations: «کریپتو», «طلا», «بورس». */
market?: ReactNode;
direction: PredictionDirection;
/** The exact entry, or the middle of a range: every distance and return reads this. */
entryPrice: number;
/** A range entry: both, low below high. */
entryLow?: number | null;
entryHigh?: number | null;
/** One or more, nearest first; designed for up to three. The last one is the final target. */
targetPrices: number[];
/** Optional: without it there is no stop marker, risk zone, level or «تا حد ضرر». */
@ -90,6 +94,8 @@ export type PredictionCardLabels = {
toStop: ReactNode;
/** «ریسک به ریوارد», against the first target. */
riskReward: ReactNode;
/** A range entry's lower and higher ratio, already formatted: «۱ : ۱٫۴ تا ۱ : ۳٫۰». */
riskRewardRange: (worst: string, best: string) => ReactNode;
/** The names of the price levels, in the levels grid, the ladder and the range axis. */
levels: {
/** «حد ضرر». */
@ -98,6 +104,10 @@ export type PredictionCardLabels = {
entry: ReactNode;
/** Entry's reference mark in place of a % change: «مبنا». */
base: ReactNode;
/** The same mark on a range entry: «بازه». */
range: ReactNode;
/** The ladder's row for a range entry: «ورود (بازه)». */
entryRange: ReactNode;
/** A target, numbered only when there are several: `(n) => (n ? <>هدف {n}</> : 'هدف')`. */
target: (n?: string) => ReactNode;
/** «هدف نهایی», the range axis's end when there are several targets. */
@ -122,7 +132,7 @@ export type PredictionCardLabels = {
notTriggered: ReactNode;
};
/**
* The range bar's `aria-label`: «محدوده پیش‌بینی: حد ضرر ۹۵٬۰۰۰، ورود ۱۰۰٬۰۰۰، هدف ۱ ۱۱۰٬۰۰۰،
* The range bar's `aria-label`: «محدوده سیگنال: حد ضرر ۹۵٬۰۰۰، ورود ۱۰۰٬۰۰۰، هدف ۱ ۱۱۰٬۰۰۰،
* بسته‌شدن ۱۰۸٬۰۰۰».
*/
rangeLabel: (values: PredictionRangeValues) => string;
@ -141,7 +151,7 @@ export type PredictionCardLabels = {
/** The owner's pending-close row title, in bold: «در انتظار تأیید بسته‌شدن» (J09-5). */
pendingClose?: ReactNode;
/**
* Why «بستن زودهنگام» is frozen while a close waits for ops: «این پیش‌بینی به‌زودی به‌صورت خودکار
* Why «بستن زودهنگام» is frozen while a close waits for ops: «این سیگنال به‌زودی به‌صورت خودکار
* بسته می‌شود.» (J10-3f).
*/
closeFrozen?: ReactNode;
@ -171,7 +181,7 @@ export type PredictionCardLabels = {
};
/** A premium card for a viewer without access. */
locked: {
/** «پیش‌بینی پریمیوم». */
/** «سیگنال پریمیوم». */
title: ReactNode;
/** «دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.» */
description: ReactNode;
@ -235,6 +245,8 @@ export type PredictionCardProps = PredictionCardOwnProps &
}
);
export type RiskReward = { worst: number; best: number };
/** Every number the card shows, computed once from the prediction. */
export type PredictionMath = {
targetsFav: number[];
@ -242,8 +254,8 @@ export type PredictionMath = {
risk: number | null;
/** The final target's favourable %. */
reward: number | null;
/** x in «۱ : x», against the first target. */
riskReward: number | null;
/** Rewards per unit of risk to the first target: one answer for an exact entry, or a range's two ends. */
riskReward: RiskReward | null;
/** Closed with a close price: the range draws a fill and a pin. */
closed: boolean;
closeFav: number | null;
@ -358,6 +370,8 @@ export type LadderRow = {
glyph: ReactNode;
label: ReactNode;
price: number;
/** In place of `price`: a range entry's two ends. */
priceText?: string;
state: ReactNode;
/** A target the close reached. */
hit?: boolean;

View File

@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest';
import type { PredictionData } from './types';
import { entryText, isRangeEntry, predictionMath, riskRewardOf } from './utils';
const exact: PredictionData = {
symbol: 'XAUUSD',
direction: 'long',
entryPrice: 100,
targetPrices: [120],
stopLoss: 90,
horizon: '1w',
};
const range: PredictionData = {
...exact,
entryPrice: 68000,
entryLow: 67500,
entryHigh: 68500,
targetPrices: [70000],
stopLoss: 67000,
};
describe('riskRewardOf', () => {
it('has one answer for an exact entry', () => {
expect(riskRewardOf(exact)).toEqual({ worst: 2, best: 2 });
});
it('works a long range out at both ends, the lower ratio first', () => {
// From the top: 1500 of reward for 1500 of risk. From the bottom: 2500 for 500.
expect(riskRewardOf(range)).toEqual({ worst: 1, best: 5 });
});
it('mirrors for a short', () => {
const short: PredictionData = {
...exact,
direction: 'short',
entryPrice: 100,
entryLow: 98,
entryHigh: 102,
targetPrices: [90],
stopLoss: 110,
};
expect(riskRewardOf(short)).toEqual({ worst: 8 / 12, best: 12 / 8 });
});
it('reads the first target, not the final one', () => {
expect(riskRewardOf({ ...exact, targetPrices: [110, 200] })).toEqual({
worst: 1,
best: 1,
});
});
it.each([
['no stop', { stopLoss: null }],
['no target', { targetPrices: [] }],
['a stop on the wrong side', { stopLoss: 105 }],
['a stop on the entry', { stopLoss: 100 }],
['a target on the wrong side', { targetPrices: [95] }],
])('is null with %s', (_name, over) => {
expect(riskRewardOf({ ...exact, ...over })).toBeNull();
});
});
describe('the entry', () => {
it('knows a range only when both ends are there', () => {
expect(isRangeEntry(range)).toBe(true);
expect(isRangeEntry(exact)).toBe(false);
expect(isRangeEntry({ entryLow: 1, entryHigh: null })).toBe(false);
});
it('writes both ends of a range, low first', () => {
expect(entryText(range)).toBe('67٬500 – 68٬500');
expect(entryText(exact)).toBe('100');
});
it('measures every distance from the middle of a range', () => {
const math = predictionMath(range);
expect(math.targetsFav[0]).toBeCloseTo((2000 / 68000) * 100);
expect(math.risk).toBeCloseTo((-1000 / 68000) * 100);
});
});

View File

@ -13,6 +13,7 @@ import type {
PredictionOutcome,
PredictionStatus,
PredictionTrend,
RiskReward,
} from './types';
export function toTime(value: DateInput): number {
@ -48,6 +49,46 @@ export function resolveStatus(
: 'open';
}
/** The entry is a range, not one price. */
export function isRangeEntry(
prediction: Pick<PredictionData, 'entryLow' | 'entryHigh'>,
): boolean {
return prediction.entryLow != null && prediction.entryHigh != null;
}
/** The entry as text: one price, or a range's two ends, low first: `۶۷٬۵۰۰ – ۶۸٬۵۰۰`. */
export function entryText(
prediction: Pick<PredictionData, 'entryPrice' | 'entryLow' | 'entryHigh'>,
): string {
return isRangeEntry(prediction)
? `${price(prediction.entryLow)} – ${price(prediction.entryHigh)}`
: price(prediction.entryPrice);
}
/**
* Reward per unit of risk to the first target, as the API works it out. An exact entry has one
* answer; a range is worked out at both ends, `worst` being the lower ratio and `best` the higher.
* Null without a stop or a target, or when a level isn't on its side of the entry.
*/
export function riskRewardOf(prediction: PredictionData): RiskReward | null {
const { direction, targetPrices, stopLoss } = prediction;
const target = targetPrices[0];
if (stopLoss == null || target == null) return null;
const sign = direction === 'short' ? -1 : 1;
const ends = isRangeEntry(prediction)
? [prediction.entryLow as number, prediction.entryHigh as number]
: [prediction.entryPrice];
const ratios = ends.map(
(end) => ((target - end) * sign) / ((end - stopLoss) * sign),
);
const onSide = ends.every(
(end) => (target - end) * sign > 0 && (end - stopLoss) * sign > 0,
);
return onSide
? { worst: Math.min(...ratios), best: Math.max(...ratios) }
: null;
}
/**
* Every value is a "favourable %": the move from entry in the prediction's own direction, so a
* positive number always points toward the targets, for a long and a short alike.
@ -72,12 +113,6 @@ export function predictionMath(prediction: PredictionData): PredictionMath {
const targetsFav = targetPrices.map(fav);
const risk = stopLoss != null ? fav(stopLoss) : null;
const reward = targetsFav.at(-1) ?? null;
const firstReward = targetsFav[0] ?? null;
// Risk to reward reads against the first target: the one most likely to be reached.
const riskReward =
risk != null && risk < 0 && firstReward != null && firstReward > 0
? firstReward / -risk
: null;
const points = [0, ...targetsFav];
if (risk != null) points.push(risk);
@ -91,7 +126,8 @@ export function predictionMath(prediction: PredictionData): PredictionMath {
targetsFav,
risk,
reward,
riskReward,
// Against the first target: the one most likely to be reached.
riskReward: riskRewardOf(prediction),
closed: closeFav != null,
closeFav,
roi,

View File

@ -121,8 +121,13 @@ export const levelsVariants = cva('m-0', {
true: 'grid-cols-[repeat(auto-fit,minmax(6rem,1fr))]',
false: 'grid-cols-[repeat(auto-fit,minmax(4.5rem,1fr))]',
},
/** A range entry's two ends need a tile of their own width. */
range: {
true: 'grid-cols-[repeat(auto-fit,minmax(10.5rem,1fr))]',
false: '',
},
},
defaultVariants: { wide: false },
defaultVariants: { wide: false, range: false },
});
export const ladderHeadVariants = cva(

View File

@ -2,7 +2,7 @@ export type PartBoundaryProps = {
/** The part, for the error report: «creator-stats», «feed». Never personal data. */
name: string;
/**
* The part's own failure copy, such as «عملکرد پیش‌بینی‌ها بارگذاری نشد» / «بقیه کانال در دسترس
* The part's own failure copy, such as «عملکرد سیگنال‌ها بارگذاری نشد» / «بقیه کانال در دسترس
* است…» (S3); without it the fallback says what every part says.
*/
title?: string;

View File

@ -6,7 +6,7 @@ import type { OverridePredictionArgs } from '../../repositories/predictions';
/**
* «ثبت اصلاح» (J11-8d): a closed prediction's close price changes from the same source. On an open
* prediction, «بستن پیش‌بینی» closes it now at the admin's price (a symbol with no quote is never
* prediction, «بستن سیگنال» closes it now at the admin's price (a symbol with no quote is never
* proposed). Either way investors see «علت: اصلاح توسط ادمین» (J09-5d) and the analyst's track
* record follows the outcome. Emits `prediction.overridden`.
*/

View File

@ -6,7 +6,7 @@ import {
} from '../../repositories/predictions';
import type { PredictionDetailPartModel } from './types';
/** «جزئیات پیش‌بینی» (J11-8c): the card, «خط زمانی» and «گزارش ممیزی»; refetched after each action. */
/** «جزئیات سیگنال» (J11-8c): the card, «خط زمانی» and «گزارش ممیزی»; refetched after each action. */
export function usePredictionDetailPart(id: string): PredictionDetailPartModel {
const { data } = useSuspenseQuery({
queryKey: predictionKeys.detail(id),

View File

@ -10,7 +10,7 @@ import type { PredictionsPageModel } from './types';
import { usePredictionActions } from './use-prediction-actions';
/**
* پیش‌بینی‌ها (J11-8): the queue (نیاز به تأیید by default, with the sidebar's count), its page and
* سیگنال‌ها (J11-8): the queue (نیاز به تأیید by default, with the sidebar's count), its page and
* the prediction open beside the table (J11-8c) live in the URL, so a reload or a shared link
* keeps them. Closing never happens without ops: a detected close waits in نیاز به تأیید while the
* card stays «فعال».

View File

@ -13,7 +13,7 @@
"analysts": "مدیریت تحلیلگران",
"codes": "کدهای دعوت",
"subs": "اشتراک‌ها",
"preds": "پیش‌بینی‌ها",
"preds": "سیگنال‌ها",
"payouts": "تسویه تحلیلگران",
"featured": "تحلیلگران منتخب",
"soon": "به‌زودی",

View File

@ -83,7 +83,7 @@
"verified": "تأییدشده",
"markets": "بازارهای تخصصی",
"win-rate": "نرخ موفقیت",
"predictions": "پیش‌بینی",
"predictions": "سیگنال",
"avg-roi": "میانگین بازده",
"no-record": "کارنامه عمومی هنوز فعال نشده است.",
"followers": "{{followers}} دنبال‌کننده",

View File

@ -29,7 +29,7 @@
"labels": {
"active_analysts": "تحلیلگران فعال",
"avg_paid_subscribers": "میانگین مشترک پرداختی هر تحلیلگر",
"publishing_analysts": "تحلیلگرانی که پیش‌بینی منتشر کرده‌اند",
"publishing_analysts": "تحلیلگرانی که سیگنال منتشر کرده‌اند",
"paid_subscribers": "کل مشترکان پرداختی"
},
"value": "{{value}} / {{target}}",
@ -58,7 +58,7 @@
"payment_result": "پرداخت موفق",
"kyc_submitted": "ارسال مدارک احراز هویت",
"verification_approved": "تأیید احراز هویت",
"first_prediction_published": "اولین پیش‌بینی منتشرشده"
"first_prediction_published": "اولین سیگنال منتشرشده"
}
},
"timeline": {
@ -82,7 +82,7 @@
"columns": {
"analyst": "تحلیلگر",
"paid": "مشترک پرداختی",
"predictions": "پیش‌بینی منتشرشده",
"predictions": "سیگنال منتشرشده",
"capacity": "ظرفیت کد",
"completion": "نرخ تکمیل پرداخت"
},
@ -103,7 +103,7 @@
"onboarding": {
"label": "زمان آماده‌سازی تحلیلگر",
"value": "{{days}} روز",
"hint": "میانه، از ثبت‌نام تا اولین پیش‌بینی منتشرشده"
"hint": "میانه، از ثبت‌نام تا اولین سیگنال منتشرشده"
},
"churn": {
"label": "ریزش ماه اول",
@ -114,8 +114,8 @@
"hint": "{{completed}} پرداخت موفق از {{started}} ورود به درگاه"
},
"pace": {
"label": "پیش‌بینی هر تحلیلگر در ماه",
"hint": "{{predictions}} پیش‌بینی در {{days}} روز، {{analysts}} تحلیلگر فعال"
"label": "سیگنال هر تحلیلگر در ماه",
"hint": "{{predictions}} سیگنال در {{days}} روز، {{analysts}} تحلیلگر فعال"
},
"views": {
"label": "بازدید کارنامه",

View File

@ -1,9 +1,9 @@
{
"page": {
"title": "پیش‌بینی‌ها",
"meta-title": "پیش‌بینی‌ها",
"subtitle": "بستن خودکار تا تأیید ادمین منتشر نمی‌شود؛ پیش‌بینی تا آن زمان «فعال» می‌ماند.",
"loading": "در حال بارگذاری پیش‌بینی‌ها…"
"title": "سیگنال‌ها",
"meta-title": "سیگنال‌ها",
"subtitle": "بستن خودکار تا تأیید ادمین منتشر نمی‌شود؛ سیگنال تا آن زمان «فعال» می‌ماند.",
"loading": "در حال بارگذاری سیگنال‌ها…"
},
"health": {
"title": "وضعیت منابع قیمت",
@ -15,7 +15,7 @@
"fresh": "به‌روز",
"stale": "{{minutes}} دقیقه بدون قیمت",
"stale-no-price": "بدون قیمت",
"banner": "پیشنهاد بستن پیش‌بینی‌های {{markets}} تا رسیدن قیمت تازه منتظر می‌ماند و در این صف نمایش داده نمی‌شود. این پیش‌بینی‌ها تا آن زمان باز می‌مانند.",
"banner": "پیشنهاد بستن سیگنال‌های {{markets}} تا رسیدن قیمت تازه منتظر می‌ماند و در این صف نمایش داده نمی‌شود. این سیگنال‌ها تا آن زمان باز می‌مانند.",
"loading": "در حال بررسی منابع قیمت…",
"error": "وضعیت منابع قیمت بارگذاری نشد."
},
@ -49,7 +49,7 @@
"other": "سایر"
},
"queues": {
"label": "صف‌های پیش‌بینی",
"label": "صف‌های سیگنال",
"tabs": {
"needs_review": "نیاز به تأیید",
"open": "باز",
@ -57,8 +57,8 @@
"flagged": "پرچم‌خورده"
},
"count": "{{count}} پیشنهاد در انتظار تأیید",
"loading": "در حال بارگذاری پیش‌بینی‌ها…",
"error": "فهرست پیش‌بینی‌ها بارگذاری نشد.",
"loading": "در حال بارگذاری سیگنال‌ها…",
"error": "فهرست سیگنال‌ها بارگذاری نشد.",
"columns": {
"symbol": "نماد",
"analyst": "تحلیلگر",
@ -82,16 +82,16 @@
"flag": "پرچم‌گذاری",
"open": "جزئیات"
},
"open-row": "جزئیات پیش‌بینی {{symbol}} از {{name}}",
"open-row": "جزئیات سیگنال {{symbol}} از {{name}}",
"pending": "پیشنهاد بستن در انتظار تأیید",
"held": "در انتظار قیمت {{source}}",
"review": "بررسی و بستن",
"close-admin": "بستن با قیمت ادمین",
"flag": "پرچم‌گذاری",
"flag-row": "پرچم‌گذاری پیش‌بینی {{symbol}} از {{name}}",
"flag-row": "پرچم‌گذاری سیگنال {{symbol}} از {{name}}",
"unflag": "برداشتن پرچم",
"order": {
"needs_review": "ترتیب: قدیمی‌ترین رویداد اول. پیش‌بینی تا تأیید ادمین باز می‌ماند.",
"needs_review": "ترتیب: قدیمی‌ترین رویداد اول. سیگنال تا تأیید ادمین باز می‌ماند.",
"open": "جدیدترین انتشار اول",
"closed": "ترتیب: جدیدترین بسته‌شدن اول.",
"flagged": "ترتیب: جدیدترین پرچم اول."
@ -104,24 +104,24 @@
"description": "بستن‌های خودکار تازه پیش از انتشار اینجا منتظر تأیید می‌مانند."
},
"open": {
"title": "پیش‌بینی بازی نیست",
"description": "پیش‌بینی‌های منتشرشده تا بسته شدن اینجا نمایش داده می‌شوند."
"title": "سیگنال بازی نیست",
"description": "سیگنال‌های منتشرشده تا بسته شدن اینجا نمایش داده می‌شوند."
},
"closed": {
"title": "هنوز پیش‌بینی‌ای بسته نشده است",
"description": "پیش‌بینی‌های بسته‌شده با نتیجه‌شان اینجا نمایش داده می‌شوند."
"title": "هنوز سیگنالی بسته نشده است",
"description": "سیگنال‌های بسته‌شده با نتیجه‌شان اینجا نمایش داده می‌شوند."
},
"flagged": {
"title": "پیش‌بینی پرچم‌خورده‌ای نیست",
"description": "پیش‌بینی‌هایی که پرچم بخورند اینجا نمایش داده می‌شوند."
"title": "سیگنال پرچم‌خورده‌ای نیست",
"description": "سیگنال‌هایی که پرچم بخورند اینجا نمایش داده می‌شوند."
}
}
},
"detail": {
"title": "جزئیات پیش‌بینی",
"title": "جزئیات سیگنال",
"channel": "کانال",
"loading": "در حال بارگذاری پیش‌بینی…",
"error": "پیش‌بینی بارگذاری نشد.",
"loading": "در حال بارگذاری سیگنال…",
"error": "سیگنال بارگذاری نشد.",
"review": "بررسی و بستن",
"override": "اصلاح نتیجه",
"close-admin": "بستن با قیمت ادمین",
@ -148,7 +148,7 @@
}
},
"confirm": {
"title": "تأیید بستن پیش‌بینی",
"title": "تأیید بستن سیگنال",
"fields": {
"event": "رویداد",
"proposed": "قیمت پیشنهادی",
@ -162,8 +162,8 @@
"reject": "رد پیشنهاد",
"lock": "پس از تأیید، نتیجه روی کارت و در کارنامه تحلیلگر ثبت می‌شود و فقط با «اصلاح نتیجه» تغییر می‌کند.",
"confirm": "تأیید و بستن",
"done": "پیش‌بینی بسته شد.",
"failed": "بستن پیش‌بینی انجام نشد"
"done": "سیگنال بسته شد.",
"failed": "بستن سیگنال انجام نشد"
},
"correct": {
"price": "قیمت اصلاح‌شده",
@ -173,18 +173,18 @@
"price-required": "قیمت اصلاح‌شده را بنویسید.",
"price-invalid": "قیمت را به‌صورت یک عدد مثبت بنویسید.",
"price-same": "قیمت اصلاح‌شده با قیمت ثبت‌شده یکی است؛ برای همین قیمت «لغو اصلاح» را بزنید.",
"done": "پیش‌بینی با قیمت اصلاح‌شده بسته شد."
"done": "سیگنال با قیمت اصلاح‌شده بسته شد."
},
"reject": {
"title": "رد پیشنهاد بستن",
"banner": "پیش‌بینی باز می‌ماند و بررسی قیمت ادامه پیدا می‌کند. قیمت ثبت‌شده حذف نمی‌شود و در گزارش ممیزی می‌ماند.",
"banner": "سیگنال باز می‌ماند و بررسی قیمت ادامه پیدا می‌کند. قیمت ثبت‌شده حذف نمی‌شود و در گزارش ممیزی می‌ماند.",
"empty": "ابتدا دلیل رد پیشنهاد را بنویسید.",
"confirm": "رد پیشنهاد",
"done": "پیشنهاد بستن رد شد.",
"failed": "رد پیشنهاد انجام نشد"
},
"override": {
"title": "اصلاح نتیجه پیش‌بینی",
"title": "اصلاح نتیجه سیگنال",
"compare": "فعلی ← پس از اصلاح",
"fields": {
"closed-price": "قیمت بسته‌شدن",
@ -194,7 +194,7 @@
"price": "قیمت بسته‌شدن جدید",
"source-fixed": "منبع ثابت است: {{source}}",
"source-fixed-horizon": "منبع ثابت است: {{source}}، قیمت پایان افق ({{time}})",
"impact": "سرمایه‌گذاران روی کارت این پیش‌بینی می‌بینند: «علت: اصلاح توسط ادمین».",
"impact": "سرمایه‌گذاران روی کارت این سیگنال می‌بینند: «علت: اصلاح توسط ادمین».",
"impact-record": "کارنامه {{name}} تغییر می‌کند: نرخ موفقیت {{before}} ← {{after}}.",
"confirm": "ثبت اصلاح",
"price-required": "قیمت بسته‌شدن را بنویسید.",
@ -204,22 +204,22 @@
"failed": "اصلاح نتیجه انجام نشد"
},
"close-admin": {
"title": "بستن پیش‌بینی با قیمت ادمین",
"title": "بستن سیگنال با قیمت ادمین",
"compare": "پس از بستن",
"fields": {
"entry": "قیمت ورود"
},
"price": "قیمت بسته‌شدن",
"hint": "زمان بسته‌شدن همین لحظه ثبت می‌شود.",
"impact": "پیش‌بینی با این قیمت بسته می‌شود و دوباره باز نمی‌شود. سرمایه‌گذاران روی کارت می‌بینند: «علت: اصلاح توسط ادمین» و تحلیلگر و دنبال‌کنندگان اعلان بسته‌شدن می‌گیرند.",
"impact-pending": "پیشنهاد بستن در انتظار این پیش‌بینی هم کنار گذاشته می‌شود.",
"confirm": "بستن پیش‌بینی",
"done": "پیش‌بینی با قیمت ادمین بسته شد.",
"failed": "بستن پیش‌بینی انجام نشد"
"impact": "سیگنال با این قیمت بسته می‌شود و دوباره باز نمی‌شود. سرمایه‌گذاران روی کارت می‌بینند: «علت: اصلاح توسط ادمین» و تحلیلگر و دنبال‌کنندگان اعلان بسته‌شدن می‌گیرند.",
"impact-pending": "پیشنهاد بستن در انتظار این سیگنال هم کنار گذاشته می‌شود.",
"confirm": "بستن سیگنال",
"done": "سیگنال با قیمت ادمین بسته شد.",
"failed": "بستن سیگنال انجام نشد"
},
"flag": {
"title": "پرچم‌گذاری پیش‌بینی",
"banner": "پرچم‌ها داخلی‌اند: روی کارت، کارنامه و نتیجهٔ این پیش‌بینی اثری ندارند و فقط ادمین‌ها آن‌ها را می‌بینند.",
"title": "پرچم‌گذاری سیگنال",
"banner": "پرچم‌ها داخلی‌اند: روی کارت، کارنامه و نتیجهٔ این سیگنال اثری ندارند و فقط ادمین‌ها آن‌ها را می‌بینند.",
"reason": "دلیل",
"reason-label": "دلیل پرچم",
"note": "توضیح",
@ -236,7 +236,7 @@
"done": "پرچم برداشته شد.",
"failed": "برداشتن پرچم انجام نشد"
},
"conflict": "این پیش‌بینی پیش‌تر بسته یا بررسی شده است؛ اطلاعات به‌روز شد.",
"conflict": "این سیگنال پیش‌تر بسته یا بررسی شده است؛ اطلاعات به‌روز شد.",
"card": {
"status": {
"open": "فعال",
@ -263,7 +263,9 @@
"target-n": "هدف {{n}}",
"final-target": "هدف نهایی",
"close": "بسته‌شدن",
"horizon": "افق"
"horizon": "افق",
"range": "بازه",
"entry-range": "ورود (بازه)"
},
"ladder": {
"level": "سطح",
@ -276,7 +278,7 @@
"not-triggered": "فعال نشد"
},
"range": {
"label": "محدوده پیش‌بینی: {{values}}",
"label": "محدوده سیگنال: {{values}}",
"stop": "حد ضرر {{price}}",
"entry": "ورود {{price}}",
"target": "هدف {{price}}",
@ -299,10 +301,11 @@
"price-source": "منبع قیمت:"
},
"locked": {
"title": "پیش‌بینی پریمیوم",
"title": "سیگنال پریمیوم",
"description": "دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.",
"hidden": "پنهان",
"content": "محتوای پریمیوم"
}
},
"risk-reward-range": "{{worst}} تا {{best}}"
}
}

View File

@ -2,7 +2,7 @@ export type PartBoundaryProps = {
/** The part, for the error report: «creator-stats», «feed». Never personal data. */
name: string;
/**
* The part's own failure copy, such as «عملکرد پیش‌بینی‌ها بارگذاری نشد» / «بقیه کانال در دسترس
* The part's own failure copy, such as «عملکرد سیگنال‌ها بارگذاری نشد» / «بقیه کانال در دسترس
* است…» (S3); without it the fallback says what every part says.
*/
title?: string;

View File

@ -19,7 +19,7 @@ const isBlocked = (standing: string): standing is BlockedStanding =>
standing === 'pending' || standing === 'rejected' || standing === 'suspended';
/**
* «انتشار» (C4 ۱.۱, ۱.۲, ۷.۱): a verified creator gets the menu, «پست جدید» or «پیش‌بینی جدید». A
* «انتشار» (C4 ۱.۱, ۱.۲, ۷.۱): a verified creator gets the menu, «پست جدید» or «سیگنال جدید». A
* creator who can't publish sees it frozen, and a press explains why instead of a tooltip. On
* mobile the open menu sits centred over the nav, on a light scrim that dims the page down to the
* nav; a press on the scrim closes it, and the FAB turns into an icon-only ✕ «بستن» (J08-1b). A

View File

@ -57,10 +57,10 @@ export const ROUTES = {
subscriptions: '/dashboard/subscriptions',
transactions: '/dashboard/transactions',
following: '/dashboard/following',
/** The creator's داشبورد: «طرح‌های اشتراک» (the default tab), «پیش‌بینی‌ها» and «مالی». */
/** The creator's داشبورد: «طرح‌های اشتراک» (the default tab), «سیگنال‌ها» and «مالی». */
plans: '/dashboard/plans',
predictions: '/dashboard/predictions',
/** «همه پیش‌بینی‌ها», pushed from the «پیش‌بینی‌ها» tab; `?status=closed|all`. */
/** «همه سیگنال‌ها», pushed from the «سیگنال‌ها» tab; `?status=closed|all`. */
predictionsAll: '/dashboard/predictions/all',
finance: '/dashboard/finance',
/** C7, pushed from the «قیمت طرح‌ها» card. */

View File

@ -10,7 +10,7 @@ import { ComposerLockedRedirect } from '../../../organisms/composer-locked';
import { PredictionComposerDialogSkeleton } from './PredictionComposerDialogSkeleton';
/**
* «پیش‌بینی جدید» over the current page on desktop (J09-1-D, 0023), for the route that intercepts
* «سیگنال جدید» over the current page on desktop (J09-1-D, 0023), for the route that intercepts
* /compose/prediction. The app wraps it in AuthGuard with `PredictionComposerDialogSkeleton`, so
* it renders once the browser knows a signed-in viewer. Only a creator who may publish gets the
* composer; another creator goes to their own channel, which says why not (J09-1e, 0060), and

View File

@ -7,7 +7,7 @@ import { ROUTES } from '../../../../../../navigation/navigation';
import { ComposerDialogPlaceholder } from './components/ComposerDialogPlaceholder';
/**
* The «پیش‌بینی جدید» dialog until the browser knows the viewer: the same 960px frame with the
* The «سیگنال جدید» dialog until the browser knows the viewer: the same 960px frame with the
* form skeleton in its body, AuthGuard's fallback on the intercepted route. «انصراف» still closes
* it.
*/

View File

@ -11,7 +11,7 @@ import { ConfirmPublish } from './ConfirmPublish';
import { LeaveConfirm } from './LeaveConfirm';
/**
* «پیش‌بینی جدید» in the 960px dialog over the current page (J09-1-D, 0023). Escape, the scrim and
* «سیگنال جدید» in the 960px dialog over the current page (J09-1-D, 0023). Escape, the scrim and
* «انصراف» close an empty one and ask first about one with something to lose; the confirm step
* and the question open over it. Published, it closes onto the creator's channel, the new
* prediction on top, with the toast.

View File

@ -25,8 +25,8 @@ import { SymbolField } from './SymbolField';
import { TargetsField } from './TargetsField';
/**
* Every field of «پیش‌بینی جدید» in the boards' order (J09-1): access with the premium note, market,
* symbol and direction (side by side on desktop), the locked entry, targets, stop, horizon with
* Every field of «سیگنال جدید» in the boards' order (J09-1): access with the premium note, market,
* symbol and direction (side by side on desktop), the entry, targets, stop, horizon with
* its end, the note and the chart. A failed publish says so above them (J09-3d); while publishing,
* everything holds still.
*/
@ -69,7 +69,7 @@ export function ComposerFields({ model, layout }: ComposerPartProps) {
return (
<FlexBox direction="flex-col" gap="gap-5">
{/* «انتشار پیش‌بینی» is the retry, with the same key while nothing changes. */}
{/* «انتشار سیگنال» is the retry, with the same key while nothing changes. */}
{model.publishError && (
<Banner tone="danger" title={model.publishError} />
)}

View File

@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';
import type { ComposerFrameProps } from '../types';
/**
* The «پیش‌بینی جدید» dialog's frame (J09-1-D, 0023): 960px over the page, the title with a ghost
* The «سیگنال جدید» dialog's frame (J09-1-D, 0023): 960px over the page, the title with a ghost
* «انصراف» at the end of its header row, and the workspace edge to edge under the hairline.
* While publishing, Escape, the scrim and «انصراف» do nothing.
*/

View File

@ -21,8 +21,8 @@ import { LeaveConfirm } from './LeaveConfirm';
import { PublishButton } from './PublishButton';
/**
* «پیش‌بینی جدید» on its own page. Mobile (J09-1-M): back · title · support, the ghost «انصراف»
* row, the fields, the preview, and «انتشار پیش‌بینی» pinned to the bottom; back and «انصراف» ask
* «سیگنال جدید» on its own page. Mobile (J09-1-M): back · title · support, the ghost «انصراف»
* row, the fields, the preview, and «انتشار سیگنال» pinned to the bottom; back and «انصراف» ask
* first about something to lose (J09-3e). Desktop, on a direct load: a 960px card drawn as the
* dialog (J09-1-D). Published, it lands on the creator's channel in the composer's place, the new
* prediction on top (J09-3c); left, it goes back.

View File

@ -40,6 +40,8 @@ export function ComposerPreview({ model }: Pick<ComposerPartProps, 'model'>) {
market: t(`common:markets.${summary.market}`),
direction: summary.direction,
entryPrice: summary.entryPrice,
entryLow: summary.entryLow,
entryHigh: summary.entryHigh,
targetPrices: summary.targetPrices,
stopLoss: summary.stopLoss,
horizon: summary.horizon,

View File

@ -11,7 +11,7 @@ import { PublishButton } from './PublishButton';
/**
* The desktop composer under its header row (J09-1-D), the same in the 960px dialog and on the
* full page: the fields beside a 400px sunken «پیش‌نمایش» panel, scrolling together, and
* «انتشار پیش‌بینی» at the end of the footer bar.
* «انتشار سیگنال» at the end of the footer bar.
*/
export function ComposerWorkspace({ model }: ComposerWorkspaceProps) {
const { t } = useTranslation('predictions');

View File

@ -0,0 +1,65 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type {
ComposerSummary,
PredictionComposerPageModel,
} from '../../../../../../../../features/prediction';
import { ConfirmPublish } from './ConfirmPublish';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const summary: ComposerSummary = {
symbol: 'BTCUSDT',
market: 'crypto',
direction: 'long',
entryMode: 'exact',
entryPrice: 68000,
entryLow: null,
entryHigh: null,
targetPrices: [70000],
stopLoss: 67000,
horizon: '1w',
expiresAt: '2026-01-08T00:00:00Z',
accessLevel: 'free',
};
const open = (confirmSummary: ComposerSummary) =>
render(
<ConfirmPublish
layout="desktop"
model={
{
confirmSummary,
phase: 'confirming',
publish: vi.fn(),
cancelConfirm: vi.fn(),
} as unknown as PredictionComposerPageModel
}
/>,
);
describe('ConfirmPublish', () => {
it('shows an exact entry with «قیمت دقیق» next to it', () => {
open(summary);
expect(screen.getByText('68٬000')).toBeTruthy();
expect(screen.getByText('composer.confirm.entry-exact')).toBeTruthy();
});
it('shows a range as its two ends', () => {
open({
...summary,
entryMode: 'range',
entryLow: 67500,
entryHigh: 68500,
});
expect(screen.getByText('67٬500 – 68٬500')).toBeTruthy();
expect(screen.queryByText('composer.confirm.entry-exact')).toBeNull();
});
it('always carries the lock line', () => {
open(summary);
expect(screen.getByText('composer.confirm.warning')).toBeTruthy();
});
});

View File

@ -8,14 +8,15 @@ import { DetailRow } from '@lumina/island/molecules/detail-row';
import { KeyValue } from '@lumina/island/molecules/key-value';
import { Modal } from '@lumina/island/molecules/modal';
import { Sheet } from '@lumina/island/molecules/sheet';
import { entryText } from '@lumina/island/organisms/prediction-card';
import { date, number, price } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import type { ComposerPartProps } from '../types';
/**
* «انتشار پیش‌بینی» (J09-3, J09-3b): what goes live, row by row (a field left empty has none), the
* entry as «≈» the live price since the API stamps its own, and that it can't be edited or
* «انتشار سیگنال» (J09-3, J09-3b): what goes live, row by row (a field left empty has none), the
* entry as the number with «قیمت دقیق» beside it, or the range, and that it can't be edited or
* deleted afterwards. While it publishes «انتشار» spins, «ادامه ویرایش» freezes and nothing
* dismisses it. A bottom sheet on mobile, a 420px modal on desktop.
*/
@ -45,14 +46,16 @@ export function ConfirmPublish({ model, layout }: ComposerPartProps) {
</DetailRow>
<DetailRow label={t('composer.confirm.entry')} strong>
<Typography tag="bdi" dir="ltr" variant="inherit" color="inherit">
{t('composer.confirm.entry-value', {
price: price(summary.entryPrice),
})}
</Typography>
<Separator />
<Typography tag="span" variant="caption" color="secondary">
{t('composer.confirm.entry-note')}
{entryText(summary)}
</Typography>
{summary.entryMode === 'exact' && (
<>
<Separator />
<Typography tag="span" variant="caption" color="secondary">
{t('composer.confirm.entry-exact')}
</Typography>
</>
)}
</DetailRow>
{summary.targetPrices.map((target, index) => (
<DetailRow

View File

@ -0,0 +1,102 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { describe, expect, it, vi } from 'vitest';
import type { PredictionComposerPageModel } from '../../../../../../../../features/prediction';
import type { PredictionComposerFormValues } from '../../../../../../../../shared/validations';
import { EntryField } from './EntryField';
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: object) =>
values ? `${key} ${JSON.stringify(values)}` : key,
}),
}));
function Harness({ over }: { over: Partial<PredictionComposerPageModel> }) {
const form = useForm<PredictionComposerFormValues>({
defaultValues: {
entryMode: 'exact',
entryPrice: '100',
entryLow: '',
entryHigh: '',
} as PredictionComposerFormValues,
});
const model = {
entryMode: 'exact',
setEntryMode: vi.fn(),
markEntryEdited: vi.fn(),
retryQuote: vi.fn(),
phase: 'idle',
symbol: 'BTCUSDT',
quote: { status: 'none' },
...over,
} as unknown as PredictionComposerPageModel;
return <EntryField model={{ ...model, form }} />;
}
const ready = {
status: 'ready',
price: 68000,
at: '2026-01-01T10:00:00Z',
source: 'Binance',
} as const;
describe('EntryField', () => {
it('offers an editable exact entry with the live price under it', async () => {
const markEntryEdited = vi.fn();
render(<Harness over={{ quote: ready, markEntryEdited }} />);
const input = screen.getByLabelText<HTMLInputElement>(
'composer.entry-price',
);
expect(input.value).toBe('100');
expect(input.readOnly).toBe(false);
await userEvent.type(input, '5');
expect(markEntryEdited).toHaveBeenCalled();
expect(screen.getByText(/composer\.entry-hint/).textContent).toContain(
'Binance',
);
});
it('switches to the range through the segmented control', async () => {
const setEntryMode = vi.fn();
render(<Harness over={{ quote: ready, setEntryMode }} />);
await userEvent.click(
screen.getByRole('radio', { name: 'composer.entry-range' }),
);
expect(setEntryMode).toHaveBeenCalledWith('range');
});
it('shows «از» and «تا» for a range', () => {
render(<Harness over={{ quote: ready, entryMode: 'range' }} />);
expect(screen.getByLabelText('composer.entry-from')).toBeTruthy();
expect(screen.getByLabelText('composer.entry-to')).toBeTruthy();
expect(screen.queryByLabelText('composer.entry-price')).toBeNull();
});
it('says there is no price now and offers a retry, keeping the field', async () => {
const retryQuote = vi.fn();
render(
<Harness
over={{
quote: { status: 'unavailable', isRetrying: false },
retryQuote,
}}
/>,
);
expect(screen.getByRole('alert').textContent).toBe(
'composer.quote-unavailable',
);
expect(screen.getByLabelText('composer.entry-price')).toBeTruthy();
await userEvent.click(
screen.getByRole('button', { name: 'composer.retry' }),
);
expect(retryQuote).toHaveBeenCalled();
});
it('says the price comes once a symbol is picked', () => {
render(<Harness over={{ symbol: '', quote: { status: 'none' } }} />);
expect(screen.getByText('composer.entry-pending')).toBeTruthy();
});
});

View File

@ -1,77 +1,113 @@
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { Typography } from '@lumina/island/atoms/typography';
import { SegmentedChoice } from '@lumina/island/molecules/segmented-choice';
import { TextInput } from '@lumina/island/molecules/text-input';
import { price, time } from '@lumina/tools/format';
import { useTranslation } from 'react-i18next';
import type { EntryMode } from '../../../../../../../../shared/validations';
import { translateMessage } from '../../../../../../../../shared/utils';
import type { ComposerPartProps } from '../types';
import { FieldGroup } from './FieldGroup';
/**
* «قیمت ورود» (J09-1, J09-2c): locked, since the API stamps the market price at publish; it shows
* the live price with its source and time, «—» before a symbol, a skeleton line while the price
* loads, or that there is no price now with «تلاش مجدد».
* «ورود» (J09-1, J09-2c): «قیمت دقیق», prefilled from the live quote and editable, or «بازه» with
* «از» and «تا». Under it, the live price with its source and time, a skeleton line while it loads,
* or that there is no price now with «تلاش مجدد». An exact entry waits for a symbol.
*/
export function EntryField({ model }: Pick<ComposerPartProps, 'model'>) {
const { t } = useTranslation('predictions');
const { quote } = model;
const stamp = (
<Typography tag="span" variant="caption" color="secondary">
{t('composer.entry-stamp')}
</Typography>
);
const { t } = useTranslation(['predictions', 'content']);
const { form, quote, entryMode, phase, symbol } = model;
const { errors } = form.formState;
const busy = phase === 'publishing';
if (quote.status === 'loading') {
return (
<FlexBox direction="flex-col" gap="gap-2">
<Typography tag="span" variant="label">
{t('composer.entry')}
</Typography>
<SkeletonRegion label={t('composer.entry-loading')}>
<Skeleton height={48} />
</SkeletonRegion>
{stamp}
</FlexBox>
);
}
const input = (name: 'entryPrice' | 'entryLow' | 'entryHigh') =>
({
dir: 'ltr',
inputMode: 'decimal',
autoComplete: 'off',
frozen: busy,
error: translateMessage(t, errors[name]?.message),
}) as const;
return (
<FlexBox direction="flex-col" gap="gap-2">
<TextInput
label={t('composer.entry')}
locked
dir="ltr"
placeholder="—"
value={quote.status === 'ready' ? price(quote.price) : ''}
lockedNote={
quote.status === 'ready'
? t('composer.entry-note', {
source: quote.source,
time: time(quote.at),
})
: t('composer.entry-pending')
}
error={
quote.status === 'unavailable'
? t('composer.quote-unavailable')
: undefined
}
/>
{quote.status === 'unavailable' && (
<FlexBox>
<Button
variant="ghost"
size="sm"
icon="refresh"
onClick={model.retryQuote}
isLoading={quote.isRetrying}
>
{t('composer.retry')}
</Button>
</FlexBox>
<FieldGroup label={t('composer.entry')}>
<SegmentedChoice<EntryMode>
label={t('composer.entry')}
options={[
{ value: 'exact', label: t('composer.entry-exact') },
{ value: 'range', label: t('composer.entry-range') },
]}
value={entryMode}
onChange={model.setEntryMode}
tone="neutral"
block
disabled={busy}
/>
</FieldGroup>
{entryMode === 'exact' ? (
<TextInput
label={t('composer.entry-price')}
placeholder="—"
{...input('entryPrice')}
frozen={busy || symbol === ''}
{...form.register('entryPrice', { onChange: model.markEntryEdited })}
/>
) : (
<GridBox cols="grid-cols-2" gap="gap-3" alignItems="items-start">
<TextInput
label={t('composer.entry-from')}
{...input('entryLow')}
{...form.register('entryLow')}
/>
<TextInput
label={t('composer.entry-to')}
{...input('entryHigh')}
{...form.register('entryHigh')}
/>
</GridBox>
)}
{quote.status === 'loading' && (
<SkeletonRegion label={t('composer.entry-loading')}>
<Skeleton height={16} />
</SkeletonRegion>
)}
{quote.status === 'none' && (
<Typography tag="span" variant="caption" color="secondary">
{t('composer.entry-pending')}
</Typography>
)}
{quote.status === 'ready' && (
<Typography tag="span" variant="caption" color="secondary">
{t('composer.entry-hint', {
price: price(quote.price),
source: quote.source,
time: time(quote.at),
})}
</Typography>
)}
{quote.status === 'unavailable' && (
<>
<Typography tag="span" variant="caption" color="danger" role="alert">
{t('composer.quote-unavailable')}
</Typography>
<FlexBox>
<Button
variant="ghost"
size="sm"
icon="refresh"
onClick={model.retryQuote}
isLoading={quote.isRetrying}
>
{t('composer.retry')}
</Button>
</FlexBox>
</>
)}
{stamp}
</FlexBox>
);
}

View File

@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';
import type { ComposerPartProps } from '../types';
/**
* «انتشار پیش‌بینی»: frozen until the form can publish, saying why (J09-1b, J09-2, J09-2c); a
* «انتشار سیگنال»: frozen until the form can publish, saying why (J09-1b, J09-2, J09-2c); a
* press checks the form, then asks to confirm (J09-3). Offline it freezes and says why (0043).
*/
export function PublishButton({ model, layout }: ComposerPartProps) {

View File

@ -10,7 +10,7 @@ import type { DashboardTabsProps } from './types';
/**
* The داشبورد's section row, full width, the current one underlined: the investor's «اشتراک‌ها» ·
* «تراکنش‌ها» · «دنبال‌شده‌ها» (U8 ۴.۱, ۶.۱; U8 ۵.۲), or the creator's «طرح‌های اشتراک» ·
* «پیش‌بینی‌ها» · «مالی» (Creator Dashboard ۱.۱, J10-0, 0034). The dashboard layout renders it once, so it stays put while a section
* «سیگنال‌ها» · «مالی» (Creator Dashboard ۱.۱, J10-0, 0034). The dashboard layout renders it once, so it stays put while a section
* loads; the current one comes from the URL, which the server render already knows.
*/
export function DashboardTabs({

View File

@ -17,7 +17,7 @@ import type { PredictionListProps } from './types';
const FILTERS: readonly OwnPredictionsStatus[] = ['open', 'closed', 'all'];
/**
* «همه پیش‌بینی‌ها» (J10-3f, J10-3g): «باز» · «بسته‌شده» · «همه» with the API's totals, open ones
* «همه سیگنال‌ها» (J10-3f, J10-3g): «باز» · «بسته‌شده» · «همه» with the API's totals, open ones
* with «بستن زودهنگام», closed ones with why and at whose price they closed, 20 at a time with
* «نمایش بیشتر». The cards stay while another chip's list or the next page loads; a failed page
* says so in place of «نمایش بیشتر».

View File

@ -4,7 +4,7 @@ import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import type { PredictionListSkeletonProps } from './types';
/** «همه پیش‌بینی‌ها» before it arrives: the chips' row, then the cards. */
/** «همه سیگنال‌ها» before it arrives: the chips' row, then the cards. */
export function PredictionListSkeleton({
label,
delayed,

View File

@ -17,9 +17,9 @@ import { PredictionsTabSkeleton } from './PredictionsTabSkeleton';
import type { PredictionsTabProps } from './types';
/**
* داشبورد › پیش‌بینی‌ها (J10-3), the creator's own, in the browser only: the record or its progress
* داشبورد › سیگنال‌ها (J10-3), the creator's own, in the browser only: the record or its progress
* to public, every open prediction with «بستن زودهنگام», the two closed most recently and
* «همه پیش‌بینی‌ها». Each block loads and fails on its own (J10-3e). Before the first prediction,
* «همه سیگنال‌ها». Each block loads and fails on its own (J10-3e). Before the first prediction,
* only the way to publish one (J10-3c). No edit or delete: a published prediction is final.
*/
export function PredictionsTab({ layout }: PredictionsTabProps) {

View File

@ -3,7 +3,7 @@ import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import type { PredictionsTabSkeletonProps } from './types';
/** داشبورد › پیش‌بینی‌ها before it arrives, block for block: the record, then two cards. */
/** داشبورد › سیگنال‌ها before it arrives, block for block: the record, then two cards. */
export function PredictionsTabSkeleton({
label,
delayed,

View File

@ -10,7 +10,7 @@ import type { PredictionSectionProps } from '../types';
import { SectionCards } from './SectionCards';
/**
* «پیش‌بینی‌های باز (۳)» or «بسته‌شده‌های اخیر» (J10-3): its title stays over its cards, or over its
* «سیگنال‌های باز (۳)» or «بسته‌شده‌های اخیر» (J10-3): its title stays over its cards, or over its
* own error in a card, the count dropped (J10-3e); it loads and fails on its own. A section with
* nothing in it isn't drawn.
*/

View File

@ -23,7 +23,7 @@ const FILTERS: readonly NotificationFilter[] = [
/**
* اعلان‌ها (U5 §۲, J07-5, J07-5h): every notification of the last 30 days, newest first, in one
* list of rows whatever its type. Opening it clears the bell. A creator filters it with chips
* «همه · پیش‌بینی‌ها · مالی · حساب» in place (0058), which stay in both empty states: nothing at
* «همه · سیگنال‌ها · مالی · حساب» in place (0058), which stay in both empty states: nothing at
* all says what will arrive here (J07-5k), and an empty chip offers «نمایش همه». An investor's
* empty list is one calm line under a muted bell, with no action (۲.۳, J07-5e).
*/

View File

@ -1,6 +1,7 @@
import { Icon } from '@lumina/island/atoms/icon';
import { Separator } from '@lumina/island/atoms/separator';
import { Typography } from '@lumina/island/atoms/typography';
import { entryText } from '@lumina/island/organisms/prediction-card';
import { DetailRow } from '@lumina/island/molecules/detail-row';
import { KeyValue } from '@lumina/island/molecules/key-value';
import { price } from '@lumina/tools/format';
@ -33,7 +34,7 @@ export function PredictionSummary({ post, children }: PredictionSummaryProps) {
</Typography>
</DetailRow>
<DetailRow label={t('close.entry')} strong ltr>
{price(prediction.entryPrice)}
{entryText(prediction)}
</DetailRow>
{finalTarget != null && (
<DetailRow label={t('close.target')} strong ltr>

View File

@ -6,7 +6,7 @@ export const UNREAD_BADGE_CAP = 99;
/** A creator's filter chips over their one list (J07-5h, 0058), after «همه». */
export type NotificationCategory = 'predictions' | 'finance' | 'account';
/** The chips in reading order: «همه · پیش‌بینی‌ها · مالی · حساب». */
/** The chips in reading order: «همه · سیگنال‌ها · مالی · حساب». */
export const NOTIFICATION_CATEGORIES = [
'predictions',
'finance',

View File

@ -15,7 +15,7 @@ export type NotificationCentreModel = {
items: NotificationPayload[];
/** The items under the chosen chip; all of them for an investor, who has no chips. */
visibleItems: NotificationPayload[];
/** A creator filters the one list with chips «همه · پیش‌بینی‌ها · مالی · حساب» (0058). */
/** A creator filters the one list with chips «همه · سیگنال‌ها · مالی · حساب» (0058). */
showsCategories: boolean;
category: NotificationFilter;
/** Filters in place: no URL change, so back still returns to where the bell was tapped. */

View File

@ -59,8 +59,11 @@ export type PredictionEntity = {
/** `gold`, `crypto`, `equities`, `forex` or `USDT`; older posts may carry another key. */
market: string;
direction: PredictionDirection;
/** The market quote at publish, stamped by the API. */
/** The analyst's exact entry, or the middle of a range. */
entryPrice: number;
/** A range entry: both, low below high. */
entryLow?: number;
entryHigh?: number;
/** One to three, each further from the entry; the last one is final. */
targetPrices: number[];
stopLoss?: number;

View File

@ -27,6 +27,8 @@ export function toPredictionPayload(
market: entity.market,
direction: entity.direction,
entryPrice: entity.entryPrice,
entryLow: entity.entryLow ?? null,
entryHigh: entity.entryHigh ?? null,
targetPrices: entity.targetPrices,
stopLoss: entity.stopLoss ?? null,
horizon: entity.horizon,
@ -110,6 +112,9 @@ function toPredictionDto(args: PredictionArgs): PredictionDto {
symbol: args.symbol.trim().toUpperCase(),
market: args.market.trim(),
direction: args.direction,
entryPrice: args.entryPrice ?? undefined,
entryLow: args.entryLow ?? undefined,
entryHigh: args.entryHigh ?? undefined,
targetPrices: args.targetPrices,
stopLoss: args.stopLoss ?? undefined,
horizon: args.horizon.trim(),

View File

@ -17,7 +17,11 @@ export type PredictionPayload = {
symbol: string;
market: string;
direction: PredictionDirection;
/** The exact entry, or the middle of a range. */
entryPrice: number;
/** A range entry: both, low below high; otherwise null. */
entryLow: number | null;
entryHigh: number | null;
/** Nearest first; the last one is the final target. */
targetPrices: number[];
stopLoss: number | null;
@ -150,6 +154,10 @@ export type PredictionArgs = {
symbol: string;
market: string;
direction: PredictionDirection;
/** Exactly one form to publish: this, or `entryLow` with `entryHigh`. */
entryPrice?: number;
entryLow?: number;
entryHigh?: number;
/** One to three, each further from the entry than the one before. */
targetPrices: number[];
stopLoss?: number | null;
@ -195,6 +203,9 @@ export type PredictionDto = {
symbol: string;
market: string;
direction: PredictionDirection;
entryPrice?: number;
entryLow?: number;
entryHigh?: number;
targetPrices: number[];
stopLoss?: number;
horizon: string;

View File

@ -22,8 +22,8 @@ export type PublishPredictionArgs = {
};
/**
* Publishes a prediction as a post: the API stamps the entry at the market price now, and from
* then on it can't be edited or deleted. Send the same `idempotencyKey` with an unchanged form, so
* Publishes a prediction as a post, with the entry and stop the analyst stated. From then on it
* can't be edited or deleted. Send the same `idempotencyKey` with an unchanged form, so
* a retry after a lost answer returns the first post instead of a second. It waits 10 seconds for
* the answer (J09-3). Emits `post.publish` and `prediction.publish`.
*/

View File

@ -4,7 +4,7 @@ import type { OwnPredictionPayload } from '../../repositories/prediction';
export type OwnPredictionSection = 'open' | 'closed';
/**
* داشبورد › پیش‌بینی‌ها as a whole (J10-3c): waiting for the first list, nothing published yet
* داشبورد › سیگنال‌ها as a whole (J10-3c): waiting for the first list, nothing published yet
* (the API's `counts.all` is 0), or its sections.
*/
export type PredictionsTabPartModel = { status: 'loading' | 'empty' | 'ready' };

View File

@ -4,7 +4,7 @@ import { ownSectionQueryOptions } from './queries';
import type { OwnPredictionSection } from './types';
/**
* A section's total for its title, «پیش‌بینی‌های باز (۳)», from the API's counts; `undefined`
* A section's total for its title, «سیگنال‌های باز (۳)», from the API's counts; `undefined`
* while loading or failed, so the title stands without it over the section's error (J10-3e).
*/
export function useOwnPredictionCount(

View File

@ -4,7 +4,7 @@ import { ownSectionQueryOptions } from './queries';
import type { OwnPredictionSection, OwnPredictionsSectionModel } from './types';
/**
* A داشبورد › پیش‌بینی‌ها section's cards (J10-3): every open prediction, newest first, or the two
* A داشبورد › سیگنال‌ها section's cards (J10-3): every open prediction, newest first, or the two
* closed most recently. Loads and fails on its own.
*/
export function useOwnPredictionsSection(

View File

@ -9,7 +9,7 @@ type OwnList = InfiniteData<OwnPredictionsPagePayload, string | undefined>;
/**
* A prediction closed (early, or found closed by the system): every cached copy shows it closed
* in place, «همه پیش‌بینی‌ها» included, where it stays until the list is read again. The tab's
* in place, «همه سیگنال‌ها» included, where it stays until the list is read again. The tab's
* lists, the track record and the public record are read again.
*/
export function applyClosedPrediction(

View File

@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import { publishReason } from './publish-reason';
const clear = {
invalid: [],
missing: [],
quoteUnavailable: false,
chart: null,
};
describe('publishReason', () => {
it('has nothing to say about a complete form', () => {
expect(publishReason(clear)).toBeUndefined();
});
it('lists what is empty', () => {
expect(publishReason({ ...clear, missing: ['حد ضرر'] })).toEqual({
kind: 'missing',
fields: ['حد ضرر'],
});
});
it('puts «اصلاح» before «کامل»', () => {
expect(
publishReason({ ...clear, invalid: ['هدف ۱'], missing: ['حد ضرر'] }),
).toEqual({ kind: 'invalid', fields: ['هدف ۱'] });
});
it('puts the fields before the price and the upload', () => {
expect(
publishReason({
...clear,
missing: ['ورود'],
quoteUnavailable: true,
chart: 'uploading',
})?.kind,
).toBe('missing');
});
it('then the price, then the upload', () => {
expect(
publishReason({ ...clear, quoteUnavailable: true, chart: 'failed' })
?.kind,
).toBe('quote-unavailable');
expect(publishReason({ ...clear, chart: 'uploading' })?.kind).toBe(
'chart-uploading',
);
expect(publishReason({ ...clear, chart: 'failed' })?.kind).toBe(
'chart-failed',
);
});
});

View File

@ -0,0 +1,27 @@
/** What stands between the form and «انتشار سیگنال», worst first. */
export type PublishReasonInput = {
/** Field names that need fixing. */
invalid: string[];
/** Field names still empty. */
missing: string[];
quoteUnavailable: boolean;
chart: 'uploading' | 'failed' | null;
};
export type PublishReason =
| { kind: 'invalid' | 'missing'; fields: string[] }
| { kind: 'quote-unavailable' | 'chart-uploading' | 'chart-failed' };
/** Why the CTA waits, or `undefined`: «اصلاح» beats «کامل», and both beat the price or an upload. */
export function publishReason({
invalid,
missing,
quoteUnavailable,
chart,
}: PublishReasonInput): PublishReason | undefined {
if (invalid.length > 0) return { kind: 'invalid', fields: invalid };
if (missing.length > 0) return { kind: 'missing', fields: missing };
if (quoteUnavailable) return { kind: 'quote-unavailable' };
if (chart === 'uploading') return { kind: 'chart-uploading' };
return chart === 'failed' ? { kind: 'chart-failed' } : undefined;
}

View File

@ -1,6 +1,9 @@
import type { UseFormReturn } from 'react-hook-form';
import type { PredictionComposerFormValues } from '../../../../shared/validations';
import type {
EntryMode,
PredictionComposerFormValues,
} from '../../../../shared/validations';
import type { PostAccessLevel, PostPayload } from '../../../post';
import type { PREDICTION_HORIZONS } from '../../constants';
import type { PredictionMarket } from '../../entities/market-data';
@ -36,8 +39,8 @@ export type ChartImageModel = {
};
/**
* The entry price field (J09-1, J09-2c): nothing until a symbol is picked, a skeleton line while
* its price loads, the live price with who priced it, or unavailable with «تلاش مجدد».
* The live price under the entry (J09-1, J09-2c): nothing until a symbol is picked, a skeleton line
* while its price loads, the price with who priced it, or unavailable with «تلاش مجدد».
*/
export type ComposerQuote =
| { status: 'none' }
@ -57,8 +60,12 @@ export type ComposerSummary = {
symbol: string;
market: PredictionMarket;
direction: PredictionDirection;
/** The live price now; the API stamps its own at publish («≈»). */
entryMode: EntryMode;
/** The exact entry, or the middle of a range: what the card measures from. */
entryPrice: number;
/** A range entry's ends; `null` for an exact one. */
entryLow: number | null;
entryHigh: number | null;
targetPrices: number[];
stopLoss: number | null;
horizon: PredictionHorizon;
@ -68,7 +75,7 @@ export type ComposerSummary = {
};
/**
* idle → confirming (the «انتشار پیش‌بینی» sheet) → publishing → published (it stays publishing
* idle → confirming (the «انتشار سیگنال» sheet) → publishing → published (it stays publishing
* until `onDone`'s navigation takes the composer away), or back to idle with the failure shown.
*/
export type ComposerPhase = 'idle' | 'confirming' | 'publishing';
@ -90,6 +97,11 @@ export type PredictionComposerPageModel = {
setMarket: (market: PredictionMarket) => void;
direction: PredictionDirection | '';
setDirection: (direction: PredictionDirection) => void;
/** «قیمت دقیق» or «بازه». */
entryMode: EntryMode;
setEntryMode: (mode: EntryMode) => void;
/** The analyst typed in the exact entry: it stops following the live quote. */
markEntryEdited: () => void;
horizon: PredictionHorizon | '';
setHorizon: (horizon: PredictionHorizon) => void;
accessLevel: PostAccessLevel;
@ -116,7 +128,7 @@ export type PredictionComposerPageModel = {
/** The CTA waits frozen, saying why: what to fix, what is missing, the price, an upload. */
publishBlock: { frozen: boolean; reason?: string };
phase: ComposerPhase;
/** «انتشار پیش‌بینی»: checks the form, then asks to confirm. */
/** «انتشار سیگنال»: checks the form, then asks to confirm. */
requestPublish: () => void;
/** The confirm step's summary while it is open. */
confirmSummary: ComposerSummary | null;

View File

@ -0,0 +1,264 @@
import { HttpError } from '@lumina/libs/http';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { publishPrediction } from '../../actions/publish-prediction';
import { usePredictionComposerPage } from './use-prediction-composer-page';
const quotes = vi.hoisted(() => ({ price: 100 }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: { fields?: string }) =>
values?.fields ? `${key} ${values.fields}` : key,
}),
}));
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
vi.mock('../../../../app/navigation/hooks/use-leave-guard', () => ({
useLeaveGuard: vi.fn(),
}));
vi.mock('../../../profile', () => ({
profileKeys: { mine: () => ['profile'] },
profileRepository: { getMine: async () => ({ markets: [] }) },
}));
vi.mock('../../../post', () => ({ resetCachedChannel: vi.fn() }));
vi.mock('../prediction-cache', () => ({ refreshOwnPredictions: vi.fn() }));
vi.mock('../symbol-picker', () => ({
symbolsQueryOptions: (market: string) => ({
queryKey: ['symbols', market],
queryFn: async () => [
{ symbol: 'BTCUSDT', source: 'Binance', market: 'crypto', quote: null },
],
}),
}));
vi.mock('../../repositories/market-data', () => ({
QUOTE_REFRESH_MS: 15_000,
marketDataKeys: { quote: (symbol: string) => ['quote', symbol] },
marketDataRepository: {
getQuote: async (symbol: string) => ({
symbol,
price: quotes.price,
at: '2026-01-01T10:00:00Z',
source: 'mock',
}),
},
}));
vi.mock('../../actions/publish-prediction', () => ({
publishPrediction: vi.fn(),
}));
vi.mock('./use-chart-image', () => ({
useChartImage: () => ({
image: null,
error: null,
add: vi.fn(),
remove: vi.fn(),
retry: vi.fn(),
abort: vi.fn(),
}),
}));
const onDone = vi.fn();
function setup() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const hook = renderHook(
() =>
usePredictionComposerPage({
creatorId: 'c1',
onDone,
onLeave: vi.fn(),
}),
{ wrapper },
);
return { ...hook, queryClient };
}
type Hook = ReturnType<typeof setup>['result'];
async function pickSymbol(result: Hook) {
act(() => result.current.setMarket('crypto'));
act(() =>
result.current.selectSymbol({
symbol: 'BTCUSDT',
} as Parameters<typeof result.current.selectSymbol>[0]),
);
await waitFor(() => expect(result.current.quote.status).toBe('ready'));
await waitFor(() =>
expect(result.current.form.getValues('entryPrice')).not.toBe(''),
);
}
function fill(result: Hook) {
act(() => {
result.current.setDirection('long');
result.current.setHorizon('1w');
result.current.form.setValue('targets.0.value', '120');
result.current.form.setValue('stopLoss', '90');
});
}
beforeEach(() => {
quotes.price = 100;
vi.mocked(publishPrediction).mockReset();
});
describe('usePredictionComposerPage entry', () => {
it('prefills the exact entry from the live quote', async () => {
const { result } = setup();
await pickSymbol(result);
expect(result.current.form.getValues('entryPrice')).toBe('100');
});
it('follows the quote until the analyst edits it', async () => {
const { result, queryClient } = setup();
await pickSymbol(result);
quotes.price = 105;
await act(() =>
queryClient.refetchQueries({ queryKey: ['quote', 'BTCUSDT'] }),
);
await waitFor(() =>
expect(result.current.form.getValues('entryPrice')).toBe('105'),
);
act(() => {
result.current.markEntryEdited();
result.current.form.setValue('entryPrice', '101');
});
quotes.price = 110;
await act(() =>
queryClient.refetchQueries({ queryKey: ['quote', 'BTCUSDT'] }),
);
await waitFor(() => {
const { quote } = result.current;
expect(quote.status === 'ready' && quote.price).toBe(110);
});
expect(result.current.form.getValues('entryPrice')).toBe('101');
});
});
describe('usePredictionComposerPage publish block', () => {
it('lists the stop and the entry as missing', async () => {
const { result } = setup();
act(() => result.current.setEntryMode('range'));
expect(result.current.publishBlock.reason).toContain('composer.missing');
expect(result.current.publishBlock.reason).toContain(
'composer.fields.entry',
);
expect(result.current.publishBlock.reason).toContain(
'composer.fields.stop',
);
});
it('asks to fix a level on a direction change, ahead of what is missing', async () => {
const { result } = setup();
await pickSymbol(result);
fill(result);
act(() => result.current.form.setValue('horizon', ''));
await waitFor(() =>
expect(result.current.publishBlock.reason).toContain('composer.missing'),
);
act(() => result.current.setDirection('short'));
await waitFor(() =>
expect(result.current.publishBlock.reason).toContain('composer.invalid'),
);
});
it('is clear on a complete form', async () => {
const { result } = setup();
await pickSymbol(result);
fill(result);
await waitFor(() => expect(result.current.publishBlock.frozen).toBe(false));
expect(result.current.preview.status).toBe('ready');
});
});
describe('usePredictionComposerPage publishing', () => {
async function confirm(result: Hook) {
await waitFor(() => expect(result.current.publishBlock.frozen).toBe(false));
await act(async () => result.current.requestPublish());
await waitFor(() => expect(result.current.phase).toBe('confirming'));
}
it('sends the exact entry it showed, even when the quote moved since', async () => {
vi.mocked(publishPrediction).mockResolvedValue({ id: 'p1' } as never);
const { result, queryClient } = setup();
await pickSymbol(result);
fill(result);
await confirm(result);
quotes.price = 105;
await act(() =>
queryClient.refetchQueries({ queryKey: ['quote', 'BTCUSDT'] }),
);
expect(result.current.confirmSummary?.entryPrice).toBe(100);
await act(async () => result.current.publish());
const [args] = vi.mocked(publishPrediction).mock.calls[0];
expect(args.prediction).toMatchObject({
entryPrice: 100,
stopLoss: 90,
targetPrices: [120],
});
expect(args.prediction.entryLow).toBeUndefined();
});
it('sends a range as its two ends, with the middle in the summary', async () => {
vi.mocked(publishPrediction).mockResolvedValue({ id: 'p1' } as never);
const { result } = setup();
await pickSymbol(result);
fill(result);
act(() => {
result.current.setEntryMode('range');
result.current.form.setValue('entryLow', '98');
result.current.form.setValue('entryHigh', '102');
});
await confirm(result);
expect(result.current.confirmSummary).toMatchObject({
entryPrice: 100,
entryLow: 98,
entryHigh: 102,
});
await act(async () => result.current.publish());
const [args] = vi.mocked(publishPrediction).mock.calls[0];
expect(args.prediction).toMatchObject({ entryLow: 98, entryHigh: 102 });
expect(args.prediction.entryPrice).toBeUndefined();
});
it.each([
['entry', 'entry_required', 'entryPrice', 'validation.entry-required'],
['stopLoss', 'stop_required', 'stopLoss', 'validation.stop-required'],
] as const)(
'puts a refused %s back on its field',
async (field, code, name, message) => {
vi.mocked(publishPrediction).mockRejectedValue(
new HttpError({
message: 'refused',
code: 'PREDICTION_INVALID',
status: 422,
details: { errors: [{ field, code }] },
method: 'POST',
url: '/posts',
}),
);
const { result } = setup();
await pickSymbol(result);
fill(result);
await confirm(result);
await act(async () => result.current.publish());
expect(result.current.form.getFieldState(name).error?.message).toContain(
message,
);
},
);
});

View File

@ -1,7 +1,7 @@
import { valibotResolver } from '@hookform/resolvers/valibot';
import { showToast } from '@lumina/island/molecules/toast';
import { isHttpError } from '@lumina/libs/http';
import { list, number } from '@lumina/tools/format';
import { list, number, price } from '@lumina/tools/format';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import {
@ -17,13 +17,24 @@ import { useTranslation } from 'react-i18next';
import { useLeaveGuard } from '../../../../app/navigation/hooks/use-leave-guard';
import {
ENTRY_RANGE_ORDER_MESSAGE,
ENTRY_REQUIRED_MESSAGE,
entryFieldsOf,
entryIssue,
entryLevels,
levelPrice,
PREDICTION_FORM_LIMITS,
predictionComposerSchema,
STOP_REQUIRED_MESSAGE,
stopIssue,
stopSideMessage,
targetIssues,
targetSideMessage,
} from '../../../../shared/validations';
import type {
EntryMode,
PredictionComposerFormValues,
} from '../../../../shared/validations';
import type { PredictionComposerFormValues } from '../../../../shared/validations';
import { resetCachedChannel } from '../../../post';
import { profileKeys, profileRepository } from '../../../profile';
import { publishPrediction } from '../../actions/publish-prediction';
@ -40,11 +51,11 @@ import {
PREDICTION_ERROR_CODES,
predictionErrorCode,
predictionFieldIssues,
quoteOfError,
} from '../../repositories/prediction';
import type { PredictionFieldIssue } from '../../repositories/prediction';
import { refreshOwnPredictions } from '../prediction-cache';
import { symbolsQueryOptions } from '../symbol-picker';
import { publishReason } from './publish-reason';
import type {
ComposerPhase,
ComposerQuote,
@ -64,6 +75,10 @@ const DEFAULT_VALUES: PredictionComposerFormValues = {
market: '',
symbol: '',
direction: '',
entryMode: 'exact',
entryPrice: '',
entryLow: '',
entryHigh: '',
targets: [{ value: '' }],
stopLoss: '',
horizon: '',
@ -83,8 +98,8 @@ function toFieldError(
{ field, code }: PredictionFieldIssue,
direction: string,
targetCount: number,
mode: EntryMode,
): { name: FormPath | 'root.chart'; message: string } {
const side = direction === 'short' ? 'short' : 'long';
const target = /^targetPrices\.(\d+)$/.exec(field);
if (target) {
return {
@ -92,15 +107,21 @@ function toFieldError(
message:
code === 'targets_order'
? 'predictions:validation.targets-order'
: `predictions:validation.target-side.${side}`,
: targetSideMessage(direction, mode),
};
}
switch (code) {
case 'stop_wrong_side':
case 'entry_required':
return {
name: 'stopLoss',
message: `predictions:validation.stop-side.${side}`,
name: entryFieldsOf(mode)[0],
message: ENTRY_REQUIRED_MESSAGE,
};
case 'entry_range_order':
return { name: 'entryLow', message: ENTRY_RANGE_ORDER_MESSAGE };
case 'stop_required':
return { name: 'stopLoss', message: STOP_REQUIRED_MESSAGE };
case 'stop_wrong_side':
return { name: 'stopLoss', message: stopSideMessage(direction, mode) };
case 'targets_too_many':
return {
name: `targets.${Math.max(0, targetCount - 1)}.value`,
@ -119,13 +140,13 @@ function toFieldError(
}
/**
* «پیش‌بینی جدید» (J09-1…J09-3): access, market, symbol with its live price, direction, up to
* three targets, an optional stop, the horizon, a note and one chart image, then a confirm step.
* The entry is the market price at publish, which the API stamps; the form shows the live one,
* read every 15 seconds, and checks the levels against it on blur, on a direction change and on
* every new price. The CTA stays frozen and says why until the form can publish. A publish sends
* one idempotency key per unchanged form, so a retry never publishes twice. Nothing is kept as a
* draft: leaving with something typed asks first.
* «سیگنال جدید» (J09-1…J09-3): access, market, symbol with its live price, direction, the entry, up
* to three targets, the required stop, the horizon, a note and one chart image, then a confirm
* step. The entry is one exact price, prefilled from the live quote (read every 15 seconds) and
* following it until the analyst edits it, or a range. The levels are checked against it on blur, on
* a direction change and on every new price. The CTA stays frozen and says why until the form can
* publish. A publish sends one idempotency key per unchanged form, so a retry never publishes twice.
* Nothing is kept as a draft: leaving with something typed asks first.
*/
export function usePredictionComposerPage({
creatorId,
@ -140,7 +161,7 @@ export function usePredictionComposerPage({
const [isConfirmingLeave, setIsConfirmingLeave] = useState(false);
// A link elsewhere in the app the creator followed with something typed: asked first.
const [leaveTo, setLeaveTo] = useState<string | null>(null);
// What the confirm step opened with, should the price drop out while it is open.
// What the confirm step shows and sends: a live quote moving the entry mustn't change it.
const [confirmed, setConfirmed] = useState<ComposerSummary | null>(null);
// When the API last said there was no price at publish: a newer price clears it.
const [noPriceSince, setNoPriceSince] = useState<number | null>(null);
@ -152,16 +173,11 @@ export function usePredictionComposerPage({
}, []);
// The key goes with the body it was made for; any change makes a new one.
const attempt = useRef<{ key: string; body: string } | null>(null);
// The levels are checked against the price the form shows.
const entryRef = useRef<number | null>(null);
// The analyst typed in the exact entry: the live quote no longer fills it.
const entryEdited = useRef(false);
const form = useForm<PredictionComposerFormValues>({
resolver: (values, context, options) =>
valibotResolver(predictionComposerSchema(entryRef.current))(
values,
context,
options,
),
resolver: valibotResolver(predictionComposerSchema()),
mode: 'onTouched',
defaultValues: DEFAULT_VALUES,
});
@ -171,6 +187,10 @@ export function usePredictionComposerPage({
marketValue,
symbol,
directionValue,
entryMode,
entryPriceText,
entryLow,
entryHigh,
targets,
stopLoss,
horizonValue,
@ -182,6 +202,10 @@ export function usePredictionComposerPage({
'market',
'symbol',
'direction',
'entryMode',
'entryPrice',
'entryLow',
'entryHigh',
'targets',
'stopLoss',
'horizon',
@ -244,20 +268,42 @@ export function usePredictionComposerPage({
// The market's real source; the quote's own says `mock` in development.
source: symbolRow?.source ?? quoteData.source,
};
const entryPrice = quote.status === 'ready' ? quote.price : null;
const livePrice = quote.status === 'ready' ? quote.price : null;
const entryValues = {
entryMode,
entryPrice: entryPriceText,
entryLow,
entryHigh,
};
const entry = entryLevels(entryValues);
// A new price or direction checks every typed level again; without a price the checks pause.
// Until the analyst edits it, the exact entry follows the live quote of the picked symbol.
const fillEntry = useEffectEvent(() => {
if (!entryEdited.current && livePrice !== null) {
form.setValue('entryPrice', price(livePrice));
}
});
useEffect(() => fillEntry(), [livePrice, symbol]);
// A new price, entry or direction checks every typed level again.
const recheck = () => {
entryRef.current = entryPrice;
const values = form.getValues();
const names: FormPath[] = values.targets.flatMap((target, index) =>
target.value.trim() ? [`targets.${index}.value` as const] : [],
);
if (values.stopLoss.trim()) names.push('stopLoss');
names.push(
...entryFieldsOf(values.entryMode).filter((field) =>
values[field].trim(),
),
);
if (names.length > 0) void form.trigger(names);
};
const recheckLevels = useEffectEvent(recheck);
useEffect(() => recheckLevels(), [entryPrice, direction]);
useEffect(
() => recheckLevels(),
[livePrice, direction, entryMode, entry?.low, entry?.high],
);
const { errors } = form.formState;
const targetLabel = (index: number) =>
@ -267,49 +313,66 @@ export function usePredictionComposerPage({
!market && t('composer.fields.market'),
!symbol && t('composer.fields.symbol'),
!direction && t('composer.fields.direction'),
entryFieldsOf(entryMode).some(
(field) => entryIssue(entryValues, field) === 'required',
) && t('composer.fields.entry'),
...targets.map(
(target, index) => !target.value.trim() && targetLabel(index),
),
!stopLoss.trim() && t('composer.fields.stop'),
!horizon && t('composer.fields.horizon'),
].filter((label): label is string => typeof label === 'string');
const invalid = [
errors.market && t('composer.fields.market'),
errors.symbol && t('composer.fields.symbol'),
entryFieldsOf(entryMode).some(
// Empty says «کامل», not «اصلاح», even with its error showing.
(field) => errors[field] && entryValues[field].trim(),
) && t('composer.fields.entry'),
...targets.map(
(_target, index) => errors.targets?.[index]?.value && targetLabel(index),
),
errors.stopLoss && t('composer.fields.stop'),
errors.stopLoss && stopLoss.trim() && t('composer.fields.stop'),
errors.horizon && t('composer.fields.horizon'),
errors.note && t('composer.fields.note'),
errors.root?.chart && t('composer.fields.chart'),
].filter((label): label is string => typeof label === 'string');
const reason = invalid.length
? t('composer.invalid', { fields: list(invalid) })
: missing.length
? t('composer.missing', { fields: list(missing) })
: quote.status === 'unavailable'
? t('composer.quote-unavailable')
: chart.image?.status === 'uploading'
? t('content:composer.uploading-reason')
: chart.image?.status === 'failed'
? t('content:composer.images.failed', { n: number(1) })
: undefined;
const block = publishReason({
invalid,
missing,
quoteUnavailable: quote.status === 'unavailable',
chart:
chart.image?.status === 'uploading' || chart.image?.status === 'failed'
? chart.image.status
: null,
});
const reason = !block
? undefined
: block.kind === 'invalid'
? t('composer.invalid', { fields: list(block.fields) })
: block.kind === 'missing'
? t('composer.missing', { fields: list(block.fields) })
: block.kind === 'quote-unavailable'
? t('composer.quote-unavailable')
: block.kind === 'chart-uploading'
? t('content:composer.uploading-reason')
: t('content:composer.images.failed', { n: number(1) });
const levelsBroken =
targetIssues(direction, targets, entryPrice).some(Boolean) ||
stopIssue(direction, stopLoss, entryPrice) !== null;
targetIssues(direction, targets, entry).some(Boolean) ||
stopIssue(direction, stopLoss, entry) !== null;
const summary: ComposerSummary | null =
missing.length === 0 &&
entryPrice !== null &&
market &&
direction &&
horizon
missing.length === 0 && entry !== null && market && direction && horizon
? {
symbol,
market,
direction,
entryPrice,
entryMode,
// A range's distances and returns read its middle, as the API stores it.
entryPrice: (entry.low + entry.high) / 2,
entryLow: entryMode === 'range' ? entry.low : null,
entryHigh: entryMode === 'range' ? entry.high : null,
targetPrices: targets.flatMap(
(target) => levelPrice(target.value) ?? [],
),
@ -325,16 +388,12 @@ export function usePredictionComposerPage({
const failPublish = (error: unknown) => {
const code = predictionErrorCode(error);
if (code === PREDICTION_ERROR_CODES.invalid) {
// The levels were checked against a newer price: the form shows it.
const checked = quoteOfError(error);
if (checked) {
queryClient.setQueryData(marketDataKeys.quote(checked.symbol), checked);
}
predictionFieldIssues(error).forEach((issue, index) => {
const { name, message } = toFieldError(
issue,
form.getValues('direction'),
form.getValues('targets').length,
form.getValues('entryMode'),
);
form.setError(
name,
@ -362,7 +421,7 @@ export function usePredictionComposerPage({
};
const publish = async () => {
const sent = summary ?? confirmed;
const sent = confirmed;
if (phase !== 'confirming' || !sent) return;
const args: PublishPredictionArgs = {
accessLevel: sent.accessLevel,
@ -372,6 +431,12 @@ export function usePredictionComposerPage({
symbol: sent.symbol,
market: sent.market,
direction: sent.direction,
...(sent.entryMode === 'range'
? {
entryLow: sent.entryLow ?? undefined,
entryHigh: sent.entryHigh ?? undefined,
}
: { entryPrice: sent.entryPrice }),
targetPrices: sent.targetPrices,
stopLoss: sent.stopLoss,
horizon: sent.horizon,
@ -404,6 +469,8 @@ export function usePredictionComposerPage({
return (
values.market !== '' ||
values.direction !== '' ||
values.entryLow.trim() !== '' ||
values.entryHigh.trim() !== '' ||
values.targets.some((target) => target.value.trim() !== '') ||
values.stopLoss.trim() !== '' ||
values.horizon !== '' ||
@ -431,6 +498,13 @@ export function usePredictionComposerPage({
// `requestLeave`. A publish in flight navigates by itself.
useLeaveGuard(phase !== 'publishing' && hasSomethingToLose(), requestLink);
// Another symbol's price can't stay as the entry; the new quote fills it.
const clearEntry = () => {
entryEdited.current = false;
form.setValue('entryPrice', '');
form.clearErrors('entryPrice');
};
return {
form,
markets,
@ -440,11 +514,20 @@ export function usePredictionComposerPage({
form.setValue('market', next, { shouldDirty: true });
// Another market's symbol can't stay: it goes, with its price.
form.setValue('symbol', '', { shouldDirty: true });
clearEntry();
form.clearErrors(['market', 'symbol']);
},
direction,
setDirection: (next) =>
form.setValue('direction', next, { shouldDirty: true }),
entryMode,
setEntryMode: (next) => {
form.setValue('entryMode', next, { shouldDirty: true });
form.clearErrors(['entryPrice', 'entryLow', 'entryHigh']);
},
markEntryEdited: () => {
entryEdited.current = true;
},
horizon,
setHorizon: (next) => {
form.setValue('horizon', next, { shouldDirty: true });
@ -463,6 +546,7 @@ export function usePredictionComposerPage({
) {
queryClient.setQueryData(marketDataKeys.quote(row.symbol), row.quote);
}
if (row.symbol !== symbol) clearEntry();
form.setValue('symbol', row.symbol, { shouldDirty: true });
form.clearErrors('symbol');
},
@ -502,7 +586,7 @@ export function usePredictionComposerPage({
setPhase('confirming');
})();
},
confirmSummary: phase === 'idle' ? null : (summary ?? confirmed),
confirmSummary: phase === 'idle' ? null : confirmed,
publish: () => void publish(),
cancelConfirm: () => {
if (phase === 'confirming') setPhase('idle');

View File

@ -1,2 +1,2 @@
/** The «همه پیش‌بینی‌ها» chip in the URL: `?status=closed`; «باز» has none. */
/** The «همه سیگنال‌ها» chip in the URL: `?status=closed`; «باز» has none. */
export const PREDICTION_STATUS_PARAM = 'status';

View File

@ -5,7 +5,7 @@ import type {
OwnPredictionPayload,
} from '../../repositories/prediction';
/** «همه پیش‌بینی‌ها» (J10-3f, J10-3g). */
/** «همه سیگنال‌ها» (J10-3f, J10-3g). */
export type PredictionListPageModel = {
/** The chip in the URL (`?status=`), «باز» by default. */
status: OwnPredictionsStatus;

View File

@ -19,7 +19,7 @@ function toStatus(value: string | null): OwnPredictionsStatus {
}
/**
* «همه پیش‌بینی‌ها» (J10-3f, J10-3g): «باز» · «بسته‌شده» · «همه» with the API's totals, the chip in
* «همه سیگنال‌ها» (J10-3f, J10-3g): «باز» · «بسته‌شده» · «همه» with the API's totals, the chip in
* the URL so back and a reload keep it, 20 a page by cursor. open and all list the newest
* published first, closed the newest closed first. A card closed here stays in place, closed.
*/

View File

@ -7,7 +7,7 @@ import {
import type { TrackRecordPartModel } from './types';
/**
* داشبورد › پیش‌بینی‌ها › the record (J10-3): the creator's own numbers once the record is public
* داشبورد › سیگنال‌ها › the record (J10-3): the creator's own numbers once the record is public
* (10 closed, a month since the first prediction, as the API decides); before that, how far it is
* from public, since the channel shows no record yet.
*/

View File

@ -13,7 +13,7 @@ export const PREDICTION_ENDPOINTS = {
/** The codes the API marks prediction failures with; branch on these, never on the message. */
export const PREDICTION_ERROR_CODES = {
/** 422 on publish: `details.errors` lists `{ field, code }`, with `details.quote` for levels. */
/** 422 on publish: `details.errors` lists `{ field, code }`. */
invalid: 'PREDICTION_INVALID',
/** 503 on a price read or an early close, 409 on publish: no fresh price for the symbol. */
quoteUnavailable: 'QUOTE_UNAVAILABLE',
@ -35,15 +35,18 @@ export const PREDICTION_FIELD_CODES = [
'horizon_invalid',
'note_too_long',
'chart_too_many',
'entry_required',
'entry_range_order',
'stop_required',
'target_wrong_side',
'targets_order',
'stop_wrong_side',
] as const;
/** The «همه پیش‌بینی‌ها» page size. */
/** The «همه سیگنال‌ها» page size. */
export const OWN_PREDICTIONS_PAGE_LIMIT = 20;
/** The tab's «پیش‌بینی‌های باز» reads every open one in one go: the API's largest page. */
/** The tab's «سیگنال‌های باز» reads every open one in one go: the API's largest page. */
export const OWN_OPEN_PREVIEW_LIMIT = 50;
/** The tab's «بسته‌شده‌های اخیر». */
@ -60,7 +63,7 @@ export const predictionKeys = {
/** A first page the داشبورد tab shows. */
ownPreview: (status: OwnPredictionsStatus, limit: number) =>
[...predictionKeys.own(), 'preview', status, limit] as const,
/** «همه پیش‌بینی‌ها», page after page. */
/** «همه سیگنال‌ها», page after page. */
ownList: (status: OwnPredictionsStatus) =>
[...predictionKeys.own(), 'list', status] as const,
/** The price an early close would record now. */

View File

@ -1,9 +1,6 @@
import { isHttpError } from '@lumina/libs/http';
import type { PostEntity } from '../../../post';
import type { QuoteEntity } from '../../entities/market-data';
import { toQuotePayload } from '../market-data';
import type { QuotePayload } from '../market-data';
import { PREDICTION_ERROR_CODES, PREDICTION_FIELD_CODES } from './constants';
import { toOwnPredictionPayload } from './mappers';
import type {
@ -48,18 +45,6 @@ export function predictionFieldIssues(error: unknown): PredictionFieldIssue[] {
);
}
/** The price a 422 checked the levels against, to show it in place of the old one. */
export function quoteOfError(error: unknown): QuotePayload | null {
const quote = detailsOf(error)?.quote;
return isRecord(quote) &&
typeof quote.symbol === 'string' &&
typeof quote.price === 'number' &&
typeof quote.at === 'string' &&
typeof quote.source === 'string'
? toQuotePayload(quote as QuoteEntity)
: null;
}
/** The closed post a 409 `PREDICTION_ALREADY_CLOSED` carries, to show it as it is now. */
export function closedPostOfError(error: unknown): OwnPredictionPayload | null {
const post = detailsOf(error)?.post;

View File

@ -10,7 +10,6 @@ export {
closedPostOfError,
predictionErrorCode,
predictionFieldIssues,
quoteOfError,
} from './errors';
export { predictionRepository } from './prediction';
export type {

View File

@ -23,8 +23,9 @@ export type PredictionErrorCode =
export type PredictionFieldCode = (typeof PREDICTION_FIELD_CODES)[number];
/**
* One field a 422 `PREDICTION_INVALID` refused, with the API's path: `market`, `symbol`,
* `targetPrices` or `targetPrices.<i>`, `stopLoss`, `horizon`, `caption` (the note), `media`.
* One field a 422 `PREDICTION_INVALID` refused, with the API's path: `market`, `symbol`, `entry`,
* `entryLow`, `targetPrices` or `targetPrices.<i>`, `stopLoss`, `horizon`, `caption` (the note),
* `media`.
*/
export type PredictionFieldIssue = { field: string; code: PredictionFieldCode };

View File

@ -79,10 +79,14 @@ export function predictionCardLabels(t: ContentT): PredictionCardLabels {
toFinalTarget: t('prediction.to-final-target'),
toStop: t('prediction.to-stop'),
riskReward: t('prediction.risk-reward'),
riskRewardRange: (worst, best) =>
t('prediction.risk-reward-range', { worst, best }),
levels: {
stop: t('prediction.levels.stop'),
entry: t('prediction.levels.entry'),
base: t('prediction.levels.base'),
range: t('prediction.levels.range'),
entryRange: t('prediction.levels.entry-range'),
target,
finalTarget: t('prediction.levels.final-target'),
close: t('prediction.levels.close'),

View File

@ -99,10 +99,10 @@
"description": "کانال‌هایی که مشترک هستید"
},
"newPredictions": {
"label": "پیش‌بینی‌های تازه"
"label": "سیگنال‌های تازه"
},
"predictionClosed": {
"label": "بسته شدن پیش‌بینی‌ها",
"label": "بسته شدن سیگنال‌ها",
"description": "رسیدن به هدف، حد ضرر یا پایان افق"
},
"followedAnalysts": {
@ -112,7 +112,7 @@
},
"sms": {
"newPredictions": {
"label": "پیش‌بینی‌های تازه"
"label": "سیگنال‌های تازه"
},
"subscriptionReminder": {
"label": "یادآوری پایان اشتراک",
@ -133,7 +133,7 @@
"label": "مشترک تازه"
},
"predictionClosed": {
"label": "بسته شدن خودکار پیش‌بینی‌ها",
"label": "بسته شدن خودکار سیگنال‌ها",
"description": "رسیدن به هدف، حد ضرر یا پایان افق"
},
"capacityRequestResult": {
@ -181,7 +181,7 @@
"body": "از این به بعد از آیکون لومینا روی دسکتاپ وارد شوید."
}
},
"notifications": "دریافت اعلان پست‌ها و پیش‌بینی‌ها",
"notifications": "دریافت اعلان پست‌ها و سیگنال‌ها",
"no-browser-bar": "بدون نوار مرورگر",
"action": "نصب اپلیکیشن",
"ios": {

View File

@ -94,7 +94,7 @@
"investor": "سرمایه‌گذار",
"investor-description": "تحلیلگران را با کارنامه‌شان مقایسه می‌کنم و در کانالشان مشترک می‌شوم.",
"creator": "تحلیلگر",
"creator-description": "تحلیل و پیش‌بینی منتشر می‌کنم و از اشتراک کانالم درآمد دارم.",
"creator-description": "تحلیل و سیگنال منتشر می‌کنم و از اشتراک کانالم درآمد دارم.",
"note": "نوع حساب پس از ثبت‌نام قابل تغییر نیست.",
"submit": "ادامه"
},
@ -237,7 +237,7 @@
"title": "پیش‌نمایش پروفایل",
"live": "پیش‌نمایش زنده — سرمایه‌گذاران این را می‌بینند",
"channel": "کانال در لومینا",
"note": "آمار و کارنامه پیش‌بینی‌ها پس از اولین پیش‌بینی‌های شما در همین صفحه نمایش داده می‌شود.",
"note": "آمار و کارنامه سیگنال‌ها پس از اولین سیگنال‌های شما در همین صفحه نمایش داده می‌شود.",
"close": "بستن پیش‌نمایش"
},
"done": {

View File

@ -1,7 +1,7 @@
{
"meta": {
"title": "@{{username}}",
"description": "کانال @{{username}} در لومینا: پست‌ها و پیش‌بینی‌های ثبت‌شده، با کارنامه‌ای که پیش از اشتراک می‌بینید.",
"description": "کانال @{{username}} در لومینا: پست‌ها و سیگنال‌های ثبت‌شده، با کارنامه‌ای که پیش از اشتراک می‌بینید.",
"post-title": "پست @{{username}}",
"post-missing-title": "پست پیدا نشد",
"unavailable-title": "کانال در دسترس نیست"
@ -88,8 +88,8 @@
}
},
"stats": {
"loading": "در حال بارگذاری عملکرد پیش‌بینی‌ها…",
"error-title": "عملکرد پیش‌بینی‌ها بارگذاری نشد",
"loading": "در حال بارگذاری عملکرد سیگنال‌ها…",
"error-title": "عملکرد سیگنال‌ها بارگذاری نشد",
"error-description": "بقیه کانال در دسترس است. این بخش را دوباره بارگذاری کنید."
},
"feed": {
@ -100,13 +100,13 @@
"no-subscribers": "این پست تا پیوستن نخستین مشترک، برای همه قفل می‌ماند.",
"empty": {
"title": "این کانال هنوز پستی منتشر نکرده است",
"description": "با دنبال کردن، از پست‌ها و پیش‌بینی‌های تازه باخبر می‌شوید."
"description": "با دنبال کردن، از پست‌ها و سیگنال‌های تازه باخبر می‌شوید."
},
"own-empty": {
"title": "هنوز پستی منتشر نکرده‌اید",
"description": "اولین پست یا پیش‌بینی خود را منتشر کنید تا دنبال‌کنندگان آن را ببینند.",
"description": "اولین پست یا سیگنال خود را منتشر کنید تا دنبال‌کنندگان آن را ببینند.",
"post": "پست جدید",
"prediction": "پیش‌بینی جدید"
"prediction": "سیگنال جدید"
}
},
"post": {
@ -142,7 +142,7 @@
"subtitle": "کد شما ساخته شد: ⁦{{code}}⁩"
},
"prediction": {
"title": "اولین پیش‌بینی را منتشر کنید",
"title": "اولین سیگنال را منتشر کنید",
"subtitle": "کارنامه عمومی شما از همین‌جا شروع می‌شود."
},
"cta": "تعیین قیمت‌ها",

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