games_app/prediqo_web/src/features/wallet/components/TestWalletCard.tsx

237 lines
7.8 KiB
TypeScript

/**
* Test USDT wallet — play-money for discovering the platform without real funds.
*/
import {
Alert,
Box,
Button,
Card,
CardContent,
Chip,
Stack,
Typography,
} from '@mui/material';
import ScienceRoundedIcon from '@mui/icons-material/ScienceRounded';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { api } from '../../../shared/services/api';
import { apiErrorMessage } from '../../../shared/utils/apiError';
import type { BalanceEntry } from '../types';
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
import { formatBalance, rawToHuman } from '../utils/walletFormat';
type TestPredictionLimit = {
enabled: boolean;
maxPerWindow: number;
windowHours: number;
usedInWindow: number;
remaining: number;
resetsAt: string | null;
canPredict: boolean;
reason: string | null;
};
type TestWalletStatus = {
enabled: boolean;
balanceRaw: string;
walletTypeId: number;
walletCode: string | null;
decimals: number;
creditAmountRaw: string;
maxRequests: number;
requestsUsed: number;
canRequest: boolean;
reason: string | null;
cooldownEndsAt: string | null;
predictionLimit?: TestPredictionLimit;
};
function formatWaitUntil(resetsAt: string | null, windowHours: number): string {
if (resetsAt) {
const ms = Math.max(0, new Date(resetsAt).getTime() - Date.now());
const totalMinutes = Math.max(1, Math.ceil(ms / 60_000));
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0 && days === 0) parts.push(`${minutes}m`);
if (parts.length === 0) parts.push('1m');
return parts.join(' ');
}
return `${windowHours}h`;
}
type TestWalletCardProps = {
balance: BalanceEntry;
onSuccess?: (message: string) => void;
onError?: (message: string) => void;
};
export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardProps) {
const { t } = useTranslation();
const qc = useQueryClient();
const [requesting, setRequesting] = useState(false);
const statusQ = useQuery({
queryKey: ['test-wallet-status'],
queryFn: async () => {
const res = await api.get<TestWalletStatus>('/api/v1/test-wallet');
return res.data;
},
});
const testRaw = balance.testAvailable ?? statusQ.data?.balanceRaw ?? '0';
const hasTest = BigInt(testRaw) > 0n;
const status = statusQ.data;
const creditHuman = status ? rawToHuman(status.creditAmountRaw, status.decimals) : '—';
const requestCredits = async () => {
setRequesting(true);
try {
const res = await api.post<{ message: string }>('/api/v1/test-wallet/request-credits');
await Promise.all([
qc.invalidateQueries({ queryKey: ['wallet-balances'] }),
qc.invalidateQueries({ queryKey: ['test-wallet-status'] }),
]);
onSuccess?.(res.data.message);
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError?.(apiErrorMessage(err, t('auth.requestFailed')));
} finally {
setRequesting(false);
}
};
return (
<Card
sx={{
borderRadius: 3,
height: '100%',
border: '1px solid rgba(76,175,80,0.35)',
background:
'linear-gradient(160deg, rgba(76,175,80,0.12) 0%, rgba(18,23,36,0.95) 55%)',
}}
>
<CardContent sx={{ p: 2.5 }}>
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center' }}>
<Box
sx={{
width: 44,
height: 44,
borderRadius: '50%',
display: 'grid',
placeItems: 'center',
background: 'linear-gradient(135deg, #4CAF50, #2E7D32)',
color: '#fff',
boxShadow: '0 4px 14px rgba(76,175,80,0.45)',
}}
>
<ScienceRoundedIcon fontSize="small" />
</Box>
<Box sx={{ flex: 1 }}>
<Typography sx={{ fontWeight: 800 }}>{t('wallet.testCard.title')}</Typography>
<Typography variant="body2" sx={{ opacity: 0.65 }}>
{t('wallet.testCard.subtitle')}
</Typography>
<Chip
size="small"
color="success"
variant="outlined"
label={hasTest ? t('common.fundsAvailable') : t('common.empty')}
sx={{ mt: 0.75, fontWeight: 700 }}
/>
</Box>
</Stack>
<Typography variant="caption" sx={{ opacity: 0.6, textTransform: 'uppercase', mt: 2, display: 'block' }}>
{t('wallet.testCard.balance')}
</Typography>
<Typography
variant="h5"
sx={{ fontWeight: 900, color: hasTest ? 'success.light' : 'text.secondary' }}
>
{formatBalance(testRaw, balance.walletType.decimals, USDT_WALLET_CODE)}
</Typography>
<Typography variant="body2" sx={{ opacity: 0.7, mt: 1 }}>
{t('wallet.testCard.hint')}
</Typography>
{status?.enabled ? (
<Stack spacing={1} sx={{ mt: 2 }}>
<Button
size="small"
variant="contained"
color="success"
disabled={!status.canRequest || requesting}
onClick={requestCredits}
>
{requesting
? t('wallet.testCard.crediting')
: t('wallet.testCard.requestCredits', { amount: creditHuman })}
</Button>
{status.maxRequests > 0 && (
<Typography variant="caption" sx={{ opacity: 0.65 }}>
{t('wallet.testCard.requestsUsed', {
used: status.requestsUsed,
max: status.maxRequests,
})}
</Typography>
)}
{!status.canRequest && status.reason && (
<Alert severity="info" variant="outlined" sx={{ borderRadius: 2 }}>
{status.reason}
{status.cooldownEndsAt && (
<>
{' '}
{t('wallet.testCard.availableAfter', {
date: new Date(status.cooldownEndsAt).toLocaleString(),
})}
</>
)}
</Alert>
)}
</Stack>
) : (
<Alert severity="warning" sx={{ mt: 2, borderRadius: 2 }} variant="outlined">
{t('wallet.testCard.disabled')}
</Alert>
)}
{status?.predictionLimit?.enabled && status.predictionLimit.maxPerWindow > 0 && (
<Stack spacing={1} sx={{ mt: 2 }}>
<Typography variant="caption" sx={{ opacity: 0.65 }}>
{t('wallet.testCard.predictionsUsed', {
used: status.predictionLimit.usedInWindow,
max: status.predictionLimit.maxPerWindow,
hours: status.predictionLimit.windowHours,
})}
</Typography>
{!status.predictionLimit.canPredict && (
<Alert severity="warning" variant="outlined" sx={{ borderRadius: 2 }}>
{t('wallet.testCard.predictionLimitReached', {
wait: formatWaitUntil(
status.predictionLimit.resetsAt,
status.predictionLimit.windowHours
),
})}
{status.predictionLimit.resetsAt && (
<>
{' '}
{t('wallet.testCard.resetsAt', {
date: new Date(status.predictionLimit.resetsAt).toLocaleString(),
})}
</>
)}
</Alert>
)}
</Stack>
)}
</CardContent>
</Card>
);
}