From 69a76446d20c9a5c8d062153a03c226ab54c617b Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Mon, 2 Nov 2026 01:58:25 +0400 Subject: [PATCH] feat(dashboard): add the signal performance card to the signals tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tab reads GET /me/signal-stats instead of the track-record route: four tiles, how signals ended, risk to reward as worst to best, and progress to a public record, with tips on this tab only. Before the first nightly evaluation a message replaces the numbers, never zeros. The tiles, progress and pending state are shared organisms, ready for the overview tab. The channel's split now reads «رسیده به هدف», «خورده به حد ضرر» and «پایان مهلت», since those three counts no longer mean win, loss and breakeven. Co-Authored-By: Claude Opus 5.5 --- docs/pages/market/dashboard-predictions.md | 15 +- .../creator-stats/components/OutcomeSplit.tsx | 2 +- .../src/organisms/creator-stats/types.ts | 13 +- .../signal-progress/SignalProgress.tsx | 52 +++++ .../organisms/signal-progress/index.ts | 2 + .../organisms/signal-progress/types.ts | 5 + .../signal-stat-tiles/SignalStatTiles.tsx | 72 +++++++ .../organisms/signal-stat-tiles/index.ts | 2 + .../organisms/signal-stat-tiles/types.ts | 9 + .../SignalStatsPending.tsx | 19 ++ .../organisms/signal-stats-pending/index.ts | 1 + .../predictions-tab/PredictionsTab.tsx | 14 +- .../PredictionsTabSkeleton.tsx | 2 +- .../components/SignalPerformance.test.tsx | 196 ++++++++++++++++++ .../components/SignalPerformance.tsx | 104 ++++++++++ .../components/TrackRecord.tsx | 35 ---- .../components/TrackRecordProgress.tsx | 55 ----- .../organisms/predictions-tab/types.ts | 7 +- .../organisms/predictions-tab/utils.ts | 16 ++ .../entities/prediction-stats/types.ts | 20 +- .../prediction/entities/signal-stats/index.ts | 1 + .../prediction/entities/signal-stats/types.ts | 37 ++++ .../prediction/entities/track-record/index.ts | 1 - .../prediction/entities/track-record/types.ts | 15 -- .../market/src/features/prediction/index.ts | 7 +- .../prediction-cache/prediction-cache.ts | 8 +- .../prediction/models/signal-stats/index.ts | 1 + .../signal-stats/use-signal-stats-part.ts | 19 ++ .../prediction/models/track-record/index.ts | 2 - .../prediction/models/track-record/types.ts | 12 -- .../track-record/use-track-record-part.ts | 28 --- .../repositories/prediction/constants.ts | 6 +- .../repositories/prediction/index.ts | 4 +- .../repositories/prediction/mappers.ts | 49 ++++- .../repositories/prediction/prediction.ts | 20 +- .../prediction/signal-stats-mappers.test.ts | 97 +++++++++ .../repositories/prediction/types.ts | 52 ++++- .../src/shared/labels/content-labels.tsx | 5 + .../labels/creator-stats-labels.test.ts | 20 ++ .../market/src/shared/locales/fa/content.json | 7 +- .../src/shared/locales/fa/predictions.json | 51 ++++- 41 files changed, 849 insertions(+), 234 deletions(-) create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/SignalProgress.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/SignalStatTiles.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/SignalStatsPending.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.test.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.tsx delete mode 100644 platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecord.tsx delete mode 100644 platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecordProgress.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/utils.ts create mode 100644 platforms/market/src/features/prediction/entities/signal-stats/index.ts create mode 100644 platforms/market/src/features/prediction/entities/signal-stats/types.ts delete mode 100644 platforms/market/src/features/prediction/entities/track-record/index.ts delete mode 100644 platforms/market/src/features/prediction/entities/track-record/types.ts create mode 100644 platforms/market/src/features/prediction/models/signal-stats/index.ts create mode 100644 platforms/market/src/features/prediction/models/signal-stats/use-signal-stats-part.ts delete mode 100644 platforms/market/src/features/prediction/models/track-record/index.ts delete mode 100644 platforms/market/src/features/prediction/models/track-record/types.ts delete mode 100644 platforms/market/src/features/prediction/models/track-record/use-track-record-part.ts create mode 100644 platforms/market/src/features/prediction/repositories/prediction/signal-stats-mappers.test.ts create mode 100644 platforms/market/src/shared/labels/creator-stats-labels.test.ts diff --git a/docs/pages/market/dashboard-predictions.md b/docs/pages/market/dashboard-predictions.md index 011d610..a24c82f 100644 --- a/docs/pages/market/dashboard-predictions.md +++ b/docs/pages/market/dashboard-predictions.md @@ -17,15 +17,16 @@ In bull's document order. Everything sits in `AuthGuard role="creator"`, whose fallback is `PredictionsTabSkeleton`. -| 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) | -| ↳ TrackRecord | viewer | skeleton | hydrate | no | the record or its progress to public; own `PartBoundary` and `` | -| ↳ 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 `` to `/dashboard/predictions/all` | +| 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) | +| ↳ SignalPerformance | viewer | skeleton | hydrate | no | «عملکرد سیگنال‌ها» from `GET /me/signal-stats`: four tiles, outcome split, risk to reward, progress to public; before the first nightly evaluation a message, never zeros; own `PartBoundary` and `` | +| ↳ 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 `` to `/dashboard/predictions/all` | ## Notes - bull and bear differ only in `layout` (card and sheet placement). A card's tap opens its post. - `/dashboard/predictions/all` is a separate page outside the `(creator)` group, under its own `OnboardingGuard` layout: [dashboard-predictions-all.md](dashboard-predictions-all.md). +- The tiles, progress and pending state are `dashboard/organisms/signal-stat-tiles`, `signal-progress` and `signal-stats-pending`, read through `useSignalStatsPart`, so «نمای کلی» can show the same numbers. Tips (`withTips`) appear only on this tab. diff --git a/packages/island/src/organisms/creator-stats/components/OutcomeSplit.tsx b/packages/island/src/organisms/creator-stats/components/OutcomeSplit.tsx index 84a9c46..232b619 100644 --- a/packages/island/src/organisms/creator-stats/components/OutcomeSplit.tsx +++ b/packages/island/src/organisms/creator-stats/components/OutcomeSplit.tsx @@ -69,7 +69,7 @@ export function OutcomeSplit({ counts, labels }: OutcomeSplitProps) { > {formatted[outcome]} , - labels.outcomes[outcome], + labels.splitOutcomes[outcome], )} diff --git a/packages/island/src/organisms/creator-stats/types.ts b/packages/island/src/organisms/creator-stats/types.ts index 8cc6524..8b1b46b 100644 --- a/packages/island/src/organisms/creator-stats/types.ts +++ b/packages/island/src/organisms/creator-stats/types.ts @@ -22,8 +22,11 @@ export type CreatorStatsData = { /** Closed outcomes in `trendOrder`. Only the last 10 are drawn. */ accuracyTrend: TrendOutcome[]; /** The all-time split. The bar shows only when `wins` and `losses` both arrive. */ + /** «رسیده به هدف». */ wins?: number; + /** «خورده به حد ضرر». */ losses?: number; + /** «پایان مهلت». */ breakeven?: number; }; @@ -40,11 +43,13 @@ export type CreatorStatsLabels = { winRate: ReactNode; /** 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: «موفق», «ناموفق», «سربه‌سر». */ + /** A signal's return at close in words, for the key, the tooltips and the curve's sentence: «موفق», «ناموفق», «سربه‌سر». */ outcomes: Record; - /** One legend entry, `count` already bold: `(count, outcome) => <>{count} {outcome}` → «۲۲ موفق». */ + /** How signals ended in the split's legend: «رسیده به هدف» (`wins`), «خورده به حد ضرر» (`losses`), «پایان مهلت» (`breakeven`). */ + splitOutcomes: Record; + /** One legend entry, `count` already bold: `(count, outcome) => <>{count} {outcome}` → «۲۲ رسیده به هدف». */ splitLegend: (count: ReactNode, outcome: string) => ReactNode; - /** The split bar as one sentence: `({ win, breakeven, loss }) => \`${win} موفق، ${breakeven} سربه‌سر، ${loss} ناموفق\``. */ + /** The split bar as one sentence: `({ win, breakeven, loss }) => \`${win} رسیده به هدف، ${breakeven} پایان مهلت، ${loss} خورده به حد ضرر\``. */ splitSentence: (counts: Record) => string; /** «بازدهی میانگین». */ avgRoi: ReactNode; @@ -112,7 +117,7 @@ export type OutcomeSplitProps = { counts: Record; labels: Pick< CreatorStatsLabels, - 'outcomes' | 'splitLegend' | 'splitSentence' + 'splitOutcomes' | 'splitLegend' | 'splitSentence' >; }; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/SignalProgress.tsx b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/SignalProgress.tsx new file mode 100644 index 0000000..fc59e40 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/SignalProgress.tsx @@ -0,0 +1,52 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Meter } from '@lumina/island/molecules/meter'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { SignalProgressProps } from './types'; + +/** + * How far the record is from public: the closed signals against the required ones and the days + * left to a month of activity while there are any; or that it is public, once it is. + */ +export function SignalProgress({ progress }: SignalProgressProps) { + const { t } = useTranslation('predictions'); + + if (progress.isPublic) { + return ( + + + + {t('performance.public')} + + + ); + } + return ( + + + {progress.daysLeft !== null && ( + + + + {t('performance.days-left', { n: number(progress.daysLeft) })} + + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/index.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/index.ts new file mode 100644 index 0000000..7d5bcf1 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/index.ts @@ -0,0 +1,2 @@ +export { SignalProgress } from './SignalProgress'; +export type { SignalProgressProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/types.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/types.ts new file mode 100644 index 0000000..9c258ea --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-progress/types.ts @@ -0,0 +1,5 @@ +import type { SignalProgressPayload } from '../../../../../../features/prediction'; + +export type SignalProgressProps = { + progress: SignalProgressPayload; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/SignalStatTiles.tsx b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/SignalStatTiles.tsx new file mode 100644 index 0000000..3c6436a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/SignalStatTiles.tsx @@ -0,0 +1,72 @@ +'use client'; + +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { InfoTip } from '@lumina/island/molecules/info-tip'; +import { StatTile } from '@lumina/island/molecules/stat-tile'; +import { Element } from '@lumina/island/primitives/element'; +import { iso, number, percent, signedPercent } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { SignalStatTilesProps } from './types'; + +/** The four numbers the channel, نمای کلی and سیگنال‌ها all show, from one snapshot. */ +export function SignalStatTiles({ + stats, + layout, + withTips = false, +}: SignalStatTilesProps) { + const { t } = useTranslation('predictions'); + + return ( + + + {t('performance.tiles.win-rate')} + {withTips && ( + + {t('performance.tips.win-rate')} + + )} + + } + value={iso(percent(stats.winRate))} + /> + + {t('performance.tiles.avg-roi')} + {withTips && ( + + {t('performance.tips.avg-roi')} + + )} + + } + value={ + + {signedPercent(stats.avgRoi)} + + } + valueTone={ + stats.avgRoi > 0 ? 'success' : stats.avgRoi < 0 ? 'danger' : 'default' + } + /> + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/index.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/index.ts new file mode 100644 index 0000000..ccde967 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/index.ts @@ -0,0 +1,2 @@ +export { SignalStatTiles } from './SignalStatTiles'; +export type { SignalStatTilesProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/types.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/types.ts new file mode 100644 index 0000000..beaa0da --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stat-tiles/types.ts @@ -0,0 +1,9 @@ +import type { SignalNumbersPayload } from '../../../../../../features/prediction'; + +export type SignalStatTilesProps = { + stats: Pick; + /** mobile: two by two; desktop: one row. */ + layout: 'mobile' | 'desktop'; + /** The ⓘ beside the rate and the return: only on سیگنال‌ها, never on نمای کلی. */ + withTips?: boolean; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/SignalStatsPending.tsx b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/SignalStatsPending.tsx new file mode 100644 index 0000000..91542bf --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/SignalStatsPending.tsx @@ -0,0 +1,19 @@ +'use client'; + +import { StateMessage } from '@lumina/island/molecules/state-message'; +import { useTranslation } from 'react-i18next'; + +/** In place of the numbers before the first nightly evaluation: never zeros, which would be false. */ +export function SignalStatsPending() { + const { t } = useTranslation('predictions'); + + return ( + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/index.ts b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/index.ts new file mode 100644 index 0000000..34707ff --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/organisms/signal-stats-pending/index.ts @@ -0,0 +1 @@ +export { SignalStatsPending } from './SignalStatsPending'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTab.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTab.tsx index 656447e..4e32ab1 100644 --- a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTab.tsx +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTab.tsx @@ -12,13 +12,13 @@ import { usePredictionsTabPart } from '../../../../../../../features/prediction' import { PartBoundary } from '../../../../../../error-boundaries'; import { ROUTES } from '../../../../../../navigation/navigation'; import { PredictionSection } from './components/PredictionSection'; -import { TrackRecord } from './components/TrackRecord'; +import { SignalPerformance } from './components/SignalPerformance'; import { PredictionsTabSkeleton } from './PredictionsTabSkeleton'; import type { PredictionsTabProps } from './types'; /** - * داشبورد › سیگنال‌ها (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 + * داشبورد › سیگنال‌ها (J10-3), the creator's own, in the browser only: «عملکرد سیگنال‌ها», every + * open prediction with «بستن زودهنگام», the two closed most recently and * «همه سیگنال‌ها». 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. */ @@ -46,16 +46,16 @@ export function PredictionsTab({ layout }: PredictionsTabProps) { return ( + } > - + diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTabSkeleton.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTabSkeleton.tsx index 5e97a50..f76e466 100644 --- a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTabSkeleton.tsx +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/PredictionsTabSkeleton.tsx @@ -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 numbers, then two cards. */ export function PredictionsTabSkeleton({ label, delayed, diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.test.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.test.tsx new file mode 100644 index 0000000..f02c74c --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.test.tsx @@ -0,0 +1,196 @@ +import { render, screen, within } from '@testing-library/react'; +import { number, ratio } from '@lumina/tools/format'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { SignalStatsPayload } from '../../../../../../../../features/prediction'; +import predictions from '../../../../../../../../shared/locales/fa/predictions.json'; +import { SignalProgress } from '../../../../organisms/signal-progress'; +import { SignalStatTiles } from '../../../../organisms/signal-stat-tiles'; +import { riskRewardText } from '../utils'; +import { SignalPerformance } from './SignalPerformance'; + +let answer: SignalStatsPayload; + +vi.mock('../../../../../../../../features/prediction', () => ({ + useSignalStatsPart: () => answer, +})); + +// The real Persian strings, so the spec's exact wording is what's tested. +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string, values: Record = {}) => { + const text = key + .split('.') + .reduce((node: any, part) => node?.[part], predictions) as string; + return text.replace(/{{(\w+)}}/g, (_, name) => values[name]); + }, + }), +})); + +const ready = ( + over: Partial> = {}, +) => + ({ + status: 'ready', + stats: { + winRate: 60, + avgRoi: 4.2, + total: 12, + active: 2, + outcomes: { target: 6, stop: 3, expired: 1, active: 2, voided: 0 }, + riskReward: { worst: 1.4, best: 3 }, + }, + progress: { isPublic: false, closed: 4, required: 10, daysLeft: 18 }, + ...over, + }) as SignalStatsPayload; + +describe('SignalPerformance', () => { + beforeEach(() => { + answer = ready(); + }); + + it('shows the message and no numbers before the first evaluation', () => { + answer = { status: 'pending' }; + render(); + expect( + screen.getByText('ارزیابی عملکرد سیگنال‌ها به‌زودی فعال می‌شود.'), + ).toBeTruthy(); + expect( + screen.getByText('عددها پس از اولین ارزیابی شبانه نمایش داده می‌شوند.'), + ).toBeTruthy(); + expect(screen.queryByText('نرخ موفقیت')).toBeNull(); + expect(screen.queryByText('رسیده به هدف')).toBeNull(); + expect(screen.queryByRole('progressbar')).toBeNull(); + }); + + it('shows the owner the numbers below the threshold, with the way to public', () => { + render(); + for (const label of [ + 'نرخ موفقیت', + 'بازدهی میانگین', + 'کل سیگنال‌ها', + 'سیگنال‌های فعال', + ]) { + expect(screen.getByText(label)).toBeTruthy(); + } + expect( + screen.getByText( + `${number(4)} از ${number(10)} سیگنال بسته‌شده تا نمایش عمومی`, + ), + ).toBeTruthy(); + expect(screen.getByText(`${number(18)} روز تا یک ماه فعالیت`)).toBeTruthy(); + expect(screen.queryByText('کارنامه عمومی شما فعال است')).toBeNull(); + }); + + it('says the record is public once it is', () => { + answer = ready({ + progress: { isPublic: true, closed: 10, required: 10, daysLeft: null }, + }); + render(); + expect(screen.getByText('کارنامه عمومی شما فعال است')).toBeTruthy(); + expect(screen.queryByText(/تا نمایش عمومی/)).toBeNull(); + }); + + it('lists every outcome', () => { + render(); + for (const label of [ + 'رسیده به هدف', + 'خورده به حد ضرر', + 'پایان مهلت', + 'فعال', + 'باطل‌شده', + ]) { + expect(screen.getByText(label)).toBeTruthy(); + } + }); + + it('shows risk to reward as worst to best', () => { + render(); + expect(screen.getByText(`${ratio(1, 1.4)} تا ${ratio(1, 3)}`)).toBeTruthy(); + }); + + it('shows a dash with no risk to reward', () => { + const base = ready() as Extract; + answer = { ...base, stats: { ...base.stats, riskReward: null } }; + render(); + expect(screen.getByText('—')).toBeTruthy(); + }); + + it.each([ + [ + 'توضیح نرخ موفقیت', + 'سیگنال‌هایی که با پایان مهلت بسته شده‌اند، ناموفق حساب می‌شوند.', + ], + [ + 'توضیح بازدهی میانگین', + 'بازدهی هر سیگنال با تقسیم مساوی سرمایه بین هدف‌ها محاسبه می‌شود.', + ], + [ + 'توضیح ریسک به ریوارد', + 'بدترین و بهترین حالت: در سیگنال‌های بازه‌ای، ورود در دورترین و نزدیک‌ترین نقطهٔ بازه به هدف.', + ], + ['توضیح پایان مهلت', 'در نرخ موفقیت، ناموفق حساب می‌شود.'], + ['توضیح باطل‌شده', 'در نرخ موفقیت و بازدهی حساب نمی‌شود.'], + ])('%s explains itself', (label, text) => { + render(); + const button = screen.getByRole('button', { name: label }); + const tip = document.getElementById( + button.getAttribute('aria-describedby')!, + )!; + expect(within(tip.parentElement!).getByRole('tooltip').textContent).toBe( + text, + ); + }); +}); + +describe('SignalStatTiles', () => { + const stats = { winRate: 50, avgRoi: 0, total: 0, active: 0 }; + + it('has no tips unless asked, as on نمای کلی', () => { + render(); + expect(screen.queryByRole('button')).toBeNull(); + }); + + it.each([ + [4.2, 'text-success-text'], + [-3, 'text-danger-text'], + [0, 'text-text-primary'], + ])('colours a return of %d', (avgRoi, tone) => { + const { container } = render( + , + ); + const value = container.querySelector('bdi')!.parentElement!; + expect(value.className).toContain(tone); + expect(container.querySelector('bdi')!.getAttribute('dir')).toBe('ltr'); + }); +}); + +describe('SignalProgress', () => { + it('leaves the days out once the month is met', () => { + render( + , + ); + expect(screen.queryByText(/یک ماه فعالیت/)).toBeNull(); + }); +}); + +describe('riskRewardText', () => { + const range = ({ worst, best }: { worst: string; best: string }) => + `${worst} تا ${best}`; + + it('reads one ratio when the two read the same', () => { + expect(riskRewardText({ worst: 2, best: 2.01 }, range)).toBe(ratio(1, 2)); + }); + + it('reads worst to best', () => { + expect(riskRewardText({ worst: 1.4, best: 3 }, range)).toBe( + `${ratio(1, 1.4)} تا ${ratio(1, 3)}`, + ); + }); + + it('is a dash with nothing to read', () => { + expect(riskRewardText(null, range)).toBe('—'); + }); +}); diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.tsx new file mode 100644 index 0000000..c94659f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/SignalPerformance.tsx @@ -0,0 +1,104 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { InfoTip } from '@lumina/island/molecules/info-tip'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { number } from '@lumina/tools/format'; +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { useSignalStatsPart } from '../../../../../../../../features/prediction'; +import { SignalProgress } from '../../../../organisms/signal-progress'; +import { SignalStatTiles } from '../../../../organisms/signal-stat-tiles'; +import { SignalStatsPending } from '../../../../organisms/signal-stats-pending'; +import type { SignalPerformanceProps } from '../types'; +import { riskRewardText } from '../utils'; + +/** + * «عملکرد سیگنال‌ها» at the top of the tab: the four numbers, how signals ended, risk to reward and + * the way to a public record, with an ⓘ on what isn't obvious. The owner sees the numbers below the + * public threshold too. Before the first nightly evaluation, a message in their place. + */ +export function SignalPerformance({ layout }: SignalPerformanceProps) { + const { t } = useTranslation('predictions'); + const headingId = useId(); + const performance = useSignalStatsPart(); + + return ( + + + + {t('performance.title')} + + {performance.status === 'pending' ? ( + + ) : ( + <> + + + + {number(performance.stats.outcomes.target)} + + + {number(performance.stats.outcomes.stop)} + + + {t('performance.outcomes.expired')} + + {t('performance.tips.expired')} + + + } + > + {number(performance.stats.outcomes.expired)} + + + {number(performance.stats.outcomes.active)} + + + {t('performance.outcomes.voided')} + + {t('performance.tips.voided')} + + + } + > + {number(performance.stats.outcomes.voided)} + + + {t('performance.risk-reward')} + + {t('performance.tips.risk-reward')} + + + } + > + {riskRewardText(performance.stats.riskReward, (range) => + t('performance.risk-reward-range', range), + )} + + + + + )} + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecord.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecord.tsx deleted file mode 100644 index 0cecfd5..0000000 --- a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecord.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { CreatorStats } from '@lumina/island/organisms/creator-stats'; -import { useMemo } from 'react'; -import { useTranslation } from 'react-i18next'; - -import { useTrackRecordPart } from '../../../../../../../../features/prediction'; -import { creatorStatsLabels } from '../../../../../../../../shared/labels'; -import { TrackRecordProgress } from './TrackRecordProgress'; - -/** - * The tab's record (J10-3, J10-3b): «کارنامه شما» with the creator's own numbers once public, or - * «کارنامه عمومی» with how far it is from public, since the channel shows none yet. - */ -export function TrackRecord() { - const { t } = useTranslation('predictions'); - const { t: tContent } = useTranslation('content'); - const labels = useMemo( - () => ({ ...creatorStatsLabels(tContent), title: t('tab.record.title') }), - [t, tContent], - ); - const record = useTrackRecordPart(); - - return record.kind === 'public' ? ( - - ) : ( - - ); -} diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecordProgress.tsx b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecordProgress.tsx deleted file mode 100644 index a320585..0000000 --- a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/components/TrackRecordProgress.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { FlexBox } from '@lumina/island/atoms/flex-box'; -import { Icon } from '@lumina/island/atoms/icon'; -import { Typography } from '@lumina/island/atoms/typography'; -import { Card } from '@lumina/island/molecules/card'; -import { Meter } from '@lumina/island/molecules/meter'; -import { number } from '@lumina/tools/format'; -import { useId } from 'react'; -import { useTranslation } from 'react-i18next'; - -import type { TrackRecordProgressProps } from '../types'; - -/** - * «کارنامه عمومی» below the threshold (J10-3b): when it goes public, the closed predictions so far - * against the required ones, and the days left to a month of activity while there are any. - */ -export function TrackRecordProgress({ - closed, - required, - daysLeft, -}: TrackRecordProgressProps) { - const { t } = useTranslation('predictions'); - const headingId = useId(); - - return ( - - - - {t('tab.record.public-title')} - - - {t('tab.record.threshold', { required: number(required) })} - - - {daysLeft !== null && ( - - - - {t('tab.record.days-left', { n: number(daysLeft) })} - - - )} - - - ); -} diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/types.ts b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/types.ts index eed6095..33f680a 100644 --- a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/types.ts +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/types.ts @@ -18,9 +18,6 @@ export type PredictionSectionProps = { export type SectionCardsProps = PredictionSectionProps; -export type TrackRecordProgressProps = { - closed: number; - required: number; - /** `null` once a month of activity is met. */ - daysLeft: number | null; +export type SignalPerformanceProps = { + layout: 'mobile' | 'desktop'; }; diff --git a/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/utils.ts b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/utils.ts new file mode 100644 index 0000000..35be21e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/predictions/organisms/predictions-tab/utils.ts @@ -0,0 +1,16 @@ +import { ratio } from '@lumina/tools/format'; + +import type { SignalNumbersPayload } from '../../../../../../../features/prediction'; + +type RangeText = (range: { worst: string; best: string }) => string; + +/** «۱ : ۱٫۴ تا ۱ : ۳٫۰», one ratio when the two read the same, or a dash with nothing to read. */ +export function riskRewardText( + riskReward: SignalNumbersPayload['riskReward'], + rangeText: RangeText, +): string { + if (!riskReward) return '—'; + const worst = ratio(1, riskReward.worst); + const best = ratio(1, riskReward.best); + return worst === best ? worst : rangeText({ worst, best }); +} diff --git a/platforms/market/src/features/prediction/entities/prediction-stats/types.ts b/platforms/market/src/features/prediction/entities/prediction-stats/types.ts index f6d1e9e..cc8ac45 100644 --- a/platforms/market/src/features/prediction/entities/prediction-stats/types.ts +++ b/platforms/market/src/features/prediction/entities/prediction-stats/types.ts @@ -1,27 +1,29 @@ import type { PredictionOutcome } from '../../../post'; /** - * content-service `getCreatorPredictionStats`: a creator's track record over their published - * predictions. Below the threshold (10 closed and 30 days since the first prediction) the public - * read answers `public: false` with every number 0 and no trend; the owner's track record always - * carries the real numbers. + * `GET /creators/:id/prediction-stats`: a creator's track record from the last nightly evaluation. + * Below the threshold (10 closed and 30 days since the first signal), or before the first run, it + * answers `public: false` with every number 0 and no trend. */ export type PredictionStatsEntity = { creatorId: string; - /** The record may be shown; absent from the owner's track record. */ + /** The record may be shown. */ public?: boolean; - /** Published predictions, open and closed. */ + /** Published signals, open and closed; voided ones are left out. */ totalPredictions: number; activePredictions: number; - /** Closed: wins + losses + breakeven. */ + /** Closed: wins + losses + breakeven, as those three are named here. */ pastPredictions: number; + /** «رسیده به هدف». */ wins: number; + /** «خورده به حد ضرر». */ losses: number; + /** «پایان مهلت». The API's name stays, though most of these are not a breakeven. */ breakeven: number; /** A percentage with two decimals (`62.86`); 0 before the first close. */ winRate: number; - /** The mean ROI of closed predictions, a percentage with two decimals. */ + /** The mean ROI of closed signals, the stake split across targets; two decimals. */ avgRoiPercent: number; - /** The last 10 closed outcomes, oldest first. */ + /** The last 10 closed outcomes by their return (not the buckets above), oldest first. */ accuracyTrend: PredictionOutcome[]; }; diff --git a/platforms/market/src/features/prediction/entities/signal-stats/index.ts b/platforms/market/src/features/prediction/entities/signal-stats/index.ts new file mode 100644 index 0000000..69b9a84 --- /dev/null +++ b/platforms/market/src/features/prediction/entities/signal-stats/index.ts @@ -0,0 +1 @@ +export type { SignalStatsEntity } from './types'; diff --git a/platforms/market/src/features/prediction/entities/signal-stats/types.ts b/platforms/market/src/features/prediction/entities/signal-stats/types.ts new file mode 100644 index 0000000..9093ad4 --- /dev/null +++ b/platforms/market/src/features/prediction/entities/signal-stats/types.ts @@ -0,0 +1,37 @@ +/** + * `GET /me/signal-stats`: the signed-in analyst's numbers from the last nightly evaluation, the + * same snapshot the channel and the cards read. `status: 'pending'` until the first run, with no + * `stats`. Voided signals count nowhere but `outcomes.voided`. + */ +export type SignalStatsEntity = { + status: 'pending' | 'ready'; + stats?: { + /** target ÷ (target + stop + expired), a percentage with two decimals. */ + winRate: number; + /** A percentage with the stake split equally across each signal's targets. */ + avgRoi: number; + /** Closed and active. */ + total: number; + active: number; + outcomes: { + target: number; + stop: number; + expired: number; + active: number; + voided: number; + }; + /** Reward per unit of risk to the first target; null with no signal to read it from. */ + rrWorstAvg: number | null; + rrBestAvg: number | null; + closedCount: number; + daysActive: number; + isPublic: boolean; + evaluatedAt: string | null; + }; + progress: { + closed: number; + requiredClosed: number; + daysActive: number; + requiredDays: number; + }; +}; diff --git a/platforms/market/src/features/prediction/entities/track-record/index.ts b/platforms/market/src/features/prediction/entities/track-record/index.ts deleted file mode 100644 index 027662e..0000000 --- a/platforms/market/src/features/prediction/entities/track-record/index.ts +++ /dev/null @@ -1 +0,0 @@ -export type { TrackRecordEntity } from './types'; diff --git a/platforms/market/src/features/prediction/entities/track-record/types.ts b/platforms/market/src/features/prediction/entities/track-record/types.ts deleted file mode 100644 index afede87..0000000 --- a/platforms/market/src/features/prediction/entities/track-record/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { PredictionStatsEntity } from '../prediction-stats'; - -/** - * `GET /creators/me/track-record`: the signed-in creator's own record and how far it is from - * going public (`closed >= required` and `daysActive >= requiredDays`, counted from the first - * published prediction). `stats` is always filled for the owner. - */ -export type TrackRecordEntity = { - public: boolean; - closed: number; - required: number; - daysActive: number; - requiredDays: number; - stats: PredictionStatsEntity; -}; diff --git a/platforms/market/src/features/prediction/index.ts b/platforms/market/src/features/prediction/index.ts index a36636a..2eb1302 100644 --- a/platforms/market/src/features/prediction/index.ts +++ b/platforms/market/src/features/prediction/index.ts @@ -51,8 +51,7 @@ export { export type { PredictionListPageModel } from './models/prediction-list'; export { useSymbolPickerPart } from './models/symbol-picker'; export type { SymbolPickerPartModel } from './models/symbol-picker'; -export { useTrackRecordPart } from './models/track-record'; -export type { TrackRecordPartModel } from './models/track-record'; +export { useSignalStatsPart } from './models/signal-stats'; export { MARKET_DATA_ENDPOINTS, marketDataKeys, @@ -77,5 +76,7 @@ export type { OwnPredictionPayload, OwnPredictionsPagePayload, PredictionStatsPayload, - TrackRecordPayload, + SignalNumbersPayload, + SignalProgressPayload, + SignalStatsPayload, } from './repositories/prediction'; diff --git a/platforms/market/src/features/prediction/models/prediction-cache/prediction-cache.ts b/platforms/market/src/features/prediction/models/prediction-cache/prediction-cache.ts index 1711ec9..41ca60b 100644 --- a/platforms/market/src/features/prediction/models/prediction-cache/prediction-cache.ts +++ b/platforms/market/src/features/prediction/models/prediction-cache/prediction-cache.ts @@ -10,7 +10,7 @@ type OwnList = InfiniteData; /** * 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 - * lists, the track record and the public record are read again. + * lists, the analyst's numbers and the public record are read again. */ export function applyClosedPrediction( queryClient: QueryClient, @@ -42,17 +42,17 @@ export function applyClosedPrediction( queryKey: [...predictionKeys.own(), 'preview'], }); void queryClient.invalidateQueries({ - queryKey: predictionKeys.trackRecord(), + queryKey: predictionKeys.signalStats(), }); void queryClient.invalidateQueries({ queryKey: predictionKeys.stats(post.creatorId), }); } -/** A new prediction: the creator's lists and track record are read again. */ +/** A new signal: the creator's lists and numbers are read again. */ export function refreshOwnPredictions(queryClient: QueryClient): void { void queryClient.invalidateQueries({ queryKey: predictionKeys.own() }); void queryClient.invalidateQueries({ - queryKey: predictionKeys.trackRecord(), + queryKey: predictionKeys.signalStats(), }); } diff --git a/platforms/market/src/features/prediction/models/signal-stats/index.ts b/platforms/market/src/features/prediction/models/signal-stats/index.ts new file mode 100644 index 0000000..ae0c99e --- /dev/null +++ b/platforms/market/src/features/prediction/models/signal-stats/index.ts @@ -0,0 +1 @@ +export { useSignalStatsPart } from './use-signal-stats-part'; diff --git a/platforms/market/src/features/prediction/models/signal-stats/use-signal-stats-part.ts b/platforms/market/src/features/prediction/models/signal-stats/use-signal-stats-part.ts new file mode 100644 index 0000000..0a0c0c3 --- /dev/null +++ b/platforms/market/src/features/prediction/models/signal-stats/use-signal-stats-part.ts @@ -0,0 +1,19 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + predictionKeys, + predictionRepository, +} from '../../repositories/prediction'; +import type { SignalStatsPayload } from '../../repositories/prediction'; + +/** + * «عملکرد سیگنال‌ها», shared by داشبورد's سیگنال‌ها and نمای کلی so they read one cached answer: + * `pending` before the first nightly evaluation, when no client shows a number. + */ +export function useSignalStatsPart(): SignalStatsPayload { + const { data } = useSuspenseQuery({ + queryKey: predictionKeys.signalStats(), + queryFn: ({ signal }) => predictionRepository.getSignalStats({ signal }), + }); + return data; +} diff --git a/platforms/market/src/features/prediction/models/track-record/index.ts b/platforms/market/src/features/prediction/models/track-record/index.ts deleted file mode 100644 index ca0479e..0000000 --- a/platforms/market/src/features/prediction/models/track-record/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { useTrackRecordPart } from './use-track-record-part'; -export type { TrackRecordPartModel } from './types'; diff --git a/platforms/market/src/features/prediction/models/track-record/types.ts b/platforms/market/src/features/prediction/models/track-record/types.ts deleted file mode 100644 index 8be856d..0000000 --- a/platforms/market/src/features/prediction/models/track-record/types.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { PredictionStatsPayload } from '../../repositories/prediction'; - -/** «کارنامه شما» once public, else «کارنامه عمومی» with its progress (J10-3, J10-3b). */ -export type TrackRecordPartModel = - | { kind: 'public'; stats: PredictionStatsPayload } - | { - kind: 'progress'; - closed: number; - required: number; - /** Days left to a month of activity; `null` once that part is met. */ - daysLeft: number | null; - }; diff --git a/platforms/market/src/features/prediction/models/track-record/use-track-record-part.ts b/platforms/market/src/features/prediction/models/track-record/use-track-record-part.ts deleted file mode 100644 index e4c225f..0000000 --- a/platforms/market/src/features/prediction/models/track-record/use-track-record-part.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query'; - -import { - predictionKeys, - predictionRepository, -} from '../../repositories/prediction'; -import type { TrackRecordPartModel } from './types'; - -/** - * داشبورد › سیگنال‌ها › 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. - */ -export function useTrackRecordPart(): TrackRecordPartModel { - const { data } = useSuspenseQuery({ - queryKey: predictionKeys.trackRecord(), - queryFn: ({ signal }) => predictionRepository.getTrackRecord({ signal }), - }); - - if (data.isPublic) return { kind: 'public', stats: data.stats }; - const daysLeft = data.requiredDays - data.daysActive; - return { - kind: 'progress', - closed: data.closed, - required: data.required, - daysLeft: daysLeft > 0 ? daysLeft : null, - }; -} diff --git a/platforms/market/src/features/prediction/repositories/prediction/constants.ts b/platforms/market/src/features/prediction/repositories/prediction/constants.ts index 0c843f8..ec9dd7c 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/constants.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/constants.ts @@ -7,7 +7,7 @@ export const PREDICTION_ENDPOINTS = { closeEarly: (postId: string) => `${post(postId)}/close-early`, stats: (creatorId: string) => `/creators/${encodeURIComponent(creatorId)}/prediction-stats`, - trackRecord: '/creators/me/track-record', + signalStats: '/me/signal-stats', own: '/posts/me/predictions', } as const; @@ -56,8 +56,8 @@ export const predictionKeys = { all: ['prediction'] as const, stats: (creatorId: string) => [...predictionKeys.all, 'stats', creatorId] as const, - /** The signed-in creator's own track record and its progress to public. */ - trackRecord: () => [...predictionKeys.all, 'track-record'] as const, + /** The signed-in analyst's numbers from the last nightly evaluation. */ + signalStats: () => [...predictionKeys.all, 'signal-stats'] as const, /** Every list of the creator's own predictions, for invalidation. */ own: () => [...predictionKeys.all, 'own'] as const, /** A first page the داشبورد tab shows. */ diff --git a/platforms/market/src/features/prediction/repositories/prediction/index.ts b/platforms/market/src/features/prediction/repositories/prediction/index.ts index c77ce0c..268526e 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/index.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/index.ts @@ -22,5 +22,7 @@ export type { PredictionFieldCode, PredictionFieldIssue, PredictionStatsPayload, - TrackRecordPayload, + SignalNumbersPayload, + SignalProgressPayload, + SignalStatsPayload, } from './types'; diff --git a/platforms/market/src/features/prediction/repositories/prediction/mappers.ts b/platforms/market/src/features/prediction/repositories/prediction/mappers.ts index 4f539a1..bd64193 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/mappers.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/mappers.ts @@ -8,8 +8,9 @@ import type { OwnPredictionsPageResponseDto, PredictionStatsPayload, PredictionStatsResponseDto, - TrackRecordPayload, - TrackRecordResponseDto, + SignalProgressPayload, + SignalStatsPayload, + SignalStatsResponseDto, } from './types'; export function toPredictionStatsPayload( @@ -31,16 +32,42 @@ export function toPredictionStatsPayload( }; } -export function toTrackRecordPayload( - dto: TrackRecordResponseDto, -): TrackRecordPayload { +/** + * How far from public: `closed` stops at what is required, so it never reads «۱۲ از ۱۰»; + * `daysLeft` is `null` once the month of activity is met. + */ +export function toSignalProgressPayload( + progress: SignalStatsResponseDto['progress'], + isPublic: boolean, +): SignalProgressPayload { + const daysLeft = progress.requiredDays - progress.daysActive; return { - isPublic: dto.public, - closed: dto.closed, - required: dto.required, - daysActive: dto.daysActive, - requiredDays: dto.requiredDays, - stats: toPredictionStatsPayload(dto.stats, dto.public), + isPublic, + closed: Math.min(progress.closed, progress.requiredClosed), + required: progress.requiredClosed, + daysLeft: daysLeft > 0 ? daysLeft : null, + }; +} + +export function toSignalStatsPayload( + dto: SignalStatsResponseDto, +): SignalStatsPayload { + const { stats, progress } = dto; + if (dto.status !== 'ready' || !stats) return { status: 'pending' }; + return { + status: 'ready', + stats: { + winRate: stats.winRate, + avgRoi: stats.avgRoi, + total: stats.total, + active: stats.active, + outcomes: stats.outcomes, + riskReward: + stats.rrWorstAvg != null && stats.rrBestAvg != null + ? { worst: stats.rrWorstAvg, best: stats.rrBestAvg } + : null, + }, + progress: toSignalProgressPayload(progress, stats.isPublic), }; } diff --git a/platforms/market/src/features/prediction/repositories/prediction/prediction.ts b/platforms/market/src/features/prediction/repositories/prediction/prediction.ts index 573e9bd..302420f 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/prediction.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/prediction.ts @@ -6,7 +6,7 @@ import { toCloseQuotePayload, toOwnPredictionsPagePayload, toPredictionStatsPayload, - toTrackRecordPayload, + toSignalStatsPayload, } from './mappers'; import type { ClosePredictionResponseDto, @@ -17,14 +17,14 @@ import type { OwnPredictionsPageResponseDto, PredictionStatsPayload, PredictionStatsResponseDto, - TrackRecordPayload, - TrackRecordResponseDto, + SignalStatsPayload, + SignalStatsResponseDto, } from './types'; /** * Prediction tracking. The prediction itself lives on its post (`PredictionPayload` in the post * feature), published through the post feature with an idempotency key; this closes it early, - * reads the creator's own lists and track record, and the public record. + * reads the creator's own lists and numbers, and the public record. */ export const predictionRepository = { /** @@ -66,15 +66,15 @@ export const predictionRepository = { return toPredictionStatsPayload(response); }, - /** The signed-in creator's own record, always with its numbers, and its progress to public. */ - async getTrackRecord({ + /** The signed-in analyst's numbers from the last nightly evaluation, or `pending` before it. */ + async getSignalStats({ signal, - }: { signal?: AbortSignal } = {}): Promise { - const response = await predictionHttp.get( - PREDICTION_ENDPOINTS.trackRecord, + }: { signal?: AbortSignal } = {}): Promise { + const response = await predictionHttp.get( + PREDICTION_ENDPOINTS.signalStats, { signal }, ); - return toTrackRecordPayload(response); + return toSignalStatsPayload(response); }, /** A page of the creator's own published predictions, with the totals per status. */ diff --git a/platforms/market/src/features/prediction/repositories/prediction/signal-stats-mappers.test.ts b/platforms/market/src/features/prediction/repositories/prediction/signal-stats-mappers.test.ts new file mode 100644 index 0000000..8371eee --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/signal-stats-mappers.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest'; + +import { toSignalProgressPayload, toSignalStatsPayload } from './mappers'; +import type { SignalStatsResponseDto } from './types'; + +const progress = { + closed: 4, + requiredClosed: 10, + daysActive: 12, + requiredDays: 30, +}; +const stats = { + winRate: 60, + avgRoi: -1.5, + total: 12, + active: 2, + outcomes: { target: 6, stop: 3, expired: 1, active: 2, voided: 0 }, + rrWorstAvg: 1.4, + rrBestAvg: 3, + closedCount: 10, + daysActive: 12, + isPublic: false, + evaluatedAt: '2026-11-01T22:30:00.000Z', +}; + +describe('toSignalProgressPayload', () => { + it('counts the days left to a month of activity', () => { + expect(toSignalProgressPayload(progress, false)).toEqual({ + isPublic: false, + closed: 4, + required: 10, + daysLeft: 18, + }); + }); + + it.each([30, 45])('has no days left at %d days', (daysActive) => { + expect( + toSignalProgressPayload({ ...progress, daysActive }, false).daysLeft, + ).toBeNull(); + }); + + it('stops at what is required, so it never reads 12 of 10', () => { + expect( + toSignalProgressPayload({ ...progress, closed: 12 }, false).closed, + ).toBe(10); + }); +}); + +describe('toSignalStatsPayload', () => { + it('is pending with no numbers before the first evaluation', () => { + expect(toSignalStatsPayload({ status: 'pending', progress })).toEqual({ + status: 'pending', + }); + }); + + it('is pending when ready arrives with no stats, never zeros', () => { + expect( + toSignalStatsPayload({ + status: 'ready', + progress, + } as SignalStatsResponseDto), + ).toEqual({ + status: 'pending', + }); + }); + + it('maps the numbers and the record being public', () => { + const answer = toSignalStatsPayload({ + status: 'ready', + stats: { ...stats, isPublic: true }, + progress, + }); + expect(answer).toMatchObject({ + status: 'ready', + stats: { + winRate: 60, + avgRoi: -1.5, + total: 12, + active: 2, + riskReward: { worst: 1.4, best: 3 }, + }, + progress: { isPublic: true }, + }); + }); + + it.each([ + [{ rrWorstAvg: null, rrBestAvg: null }], + [{ rrWorstAvg: 1.4, rrBestAvg: null }], + ])('has no risk to reward for %j', (over) => { + const answer = toSignalStatsPayload({ + status: 'ready', + stats: { ...stats, ...over }, + progress, + }); + expect(answer.status === 'ready' && answer.stats.riskReward).toBeNull(); + }); +}); diff --git a/platforms/market/src/features/prediction/repositories/prediction/types.ts b/platforms/market/src/features/prediction/repositories/prediction/types.ts index b4cfda5..03034a7 100644 --- a/platforms/market/src/features/prediction/repositories/prediction/types.ts +++ b/platforms/market/src/features/prediction/repositories/prediction/types.ts @@ -11,7 +11,7 @@ import type { OwnPredictionsStatus, } from '../../entities/own-predictions'; import type { PredictionStatsEntity } from '../../entities/prediction-stats'; -import type { TrackRecordEntity } from '../../entities/track-record'; +import type { SignalStatsEntity } from '../../entities/signal-stats'; import type { PREDICTION_ERROR_CODES, PREDICTION_FIELD_CODES, @@ -60,31 +60,63 @@ export type PredictionStatsPayload = { isPublic: boolean; /** A percentage: `62.86`. */ winRate: number; - /** A percentage over closed predictions. */ + /** A percentage over closed signals, the stake split across each one's targets. */ avgRoiPercent: number; /** Published, open and closed. */ totalPredictions: number; activePredictions: number; - /** The API's `pastPredictions`: wins + losses + breakeven. */ + /** The API's `pastPredictions`: target + stop + expired. */ closedPredictions: number; + /** Closed at «هدف»; an early or admin close counts here by a profit at close. */ wins: number; + /** Closed at «حد ضرر»; an early or admin close counts here by a loss at close. */ losses: number; + /** «پایان مهلت», not a breakeven; an early or admin close at no gain or loss counts here. */ breakeven: number; - /** The last 10 closed outcomes, oldest first. */ + /** The last 10 closed outcomes by their return, oldest first. */ accuracyTrend: PredictionOutcome[]; }; export type PredictionStatsResponseDto = PredictionStatsEntity; -/** The owner's record and how far it is from going public (J10-3, J10-3b). */ -export type TrackRecordPayload = { +/** How far the analyst's record is from going public. */ +export type SignalProgressPayload = { isPublic: boolean; + /** Closed signals so far, never more than `required`. */ closed: number; required: number; - daysActive: number; - requiredDays: number; - stats: PredictionStatsPayload; + /** Days left to a month of activity; `null` once that part is met. */ + daysLeft: number | null; }; -export type TrackRecordResponseDto = TrackRecordEntity; + +/** The numbers every page shows the same: the channel, نمای کلی and سیگنال‌ها. */ +export type SignalNumbersPayload = { + /** A percentage: `62.86`. */ + winRate: number; + /** A signed percentage. */ + avgRoi: number; + /** Closed and active. */ + total: number; + active: number; + outcomes: { + target: number; + stop: number; + expired: number; + active: number; + voided: number; + }; + /** Averages of reward per unit of risk, lower then higher; `null` with no signal to read. */ + riskReward: { worst: number; best: number } | null; +}; + +/** `pending` before the first nightly evaluation: no number exists to show, not even a zero. */ +export type SignalStatsPayload = + | { status: 'pending' } + | { + status: 'ready'; + stats: SignalNumbersPayload; + progress: SignalProgressPayload; + }; +export type SignalStatsResponseDto = SignalStatsEntity; export type ListOwnPredictionsArgs = { /** `open` by default. */ diff --git a/platforms/market/src/shared/labels/content-labels.tsx b/platforms/market/src/shared/labels/content-labels.tsx index 55276b8..3a7faed 100644 --- a/platforms/market/src/shared/labels/content-labels.tsx +++ b/platforms/market/src/shared/labels/content-labels.tsx @@ -175,6 +175,11 @@ export function creatorStatsLabels(t: ContentT): CreatorStatsLabels { loss: t('stats.outcomes.loss'), breakeven: t('stats.outcomes.breakeven'), }, + splitOutcomes: { + win: t('stats.split-outcomes.win'), + loss: t('stats.split-outcomes.loss'), + breakeven: t('stats.split-outcomes.breakeven'), + }, splitLegend: (count, outcome) => ( <> {count} {outcome} diff --git a/platforms/market/src/shared/labels/creator-stats-labels.test.ts b/platforms/market/src/shared/labels/creator-stats-labels.test.ts new file mode 100644 index 0000000..0e2730d --- /dev/null +++ b/platforms/market/src/shared/labels/creator-stats-labels.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; + +import content from '../locales/fa/content.json'; + +// `wins`, `losses` and `breakeven` now hold «هدف», «حد ضرر» and «پایان مهلت»: the channel's split +// must say so, while the curve still reads each signal's return. +describe('channel stats copy', () => { + it('names the split by how signals ended', () => { + expect(content.stats['split-outcomes']).toEqual({ + win: 'رسیده به هدف', + loss: 'خورده به حد ضرر', + breakeven: 'پایان مهلت', + }); + expect(content.stats['split-sentence']).not.toContain('سربه‌سر'); + }); + + it('keeps the curve on the return at close', () => { + expect(content.stats.outcomes.breakeven).toBe('سربه‌سر'); + }); +}); diff --git a/platforms/market/src/shared/locales/fa/content.json b/platforms/market/src/shared/locales/fa/content.json index 102aa1b..2cdb40e 100644 --- a/platforms/market/src/shared/locales/fa/content.json +++ b/platforms/market/src/shared/locales/fa/content.json @@ -142,7 +142,12 @@ "loss": "ناموفق", "breakeven": "سربه‌سر" }, - "split-sentence": "{{win}} موفق، {{breakeven}} سربه‌سر، {{loss}} ناموفق", + "split-outcomes": { + "win": "رسیده به هدف", + "loss": "خورده به حد ضرر", + "breakeven": "پایان مهلت" + }, + "split-sentence": "{{win}} رسیده به هدف، {{breakeven}} پایان مهلت، {{loss}} خورده به حد ضرر", "avg-roi": "بازدهی میانگین", "total": "کل سیگنال‌ها", "active": "سیگنال‌های فعال", diff --git a/platforms/market/src/shared/locales/fa/predictions.json b/platforms/market/src/shared/locales/fa/predictions.json index 5fea0cf..e94c743 100644 --- a/platforms/market/src/shared/locales/fa/predictions.json +++ b/platforms/market/src/shared/locales/fa/predictions.json @@ -153,21 +153,54 @@ "tab": { "meta-title": "سیگنال‌ها", "loading": "در حال بارگذاری سیگنال‌ها…", - "record": { - "title": "کارنامه شما", - "loading": "در حال بارگذاری کارنامه…", - "error": "کارنامه بارگذاری نشد.", - "public-title": "کارنامه عمومی", - "threshold": "کارنامه عمومی شما پس از {{required}} سیگنال بسته‌شده و یک ماه فعالیت نمایش داده می‌شود.", - "progress": "{{closed}} از {{required}} سیگنال بسته‌شده", - "days-left": "{{n}} روز تا یک ماه فعالیت" - }, "open": "سیگنال‌های باز", "recent-closed": "بسته‌شده‌های اخیر", "all": "همه سیگنال‌ها", "empty": "هنوز سیگنال منتشر نکرده‌اید", "new": "سیگنال جدید" }, + "performance": { + "title": "عملکرد سیگنال‌ها", + "loading": "در حال بارگذاری عملکرد سیگنال‌ها…", + "error": "عملکرد سیگنال‌ها بارگذاری نشد.", + "pending": { + "title": "ارزیابی عملکرد سیگنال‌ها به‌زودی فعال می‌شود.", + "description": "عددها پس از اولین ارزیابی شبانه نمایش داده می‌شوند." + }, + "tiles": { + "win-rate": "نرخ موفقیت", + "avg-roi": "بازدهی میانگین", + "total": "کل سیگنال‌ها", + "active": "سیگنال‌های فعال" + }, + "outcomes-title": "نتیجه سیگنال‌ها", + "outcomes": { + "target": "رسیده به هدف", + "stop": "خورده به حد ضرر", + "expired": "پایان مهلت", + "active": "فعال", + "voided": "باطل‌شده" + }, + "risk-reward": "ریسک به ریوارد (میانگین)", + "risk-reward-range": "{{worst}} تا {{best}}", + "progress": "{{closed}} از {{required}} سیگنال بسته‌شده تا نمایش عمومی", + "days-left": "{{n}} روز تا یک ماه فعالیت", + "public": "کارنامه عمومی شما فعال است", + "tips": { + "win-rate": "سیگنال‌هایی که با پایان مهلت بسته شده‌اند، ناموفق حساب می‌شوند.", + "avg-roi": "بازدهی هر سیگنال با تقسیم مساوی سرمایه بین هدف‌ها محاسبه می‌شود.", + "risk-reward": "بدترین و بهترین حالت: در سیگنال‌های بازه‌ای، ورود در دورترین و نزدیک‌ترین نقطهٔ بازه به هدف.", + "expired": "در نرخ موفقیت، ناموفق حساب می‌شود.", + "voided": "در نرخ موفقیت و بازدهی حساب نمی‌شود." + }, + "tip-labels": { + "win-rate": "توضیح نرخ موفقیت", + "avg-roi": "توضیح بازدهی میانگین", + "risk-reward": "توضیح ریسک به ریوارد", + "expired": "توضیح پایان مهلت", + "voided": "توضیح باطل‌شده" + } + }, "list": { "title": "سیگنال‌ها", "loading": "در حال بارگذاری سیگنال‌ها…",