feat/pre-launch-4-overview #1
|
|
@ -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 `<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` |
|
||||
| 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 `<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` |
|
||||
|
||||
## 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.
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ export function OutcomeSplit({ counts, labels }: OutcomeSplitProps) {
|
|||
>
|
||||
{formatted[outcome]}
|
||||
</Typography>,
|
||||
labels.outcomes[outcome],
|
||||
labels.splitOutcomes[outcome],
|
||||
)}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
|
|
|
|||
|
|
@ -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<TrendOutcome, string>;
|
||||
/** One legend entry, `count` already bold: `(count, outcome) => <>{count} {outcome}</>` → «۲۲ موفق». */
|
||||
/** How signals ended in the split's legend: «رسیده به هدف» (`wins`), «خورده به حد ضرر» (`losses`), «پایان مهلت» (`breakeven`). */
|
||||
splitOutcomes: Record<TrendOutcome, string>;
|
||||
/** 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<TrendOutcome, string>) => string;
|
||||
/** «بازدهی میانگین». */
|
||||
avgRoi: ReactNode;
|
||||
|
|
@ -112,7 +117,7 @@ export type OutcomeSplitProps = {
|
|||
counts: Record<TrendOutcome, number>;
|
||||
labels: Pick<
|
||||
CreatorStatsLabels,
|
||||
'outcomes' | 'splitLegend' | 'splitSentence'
|
||||
'splitOutcomes' | 'splitLegend' | 'splitSentence'
|
||||
>;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<FlexBox alignItems="items-center" className="gap-1.5 text-success-text">
|
||||
<Icon name="check" size={16} className="flex-none" />
|
||||
<Typography tag="span" variant="body-sm" color="inherit">
|
||||
{t('performance.public')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
<Meter
|
||||
value={progress.closed}
|
||||
max={progress.required}
|
||||
label={t('performance.progress', {
|
||||
closed: number(progress.closed),
|
||||
required: number(progress.required),
|
||||
})}
|
||||
/>
|
||||
{progress.daysLeft !== null && (
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
className="gap-1.5 text-text-secondary"
|
||||
>
|
||||
<Icon name="calendar" size={16} className="flex-none" />
|
||||
<Typography tag="span" variant="caption" color="inherit">
|
||||
{t('performance.days-left', { n: number(progress.daysLeft) })}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { SignalProgress } from './SignalProgress';
|
||||
export type { SignalProgressProps } from './types';
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import type { SignalProgressPayload } from '../../../../../../features/prediction';
|
||||
|
||||
export type SignalProgressProps = {
|
||||
progress: SignalProgressPayload;
|
||||
};
|
||||
|
|
@ -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 (
|
||||
<GridBox
|
||||
cols={layout === 'desktop' ? 'grid-cols-4' : 'grid-cols-2'}
|
||||
gap="gap-2"
|
||||
>
|
||||
<StatTile
|
||||
tone="soft"
|
||||
label={
|
||||
<>
|
||||
{t('performance.tiles.win-rate')}
|
||||
{withTips && (
|
||||
<InfoTip label={t('performance.tip-labels.win-rate')}>
|
||||
{t('performance.tips.win-rate')}
|
||||
</InfoTip>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
value={iso(percent(stats.winRate))}
|
||||
/>
|
||||
<StatTile
|
||||
tone="soft"
|
||||
label={
|
||||
<>
|
||||
{t('performance.tiles.avg-roi')}
|
||||
{withTips && (
|
||||
<InfoTip label={t('performance.tip-labels.avg-roi')}>
|
||||
{t('performance.tips.avg-roi')}
|
||||
</InfoTip>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
value={
|
||||
<Element tag="bdi" dir="ltr">
|
||||
{signedPercent(stats.avgRoi)}
|
||||
</Element>
|
||||
}
|
||||
valueTone={
|
||||
stats.avgRoi > 0 ? 'success' : stats.avgRoi < 0 ? 'danger' : 'default'
|
||||
}
|
||||
/>
|
||||
<StatTile
|
||||
tone="soft"
|
||||
label={t('performance.tiles.total')}
|
||||
value={number(stats.total)}
|
||||
/>
|
||||
<StatTile
|
||||
tone="soft"
|
||||
label={t('performance.tiles.active')}
|
||||
value={number(stats.active)}
|
||||
/>
|
||||
</GridBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { SignalStatTiles } from './SignalStatTiles';
|
||||
export type { SignalStatTilesProps } from './types';
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import type { SignalNumbersPayload } from '../../../../../../features/prediction';
|
||||
|
||||
export type SignalStatTilesProps = {
|
||||
stats: Pick<SignalNumbersPayload, 'winRate' | 'avgRoi' | 'total' | 'active'>;
|
||||
/** mobile: two by two; desktop: one row. */
|
||||
layout: 'mobile' | 'desktop';
|
||||
/** The ⓘ beside the rate and the return: only on سیگنالها, never on نمای کلی. */
|
||||
withTips?: boolean;
|
||||
};
|
||||
|
|
@ -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 (
|
||||
<StateMessage
|
||||
size="compact"
|
||||
icon="clock"
|
||||
tone="brand"
|
||||
title={t('performance.pending.title')}
|
||||
description={t('performance.pending.description')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { SignalStatsPending } from './SignalStatsPending';
|
||||
|
|
@ -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 (
|
||||
<FlexBox direction="flex-col" gap="gap-6">
|
||||
<PartBoundary
|
||||
name="track-record"
|
||||
description={t('tab.record.error')}
|
||||
name="signal-performance"
|
||||
description={t('performance.error')}
|
||||
framed
|
||||
>
|
||||
<Suspense
|
||||
fallback={
|
||||
<SkeletonPreset preset="stats" label={t('tab.record.loading')} />
|
||||
<SkeletonPreset preset="stats" label={t('performance.loading')} />
|
||||
}
|
||||
>
|
||||
<TrackRecord />
|
||||
<SignalPerformance layout={layout} />
|
||||
</Suspense>
|
||||
</PartBoundary>
|
||||
<PredictionSection section="open" layout={layout} />
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<string, string> = {}) => {
|
||||
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<Extract<SignalStatsPayload, { status: 'ready' }>> = {},
|
||||
) =>
|
||||
({
|
||||
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(<SignalPerformance layout="mobile" />);
|
||||
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(<SignalPerformance layout="mobile" />);
|
||||
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(<SignalPerformance layout="desktop" />);
|
||||
expect(screen.getByText('کارنامه عمومی شما فعال است')).toBeTruthy();
|
||||
expect(screen.queryByText(/تا نمایش عمومی/)).toBeNull();
|
||||
});
|
||||
|
||||
it('lists every outcome', () => {
|
||||
render(<SignalPerformance layout="mobile" />);
|
||||
for (const label of [
|
||||
'رسیده به هدف',
|
||||
'خورده به حد ضرر',
|
||||
'پایان مهلت',
|
||||
'فعال',
|
||||
'باطلشده',
|
||||
]) {
|
||||
expect(screen.getByText(label)).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows risk to reward as worst to best', () => {
|
||||
render(<SignalPerformance layout="mobile" />);
|
||||
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<SignalStatsPayload, { status: 'ready' }>;
|
||||
answer = { ...base, stats: { ...base.stats, riskReward: null } };
|
||||
render(<SignalPerformance layout="mobile" />);
|
||||
expect(screen.getByText('—')).toBeTruthy();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'توضیح نرخ موفقیت',
|
||||
'سیگنالهایی که با پایان مهلت بسته شدهاند، ناموفق حساب میشوند.',
|
||||
],
|
||||
[
|
||||
'توضیح بازدهی میانگین',
|
||||
'بازدهی هر سیگنال با تقسیم مساوی سرمایه بین هدفها محاسبه میشود.',
|
||||
],
|
||||
[
|
||||
'توضیح ریسک به ریوارد',
|
||||
'بدترین و بهترین حالت: در سیگنالهای بازهای، ورود در دورترین و نزدیکترین نقطهٔ بازه به هدف.',
|
||||
],
|
||||
['توضیح پایان مهلت', 'در نرخ موفقیت، ناموفق حساب میشود.'],
|
||||
['توضیح باطلشده', 'در نرخ موفقیت و بازدهی حساب نمیشود.'],
|
||||
])('%s explains itself', (label, text) => {
|
||||
render(<SignalPerformance layout="mobile" />);
|
||||
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(<SignalStatTiles stats={stats} layout="mobile" />);
|
||||
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(
|
||||
<SignalStatTiles stats={{ ...stats, avgRoi }} layout="desktop" />,
|
||||
);
|
||||
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(
|
||||
<SignalProgress
|
||||
progress={{ isPublic: false, closed: 9, required: 10, daysLeft: null }}
|
||||
/>,
|
||||
);
|
||||
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('—');
|
||||
});
|
||||
});
|
||||
|
|
@ -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 (
|
||||
<Card tag="section" padding="md" aria-labelledby={headingId}>
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('performance.title')}
|
||||
</Typography>
|
||||
{performance.status === 'pending' ? (
|
||||
<SignalStatsPending />
|
||||
) : (
|
||||
<>
|
||||
<SignalStatTiles
|
||||
stats={performance.stats}
|
||||
layout={layout}
|
||||
withTips
|
||||
/>
|
||||
<KeyValue aria-label={t('performance.outcomes-title')}>
|
||||
<DetailRow label={t('performance.outcomes.target')}>
|
||||
{number(performance.stats.outcomes.target)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('performance.outcomes.stop')}>
|
||||
{number(performance.stats.outcomes.stop)}
|
||||
</DetailRow>
|
||||
<DetailRow
|
||||
label={
|
||||
<>
|
||||
{t('performance.outcomes.expired')}
|
||||
<InfoTip label={t('performance.tip-labels.expired')}>
|
||||
{t('performance.tips.expired')}
|
||||
</InfoTip>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{number(performance.stats.outcomes.expired)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('performance.outcomes.active')}>
|
||||
{number(performance.stats.outcomes.active)}
|
||||
</DetailRow>
|
||||
<DetailRow
|
||||
label={
|
||||
<>
|
||||
{t('performance.outcomes.voided')}
|
||||
<InfoTip label={t('performance.tip-labels.voided')}>
|
||||
{t('performance.tips.voided')}
|
||||
</InfoTip>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{number(performance.stats.outcomes.voided)}
|
||||
</DetailRow>
|
||||
<DetailRow
|
||||
strong
|
||||
label={
|
||||
<>
|
||||
{t('performance.risk-reward')}
|
||||
<InfoTip
|
||||
label={t('performance.tip-labels.risk-reward')}
|
||||
placement="above"
|
||||
>
|
||||
{t('performance.tips.risk-reward')}
|
||||
</InfoTip>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{riskRewardText(performance.stats.riskReward, (range) =>
|
||||
t('performance.risk-reward-range', range),
|
||||
)}
|
||||
</DetailRow>
|
||||
</KeyValue>
|
||||
<SignalProgress progress={performance.progress} />
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -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' ? (
|
||||
<CreatorStats
|
||||
stats={record.stats}
|
||||
trendOrder="oldest-first"
|
||||
labels={labels}
|
||||
/>
|
||||
) : (
|
||||
<TrackRecordProgress
|
||||
closed={record.closed}
|
||||
required={record.required}
|
||||
daysLeft={record.daysLeft}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<Card tag="section" padding="md" aria-labelledby={headingId}>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('tab.record.public-title')}
|
||||
</Typography>
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('tab.record.threshold', { required: number(required) })}
|
||||
</Typography>
|
||||
<Meter
|
||||
value={Math.min(closed, required)}
|
||||
max={required}
|
||||
label={t('tab.record.progress', {
|
||||
closed: number(closed),
|
||||
required: number(required),
|
||||
})}
|
||||
/>
|
||||
{daysLeft !== null && (
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
className="gap-1.5 text-text-secondary"
|
||||
>
|
||||
<Icon name="calendar" size={16} className="flex-none" />
|
||||
<Typography tag="span" variant="caption" color="inherit">
|
||||
{t('tab.record.days-left', { n: number(daysLeft) })}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -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';
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
}
|
||||
|
|
@ -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[];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
export type { SignalStatsEntity } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
};
|
||||
|
|
@ -1 +0,0 @@
|
|||
export type { TrackRecordEntity } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -10,7 +10,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
|
||||
* 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(),
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
export { useSignalStatsPart } from './use-signal-stats-part';
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
export { useTrackRecordPart } from './use-track-record-part';
|
||||
export type { TrackRecordPartModel } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -22,5 +22,7 @@ export type {
|
|||
PredictionFieldCode,
|
||||
PredictionFieldIssue,
|
||||
PredictionStatsPayload,
|
||||
TrackRecordPayload,
|
||||
SignalNumbersPayload,
|
||||
SignalProgressPayload,
|
||||
SignalStatsPayload,
|
||||
} from './types';
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<TrackRecordPayload> {
|
||||
const response = await predictionHttp.get<TrackRecordResponseDto>(
|
||||
PREDICTION_ENDPOINTS.trackRecord,
|
||||
}: { signal?: AbortSignal } = {}): Promise<SignalStatsPayload> {
|
||||
const response = await predictionHttp.get<SignalStatsResponseDto>(
|
||||
PREDICTION_ENDPOINTS.signalStats,
|
||||
{ signal },
|
||||
);
|
||||
return toTrackRecordPayload(response);
|
||||
return toSignalStatsPayload(response);
|
||||
},
|
||||
|
||||
/** A page of the creator's own published predictions, with the totals per status. */
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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('سربهسر');
|
||||
});
|
||||
});
|
||||
|
|
@ -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": "سیگنالهای فعال",
|
||||
|
|
|
|||
|
|
@ -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": "در حال بارگذاری سیگنالها…",
|
||||
|
|
|
|||
Loading…
Reference in New Issue