games_app/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx

572 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import TrendingDownRoundedIcon from '@mui/icons-material/TrendingDownRounded';
import TrendingUpRoundedIcon from '@mui/icons-material/TrendingUpRounded';
import {
Alert,
Box,
Chip,
Pagination,
Paper,
Skeleton,
Stack,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useEffect, useState } from 'react';
import {
PREDICTIONS_PAGE_SIZE,
useMyCandlePredictions,
} from '../hooks/useCandlePredict';
import type { CandleDirection, CandlePredictPrediction, StakeAccountKind } from '../types';
type Props = {
/** Refetch when a new prediction is placed (manual or auto). */
refreshKey?: string | null;
autoPredictionEnabled?: boolean;
roundStatus?: string;
intervalMinutes?: number;
};
const SHORT_COLOR = '#EF5350';
const LONG_COLOR = '#4CAF50';
const MULTI_ACCENT = '#5EB2D6';
function isMultiPrediction(p: CandlePredictPrediction): boolean {
return (
p.predictionMode === 'multi_candle' ||
((p.sequenceDirections?.length ?? 0) > 1 && (p.level ?? 0) > 1)
);
}
function multiCandleCount(p: CandlePredictPrediction): number {
return p.sequenceDirections?.length ?? p.level ?? 0;
}
function statusColor(status: CandlePredictPrediction['status']): string {
switch (status) {
case 'won':
return LONG_COLOR;
case 'lost':
return SHORT_COLOR;
case 'refunded':
return '#FFB74D';
case 'in_progress':
return '#29B6F6';
default:
return 'rgba(255,255,255,0.72)';
}
}
function StatusLabel({ status }: { status: CandlePredictPrediction['status'] }) {
return (
<Typography component="span" sx={{ fontWeight: 700, color: statusColor(status) }}>
{formatStatus(status)}
</Typography>
);
}
function formatStatus(status: CandlePredictPrediction['status']): string {
switch (status) {
case 'pending':
return 'Pending';
case 'in_progress':
return 'In progress';
case 'won':
return 'Won';
case 'lost':
return 'Lost';
case 'refunded':
return 'Refunded';
default:
return status;
}
}
function formatStakeAccount(kind: StakeAccountKind): string {
switch (kind) {
case 'bonus':
return 'Bonus';
case 'test':
return 'Test';
default:
return 'Main';
}
}
function stakeAccountChipColor(kind: StakeAccountKind): 'default' | 'secondary' | 'info' {
if (kind === 'bonus') return 'secondary';
if (kind === 'test') return 'info';
return 'default';
}
function formatTime(date: Date): string {
return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
}
function formatCandlePeriod(prediction: CandlePredictPrediction): {
range: string;
placedAt: string;
detail?: string;
} {
const placedAt = formatTime(new Date(prediction.createdAt));
if (isMultiPrediction(prediction)) {
const count = multiCandleCount(prediction);
const anchorMs =
prediction.anchorCandleOpenMs ??
prediction.candleOpenMs ??
prediction.currentCandleOpenMs;
if (anchorMs != null && count > 0) {
const open = new Date(anchorMs);
const close = new Date(
anchorMs + count * prediction.intervalMinutes * 60 * 1000
);
const today = new Date();
const showDate =
open.toDateString() !== today.toDateString() ||
close.toDateString() !== today.toDateString();
const dateLabel = showDate
? `${open.toLocaleDateString(undefined, { day: '2-digit', month: 'short' })} · `
: '';
return {
range: `${dateLabel}${formatTime(open)} – ${formatTime(close)}`,
placedAt: `Placed ${placedAt}`,
detail: `${count} consecutive candles · ${prediction.intervalMinutes}m each`,
};
}
return {
range: `Multi · ${count} × ${prediction.intervalMinutes}m`,
placedAt: `Placed ${placedAt}`,
};
}
if (prediction.candleOpenMs == null) {
return {
range: `${prediction.intervalMinutes}m`,
placedAt: `Placed ${placedAt}`,
};
}
const open = new Date(prediction.candleOpenMs);
const close = new Date(
prediction.candleCloseMs ?? prediction.candleOpenMs + prediction.intervalMinutes * 60 * 1000
);
const today = new Date();
const showDate =
open.toDateString() !== today.toDateString() || close.toDateString() !== today.toDateString();
const dateLabel = showDate
? `${open.toLocaleDateString(undefined, { day: '2-digit', month: 'short' })} · `
: '';
return {
range: `${dateLabel}${formatTime(open)} – ${formatTime(close)}`,
placedAt: `Placed ${placedAt}`,
};
}
function multiProgressDetail(p: CandlePredictPrediction): string | null {
if (!isMultiPrediction(p)) return null;
const total = multiCandleCount(p);
if (total <= 0) return null;
const step = p.sequenceStep ?? 0;
if (p.status === 'lost') {
return `Failed on candle ${step + 1} of ${total}`;
}
if (p.status === 'won') {
return `All ${total} candles validated`;
}
if (p.status === 'in_progress' || p.status === 'pending') {
return `Validating candle ${step + 1} of ${total}`;
}
if (p.status === 'refunded') {
return `Sequence refunded (${total} candles)`;
}
return null;
}
function ModeChip({ prediction }: { prediction: CandlePredictPrediction }) {
if (isMultiPrediction(prediction)) {
const level = prediction.level ?? multiCandleCount(prediction);
return (
<Chip
label={`Multi · L${level}`}
size="small"
sx={{
fontWeight: 800,
fontSize: 11,
bgcolor: `${MULTI_ACCENT}22`,
color: MULTI_ACCENT,
border: `1px solid ${MULTI_ACCENT}55`,
}}
/>
);
}
return (
<Stack direction="row" spacing={0.5} useFlexGap sx={{ flexWrap: 'wrap' }}>
<Chip
label="Single"
size="small"
variant="outlined"
sx={{ fontWeight: 800, fontSize: 11 }}
/>
{prediction.isAuto && (
<Chip label="Auto" size="small" color="warning" sx={{ fontWeight: 700, fontSize: 11 }} />
)}
</Stack>
);
}
function DirectionChip({ direction }: { direction: CandleDirection }) {
const isShort = direction === 'short';
const color = isShort ? SHORT_COLOR : LONG_COLOR;
return (
<Chip
size="small"
icon={
isShort ? (
<TrendingDownRoundedIcon sx={{ color: `${color} !important` }} />
) : (
<TrendingUpRoundedIcon sx={{ color: `${color} !important` }} />
)
}
label={isShort ? 'Short' : 'Long'}
sx={{
fontWeight: 800,
fontSize: 11,
color,
borderColor: `${color}66`,
bgcolor: `${color}14`,
}}
variant="outlined"
/>
);
}
function DirectionCell({ direction }: { direction: CandlePredictPrediction['direction'] }) {
const isShort = direction === 'short';
const color = isShort ? SHORT_COLOR : LONG_COLOR;
return (
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center', color, fontWeight: 800 }}>
{isShort ? (
<TrendingDownRoundedIcon fontSize="small" sx={{ color }} />
) : (
<TrendingUpRoundedIcon fontSize="small" sx={{ color }} />
)}
<span>{isShort ? 'Short' : 'Long'}</span>
</Stack>
);
}
function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction }) {
const sequence = prediction.sequenceDirections ?? [];
const step = prediction.sequenceStep ?? 0;
if (!sequence.length) {
return <DirectionCell direction={prediction.direction} />;
}
const markerForIndex = (i: number): { label: string; color: 'success' | 'error' | 'warning' | 'default' } => {
if (prediction.status === 'won') {
return { label: '✓', color: 'success' };
}
if (prediction.status === 'lost') {
if (i < step) return { label: '✓', color: 'success' };
if (i === step) return { label: '✗', color: 'error' };
return { label: `${i + 1}`, color: 'default' };
}
if (prediction.status === 'in_progress' || prediction.status === 'pending') {
if (i < step) return { label: '✓', color: 'success' };
if (i === step) return { label: `${i + 1}`, color: 'warning' };
return { label: `${i + 1}`, color: 'default' };
}
return { label: `${i + 1}`, color: 'default' };
};
return (
<Stack spacing={0.75}>
<Stack direction="row" spacing={0.5} useFlexGap sx={{ flexWrap: 'wrap', alignItems: 'center' }}>
{sequence.map((dir, i) => {
const marker = markerForIndex(i);
return (
<Stack key={i} direction="row" spacing={0.25} sx={{ alignItems: 'center' }}>
<Typography variant="caption" sx={{ opacity: 0.55, fontWeight: 700, minWidth: 14 }}>
{i + 1}.
</Typography>
<DirectionChip direction={dir} />
<Chip
size="small"
label={marker.label}
color={marker.color === 'default' ? undefined : marker.color}
variant={marker.color === 'default' ? 'outlined' : 'filled'}
sx={{ height: 20, minWidth: 24, fontSize: 11, fontWeight: 800 }}
/>
</Stack>
);
})}
</Stack>
{multiProgressDetail(prediction) && (
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 600 }}>
{multiProgressDetail(prediction)}
</Typography>
)}
</Stack>
);
}
function PredictionCell({ prediction }: { prediction: CandlePredictPrediction }) {
if (isMultiPrediction(prediction)) {
return <MultiSequenceRow prediction={prediction} />;
}
return <DirectionCell direction={prediction.direction} />;
}
/** Paginated list of the user's latest Candle Predict predictions. */
export function RecentPredictionsPanel({
refreshKey,
autoPredictionEnabled,
roundStatus,
intervalMinutes,
}: Props) {
const theme = useTheme();
const isCompact = useMediaQuery(theme.breakpoints.down('md'));
const [page, setPage] = useState(1);
const predictionsQ = useMyCandlePredictions(page, {
autoEnabled: autoPredictionEnabled,
roundStatus,
intervalMinutes,
});
useEffect(() => {
void predictionsQ.refetch();
}, [refreshKey]);
useEffect(() => {
const totalPages = predictionsQ.data?.totalPages ?? 1;
if (page > totalPages) {
setPage(totalPages);
}
}, [predictionsQ.data?.totalPages, page]);
const items = predictionsQ.data?.items ?? [];
const total = predictionsQ.data?.total ?? 0;
return (
<Paper sx={{ p: 2, borderRadius: 3, overflowX: 'auto' }}>
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={1}
sx={{ alignItems: { sm: 'center' }, justifyContent: 'space-between', mb: 1.5 }}
>
<Typography variant="h6" sx={{ fontWeight: 900 }}>
Recent predictions
</Typography>
<Typography variant="caption" sx={{ opacity: 0.65 }}>
{total} total · {PREDICTIONS_PAGE_SIZE} per page
</Typography>
</Stack>
{predictionsQ.isLoading ? (
<Skeleton variant="rounded" height={220} />
) : isCompact ? (
<>
<Stack spacing={1.25}>
{items.map((p) => {
const period = formatCandlePeriod(p);
const progressDetail = multiProgressDetail(p);
return (
<Paper
key={p.id}
variant="outlined"
sx={{
p: 1.5,
borderRadius: 2,
borderColor: isMultiPrediction(p)
? `${MULTI_ACCENT}33`
: 'rgba(255,255,255,0.08)',
}}
>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap', mb: 1 }}>
<ModeChip prediction={p} />
<Chip
label={formatStakeAccount(p.stakeAccountKind ?? 'main')}
size="small"
color={stakeAccountChipColor(p.stakeAccountKind ?? 'main')}
variant={p.stakeAccountKind === 'main' ? 'outlined' : 'filled'}
sx={{ fontWeight: 700, fontSize: 11 }}
/>
<Chip
label={<StatusLabel status={p.status} />}
size="small"
variant="outlined"
sx={{
fontWeight: 700,
borderColor: `${statusColor(p.status)}55`,
bgcolor: `${statusColor(p.status)}14`,
}}
/>
</Stack>
<Box sx={{ mb: 1 }}>
<PredictionCell prediction={p} />
</Box>
<Typography variant="body2" sx={{ fontWeight: 600 }}>
{period.range}
</Typography>
{period.detail && (
<Typography variant="caption" sx={{ opacity: 0.6, display: 'block' }}>
{period.detail}
</Typography>
)}
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block', mt: 0.25 }}>
{period.placedAt} · Stake {p.stakeDisplay} · Payout{' '}
{p.payoutDisplay > 0 ? p.payoutDisplay : '—'}
</Typography>
{progressDetail && !isMultiPrediction(p) && (
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 600, display: 'block' }}>
{progressDetail}
</Typography>
)}
</Paper>
);
})}
{!items.length && (
<Typography sx={{ opacity: 0.6, py: 2, textAlign: 'center' }}>No predictions yet</Typography>
)}
</Stack>
{total > PREDICTIONS_PAGE_SIZE && (
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
<Pagination
count={predictionsQ.data?.totalPages ?? 1}
page={page}
onChange={(_, value) => setPage(value)}
color="primary"
size="small"
/>
</Box>
)}
</>
) : (
<>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Mode</TableCell>
<TableCell>Prediction</TableCell>
<TableCell>Period</TableCell>
<TableCell>Stake</TableCell>
<TableCell>Account</TableCell>
<TableCell>Status</TableCell>
<TableCell>Payout</TableCell>
</TableRow>
</TableHead>
<TableBody>
{items.map((p) => {
const period = formatCandlePeriod(p);
const progressDetail = multiProgressDetail(p);
return (
<TableRow
key={p.id}
sx={
isMultiPrediction(p)
? { '& td': { borderBottomColor: `${MULTI_ACCENT}22` } }
: undefined
}
>
<TableCell>
<ModeChip prediction={p} />
</TableCell>
<TableCell sx={{ minWidth: 220 }}>
<PredictionCell prediction={p} />
</TableCell>
<TableCell>
<Stack spacing={0.25}>
<Stack direction="row" spacing={0.75} sx={{ alignItems: 'center' }}>
<Typography variant="body2" sx={{ fontWeight: 600 }}>
{period.range}
</Typography>
<Chip
label={`${p.intervalMinutes}m`}
size="small"
variant="outlined"
sx={{ height: 20, fontSize: 11 }}
/>
</Stack>
{period.detail && (
<Typography variant="caption" sx={{ opacity: 0.6 }}>
{period.detail}
</Typography>
)}
<Typography variant="caption" sx={{ opacity: 0.6 }}>
{period.placedAt}
</Typography>
</Stack>
</TableCell>
<TableCell>{p.stakeDisplay}</TableCell>
<TableCell>
<Chip
label={formatStakeAccount(p.stakeAccountKind ?? 'main')}
size="small"
color={stakeAccountChipColor(p.stakeAccountKind ?? 'main')}
variant={p.stakeAccountKind === 'main' ? 'outlined' : 'filled'}
sx={{ fontWeight: 700, fontSize: 11 }}
/>
</TableCell>
<TableCell>
<Stack spacing={0.25}>
<StatusLabel status={p.status} />
{progressDetail && (
<Typography variant="caption" sx={{ opacity: 0.65, fontWeight: 600 }}>
{progressDetail}
</Typography>
)}
</Stack>
</TableCell>
<TableCell>{p.payoutDisplay > 0 ? p.payoutDisplay : '—'}</TableCell>
</TableRow>
);
})}
{!items.length && (
<TableRow>
<TableCell colSpan={7} sx={{ opacity: 0.6 }}>
No predictions yet
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{total > PREDICTIONS_PAGE_SIZE && (
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
<Pagination
count={predictionsQ.data?.totalPages ?? 1}
page={page}
onChange={(_, value) => setPage(value)}
color="primary"
size="small"
/>
</Box>
)}
</>
)}
{predictionsQ.isError && (
<Alert severity="warning" sx={{ mt: 1.5 }}>
Could not load predictions. Try refreshing the page.
</Alert>
)}
</Paper>
);
}