After finalise with the internationarization of web part
This commit is contained in:
parent
7bb971b502
commit
79d18dae13
87
prediqo_web/package-lock.json
generated
87
prediqo_web/package-lock.json
generated
@ -16,9 +16,12 @@
|
||||
"@tanstack/react-query": "^5.87.1",
|
||||
"axios": "^1.11.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"i18next": "^26.3.4",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"lightweight-charts": "^5.2.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-i18next": "^17.0.8",
|
||||
"react-qr-code": "^2.2.0",
|
||||
"react-router-dom": "^7.15.0",
|
||||
"recharts": "^3.9.0",
|
||||
@ -2262,6 +2265,52 @@
|
||||
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/html-parse-stringify": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
|
||||
"integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"void-elements": "3.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/i18next": {
|
||||
"version": "26.3.4",
|
||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.4.tgz",
|
||||
"integrity": "sha512-pa7m0d7pBDqGHZxljT+WPFeyFgQ7P7SciPPo1tTqYuO0z4sqADYhwnBESmmGp/wEof1inwdls/k8ZgTg8rxFHA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://www.locize.com/i18next"
|
||||
},
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
|
||||
},
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://www.locize.com"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"typescript": "^5 || ^6"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/i18next-browser-languagedetector": {
|
||||
"version": "8.2.1",
|
||||
"resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-8.2.1.tgz",
|
||||
"integrity": "sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.23.2"
|
||||
}
|
||||
},
|
||||
"node_modules/immer": {
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",
|
||||
@ -2870,6 +2919,33 @@
|
||||
"react": "^19.2.6"
|
||||
}
|
||||
},
|
||||
"node_modules/react-i18next": {
|
||||
"version": "17.0.8",
|
||||
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.8.tgz",
|
||||
"integrity": "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.29.2",
|
||||
"html-parse-stringify": "^3.0.1",
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"i18next": ">= 26.2.0",
|
||||
"react": ">= 16.8.0",
|
||||
"typescript": "^5 || ^6"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"react-native": {
|
||||
"optional": true
|
||||
},
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "19.2.6",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.6.tgz",
|
||||
@ -3197,7 +3273,7 @@
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
|
||||
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
@ -3347,6 +3423,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/void-elements": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
|
||||
"integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wmf": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
|
||||
|
||||
@ -25,9 +25,12 @@
|
||||
"@tanstack/react-query": "^5.87.1",
|
||||
"axios": "^1.11.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"i18next": "^26.3.4",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"lightweight-charts": "^5.2.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-i18next": "^17.0.8",
|
||||
"react-qr-code": "^2.2.0",
|
||||
"react-router-dom": "^7.15.0",
|
||||
"recharts": "^3.9.0",
|
||||
|
||||
@ -4,6 +4,8 @@
|
||||
*/
|
||||
import { CssBaseline, ThemeProvider } from '@mui/material';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { createAppTheme } from './theme/theme';
|
||||
import { router } from './router/router';
|
||||
@ -21,8 +23,10 @@ const queryClient = new QueryClient({
|
||||
*
|
||||
* @returns The fully configured admin application tree.
|
||||
*/
|
||||
export function App() {
|
||||
const theme = createAppTheme();
|
||||
function AppProviders() {
|
||||
const { i18n } = useTranslation();
|
||||
const theme = useMemo(() => createAppTheme(i18n.language), [i18n.language]);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>
|
||||
@ -35,3 +39,7 @@ export function App() {
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return <AppProviders />;
|
||||
}
|
||||
|
||||
@ -2,15 +2,11 @@
|
||||
* MUI theme factory for the web admin console.
|
||||
* Provides a dark, game-ready visual baseline with consistent palette, typography, and component overrides.
|
||||
*/
|
||||
import { createTheme } from '@mui/material/styles';
|
||||
import { createTheme, type ThemeOptions } from '@mui/material/styles';
|
||||
import { enUS, frFR } from '@mui/material/locale';
|
||||
import { normalizeLocale } from '../../shared/i18n';
|
||||
|
||||
/**
|
||||
* Builds the application MUI theme with a dark palette, gold accent, and shared component styling.
|
||||
*
|
||||
* @returns A configured MUI theme instance for the admin console.
|
||||
*/
|
||||
export function createAppTheme() {
|
||||
return createTheme({
|
||||
const baseThemeOptions: ThemeOptions = {
|
||||
palette: {
|
||||
mode: 'dark',
|
||||
primary: { main: '#D6B25E' }, // gold accent
|
||||
@ -44,5 +40,14 @@ export function createAppTheme() {
|
||||
defaultProps: { disableElevation: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the application MUI theme with a dark palette, gold accent, and shared component styling.
|
||||
*
|
||||
* @returns A configured MUI theme instance for the admin console.
|
||||
*/
|
||||
export function createAppTheme(language?: string) {
|
||||
const muiLocale = normalizeLocale(language) === 'fr' ? frFR : enUS;
|
||||
return createTheme(baseThemeOptions, muiLocale);
|
||||
}
|
||||
|
||||
@ -22,6 +22,7 @@ import {
|
||||
import GavelRoundedIcon from '@mui/icons-material/GavelRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
@ -38,15 +39,16 @@ type FundRequest = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const OP_LABELS: Record<string, string> = {
|
||||
ledger_credit: 'Ledger credit',
|
||||
treasury_cold_to_hot: 'Cold → Hot funding',
|
||||
bonus_pool_fund: 'Bonus pool fund',
|
||||
sweep_manual: 'Manual sweeps',
|
||||
sweep_batch: 'Auto sweep batch',
|
||||
};
|
||||
const OP_TYPE_KEYS = [
|
||||
'ledger_credit',
|
||||
'treasury_cold_to_hot',
|
||||
'bonus_pool_fund',
|
||||
'sweep_manual',
|
||||
'sweep_batch',
|
||||
] as const;
|
||||
|
||||
export function ApprovalsPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const { canApproveFundOps } = useAuth();
|
||||
const [rejectId, setRejectId] = useState<string | null>(null);
|
||||
@ -67,7 +69,7 @@ export function ApprovalsPage() {
|
||||
const approveMut = useMutation({
|
||||
mutationFn: (id: string) => api.post(`/api/v1/admin/fund-requests/${id}/approve`),
|
||||
onSuccess: () => {
|
||||
setMessage('Request approved and executed.');
|
||||
setMessage(t('admin.approvals.approved'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] });
|
||||
},
|
||||
});
|
||||
@ -78,15 +80,20 @@ export function ApprovalsPage() {
|
||||
onSuccess: () => {
|
||||
setRejectId(null);
|
||||
setRejectReason('');
|
||||
setMessage('Request rejected.');
|
||||
setMessage(t('admin.approvals.rejected'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] });
|
||||
},
|
||||
});
|
||||
|
||||
const opLabel = (operationType: string) => {
|
||||
if ((OP_TYPE_KEYS as readonly string[]).includes(operationType)) {
|
||||
return t(`admin.approvals.opTypes.${operationType as (typeof OP_TYPE_KEYS)[number]}`);
|
||||
}
|
||||
return operationType;
|
||||
};
|
||||
|
||||
if (!canApproveFundOps) {
|
||||
return (
|
||||
<Alert severity="warning">You do not have permission to approve fund operations.</Alert>
|
||||
);
|
||||
return <Alert severity="warning">{t('admin.approvals.noPermission')}</Alert>;
|
||||
}
|
||||
|
||||
const items = listQ.data?.items ?? [];
|
||||
@ -95,10 +102,10 @@ export function ApprovalsPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<GavelRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Approvals"
|
||||
subtitle="Review and approve sensitive fund operations"
|
||||
title={t('admin.approvals.title')}
|
||||
subtitle={t('admin.approvals.subtitle')}
|
||||
actions={
|
||||
<RefreshIconButton label="Refresh approvals" onClick={() => void listQ.refetch()} />
|
||||
<RefreshIconButton label={t('admin.approvals.refresh')} onClick={() => void listQ.refetch()} />
|
||||
}
|
||||
/>
|
||||
|
||||
@ -110,7 +117,7 @@ export function ApprovalsPage() {
|
||||
|
||||
{listQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Failed to load approval queue.
|
||||
{t('admin.approvals.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -118,11 +125,11 @@ export function ApprovalsPage() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Type</TableCell>
|
||||
<TableCell>Requested by</TableCell>
|
||||
<TableCell>Created</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Actions</TableCell>
|
||||
<TableCell>{t('admin.approvals.type')}</TableCell>
|
||||
<TableCell>{t('admin.approvals.requestedBy')}</TableCell>
|
||||
<TableCell>{t('admin.approvals.created')}</TableCell>
|
||||
<TableCell>{t('common.status')}</TableCell>
|
||||
<TableCell>{t('admin.approvals.actions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -130,14 +137,14 @@ export function ApprovalsPage() {
|
||||
<TableRow>
|
||||
<TableCell colSpan={5}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.6 }}>
|
||||
No pending approvals.
|
||||
{t('admin.approvals.noPending')}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
items.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{OP_LABELS[r.operationType] ?? r.operationType}</TableCell>
|
||||
<TableCell>{opLabel(r.operationType)}</TableCell>
|
||||
<TableCell sx={{ fontFamily: 'monospace', fontSize: 12 }}>
|
||||
{r.requestedBy.slice(0, 8)}…
|
||||
</TableCell>
|
||||
@ -153,10 +160,10 @@ export function ApprovalsPage() {
|
||||
disabled={approveMut.isPending}
|
||||
onClick={() => void approveMut.mutateAsync(r.id)}
|
||||
>
|
||||
Approve
|
||||
{t('admin.approvals.approve')}
|
||||
</Button>
|
||||
<Button size="small" color="error" onClick={() => setRejectId(r.id)}>
|
||||
Reject
|
||||
{t('admin.approvals.reject')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
@ -168,13 +175,13 @@ export function ApprovalsPage() {
|
||||
</ScrollableTable>
|
||||
|
||||
<Dialog open={!!rejectId} onClose={() => setRejectId(null)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Reject request</DialogTitle>
|
||||
<DialogTitle>{t('admin.approvals.rejectTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" sx={{ mb: 2, opacity: 0.8 }}>
|
||||
Provide a reason for rejection.
|
||||
{t('admin.approvals.rejectHint')}
|
||||
</Typography>
|
||||
<TextField
|
||||
label="Reason"
|
||||
label={t('admin.approvals.reason')}
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
@ -183,7 +190,7 @@ export function ApprovalsPage() {
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setRejectId(null)}>Cancel</Button>
|
||||
<Button onClick={() => setRejectId(null)}>{t('common.cancel')}</Button>
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
@ -193,7 +200,7 @@ export function ApprovalsPage() {
|
||||
void rejectMut.mutateAsync({ id: rejectId, reason: rejectReason.trim() });
|
||||
}}
|
||||
>
|
||||
Reject
|
||||
{t('admin.approvals.reject')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -4,9 +4,12 @@
|
||||
import { Alert, Box, Button, Card, CardContent, Link, Stack, TextField, Typography } from '@mui/material';
|
||||
import { useState } from 'react';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
export function ForgotPasswordPage() {
|
||||
const { t } = useTranslation();
|
||||
const [email, setEmail] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@ -18,7 +21,7 @@ export function ForgotPasswordPage() {
|
||||
setSuccess(null);
|
||||
setDevUrl(null);
|
||||
if (!email.trim()) {
|
||||
setError('Email is required.');
|
||||
setError(t('auth.emailRequiredShort'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@ -31,22 +34,23 @@ export function ForgotPasswordPage() {
|
||||
if (res.data.devResetUrl) setDevUrl(res.data.devResetUrl);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Request failed');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('auth.requestFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2 }}>
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Reset password
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Enter your email and we'll send you a secure link to choose a new password.
|
||||
{t('auth.resetPassword')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>{t('auth.resetPasswordSubtitle')}</Typography>
|
||||
|
||||
<Stack spacing={2} sx={{ mt: 3 }}>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
@ -54,7 +58,7 @@ export function ForgotPasswordPage() {
|
||||
{devUrl && (
|
||||
<Alert severity="info">
|
||||
<Typography variant="body2" sx={{ mb: 1 }}>
|
||||
Local / console mode — no email is sent. Open this link to reset your password:
|
||||
{t('auth.consoleResetHint')}
|
||||
</Typography>
|
||||
<Link href={devUrl} target="_blank" rel="noreferrer" sx={{ wordBreak: 'break-all' }}>
|
||||
{devUrl}
|
||||
@ -62,7 +66,7 @@ export function ForgotPasswordPage() {
|
||||
</Alert>
|
||||
)}
|
||||
<TextField
|
||||
label="Email"
|
||||
label={t('common.email')}
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
@ -70,11 +74,11 @@ export function ForgotPasswordPage() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
<Button variant="contained" onClick={submit} disabled={loading}>
|
||||
{loading ? 'Sending…' : 'Send reset link'}
|
||||
{loading ? t('common.sending') : t('auth.sendResetLink')}
|
||||
</Button>
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
|
||||
<Link component={RouterLink} to="/login">
|
||||
Back to sign in
|
||||
{t('auth.backToSignIn')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
@ -7,8 +7,10 @@ import { Alert, Box, Button, Card, CardContent, Link, Stack, TextField, Typograp
|
||||
import { useState } from 'react';
|
||||
import { useLocation, useNavigate, Link as RouterLink } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
type LoginResponse = {
|
||||
accessToken: string;
|
||||
@ -26,6 +28,7 @@ type LoginResponse = {
|
||||
|
||||
/** Sign-in form with optional TOTP; redirects to `from` route on success. */
|
||||
export function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation() as any;
|
||||
const { setAuth } = useAuth();
|
||||
@ -55,7 +58,7 @@ export function LoginPage() {
|
||||
setResendSuccess(null);
|
||||
setDevVerifyUrl(null);
|
||||
if (!email.trim()) {
|
||||
setError('Enter your email address first.');
|
||||
setError(t('auth.enterEmailFirst'));
|
||||
return;
|
||||
}
|
||||
setResendLoading(true);
|
||||
@ -68,7 +71,7 @@ export function LoginPage() {
|
||||
if (res.data.devVerifyUrl) setDevVerifyUrl(res.data.devVerifyUrl);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Failed to resend verification email');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('auth.resendFailed'));
|
||||
} finally {
|
||||
setResendLoading(false);
|
||||
}
|
||||
@ -81,7 +84,7 @@ export function LoginPage() {
|
||||
setResendSuccess(null);
|
||||
setDevVerifyUrl(null);
|
||||
if (!email.trim() || !password) {
|
||||
setError('Email and password are required.');
|
||||
setError(t('auth.emailPasswordRequired'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@ -101,7 +104,7 @@ export function LoginPage() {
|
||||
});
|
||||
nav(from, { replace: true });
|
||||
} catch (e: any) {
|
||||
const msg = e?.response?.data?.error ?? e?.message ?? 'Login failed';
|
||||
const msg = e?.response?.data?.error ?? e?.message ?? t('auth.loginFailed');
|
||||
const code = e?.response?.data?.code;
|
||||
setError(String(msg));
|
||||
setEmailNotVerified(code === 'EMAIL_NOT_VERIFIED');
|
||||
@ -111,27 +114,24 @@ export function LoginPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2 }}>
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Prediqo
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Prediction games platform — sign in to manage or play.
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>{t('auth.brandSubtitle')}</Typography>
|
||||
|
||||
<Stack spacing={2} sx={{ mt: 3 }}>
|
||||
{verifyHint && (
|
||||
<Alert severity="info">
|
||||
We sent a confirmation link to your email. Verify your address before signing in.
|
||||
</Alert>
|
||||
)}
|
||||
{verifyHint && <Alert severity="info">{t('auth.verifyEmailHint')}</Alert>}
|
||||
{setupQ.data?.needsSetup && (
|
||||
<Alert severity="warning">
|
||||
Aucun administrateur n'est configuré.{' '}
|
||||
{t('auth.noAdminConfigured')}{' '}
|
||||
<Link component={RouterLink} to="/setup">
|
||||
Initialiser la plateforme
|
||||
{t('auth.initializePlatform')}
|
||||
</Link>
|
||||
</Alert>
|
||||
)}
|
||||
@ -139,8 +139,7 @@ export function LoginPage() {
|
||||
{emailNotVerified && (
|
||||
<Alert severity="warning">
|
||||
<Typography variant="body2" sx={{ mb: 1 }}>
|
||||
Your account exists but the email is not verified yet. Request a new confirmation
|
||||
link below (check spam if nothing arrives).
|
||||
{t('auth.emailNotVerified')}
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
@ -148,28 +147,28 @@ export function LoginPage() {
|
||||
onClick={resendVerification}
|
||||
disabled={resendLoading || !email.trim()}
|
||||
>
|
||||
{resendLoading ? 'Sending…' : 'Resend verification email'}
|
||||
{resendLoading ? t('common.sending') : t('auth.resendVerification')}
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
{resendSuccess && <Alert severity="success">{resendSuccess}</Alert>}
|
||||
{devVerifyUrl && (
|
||||
<Alert severity="info">
|
||||
Dev link:{' '}
|
||||
{t('auth.devVerifyLink')}{' '}
|
||||
<Link href={devVerifyUrl} target="_blank" rel="noreferrer">
|
||||
Open verification URL
|
||||
{t('auth.openVerificationUrl')}
|
||||
</Link>
|
||||
</Alert>
|
||||
)}
|
||||
<TextField
|
||||
label="Email"
|
||||
label={t('common.email')}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
label={t('common.password')}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
type="password"
|
||||
@ -177,29 +176,29 @@ export function LoginPage() {
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="2FA code (optional)"
|
||||
label={t('auth.totpOptional')}
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value)}
|
||||
slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }}
|
||||
fullWidth
|
||||
/>
|
||||
<Button variant="contained" onClick={submit} disabled={loading}>
|
||||
{loading ? 'Signing in…' : 'Sign in'}
|
||||
{loading ? t('auth.signingIn') : t('auth.signIn')}
|
||||
</Button>
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
|
||||
<Link component={RouterLink} to="/forgot-password">
|
||||
Forgot password?
|
||||
{t('auth.forgotPassword')}
|
||||
</Link>
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
|
||||
<Link component={RouterLink} to="/faq">
|
||||
Foire aux questions
|
||||
{t('auth.faqLink')}
|
||||
</Link>
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
|
||||
No account yet?{' '}
|
||||
{t('auth.noAccount')}{' '}
|
||||
<Link component={RouterLink} to="/register">
|
||||
Create one
|
||||
{t('auth.createOne')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</Stack>
|
||||
@ -208,4 +207,3 @@ export function LoginPage() {
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -15,10 +15,12 @@ import {
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link as RouterLink, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { CountryAutocomplete, type CountryOption } from '../../shared/components/CountryAutocomplete';
|
||||
import { GenderSelect } from '../../shared/components/GenderSelect';
|
||||
import type { UserGender } from '../../shared/constants/userGender';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
type RegisterResponse = {
|
||||
message: string;
|
||||
@ -28,6 +30,7 @@ type RegisterResponse = {
|
||||
};
|
||||
|
||||
export function RegisterPage() {
|
||||
const { t } = useTranslation();
|
||||
const nav = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const refFromUrl = searchParams.get('ref') ?? '';
|
||||
@ -65,7 +68,7 @@ export function RegisterPage() {
|
||||
setReferralValid(null);
|
||||
return;
|
||||
}
|
||||
const t = setTimeout(async () => {
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await api.get<{ valid: boolean }>(`/api/v1/auth/referral/validate/${encodeURIComponent(code)}`);
|
||||
setReferralValid(res.data.valid);
|
||||
@ -73,7 +76,7 @@ export function RegisterPage() {
|
||||
setReferralValid(false);
|
||||
}
|
||||
}, 400);
|
||||
return () => clearTimeout(t);
|
||||
return () => clearTimeout(timer);
|
||||
}, [referralCode]);
|
||||
|
||||
const resolvedCountry = country;
|
||||
@ -82,11 +85,11 @@ export function RegisterPage() {
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
if (!fullName.trim() || !email.trim() || !password || !resolvedCountry || !gender) {
|
||||
setError('Full name, email, password, country of residence, and gender are required.');
|
||||
setError(t('auth.registerFieldsRequired'));
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Z]{2}$/.test(resolvedCountry)) {
|
||||
setError('Country must be a 2-letter ISO code (e.g. FR).');
|
||||
setError(t('auth.countryIsoInvalid'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@ -101,33 +104,31 @@ export function RegisterPage() {
|
||||
gender,
|
||||
referralCode: referralCode.trim() || undefined,
|
||||
});
|
||||
setSuccess(
|
||||
res.data.message ||
|
||||
'Account created. Check your email and click the verification link before signing in.'
|
||||
);
|
||||
setSuccess(res.data.message || t('auth.registerSuccess'));
|
||||
setTimeout(() => nav('/login', { replace: true, state: { verifyEmail: true } }), 4000);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Registration failed');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('auth.registerFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, py: 4 }}>
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, py: 4, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Card sx={{ width: '100%', maxWidth: 560 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Create account
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Join Prediqo — use a friend's referral link or sign up directly.
|
||||
{t('auth.createAccount')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>{t('auth.registerSubtitle')}</Typography>
|
||||
|
||||
{refFromUrl && (
|
||||
<Alert severity="info" sx={{ mt: 2 }}>
|
||||
You were invited with referral code <strong>{refFromUrl}</strong>.
|
||||
<Trans i18nKey="auth.invitedWithCode" values={{ code: refFromUrl }} components={{ strong: <strong /> }} />
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -136,14 +137,14 @@ export function RegisterPage() {
|
||||
{success && <Alert severity="success">{success}</Alert>}
|
||||
|
||||
<TextField
|
||||
label="Full name *"
|
||||
label={t('auth.fullNameRequired')}
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
fullWidth
|
||||
autoComplete="name"
|
||||
/>
|
||||
<TextField
|
||||
label="Email *"
|
||||
label={t('auth.emailRequired')}
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
@ -151,14 +152,14 @@ export function RegisterPage() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
<TextField
|
||||
label="Phone (optional)"
|
||||
label={t('auth.phoneOptional')}
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
fullWidth
|
||||
autoComplete="tel"
|
||||
/>
|
||||
<TextField
|
||||
label="Password *"
|
||||
label={t('auth.passwordRequired')}
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
@ -167,60 +168,51 @@ export function RegisterPage() {
|
||||
/>
|
||||
|
||||
<CountryAutocomplete
|
||||
label="Country of residence"
|
||||
label={t('auth.countryOfResidence')}
|
||||
value={country}
|
||||
onChange={setCountry}
|
||||
options={countries}
|
||||
loading={countriesQ.isLoading}
|
||||
required
|
||||
helperText="Type a country name or ISO code (e.g. France or FR)"
|
||||
helperText={t('auth.countryHelper')}
|
||||
/>
|
||||
|
||||
<GenderSelect
|
||||
value={gender}
|
||||
onChange={setGender}
|
||||
required
|
||||
helperText="Masculin, Féminin ou Autre"
|
||||
/>
|
||||
<GenderSelect value={gender} onChange={setGender} required helperText={t('gender.helper')} />
|
||||
|
||||
{countriesQ.isError && (
|
||||
<Alert severity="warning">
|
||||
Could not load country list. Ask an admin to sync countries, then refresh.
|
||||
</Alert>
|
||||
)}
|
||||
{countriesQ.isError && <Alert severity="warning">{t('auth.countriesLoadFailed')}</Alert>}
|
||||
|
||||
<CountryAutocomplete
|
||||
label="Nationality (optional)"
|
||||
label={t('auth.nationalityOptional')}
|
||||
value={nationality}
|
||||
onChange={setNationality}
|
||||
options={countries}
|
||||
loading={countriesQ.isLoading}
|
||||
placeholder="Search nationality…"
|
||||
placeholder={t('auth.nationalityPlaceholder')}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="Referral code (optional)"
|
||||
label={t('auth.referralCodeOptional')}
|
||||
value={referralCode}
|
||||
onChange={(e) => setReferralCode(e.target.value.toUpperCase())}
|
||||
fullWidth
|
||||
helperText={
|
||||
referralValid === true
|
||||
? 'Valid referral code'
|
||||
? t('auth.referralValid')
|
||||
: referralValid === false
|
||||
? 'Unknown code — you can still register (default referrer will apply)'
|
||||
: 'Leave empty to use the platform default referrer'
|
||||
? t('auth.referralUnknown')
|
||||
: t('auth.referralEmpty')
|
||||
}
|
||||
error={referralValid === false && !!referralCode.trim()}
|
||||
/>
|
||||
|
||||
<Button variant="contained" onClick={submit} disabled={loading} size="large">
|
||||
{loading ? 'Creating account…' : 'Sign up'}
|
||||
{loading ? t('auth.creatingAccount') : t('auth.signUp')}
|
||||
</Button>
|
||||
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8 }}>
|
||||
Already have an account?{' '}
|
||||
{t('auth.alreadyHaveAccount')}{' '}
|
||||
<Link component={RouterLink} to="/login">
|
||||
Sign in
|
||||
{t('auth.signIn')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
@ -15,9 +15,12 @@ import {
|
||||
} from '@mui/material';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link as RouterLink, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
export function ResetPasswordPage() {
|
||||
const { t } = useTranslation();
|
||||
const [params] = useSearchParams();
|
||||
const token = params.get('token') ?? '';
|
||||
const [tokenValid, setTokenValid] = useState<boolean | null>(null);
|
||||
@ -51,7 +54,7 @@ export function ResetPasswordPage() {
|
||||
const submit = async () => {
|
||||
setError(null);
|
||||
if (!password || password !== confirm) {
|
||||
setError('Passwords must match.');
|
||||
setError(t('auth.passwordsMustMatch'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@ -63,18 +66,21 @@ export function ResetPasswordPage() {
|
||||
setSuccess(res.data.message);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Reset failed');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('auth.resetFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2 }}>
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Choose new password
|
||||
{t('auth.chooseNewPassword')}
|
||||
</Typography>
|
||||
|
||||
{tokenValid === null && (
|
||||
@ -85,7 +91,7 @@ export function ResetPasswordPage() {
|
||||
|
||||
{tokenValid === false && !success && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
Invalid or expired reset link. Request a new one from the forgot password page.
|
||||
{t('auth.invalidResetLink')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -93,7 +99,7 @@ export function ResetPasswordPage() {
|
||||
<Stack spacing={2} sx={{ mt: 2 }}>
|
||||
<Alert severity="success">{success}</Alert>
|
||||
<Button component={RouterLink} to="/login" variant="contained" fullWidth>
|
||||
Sign in
|
||||
{t('auth.signIn')}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
@ -102,7 +108,7 @@ export function ResetPasswordPage() {
|
||||
<Stack spacing={2} sx={{ mt: 3 }}>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
<TextField
|
||||
label="New password"
|
||||
label={t('auth.newPassword')}
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
@ -110,7 +116,7 @@ export function ResetPasswordPage() {
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<TextField
|
||||
label="Confirm password"
|
||||
label={t('auth.confirmPassword')}
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
@ -118,14 +124,14 @@ export function ResetPasswordPage() {
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button variant="contained" onClick={submit} disabled={loading}>
|
||||
{loading ? 'Updating…' : 'Update password'}
|
||||
{loading ? t('auth.updating') : t('auth.updatePassword')}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', opacity: 0.8, mt: 2 }}>
|
||||
<Link component={RouterLink} to="/forgot-password">
|
||||
Request a new link
|
||||
{t('auth.requestNewLink')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</CardContent>
|
||||
|
||||
@ -17,12 +17,16 @@ import {
|
||||
import AdminPanelSettingsRoundedIcon from '@mui/icons-material/AdminPanelSettingsRounded';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link as RouterLink, useNavigate } from 'react-router-dom';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
type SetupTab = 'create' | 'promote';
|
||||
|
||||
export function SetupPage() {
|
||||
const { t } = useTranslation();
|
||||
const nav = useNavigate();
|
||||
const [tab, setTab] = useState<SetupTab>('create');
|
||||
const [setupToken, setSetupToken] = useState('');
|
||||
@ -59,7 +63,7 @@ export function SetupPage() {
|
||||
setTimeout(() => nav('/login', { replace: true }), 2000);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Setup failed');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('setup.setupFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -78,102 +82,101 @@ export function SetupPage() {
|
||||
setTimeout(() => nav('/login', { replace: true }), 2000);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setError(err?.response?.data?.error ?? err?.message ?? 'Promotion failed');
|
||||
setError(err?.response?.data?.error ?? err?.message ?? t('setup.promotionFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (statusQ.isLoading) {
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center' }}>
|
||||
<Typography sx={{ opacity: 0.7 }}>Chargement…</Typography>
|
||||
const shell = (children: ReactNode) => (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
);
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
|
||||
if (statusQ.isLoading) {
|
||||
return shell(<Typography sx={{ opacity: 0.7 }}>{t('setup.loading')}</Typography>);
|
||||
}
|
||||
|
||||
if (statusQ.isError) {
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2 }}>
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
Impossible de vérifier l'état d'initialisation
|
||||
</Typography>
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
L'API n'a pas répondu. Vérifiez que{' '}
|
||||
<strong>VITE_API_BASE_URL</strong> correspond à l'URL publique (ex.{' '}
|
||||
<code>http://prediqo.redirectme.net:9080</code>) puis reconstruisez le frontend.
|
||||
</Alert>
|
||||
<Button variant="outlined" onClick={() => void statusQ.refetch()}>
|
||||
Réessayer
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
return shell(
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
{t('setup.statusCheckFailed')}
|
||||
</Typography>
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
<Trans
|
||||
i18nKey="setup.apiUnreachable"
|
||||
components={{ strong: <strong />, code: <code /> }}
|
||||
/>
|
||||
</Alert>
|
||||
<Button variant="outlined" onClick={() => void statusQ.refetch()}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!needsSetup) {
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2 }}>
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
Configuration terminée
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Un compte administrateur existe déjà. Connectez-vous pour accéder à la plateforme.
|
||||
</Typography>
|
||||
<Button component={RouterLink} to="/login" variant="contained">
|
||||
Aller à la connexion
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
return shell(
|
||||
<Card sx={{ width: '100%', maxWidth: 520 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
{t('setup.setupComplete')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>{t('setup.adminExists')}</Typography>
|
||||
<Button component={RouterLink} to="/login" variant="contained">
|
||||
{t('setup.goToLogin')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, py: 4 }}>
|
||||
<Box sx={{ minHeight: '100vh', display: 'grid', placeItems: 'center', px: 2, py: 4, position: 'relative' }}>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Card sx={{ width: '100%', maxWidth: 560 }}>
|
||||
<CardContent>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>
|
||||
<AdminPanelSettingsRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Initialisation Prediqo
|
||||
{t('setup.title')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Créez le premier compte administrateur pour configurer la plateforme en production.
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>{t('setup.subtitle')}</Typography>
|
||||
|
||||
{!setupEnabled && (
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
Définissez la variable d'environnement{' '}
|
||||
<strong>INITIAL_SETUP_TOKEN</strong> sur le serveur (min. 16 caractères aléatoires), puis
|
||||
redémarrez l'API.
|
||||
<Trans i18nKey="setup.tokenEnvWarning" components={{ strong: <strong /> }} />
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
label="Jeton d'initialisation (INITIAL_SETUP_TOKEN)"
|
||||
label={t('setup.setupTokenLabel')}
|
||||
fullWidth
|
||||
type="password"
|
||||
value={setupToken}
|
||||
onChange={(e) => setSetupToken(e.target.value)}
|
||||
helperText="Secret configuré uniquement sur le serveur — ne le partagez pas."
|
||||
helperText={t('setup.setupTokenHelper')}
|
||||
sx={{ mb: 2 }}
|
||||
/>
|
||||
|
||||
<Tabs value={tab} onChange={(_, v: SetupTab) => setTab(v)} sx={{ mb: 2 }}>
|
||||
<Tab value="create" label="Créer un admin" />
|
||||
<Tab value="promote" label="Promouvoir un compte existant" />
|
||||
<Tab value="create" label={t('setup.tabCreate')} />
|
||||
<Tab value="promote" label={t('setup.tabPromote')} />
|
||||
</Tabs>
|
||||
|
||||
<Stack spacing={2}>
|
||||
<TextField
|
||||
label="Email"
|
||||
label={t('common.email')}
|
||||
fullWidth
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
@ -181,25 +184,24 @@ export function SetupPage() {
|
||||
{tab === 'create' && (
|
||||
<>
|
||||
<TextField
|
||||
label="Nom complet"
|
||||
label={t('setup.fullName')}
|
||||
fullWidth
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Mot de passe"
|
||||
label={t('common.password')}
|
||||
type="password"
|
||||
fullWidth
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
helperText="Minimum 8 caractères"
|
||||
helperText={t('setup.passwordMin')}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{tab === 'promote' && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
L'utilisateur doit déjà s'être inscrit via la page Register. Son email sera
|
||||
marqué comme vérifié et son rôle passera à administrateur.
|
||||
{t('setup.promoteHint')}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
@ -222,12 +224,16 @@ export function SetupPage() {
|
||||
disabled={loading || !setupEnabled || !setupToken.trim() || !email.trim()}
|
||||
onClick={() => void (tab === 'create' ? submitCreate() : submitPromote())}
|
||||
>
|
||||
{loading ? 'En cours…' : tab === 'create' ? 'Créer l’administrateur' : 'Promouvoir en admin'}
|
||||
{loading
|
||||
? t('setup.inProgress')
|
||||
: tab === 'create'
|
||||
? t('setup.createAdmin')
|
||||
: t('setup.promoteAdmin')}
|
||||
</Button>
|
||||
|
||||
<Typography variant="body2" sx={{ textAlign: 'center', mt: 2, opacity: 0.8 }}>
|
||||
<Link component={RouterLink} to="/login">
|
||||
Retour à la connexion
|
||||
{t('setup.backToLogin')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</CardContent>
|
||||
|
||||
@ -15,12 +15,15 @@ import MarkEmailReadRoundedIcon from '@mui/icons-material/MarkEmailReadRounded';
|
||||
import ErrorOutlineRoundedIcon from '@mui/icons-material/ErrorOutlineRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link as RouterLink, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { LanguageSwitcher } from '../../shared/i18n/LanguageSwitcher';
|
||||
|
||||
type Status = 'loading' | 'success' | 'error' | 'missing';
|
||||
|
||||
/** Standalone route opened from the verification email link. */
|
||||
export function VerifyEmailPage() {
|
||||
const { t } = useTranslation();
|
||||
const [params] = useSearchParams();
|
||||
const token = params.get('token');
|
||||
const [status, setStatus] = useState<Status>(token ? 'loading' : 'missing');
|
||||
@ -41,7 +44,7 @@ export function VerifyEmailPage() {
|
||||
if (!cancelled) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setStatus('error');
|
||||
setMessage(err?.response?.data?.error ?? err?.message ?? 'Verification failed');
|
||||
setMessage(err?.response?.data?.error ?? err?.message ?? t('auth.verificationFailed'));
|
||||
}
|
||||
}
|
||||
})();
|
||||
@ -49,7 +52,7 @@ export function VerifyEmailPage() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [token]);
|
||||
}, [token, t]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
@ -58,10 +61,14 @@ export function VerifyEmailPage() {
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
p: 3,
|
||||
position: 'relative',
|
||||
background:
|
||||
'radial-gradient(ellipse at top, rgba(214,178,94,0.12), transparent 55%), #0B0E14',
|
||||
}}
|
||||
>
|
||||
<Box sx={{ position: 'absolute', top: 16, right: 16 }}>
|
||||
<LanguageSwitcher />
|
||||
</Box>
|
||||
<Paper
|
||||
sx={{
|
||||
width: '100%',
|
||||
@ -79,7 +86,7 @@ export function VerifyEmailPage() {
|
||||
{status === 'loading' && (
|
||||
<>
|
||||
<CircularProgress />
|
||||
<Typography sx={{ opacity: 0.8 }}>Verifying your email…</Typography>
|
||||
<Typography sx={{ opacity: 0.8 }}>{t('auth.verifyingEmail')}</Typography>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -90,10 +97,10 @@ export function VerifyEmailPage() {
|
||||
{message}
|
||||
</Alert>
|
||||
<Button component={RouterLink} to="/profile" variant="contained" fullWidth>
|
||||
Go to profile
|
||||
{t('auth.goToProfile')}
|
||||
</Button>
|
||||
<Button component={RouterLink} to="/login" variant="text" fullWidth>
|
||||
Sign in
|
||||
{t('auth.signIn')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
@ -105,10 +112,10 @@ export function VerifyEmailPage() {
|
||||
{message}
|
||||
</Alert>
|
||||
<Button component={RouterLink} to="/profile" variant="contained" fullWidth>
|
||||
Back to profile
|
||||
{t('auth.backToProfile')}
|
||||
</Button>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Request a new link from your profile if this one expired.
|
||||
{t('auth.requestNewLinkFromProfile')}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
@ -116,10 +123,10 @@ export function VerifyEmailPage() {
|
||||
{status === 'missing' && (
|
||||
<>
|
||||
<Alert severity="warning" sx={{ width: '100%', borderRadius: 2 }}>
|
||||
Missing verification token. Open the full link from your email.
|
||||
{t('auth.missingVerificationToken')}
|
||||
</Alert>
|
||||
<Button component={RouterLink} to="/profile" variant="contained" fullWidth>
|
||||
Go to profile
|
||||
{t('auth.goToProfile')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -19,6 +19,7 @@ import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
|
||||
import CandlestickChartRoundedIcon from '@mui/icons-material/CandlestickChartRounded';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
import useMediaQuery from '@mui/material/useMediaQuery';
|
||||
import { useLiveBalances } from '../wallet/hooks/useWalletData';
|
||||
@ -66,6 +67,7 @@ function formatCountdown(totalSec: number): string {
|
||||
|
||||
/** Main play page for the Candle Predict game. */
|
||||
export function CandlePredictPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isAdmin } = useAuth();
|
||||
const theme = useTheme();
|
||||
const isCompact = useMediaQuery(theme.breakpoints.down('md'));
|
||||
@ -202,31 +204,48 @@ export function CandlePredictPage() {
|
||||
}, [round?.id, round?.settledAt, round?.outcome, balancesQ]);
|
||||
|
||||
const statusLabel = useMemo(() => {
|
||||
if (!round || !interval) return 'Loading…';
|
||||
if (!round || !interval) return t('candlePredict.status.loading');
|
||||
if (round.status === 'betting') {
|
||||
const target = new Date(round.candleOpenMs).toLocaleTimeString();
|
||||
return `${interval.label} · predictions open · target ${target} · ${formatCountdown(round.secondsToBettingEnd)} left`;
|
||||
return t('candlePredict.status.betting', {
|
||||
interval: interval.label,
|
||||
target,
|
||||
countdown: formatCountdown(round.secondsToBettingEnd),
|
||||
});
|
||||
}
|
||||
if (round.status === 'locked') {
|
||||
const live = formatCountdown(round.secondsToClose);
|
||||
const untilOpen = formatCountdown(round.secondsToBettingStart);
|
||||
return `${interval.label} · candle live · ${live} · predictions in ${untilOpen}`;
|
||||
return t('candlePredict.status.locked', {
|
||||
interval: interval.label,
|
||||
live,
|
||||
untilOpen,
|
||||
});
|
||||
}
|
||||
if (round.status === 'waiting') {
|
||||
return `${interval.label} · next window in ${formatCountdown(round.secondsToBettingStart)}`;
|
||||
return t('candlePredict.status.waiting', {
|
||||
interval: interval.label,
|
||||
countdown: formatCountdown(round.secondsToBettingStart),
|
||||
});
|
||||
}
|
||||
if (round.outcome === 'neutral') return `${interval.label} · manche nulle · mise remboursée`;
|
||||
if (round.outcome === 'short_win') return `${interval.label} · settled · Short won`;
|
||||
if (round.outcome === 'long_win') return `${interval.label} · settled · Long won`;
|
||||
return `${interval.label} · settled`;
|
||||
}, [round, interval, tick]);
|
||||
if (round.outcome === 'neutral') {
|
||||
return t('candlePredict.status.neutral', { interval: interval.label });
|
||||
}
|
||||
if (round.outcome === 'short_win') {
|
||||
return t('candlePredict.status.shortWin', { interval: interval.label });
|
||||
}
|
||||
if (round.outcome === 'long_win') {
|
||||
return t('candlePredict.status.longWin', { interval: interval.label });
|
||||
}
|
||||
return t('candlePredict.status.settled', { interval: interval.label });
|
||||
}, [round, interval, tick, t]);
|
||||
|
||||
const statusColor =
|
||||
round?.status === 'betting' ? 'warning' : round?.status === 'locked' ? 'info' : 'default';
|
||||
|
||||
const refresh = async () => {
|
||||
await Promise.all([stateQ.refetch(), candlesQ.refetch(), balancesQ.refetch()]);
|
||||
setToast('Game refreshed');
|
||||
setToast(t('common.gameRefreshed'));
|
||||
};
|
||||
|
||||
const predictionsRefreshKey = [
|
||||
@ -256,9 +275,9 @@ export function CandlePredictPage() {
|
||||
stakeAccountKind,
|
||||
});
|
||||
setStakeAccountKind('main');
|
||||
setToast(`Multi-candle level ${level} prediction placed`);
|
||||
setToast(t('candlePredict.multiPredictionPlaced', { level }));
|
||||
} catch (e: unknown) {
|
||||
setMultiPredictionError(extractGameApiError(e, 'Failed to place multi-candle prediction'));
|
||||
setMultiPredictionError(extractGameApiError(e, t('candlePredict.multiPlaceFailed')));
|
||||
}
|
||||
};
|
||||
|
||||
@ -298,10 +317,10 @@ export function CandlePredictPage() {
|
||||
}}
|
||||
>
|
||||
<ToggleButton value="single" sx={{ fontWeight: 800 }}>
|
||||
Single candle
|
||||
{t('candlePredict.singleCandle')}
|
||||
</ToggleButton>
|
||||
<ToggleButton value="multi" sx={{ fontWeight: 800 }}>
|
||||
Multi-candle
|
||||
{t('candlePredict.multiCandle')}
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
) : null;
|
||||
@ -391,11 +410,11 @@ export function CandlePredictPage() {
|
||||
stakeAccountKind,
|
||||
});
|
||||
|
||||
setToast(`Prediction placed for ${interval.label} round`);
|
||||
setToast(t('candlePredict.predictionPlaced', { interval: interval.label }));
|
||||
setDirection(null);
|
||||
setStakeAccountKind('main');
|
||||
} catch (e: unknown) {
|
||||
setPredictionError(extractGameApiError(e, 'Failed to place prediction'));
|
||||
setPredictionError(extractGameApiError(e, t('candlePredict.placePredictionFailed')));
|
||||
} finally {
|
||||
submitInFlightRef.current = false;
|
||||
setIsConfirmingBet(false);
|
||||
@ -411,7 +430,11 @@ export function CandlePredictPage() {
|
||||
});
|
||||
await stateQ.refetch();
|
||||
if (saved.autoBetPlaced) {
|
||||
setToast(`Auto prediction enabled — placed for ${interval?.label ?? 'this'} round`);
|
||||
setToast(
|
||||
t('candlePredict.autoEnabledPlaced', {
|
||||
interval: interval?.label ?? t('candlePredict.singleCandle'),
|
||||
})
|
||||
);
|
||||
} else if (input.validateWalletBalance && saved.autoBetError?.includes('Insufficient')) {
|
||||
setAutoSaveError(saved.autoBetError);
|
||||
} else if (
|
||||
@ -429,11 +452,11 @@ export function CandlePredictPage() {
|
||||
setAutoSaveError(saved.autoBetError);
|
||||
setToast(`Auto prediction saved. ${saved.autoBetError}`);
|
||||
} else {
|
||||
setToast('Auto prediction updated');
|
||||
setToast(t('candlePredict.autoUpdated'));
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
const message = err?.response?.data?.error ?? 'Failed to save auto settings';
|
||||
const message = err?.response?.data?.error ?? t('candlePredict.autoSaveFailed');
|
||||
if (input.validateWalletBalance) {
|
||||
setAutoSaveError(message);
|
||||
}
|
||||
@ -458,11 +481,11 @@ export function CandlePredictPage() {
|
||||
(stateQ.error instanceof Error ? stateQ.error.message : null);
|
||||
const hint =
|
||||
apiErr?.response?.status === 429
|
||||
? 'Too many API requests — wait a minute or restart the backend.'
|
||||
: 'Run database migrations and ensure the API is running.';
|
||||
? t('candlePredict.rateLimitHint')
|
||||
: t('candlePredict.apiHint');
|
||||
return (
|
||||
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||
Failed to load Candle Predict. {detail ? `${detail}. ` : ''}
|
||||
{t('candlePredict.loadError')} {detail ? `${detail}. ` : ''}
|
||||
{hint}
|
||||
</Alert>
|
||||
);
|
||||
@ -486,7 +509,7 @@ export function CandlePredictPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
leading={
|
||||
<IconButton component={RouterLink} to="/home" aria-label="Back to home" sx={{ flexShrink: 0 }}>
|
||||
<IconButton component={RouterLink} to="/home" aria-label={t('candlePredict.backToHome')} sx={{ flexShrink: 0 }}>
|
||||
<ArrowBackRoundedIcon />
|
||||
</IconButton>
|
||||
}
|
||||
@ -494,19 +517,14 @@ export function CandlePredictPage() {
|
||||
title={
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, fontSize: { xs: '1.5rem', sm: '2rem' } }}>
|
||||
Candle Predict
|
||||
{t('candlePredict.title')}
|
||||
</Typography>
|
||||
<Chip size="small" label={interval.label} color="primary" />
|
||||
</Stack>
|
||||
}
|
||||
subtitle={
|
||||
<>
|
||||
Prédisez si la prochaine bougie sera baissière (<strong>Short ↓</strong>) ou haussière (
|
||||
<strong>Long ↑</strong>), puis attendez le résultat de la manche.
|
||||
</>
|
||||
}
|
||||
subtitle={<Trans i18nKey="candlePredict.subtitle" components={{ strong: <strong /> }} />}
|
||||
mb={2.5}
|
||||
actions={<RefreshIconButton label="Refresh game" onClick={() => void refresh()} />}
|
||||
actions={<RefreshIconButton label={t('candlePredict.refreshGame')} onClick={() => void refresh()} />}
|
||||
/>
|
||||
|
||||
<StakeWalletBalanceBar
|
||||
@ -563,7 +581,9 @@ export function CandlePredictPage() {
|
||||
background: alpha('#D6B25E', 0.06),
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ fontWeight: 800, flexShrink: 0 }}>Round status</Typography>
|
||||
<Typography sx={{ fontWeight: 800, flexShrink: 0 }}>
|
||||
{t('candlePredict.roundStatus.title')}
|
||||
</Typography>
|
||||
<Chip
|
||||
color={statusColor}
|
||||
label={statusLabel}
|
||||
@ -584,7 +604,7 @@ export function CandlePredictPage() {
|
||||
|
||||
{!config.isActive && (
|
||||
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
This game is temporarily disabled by an administrator.
|
||||
{t('candlePredict.gameDisabledAdmin')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import { Alert, Chip, Stack, Typography } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { CandlePredictConfig, CandlePredictInterval, CandlePredictRound } from '../types';
|
||||
import { NEUTRAL_ROUND_BEHAVIOR, poolNeutralitySummary } from '../utils/poolNeutrality';
|
||||
import { poolWinnerRuleLabel } from '../utils/poolWinnerRule';
|
||||
import { PoolBar } from './PoolBar';
|
||||
|
||||
type Props = {
|
||||
@ -12,32 +11,47 @@ type Props = {
|
||||
|
||||
/** Admin-only live pool totals and internal settlement rule summary. */
|
||||
export function AdminPoolInsights({ config, interval, round }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!config.poolWinnerRule) return null;
|
||||
|
||||
const neutralityRulesSummary = poolNeutralitySummary({
|
||||
tieTolerancePercent: interval.tieTolerancePercent ?? config.tieTolerancePercent ?? 0,
|
||||
tieToleranceMaxPercent: interval.tieToleranceMaxPercent ?? config.tieToleranceMaxPercent ?? 100,
|
||||
tieToleranceMinEnabled:
|
||||
interval.tieToleranceMinEnabled ?? config.tieToleranceMinEnabled ?? true,
|
||||
tieToleranceMaxEnabled:
|
||||
interval.tieToleranceMaxEnabled ?? config.tieToleranceMaxEnabled ?? true,
|
||||
});
|
||||
const parts: string[] = [];
|
||||
const tieTolerancePercent = interval.tieTolerancePercent ?? config.tieTolerancePercent ?? 0;
|
||||
const tieToleranceMaxPercent = interval.tieToleranceMaxPercent ?? config.tieToleranceMaxPercent ?? 100;
|
||||
const tieToleranceMinEnabled =
|
||||
interval.tieToleranceMinEnabled ?? config.tieToleranceMinEnabled ?? true;
|
||||
const tieToleranceMaxEnabled =
|
||||
interval.tieToleranceMaxEnabled ?? config.tieToleranceMaxEnabled ?? true;
|
||||
|
||||
if (tieToleranceMinEnabled) {
|
||||
parts.push(t('candlePredict.adminInsights.neutralMin', { percent: tieTolerancePercent }));
|
||||
}
|
||||
if (tieToleranceMaxEnabled) {
|
||||
parts.push(t('candlePredict.adminInsights.neutralMax', { percent: tieToleranceMaxPercent }));
|
||||
}
|
||||
|
||||
const neutralityRulesSummary =
|
||||
parts.length > 0 ? parts.join(' · ') : t('candlePredict.adminInsights.neutralNone');
|
||||
|
||||
const poolWinnerLabel =
|
||||
config.poolWinnerRule === 'majority'
|
||||
? t('candlePredict.adminInsights.poolWinnerMajority')
|
||||
: t('candlePredict.adminInsights.poolWinnerMinority');
|
||||
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 0.5 }}>
|
||||
Vue administrateur — mécanismes internes
|
||||
{t('candlePredict.adminInsights.title')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap', mb: 0.75 }}>
|
||||
<Chip size="small" label={poolWinnerRuleLabel(config.poolWinnerRule)} color="warning" />
|
||||
<Chip size="small" label={poolWinnerLabel} color="warning" />
|
||||
</Stack>
|
||||
<Typography variant="body2" sx={{ opacity: 0.85 }}>
|
||||
{neutralityRulesSummary}. {NEUTRAL_ROUND_BEHAVIOR}
|
||||
{neutralityRulesSummary}. {t('candlePredict.adminInsights.neutralBehavior')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ display: 'block', mt: 0.75, opacity: 0.65 }}>
|
||||
Non visible pour les joueurs. Les pools et règles de règlement ne doivent pas influencer leurs
|
||||
prédictions.
|
||||
{t('candlePredict.adminInsights.footer')}
|
||||
</Typography>
|
||||
</Alert>
|
||||
{round && <PoolBar round={round} poolWinnerRule={config.poolWinnerRule} />}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import AutoModeRoundedIcon from '@mui/icons-material/AutoModeRounded';
|
||||
import { Alert, Button, Stack, Typography } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { AutoPredictionSettings, CandlePredictInterval } from '../types';
|
||||
|
||||
type Props = {
|
||||
@ -20,16 +21,19 @@ export function AutoPredictionBanner({
|
||||
intervals,
|
||||
onSwitchToAutoInterval,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!settings?.enabled) return null;
|
||||
|
||||
const autoLabel = intervalLabel(intervals, settings.periodMinutes);
|
||||
const viewingLabel = intervalLabel(intervals, activeIntervalMinutes);
|
||||
const onAutoInterval = settings.periodMinutes === activeIntervalMinutes;
|
||||
const directionLabel = settings.direction === 'long' ? 'Long' : 'Short';
|
||||
const directionLabel =
|
||||
settings.direction === 'long' ? t('candlePredict.betting.long') : t('candlePredict.betting.short');
|
||||
const modeLabel =
|
||||
settings.mode === 'interval'
|
||||
? `délai min. ${settings.intervalSeconds ?? 60}s entre mises auto · 1/manche`
|
||||
: 'chaque nouvelle manche';
|
||||
? t('candlePredict.autoBanner.modeInterval', { seconds: settings.intervalSeconds ?? 60 })
|
||||
: t('candlePredict.autoBanner.modeEachRound');
|
||||
|
||||
if (onAutoInterval) {
|
||||
return (
|
||||
@ -45,7 +49,9 @@ export function AutoPredictionBanner({
|
||||
}}
|
||||
>
|
||||
<Stack spacing={0.25}>
|
||||
<Typography sx={{ fontWeight: 800 }}>Prédiction auto active · {autoLabel}</Typography>
|
||||
<Typography sx={{ fontWeight: 800 }}>
|
||||
{t('candlePredict.autoBanner.activeOnInterval', { interval: autoLabel })}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
{directionLabel} · {settings.stakeDisplay} USDT · {modeLabel}
|
||||
</Typography>
|
||||
@ -68,18 +74,20 @@ export function AutoPredictionBanner({
|
||||
action={
|
||||
onSwitchToAutoInterval ? (
|
||||
<Button color="inherit" size="small" onClick={onSwitchToAutoInterval} sx={{ fontWeight: 800 }}>
|
||||
View {autoLabel}
|
||||
{t('candlePredict.autoBanner.viewInterval', { interval: autoLabel })}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<Stack spacing={0.25}>
|
||||
<Typography sx={{ fontWeight: 800 }}>
|
||||
Auto prediction active on {autoLabel}
|
||||
{t('candlePredict.autoBanner.activeOtherInterval', { interval: autoLabel })}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
You are viewing {viewingLabel}. Auto predictions only run on {autoLabel} — switch period or
|
||||
re-save auto settings here to move auto to {viewingLabel}.
|
||||
{t('candlePredict.autoBanner.viewingMismatch', {
|
||||
viewing: viewingLabel,
|
||||
auto: autoLabel,
|
||||
})}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Alert>
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import AutoModeRoundedIcon from '@mui/icons-material/AutoModeRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import type { AutoPredictionSettings, CandlePredictConfig, CandlePredictInterval, StakeAccountKind } from '../types';
|
||||
import { CustomStakeAmountField } from './CustomStakeAmountField';
|
||||
import { StakeWalletSelector } from './StakeWalletSelector';
|
||||
@ -38,7 +39,6 @@ type Props = {
|
||||
}
|
||||
) => Promise<void>;
|
||||
saving?: boolean;
|
||||
/** Compact horizontal bar when auto is already enabled (desktop layout). */
|
||||
layout?: 'vertical' | 'horizontal';
|
||||
};
|
||||
|
||||
@ -46,16 +46,6 @@ function intervalLabel(intervals: CandlePredictInterval[], minutes: number): str
|
||||
return intervals.find((i) => i.intervalMinutes === minutes)?.label ?? `${minutes} min`;
|
||||
}
|
||||
|
||||
function stakeAccountShort(kind: StakeAccountKind): string {
|
||||
if (kind === 'bonus') return 'Bonus';
|
||||
if (kind === 'test') return 'Test';
|
||||
return 'Main';
|
||||
}
|
||||
|
||||
function modeShort(mode: 'each_round' | 'interval'): string {
|
||||
return mode === 'interval' ? 'Délai minimum' : 'Chaque manche';
|
||||
}
|
||||
|
||||
/** Auto Prediction configuration panel. */
|
||||
export function AutoPredictionPanel({
|
||||
config,
|
||||
@ -71,6 +61,7 @@ export function AutoPredictionPanel({
|
||||
saving,
|
||||
layout = 'vertical',
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const serverEnabled = settings?.enabled ?? false;
|
||||
const [configuring, setConfiguring] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
@ -120,6 +111,26 @@ export function AutoPredictionPanel({
|
||||
const viewingDifferentPeriod =
|
||||
serverEnabled && savedTargetMinutes != null && savedTargetMinutes !== interval.intervalMinutes;
|
||||
|
||||
const directionLabel =
|
||||
current.direction === 'long' ? t('candlePredict.betting.long') : t('candlePredict.betting.short');
|
||||
|
||||
const stakeAccountShort = (kind: StakeAccountKind) => {
|
||||
if (kind === 'bonus') return t('candlePredict.stakeWallet.bonus');
|
||||
if (kind === 'test') return t('candlePredict.stakeWallet.test');
|
||||
return t('candlePredict.stakeWallet.main');
|
||||
};
|
||||
|
||||
const modeShort = (m: 'each_round' | 'interval') =>
|
||||
m === 'interval'
|
||||
? t('candlePredict.autoPrediction.modeShortInterval')
|
||||
: t('candlePredict.autoPrediction.modeShortEachRound');
|
||||
|
||||
const lastAutoBetLabel = current.lastAutoBetAt
|
||||
? t('candlePredict.autoPrediction.lastAutoBet', {
|
||||
date: new Date(current.lastAutoBetAt).toLocaleString(),
|
||||
})
|
||||
: null;
|
||||
|
||||
const handleToggle = async (enabled: boolean) => {
|
||||
onClearSaveError?.();
|
||||
if (enabled) {
|
||||
@ -179,26 +190,33 @@ export function AutoPredictionPanel({
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="body2" sx={{ fontWeight: 800 }}>
|
||||
Target period:
|
||||
{t('candlePredict.autoPrediction.targetPeriod')}
|
||||
</Typography>
|
||||
<Chip label={targetLabel} size="small" color="secondary" sx={{ fontWeight: 800 }} />
|
||||
</Stack>
|
||||
{viewingDifferentPeriod ? (
|
||||
<Typography variant="caption" sx={{ display: 'block', mt: 0.75, opacity: 0.7 }}>
|
||||
You are viewing {interval.label}. Save to move auto to {interval.label}.
|
||||
{t('candlePredict.autoPrediction.viewingDifferent', {
|
||||
viewing: interval.label,
|
||||
target: interval.label,
|
||||
})}
|
||||
</Typography>
|
||||
) : (
|
||||
<Typography variant="caption" sx={{ display: 'block', mt: 0.75, opacity: 0.7 }}>
|
||||
Set from the prediction period you select when saving. One auto config per account.
|
||||
{t('candlePredict.autoPrediction.targetHint')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<FormControl fullWidth size="small">
|
||||
<InputLabel>Direction</InputLabel>
|
||||
<Select name="direction" label="Direction" defaultValue={current.direction ?? 'short'}>
|
||||
<MenuItem value="short">Short candle</MenuItem>
|
||||
<MenuItem value="long">Long candle</MenuItem>
|
||||
<InputLabel>{t('candlePredict.autoPrediction.direction')}</InputLabel>
|
||||
<Select
|
||||
name="direction"
|
||||
label={t('candlePredict.autoPrediction.direction')}
|
||||
defaultValue={current.direction ?? 'short'}
|
||||
>
|
||||
<MenuItem value="short">{t('candlePredict.direction.shortCandle')}</MenuItem>
|
||||
<MenuItem value="long">{t('candlePredict.direction.longCandle')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
@ -214,58 +232,62 @@ export function AutoPredictionPanel({
|
||||
/>
|
||||
|
||||
<CustomStakeAmountField
|
||||
label="Stake amount"
|
||||
label={t('candlePredict.autoPrediction.stakeAmount')}
|
||||
value={stakeValue}
|
||||
minStake={config.minStakeAmount}
|
||||
maxStake={config.maxStakeAmount}
|
||||
onValidChange={setStakeValue}
|
||||
onValidityChange={setStakeFieldValid}
|
||||
helperText={`Quick picks: ${config.stakeAmounts.join(', ')} · custom from ${config.minStakeAmount} to ${config.maxStakeAmount} USDT`}
|
||||
helperText={t('candlePredict.autoPrediction.stakeHelper', {
|
||||
picks: config.stakeAmounts.join(', '),
|
||||
min: config.minStakeAmount,
|
||||
max: config.maxStakeAmount,
|
||||
})}
|
||||
/>
|
||||
|
||||
<FormControl fullWidth size="small">
|
||||
<InputLabel>Mode</InputLabel>
|
||||
<InputLabel>{t('candlePredict.autoPrediction.mode')}</InputLabel>
|
||||
<Select
|
||||
name="mode"
|
||||
label="Mode"
|
||||
label={t('candlePredict.autoPrediction.mode')}
|
||||
value={mode}
|
||||
onChange={(e) => setMode(e.target.value as 'each_round' | 'interval')}
|
||||
>
|
||||
{config.autoModes.includes('each_round') && (
|
||||
<MenuItem value="each_round">Chaque nouvelle manche</MenuItem>
|
||||
<MenuItem value="each_round">{t('candlePredict.autoPrediction.modeEachRound')}</MenuItem>
|
||||
)}
|
||||
{config.autoModes.includes('interval') && (
|
||||
<MenuItem value="interval">Délai minimum</MenuItem>
|
||||
<MenuItem value="interval">{t('candlePredict.autoPrediction.modeInterval')}</MenuItem>
|
||||
)}
|
||||
</Select>
|
||||
<FormHelperText>
|
||||
{mode === 'interval'
|
||||
? 'Une mise par manche maximum. Attend au moins le délai indiqué depuis la dernière mise auto avant de parier sur la manche suivante (ou au save).'
|
||||
: 'Place une mise dès l’ouverture de la fenêtre de prédiction de chaque nouvelle manche.'}
|
||||
? t('candlePredict.autoPrediction.modeIntervalHelper')
|
||||
: t('candlePredict.autoPrediction.modeEachRoundHelper')}
|
||||
</FormHelperText>
|
||||
</FormControl>
|
||||
|
||||
{mode === 'interval' && (
|
||||
<TextField
|
||||
name="intervalSeconds"
|
||||
label="Délai minimum entre mises auto (secondes)"
|
||||
label={t('candlePredict.autoPrediction.intervalSeconds')}
|
||||
type="number"
|
||||
size="small"
|
||||
defaultValue={current.intervalSeconds ?? 60}
|
||||
slotProps={{
|
||||
htmlInput: { min: 1, step: 1 },
|
||||
}}
|
||||
helperText="Temps minimal depuis la dernière mise auto réussie. Ne permet pas plusieurs mises sur la même manche — seulement d’espacer deux mises consécutives (ex. après un enregistrement récent)."
|
||||
helperText={t('candlePredict.autoPrediction.intervalSecondsHelper')}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }}>
|
||||
<Button type="submit" variant="outlined" disabled={saving || !stakeFieldValid}>
|
||||
Enregistrer les paramètres auto
|
||||
{t('candlePredict.autoPrediction.save')}
|
||||
</Button>
|
||||
{serverEnabled && (
|
||||
<Button type="button" variant="text" onClick={() => setEditing(false)} disabled={saving}>
|
||||
Annuler
|
||||
{t('candlePredict.autoPrediction.cancel')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
@ -290,9 +312,9 @@ export function AutoPredictionPanel({
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>
|
||||
<AutoModeRoundedIcon color="secondary" fontSize="small" />
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Typography sx={{ fontWeight: 900 }}>Auto Prediction</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('candlePredict.autoPrediction.title')}</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block' }}>
|
||||
Activez pour parier automatiquement à chaque manche.
|
||||
{t('candlePredict.autoPrediction.enableHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
@ -301,12 +323,12 @@ export function AutoPredictionPanel({
|
||||
control={
|
||||
<Switch checked={switchChecked} onChange={(e) => void handleToggle(e.target.checked)} />
|
||||
}
|
||||
label="Activer la prédiction auto"
|
||||
label={t('candlePredict.autoPrediction.enable')}
|
||||
/>
|
||||
</Stack>
|
||||
{current.lastAutoBetAt && (
|
||||
{lastAutoBetLabel && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block', mt: 1 }}>
|
||||
Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()}
|
||||
{lastAutoBetLabel}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
@ -314,7 +336,6 @@ export function AutoPredictionPanel({
|
||||
}
|
||||
|
||||
if (showCompact && isHorizontal) {
|
||||
const directionLabel = current.direction === 'long' ? 'Long' : 'Short';
|
||||
const accountKind = current.stakeAccountKind ?? 'main';
|
||||
|
||||
return (
|
||||
@ -334,11 +355,11 @@ export function AutoPredictionPanel({
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexShrink: 0 }}>
|
||||
<AutoModeRoundedIcon color="secondary" fontSize="small" />
|
||||
<Typography sx={{ fontWeight: 900 }}>Prédiction auto active</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('candlePredict.autoPrediction.titleActive')}</Typography>
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Button size="small" variant="outlined" onClick={() => setEditing(true)} sx={{ fontWeight: 800 }}>
|
||||
Modifier
|
||||
{t('candlePredict.autoPrediction.edit')}
|
||||
</Button>
|
||||
<FormControlLabel
|
||||
sx={{ m: 0 }}
|
||||
@ -349,7 +370,7 @@ export function AutoPredictionPanel({
|
||||
onChange={(e) => void handleToggle(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Désactiver"
|
||||
label={t('candlePredict.autoPrediction.disable')}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
@ -364,12 +385,17 @@ export function AutoPredictionPanel({
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
<Chip label={stakeAccountShort(accountKind)} size="small" variant="outlined" sx={{ fontWeight: 700 }} />
|
||||
<Chip label={modeShort(current.mode ?? 'each_round')} size="small" variant="outlined" sx={{ fontWeight: 700 }} />
|
||||
<Chip
|
||||
label={modeShort(current.mode ?? 'each_round')}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{current.lastAutoBetAt && (
|
||||
{lastAutoBetLabel && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()}
|
||||
{lastAutoBetLabel}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
@ -390,14 +416,12 @@ export function AutoPredictionPanel({
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<AutoModeRoundedIcon color="secondary" />
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Auto Prediction
|
||||
{t('candlePredict.autoPrediction.title')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
{!showCompact && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Place automatiquement <strong>une prédiction par manche</strong> sur la période cible, avec
|
||||
les paramètres ci-dessous. La mise est prélevée sur le portefeuille sélectionné. Rien n'est
|
||||
envoyé tant que vous n'avez pas cliqué sur <strong>Enregistrer</strong>.
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }} component="div">
|
||||
<Trans i18nKey="candlePredict.autoPrediction.intro" components={{ strong: <strong /> }} />
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
@ -407,12 +431,7 @@ export function AutoPredictionPanel({
|
||||
<>
|
||||
<Stack direction="row" spacing={0.75} useFlexGap sx={{ flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<Chip label={targetLabel} size="small" color="secondary" sx={{ fontWeight: 800 }} />
|
||||
<Chip
|
||||
label={current.direction === 'long' ? 'Long' : 'Short'}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
<Chip label={directionLabel} size="small" variant="outlined" sx={{ fontWeight: 700 }} />
|
||||
<Chip
|
||||
label={`${current.stakeDisplay ?? 1} USDT`}
|
||||
size="small"
|
||||
@ -428,12 +447,12 @@ export function AutoPredictionPanel({
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }}>
|
||||
<Button size="small" variant="outlined" onClick={() => setEditing(true)} sx={{ fontWeight: 800 }}>
|
||||
Modifier les paramètres
|
||||
{t('candlePredict.autoPrediction.editSettings')}
|
||||
</Button>
|
||||
</Stack>
|
||||
{current.lastAutoBetAt && (
|
||||
{lastAutoBetLabel && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()}
|
||||
{lastAutoBetLabel}
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
@ -444,23 +463,21 @@ export function AutoPredictionPanel({
|
||||
control={
|
||||
<Switch checked={switchChecked} onChange={(e) => void handleToggle(e.target.checked)} />
|
||||
}
|
||||
label="Activer la prédiction auto"
|
||||
label={t('candlePredict.autoPrediction.enable')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{configuring && !serverEnabled && (
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Paramétrez votre prédiction ci-dessous, puis cliquez sur{' '}
|
||||
<strong>Enregistrer les paramètres auto</strong> pour activer le mode. Aucune mise ne sera
|
||||
placée avant l'enregistrement.
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }} component="div">
|
||||
<Trans i18nKey="candlePredict.autoPrediction.configureAlert" components={{ strong: <strong /> }} />
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{settingsForm}
|
||||
|
||||
{!showCompact && current.lastAutoBetAt && (
|
||||
{!showCompact && lastAutoBetLabel && (
|
||||
<Alert severity="info" sx={{ py: 0.5 }}>
|
||||
Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()}
|
||||
{lastAutoBetLabel}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
@ -4,6 +4,7 @@ import useMediaQuery from '@mui/material/useMediaQuery';
|
||||
import TrendingDownRoundedIcon from '@mui/icons-material/TrendingDownRounded';
|
||||
import TrendingUpRoundedIcon from '@mui/icons-material/TrendingUpRounded';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { CandleDirection, CandlePredictConfig, CandlePredictInterval, CandlePredictRound, StakeAccountKind } from '../types';
|
||||
import { CustomStakeAmountField } from './CustomStakeAmountField';
|
||||
import { StakeWalletSelector } from './StakeWalletSelector';
|
||||
@ -51,6 +52,7 @@ export function BettingPanel({
|
||||
hasPrediction,
|
||||
error,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const isCompact = useMediaQuery(theme.breakpoints.down('sm'));
|
||||
const { secondsToBettingEnd, secondsToBettingStart, bettingOpen: liveBettingOpen } =
|
||||
@ -85,18 +87,20 @@ export function BettingPanel({
|
||||
<Stack spacing={2}>
|
||||
<Box>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Place your prediction
|
||||
{t('candlePredict.betting.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Short = bougie baissière · Long = bougie haussière. Choisissez une direction et confirmez votre
|
||||
mise.
|
||||
{t('candlePredict.betting.hint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{round?.status === 'betting' && predictionOpen && (
|
||||
<Chip
|
||||
color="warning"
|
||||
label={`Target round ${new Date(round.candleOpenMs).toLocaleTimeString()} · closes in ${formatWait(countdown)}`}
|
||||
label={t('candlePredict.betting.targetRound', {
|
||||
time: new Date(round.candleOpenMs).toLocaleTimeString(),
|
||||
wait: formatWait(countdown),
|
||||
})}
|
||||
sx={{
|
||||
alignSelf: 'flex-start',
|
||||
fontWeight: 800,
|
||||
@ -109,24 +113,25 @@ export function BettingPanel({
|
||||
{round?.status === 'locked' && untilOpen > 0 && (
|
||||
<Chip
|
||||
color="info"
|
||||
label={`Predictions open in ${formatWait(untilOpen)}`}
|
||||
label={t('candlePredict.betting.predictionsOpenIn', { wait: formatWait(untilOpen) })}
|
||||
sx={{ alignSelf: 'flex-start', fontWeight: 800 }}
|
||||
/>
|
||||
)}
|
||||
{!config.isActive && (
|
||||
<Alert severity="warning">Game disabled by admin — predictions are unavailable.</Alert>
|
||||
<Alert severity="warning">{t('candlePredict.betting.gameDisabled')}</Alert>
|
||||
)}
|
||||
{hasPrediction && (
|
||||
<Alert severity="success">Your prediction is locked for this round.</Alert>
|
||||
<Alert severity="success">{t('candlePredict.betting.predictionLocked')}</Alert>
|
||||
)}
|
||||
{round?.status === 'locked' && !hasPrediction && (
|
||||
<Alert severity="info">
|
||||
Candle in progress — place your prediction when the window opens
|
||||
{untilOpen > 0 ? ` (in ${formatWait(untilOpen)})` : ''}.
|
||||
{t('candlePredict.betting.candleInProgress', {
|
||||
suffix: untilOpen > 0 ? ` (${formatWait(untilOpen)})` : '',
|
||||
})}
|
||||
</Alert>
|
||||
)}
|
||||
{round?.status === 'waiting' && (
|
||||
<Alert severity="info">The next prediction window opens shortly before the new candle.</Alert>
|
||||
<Alert severity="info">{t('candlePredict.betting.nextWindowOpens')}</Alert>
|
||||
)}
|
||||
{error && !hasPrediction && <Alert severity="error">{error}</Alert>}
|
||||
|
||||
@ -141,7 +146,9 @@ export function BettingPanel({
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Stake amount ({config.walletTypeCode.replace('_', ' ')})
|
||||
{t('candlePredict.betting.stakeAmount', {
|
||||
code: config.walletTypeCode.replace('_', ' '),
|
||||
})}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap', mb: 1.5 }}>
|
||||
{config.stakeAmounts.map((amount) => (
|
||||
@ -169,13 +176,13 @@ export function BettingPanel({
|
||||
disabled={!predictionOpen}
|
||||
onValidChange={onStakeChange}
|
||||
onValidityChange={setCustomStakeValid}
|
||||
helperText={`Quick picks above, or enter any amount from ${minStake} to ${maxStake} USDT (e.g. 0.25)`}
|
||||
helperText={t('candlePredict.betting.stakeHelper', { min: minStake, max: maxStake })}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Prediction
|
||||
{t('candlePredict.betting.prediction')}
|
||||
</Typography>
|
||||
<ToggleButtonGroup
|
||||
exclusive
|
||||
@ -198,7 +205,7 @@ export function BettingPanel({
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<TrendingDownRoundedIcon />
|
||||
<span>Short ↓</span>
|
||||
<span>{t('candlePredict.betting.short')} ↓</span>
|
||||
</Stack>
|
||||
</ToggleButton>
|
||||
<ToggleButton
|
||||
@ -214,7 +221,7 @@ export function BettingPanel({
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<TrendingUpRoundedIcon />
|
||||
<span>Long ↑</span>
|
||||
<span>{t('candlePredict.betting.long')} ↑</span>
|
||||
</Stack>
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
@ -228,8 +235,14 @@ export function BettingPanel({
|
||||
sx={{ fontWeight: 900, py: 1.25, whiteSpace: 'normal', textAlign: 'center' }}
|
||||
>
|
||||
{isCompact
|
||||
? `Confirm · ${selectedStake} · ×${interval.payoutMultiplier}`
|
||||
: `Confirm prediction · ${selectedStake} · Payout ×${interval.payoutMultiplier}`}
|
||||
? t('candlePredict.betting.confirmCompact', {
|
||||
stake: selectedStake,
|
||||
multiplier: interval.payoutMultiplier,
|
||||
})
|
||||
: t('candlePredict.betting.confirmFull', {
|
||||
stake: selectedStake,
|
||||
multiplier: interval.payoutMultiplier,
|
||||
})}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Box, CircularProgress, Typography } from '@mui/material';
|
||||
import { CandlestickSeries, ColorType, createChart, type IChartApi, type ISeriesApi } from 'lightweight-charts';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { OhlcCandle } from '../types';
|
||||
|
||||
/** Fixed viewport: always show this many candles at the same pixel width. */
|
||||
@ -61,6 +62,7 @@ export function CandlestickChart({
|
||||
loadingOlder = false,
|
||||
onLoadOlder,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const chartRef = useRef<IChartApi | null>(null);
|
||||
const seriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
|
||||
@ -255,7 +257,7 @@ export function CandlestickChart({
|
||||
userSelect: 'none',
|
||||
}}
|
||||
>
|
||||
Glisser ou molette pour voir l'historique
|
||||
{t('candlePredict.chart.scrollHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
import { TextField } from '@mui/material';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
isPartialStakeAmountInput,
|
||||
parseStakeAmountInput,
|
||||
stakeAmountFormatError,
|
||||
stakeAmountRangeError,
|
||||
stakeAmountFormatErrorCode,
|
||||
stakeAmountRangeErrorCode,
|
||||
} from '../utils/stakeAmountInput';
|
||||
|
||||
type Props = {
|
||||
@ -20,7 +21,7 @@ type Props = {
|
||||
|
||||
/** Controlled stake text field with strict format validation. */
|
||||
export function CustomStakeAmountField({
|
||||
label = 'Custom amount',
|
||||
label,
|
||||
value,
|
||||
minStake,
|
||||
maxStake,
|
||||
@ -29,6 +30,7 @@ export function CustomStakeAmountField({
|
||||
onValidChange,
|
||||
onValidityChange,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [input, setInput] = useState(String(value));
|
||||
const [touched, setTouched] = useState(false);
|
||||
|
||||
@ -45,9 +47,13 @@ export function CustomStakeAmountField({
|
||||
}
|
||||
};
|
||||
|
||||
const formatError = stakeAmountFormatError(input, { whileTyping: !touched });
|
||||
const rangeError = stakeAmountRangeError(input, minStake, maxStake);
|
||||
const error = formatError || rangeError;
|
||||
const formatCode = stakeAmountFormatErrorCode(input, { whileTyping: !touched });
|
||||
const rangeCode = stakeAmountRangeErrorCode(input, minStake, maxStake);
|
||||
const error = formatCode
|
||||
? t(`candlePredict.stakeField.${formatCode}`)
|
||||
: rangeCode
|
||||
? t('candlePredict.stakeField.range', { min: minStake, max: maxStake })
|
||||
: null;
|
||||
const parsed = parseStakeAmountInput(input);
|
||||
const isValid = parsed.ok && parsed.value >= minStake && parsed.value <= maxStake;
|
||||
|
||||
@ -57,7 +63,7 @@ export function CustomStakeAmountField({
|
||||
|
||||
return (
|
||||
<TextField
|
||||
label={label}
|
||||
label={label ?? t('candlePredict.stakeField.customAmount')}
|
||||
type="text"
|
||||
size="small"
|
||||
fullWidth
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { Chip, Stack, Typography } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { CandlePredictInterval } from '../types';
|
||||
|
||||
type Props = {
|
||||
@ -9,12 +10,13 @@ type Props = {
|
||||
|
||||
/** Lets players pick which candle period their prediction targets. */
|
||||
export function IntervalSelector({ intervals, selectedMinutes, onChange }: Props) {
|
||||
const { t } = useTranslation();
|
||||
if (intervals.length <= 1) return null;
|
||||
|
||||
return (
|
||||
<Stack spacing={1}>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
|
||||
Prediction period
|
||||
{t('candlePredict.interval.title')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>
|
||||
{intervals.map((interval) => (
|
||||
@ -30,7 +32,7 @@ export function IntervalSelector({ intervals, selectedMinutes, onChange }: Props
|
||||
))}
|
||||
</Stack>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
Votre prédiction cible la manche qui se clôture à la fin de cette période.
|
||||
{t('candlePredict.interval.hint')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
import TrendingDownRoundedIcon from '@mui/icons-material/TrendingDownRounded';
|
||||
import TrendingUpRoundedIcon from '@mui/icons-material/TrendingUpRounded';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type {
|
||||
CandleDirection,
|
||||
CandlePredictConfig,
|
||||
@ -48,12 +49,13 @@ type Props = {
|
||||
};
|
||||
|
||||
function DirectionChip({ direction }: { direction: CandleDirection }) {
|
||||
const { t } = useTranslation();
|
||||
const isLong = direction === 'long';
|
||||
return (
|
||||
<Chip
|
||||
size="small"
|
||||
icon={isLong ? <TrendingUpRoundedIcon /> : <TrendingDownRoundedIcon />}
|
||||
label={isLong ? 'Long' : 'Short'}
|
||||
label={isLong ? t('candlePredict.betting.long') : t('candlePredict.betting.short')}
|
||||
color={isLong ? 'success' : 'error'}
|
||||
sx={{ fontWeight: 800 }}
|
||||
/>
|
||||
@ -79,6 +81,7 @@ export function MultiCandleBettingPanel({
|
||||
submitting,
|
||||
error,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const enabledLevels = useMemo(
|
||||
() => [...levels].filter((l) => l.enabled).sort((a, b) => a.sortOrder - b.sortOrder),
|
||||
[levels]
|
||||
@ -128,11 +131,15 @@ export function MultiCandleBettingPanel({
|
||||
>
|
||||
<Stack spacing={2}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Multi-candle prediction in progress
|
||||
{t('candlePredict.multiBetting.inProgress')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Level {activeBet.level} · stake {activeBet.stakeDisplay} · validating candle{' '}
|
||||
{step + 1} of {total}
|
||||
{t('candlePredict.multiBetting.progress', {
|
||||
level: activeBet.level,
|
||||
stake: activeBet.stakeDisplay,
|
||||
current: step + 1,
|
||||
total,
|
||||
})}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>
|
||||
{activeBet.sequenceDirections.map((dir, i) => (
|
||||
@ -141,7 +148,7 @@ export function MultiCandleBettingPanel({
|
||||
{i < step ? (
|
||||
<Chip size="small" label="✓" color="success" />
|
||||
) : i === step ? (
|
||||
<Chip size="small" label="current" color="warning" />
|
||||
<Chip size="small" label={t('candlePredict.multiBetting.current')} color="warning" />
|
||||
) : (
|
||||
<Chip size="small" label="…" variant="outlined" />
|
||||
)}
|
||||
@ -149,8 +156,7 @@ export function MultiCandleBettingPanel({
|
||||
))}
|
||||
</Stack>
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
One wrong candle ends the sequence immediately. Your stake stays pending until the final
|
||||
candle is validated.
|
||||
{t('candlePredict.multiBetting.progressAlert')}
|
||||
</Alert>
|
||||
</Stack>
|
||||
</Box>
|
||||
@ -169,38 +175,38 @@ export function MultiCandleBettingPanel({
|
||||
<Stack spacing={2}>
|
||||
<Box>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Multi-candle prediction
|
||||
{t('candlePredict.multiBetting.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Predict {level} consecutive candles in exact order. Minimum level 2 — use single mode for
|
||||
one candle.
|
||||
{t('candlePredict.multiBetting.hint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{!enabledLevels.length && (
|
||||
<Alert severity="warning">No multi-candle levels are currently available.</Alert>
|
||||
<Alert severity="warning">{t('candlePredict.multiBetting.noLevels')}</Alert>
|
||||
)}
|
||||
|
||||
{hasSinglePrediction && (
|
||||
<Alert severity="success">
|
||||
You already have a single-candle prediction for this round (including auto). Multi-candle
|
||||
is unavailable until the next window.
|
||||
</Alert>
|
||||
<Alert severity="success">{t('candlePredict.multiBetting.singleBlocksMulti')}</Alert>
|
||||
)}
|
||||
|
||||
{enabledLevels.length > 0 && (
|
||||
<>
|
||||
<FormControl size="small" fullWidth>
|
||||
<InputLabel>Level</InputLabel>
|
||||
<InputLabel>{t('candlePredict.multiBetting.level')}</InputLabel>
|
||||
<Select
|
||||
label="Level"
|
||||
label={t('candlePredict.multiBetting.level')}
|
||||
value={level}
|
||||
onChange={(e) => setLevel(Number(e.target.value))}
|
||||
disabled={!predictionOpen}
|
||||
>
|
||||
{enabledLevels.map((l) => (
|
||||
<MenuItem key={l.level} value={l.level}>
|
||||
Level {l.level} — {l.candleCount} candles · win ×{l.payoutMultiplier}
|
||||
{t('candlePredict.multiBetting.levelOption', {
|
||||
level: l.level,
|
||||
count: l.candleCount,
|
||||
multiplier: l.payoutMultiplier,
|
||||
})}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
@ -208,7 +214,7 @@ export function MultiCandleBettingPanel({
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Your sequence
|
||||
{t('candlePredict.multiBetting.yourSequence')}
|
||||
</Typography>
|
||||
<Stack spacing={1.5}>
|
||||
{sequence.map((dir, index) => (
|
||||
@ -219,7 +225,7 @@ export function MultiCandleBettingPanel({
|
||||
sx={{ alignItems: { sm: 'center' } }}
|
||||
>
|
||||
<Typography sx={{ minWidth: { sm: 72 }, fontWeight: 700, opacity: 0.8 }}>
|
||||
Candle {index + 1}
|
||||
{t('candlePredict.multiBetting.candleN', { n: index + 1 })}
|
||||
</Typography>
|
||||
<ToggleButtonGroup
|
||||
exclusive
|
||||
@ -231,10 +237,10 @@ export function MultiCandleBettingPanel({
|
||||
sx={{ '& .MuiToggleButton-root': { flex: 1 } }}
|
||||
>
|
||||
<ToggleButton value="short" sx={{ fontWeight: 800 }}>
|
||||
Short
|
||||
{t('candlePredict.betting.short')}
|
||||
</ToggleButton>
|
||||
<ToggleButton value="long" sx={{ fontWeight: 800 }}>
|
||||
Long
|
||||
{t('candlePredict.betting.long')}
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
</Stack>
|
||||
@ -253,7 +259,7 @@ export function MultiCandleBettingPanel({
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Stake amount
|
||||
{t('candlePredict.betting.stake')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap', mb: 1.5 }}>
|
||||
{config.stakeAmounts.map((amount) => (
|
||||
@ -284,7 +290,10 @@ export function MultiCandleBettingPanel({
|
||||
|
||||
{levelConfig && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Gain en cas de succès : mise × {levelConfig.payoutMultiplier} ({interval.label}).
|
||||
{t('candlePredict.multiBetting.winHint', {
|
||||
multiplier: levelConfig.payoutMultiplier,
|
||||
interval: interval.label,
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
@ -307,7 +316,9 @@ export function MultiCandleBettingPanel({
|
||||
background: `linear-gradient(90deg, ${alpha('#5EB2D6', 0.9)}, ${alpha('#D6B25E', 0.85)})`,
|
||||
}}
|
||||
>
|
||||
{submitting ? 'Placing…' : `Place level ${level} prediction`}
|
||||
{submitting
|
||||
? t('candlePredict.multiBetting.placing')
|
||||
: t('candlePredict.multiBetting.placeLevel', { level })}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { Box, LinearProgress, Stack, Typography, alpha } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { CandlePredictRound, PoolWinnerRule } from '../types';
|
||||
import { poolWinnerRulePoolHint } from '../utils/poolWinnerRule';
|
||||
|
||||
type Props = {
|
||||
round: CandlePredictRound | null;
|
||||
@ -9,17 +9,19 @@ type Props = {
|
||||
|
||||
/** Live Short vs Long stake pool visualization. */
|
||||
export function PoolBar({ round, poolWinnerRule }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!round) return null;
|
||||
const shortPool = round.shortPool ?? 0;
|
||||
const longPool = round.longPool ?? 0;
|
||||
const total = shortPool + longPool;
|
||||
const hasAmounts = total > 0;
|
||||
const shortPct = hasAmounts
|
||||
? (shortPool / total) * 100
|
||||
: (round.shortPoolPercent ?? 50);
|
||||
const longPct = hasAmounts
|
||||
? (longPool / total) * 100
|
||||
: (round.longPoolPercent ?? 50);
|
||||
const shortPct = hasAmounts ? (shortPool / total) * 100 : (round.shortPoolPercent ?? 50);
|
||||
const longPct = hasAmounts ? (longPool / total) * 100 : (round.longPoolPercent ?? 50);
|
||||
const winner =
|
||||
poolWinnerRule === 'majority'
|
||||
? t('candlePredict.poolBar.winnerMajority')
|
||||
: t('candlePredict.poolBar.winnerMinority');
|
||||
|
||||
return (
|
||||
<Box
|
||||
@ -31,13 +33,13 @@ export function PoolBar({ round, poolWinnerRule }: Props) {
|
||||
}}
|
||||
>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 900, mb: 1.5 }}>
|
||||
Stake pools
|
||||
{t('candlePredict.poolBar.title')}
|
||||
</Typography>
|
||||
<Stack spacing={1.25}>
|
||||
<Box>
|
||||
<Stack direction="row" sx={{ justifyContent: 'space-between', mb: 0.5 }}>
|
||||
<Typography variant="caption" sx={{ color: '#EF5350', fontWeight: 800 }}>
|
||||
Short (bearish)
|
||||
{t('candlePredict.direction.shortBearish')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700 }}>
|
||||
{hasAmounts ? `${shortPool.toFixed(0)} · ` : ''}
|
||||
@ -58,7 +60,7 @@ export function PoolBar({ round, poolWinnerRule }: Props) {
|
||||
<Box>
|
||||
<Stack direction="row" sx={{ justifyContent: 'space-between', mb: 0.5 }}>
|
||||
<Typography variant="caption" sx={{ color: '#4CAF50', fontWeight: 800 }}>
|
||||
Long (bullish)
|
||||
{t('candlePredict.direction.longBullish')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700 }}>
|
||||
{hasAmounts ? `${longPool.toFixed(0)} · ` : ''}
|
||||
@ -78,7 +80,7 @@ export function PoolBar({ round, poolWinnerRule }: Props) {
|
||||
</Box>
|
||||
</Stack>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block', mt: 1.25 }}>
|
||||
{poolWinnerRulePoolHint(poolWinnerRule)}
|
||||
{t('candlePredict.poolBar.hint', { winner })}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@ -17,7 +17,9 @@ import {
|
||||
} from '@mui/material';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
import useMediaQuery from '@mui/material/useMediaQuery';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ScrollableTable } from '../../../shared/components/ScrollableTable';
|
||||
import {
|
||||
PREDICTIONS_PAGE_SIZE,
|
||||
@ -26,7 +28,6 @@ import {
|
||||
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;
|
||||
@ -63,39 +64,27 @@ function statusColor(status: CandlePredictPrediction['status']): string {
|
||||
}
|
||||
}
|
||||
|
||||
function StatusLabel({ status }: { status: CandlePredictPrediction['status'] }) {
|
||||
function formatStatus(t: TFunction, status: CandlePredictPrediction['status']): string {
|
||||
const key = `candlePredict.recentPredictions.status.${status}` as const;
|
||||
return t(key, { defaultValue: status });
|
||||
}
|
||||
|
||||
function StatusLabel({ status, t }: { status: CandlePredictPrediction['status']; t: TFunction }) {
|
||||
return (
|
||||
<Typography component="span" sx={{ fontWeight: 700, color: statusColor(status) }}>
|
||||
{formatStatus(status)}
|
||||
{formatStatus(t, 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 {
|
||||
function formatStakeAccount(t: TFunction, kind: StakeAccountKind): string {
|
||||
switch (kind) {
|
||||
case 'bonus':
|
||||
return 'Bonus';
|
||||
return t('candlePredict.stakeWallet.bonus');
|
||||
case 'test':
|
||||
return 'Test';
|
||||
return t('candlePredict.stakeWallet.test');
|
||||
default:
|
||||
return 'Main';
|
||||
return t('candlePredict.stakeWallet.main');
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,12 +98,17 @@ function formatTime(date: Date): string {
|
||||
return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function formatCandlePeriod(prediction: CandlePredictPrediction): {
|
||||
function formatCandlePeriod(
|
||||
t: TFunction,
|
||||
prediction: CandlePredictPrediction
|
||||
): {
|
||||
range: string;
|
||||
placedAt: string;
|
||||
detail?: string;
|
||||
} {
|
||||
const placedAt = formatTime(new Date(prediction.createdAt));
|
||||
const placedAt = t('candlePredict.recentPredictions.placed', {
|
||||
time: formatTime(new Date(prediction.createdAt)),
|
||||
});
|
||||
|
||||
if (isMultiPrediction(prediction)) {
|
||||
const count = multiCandleCount(prediction);
|
||||
@ -124,9 +118,7 @@ function formatCandlePeriod(prediction: CandlePredictPrediction): {
|
||||
prediction.currentCandleOpenMs;
|
||||
if (anchorMs != null && count > 0) {
|
||||
const open = new Date(anchorMs);
|
||||
const close = new Date(
|
||||
anchorMs + count * prediction.intervalMinutes * 60 * 1000
|
||||
);
|
||||
const close = new Date(anchorMs + count * prediction.intervalMinutes * 60 * 1000);
|
||||
const today = new Date();
|
||||
const showDate =
|
||||
open.toDateString() !== today.toDateString() ||
|
||||
@ -136,20 +128,26 @@ function formatCandlePeriod(prediction: CandlePredictPrediction): {
|
||||
: '';
|
||||
return {
|
||||
range: `${dateLabel}${formatTime(open)} – ${formatTime(close)}`,
|
||||
placedAt: `Placed ${placedAt}`,
|
||||
detail: `${count} consecutive candles · ${prediction.intervalMinutes}m each`,
|
||||
placedAt,
|
||||
detail: t('candlePredict.recentPredictions.multiPeriod', {
|
||||
count,
|
||||
minutes: prediction.intervalMinutes,
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
range: `Multi · ${count} × ${prediction.intervalMinutes}m`,
|
||||
placedAt: `Placed ${placedAt}`,
|
||||
range: t('candlePredict.recentPredictions.multiPeriodShort', {
|
||||
count,
|
||||
minutes: prediction.intervalMinutes,
|
||||
}),
|
||||
placedAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (prediction.candleOpenMs == null) {
|
||||
return {
|
||||
range: `${prediction.intervalMinutes}m`,
|
||||
placedAt: `Placed ${placedAt}`,
|
||||
placedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@ -166,37 +164,37 @@ function formatCandlePeriod(prediction: CandlePredictPrediction): {
|
||||
|
||||
return {
|
||||
range: `${dateLabel}${formatTime(open)} – ${formatTime(close)}`,
|
||||
placedAt: `Placed ${placedAt}`,
|
||||
placedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function multiProgressDetail(p: CandlePredictPrediction): string | null {
|
||||
function multiProgressDetail(t: TFunction, 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}`;
|
||||
return t('candlePredict.recentPredictions.multiFailed', { current: step + 1, total });
|
||||
}
|
||||
if (p.status === 'won') {
|
||||
return `All ${total} candles validated`;
|
||||
return t('candlePredict.recentPredictions.multiWon', { total });
|
||||
}
|
||||
if (p.status === 'in_progress' || p.status === 'pending') {
|
||||
return `Validating candle ${step + 1} of ${total}`;
|
||||
return t('candlePredict.recentPredictions.multiValidating', { current: step + 1, total });
|
||||
}
|
||||
if (p.status === 'refunded') {
|
||||
return `Sequence refunded (${total} candles)`;
|
||||
return t('candlePredict.recentPredictions.multiRefunded', { total });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function ModeChip({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
function ModeChip({ prediction, t }: { prediction: CandlePredictPrediction; t: TFunction }) {
|
||||
if (isMultiPrediction(prediction)) {
|
||||
const level = prediction.level ?? multiCandleCount(prediction);
|
||||
return (
|
||||
<Chip
|
||||
label={`Multi · L${level}`}
|
||||
label={t('candlePredict.recentPredictions.modeMulti', { level })}
|
||||
size="small"
|
||||
sx={{
|
||||
fontWeight: 800,
|
||||
@ -214,14 +212,14 @@ function ModeChip({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
return (
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center', flexWrap: 'nowrap', width: 'max-content' }}>
|
||||
<Chip
|
||||
label="Single"
|
||||
label={t('candlePredict.recentPredictions.modeSingle')}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ fontWeight: 800, fontSize: 11, flexShrink: 0 }}
|
||||
/>
|
||||
{prediction.isAuto && (
|
||||
<Chip
|
||||
label="Auto"
|
||||
label={t('candlePredict.recentPredictions.modeAuto')}
|
||||
size="small"
|
||||
color="warning"
|
||||
sx={{ fontWeight: 700, fontSize: 11, flexShrink: 0 }}
|
||||
@ -231,7 +229,7 @@ function ModeChip({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
);
|
||||
}
|
||||
|
||||
function DirectionChip({ direction }: { direction: CandleDirection }) {
|
||||
function DirectionChip({ direction, t }: { direction: CandleDirection; t: TFunction }) {
|
||||
const isShort = direction === 'short';
|
||||
const color = isShort ? SHORT_COLOR : LONG_COLOR;
|
||||
return (
|
||||
@ -244,7 +242,7 @@ function DirectionChip({ direction }: { direction: CandleDirection }) {
|
||||
<TrendingUpRoundedIcon sx={{ color: `${color} !important` }} />
|
||||
)
|
||||
}
|
||||
label={isShort ? 'Short' : 'Long'}
|
||||
label={isShort ? t('candlePredict.betting.short') : t('candlePredict.betting.long')}
|
||||
sx={{
|
||||
fontWeight: 800,
|
||||
fontSize: 11,
|
||||
@ -257,7 +255,13 @@ function DirectionChip({ direction }: { direction: CandleDirection }) {
|
||||
);
|
||||
}
|
||||
|
||||
function DirectionCell({ direction }: { direction: CandlePredictPrediction['direction'] }) {
|
||||
function DirectionCell({
|
||||
direction,
|
||||
t,
|
||||
}: {
|
||||
direction: CandlePredictPrediction['direction'];
|
||||
t: TFunction;
|
||||
}) {
|
||||
const isShort = direction === 'short';
|
||||
const color = isShort ? SHORT_COLOR : LONG_COLOR;
|
||||
|
||||
@ -268,17 +272,17 @@ function DirectionCell({ direction }: { direction: CandlePredictPrediction['dire
|
||||
) : (
|
||||
<TrendingUpRoundedIcon fontSize="small" sx={{ color }} />
|
||||
)}
|
||||
<span>{isShort ? 'Short' : 'Long'}</span>
|
||||
<span>{isShort ? t('candlePredict.betting.short') : t('candlePredict.betting.long')}</span>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
function MultiSequenceRow({ prediction, t }: { prediction: CandlePredictPrediction; t: TFunction }) {
|
||||
const sequence = prediction.sequenceDirections ?? [];
|
||||
const step = prediction.sequenceStep ?? 0;
|
||||
|
||||
if (!sequence.length) {
|
||||
return <DirectionCell direction={prediction.direction} />;
|
||||
return <DirectionCell direction={prediction.direction} t={t} />;
|
||||
}
|
||||
|
||||
const markerForIndex = (i: number): { label: string; color: 'success' | 'error' | 'warning' | 'default' } => {
|
||||
@ -298,6 +302,8 @@ function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction
|
||||
return { label: `${i + 1}`, color: 'default' };
|
||||
};
|
||||
|
||||
const progressDetail = multiProgressDetail(t, prediction);
|
||||
|
||||
return (
|
||||
<Stack spacing={0.75}>
|
||||
<Stack direction="row" spacing={0.5} useFlexGap sx={{ flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
@ -309,7 +315,7 @@ function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction
|
||||
<Typography variant="caption" sx={{ opacity: 0.55, fontWeight: 700, minWidth: 14 }}>
|
||||
{i + 1}.
|
||||
</Typography>
|
||||
<DirectionChip direction={dir} />
|
||||
<DirectionChip direction={dir} t={t} />
|
||||
<Chip
|
||||
size="small"
|
||||
label={marker.label}
|
||||
@ -321,20 +327,20 @@ function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
{multiProgressDetail(prediction) && (
|
||||
{progressDetail && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 600 }}>
|
||||
{multiProgressDetail(prediction)}
|
||||
{progressDetail}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function PredictionCell({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
function PredictionCell({ prediction, t }: { prediction: CandlePredictPrediction; t: TFunction }) {
|
||||
if (isMultiPrediction(prediction)) {
|
||||
return <MultiSequenceRow prediction={prediction} />;
|
||||
return <MultiSequenceRow prediction={prediction} t={t} />;
|
||||
}
|
||||
return <DirectionCell direction={prediction.direction} />;
|
||||
return <DirectionCell direction={prediction.direction} t={t} />;
|
||||
}
|
||||
|
||||
function PeriodCell({
|
||||
@ -391,6 +397,7 @@ export function RecentPredictionsPanel({
|
||||
roundStatus,
|
||||
intervalMinutes,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const isCompact = useMediaQuery(theme.breakpoints.down('md'));
|
||||
|
||||
@ -414,6 +421,7 @@ export function RecentPredictionsPanel({
|
||||
|
||||
const items = predictionsQ.data?.items ?? [];
|
||||
const total = predictionsQ.data?.total ?? 0;
|
||||
const cols = 'candlePredict.recentPredictions.columns';
|
||||
|
||||
return (
|
||||
<Paper sx={{ p: 2, borderRadius: 3, minWidth: 0 }}>
|
||||
@ -424,10 +432,13 @@ export function RecentPredictionsPanel({
|
||||
sx={{ alignItems: 'center', justifyContent: 'space-between', mb: 1.5, flexWrap: 'wrap' }}
|
||||
>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, flex: '1 1 auto', minWidth: 0 }}>
|
||||
Recent predictions
|
||||
{t('candlePredict.recentPredictions.title')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, flexShrink: 0 }}>
|
||||
{total} total · {PREDICTIONS_PAGE_SIZE} per page
|
||||
{t('candlePredict.recentPredictions.totalPerPage', {
|
||||
total,
|
||||
size: PREDICTIONS_PAGE_SIZE,
|
||||
})}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
@ -437,8 +448,9 @@ export function RecentPredictionsPanel({
|
||||
<>
|
||||
<Stack spacing={1.25}>
|
||||
{items.map((p) => {
|
||||
const period = formatCandlePeriod(p);
|
||||
const progressDetail = multiProgressDetail(p);
|
||||
const period = formatCandlePeriod(t, p);
|
||||
const progressDetail = multiProgressDetail(t, p);
|
||||
const payout = p.payoutDisplay > 0 ? p.payoutDisplay : '—';
|
||||
return (
|
||||
<Paper
|
||||
key={p.id}
|
||||
@ -452,16 +464,16 @@ export function RecentPredictionsPanel({
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap', mb: 1 }}>
|
||||
<ModeChip prediction={p} />
|
||||
<ModeChip prediction={p} t={t} />
|
||||
<Chip
|
||||
label={formatStakeAccount(p.stakeAccountKind ?? 'main')}
|
||||
label={formatStakeAccount(t, 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} />}
|
||||
label={<StatusLabel status={p.status} t={t} />}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{
|
||||
@ -473,7 +485,7 @@ export function RecentPredictionsPanel({
|
||||
</Stack>
|
||||
|
||||
<Box sx={{ mb: 1 }}>
|
||||
<PredictionCell prediction={p} />
|
||||
<PredictionCell prediction={p} t={t} />
|
||||
</Box>
|
||||
|
||||
<Typography variant="body2" sx={{ fontWeight: 600 }}>
|
||||
@ -485,8 +497,11 @@ export function RecentPredictionsPanel({
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block', mt: 0.25 }}>
|
||||
{period.placedAt} · Stake {p.stakeDisplay} · Payout{' '}
|
||||
{p.payoutDisplay > 0 ? p.payoutDisplay : '—'}
|
||||
{t('candlePredict.recentPredictions.stakeLine', {
|
||||
placed: period.placedAt,
|
||||
stake: p.stakeDisplay,
|
||||
payout,
|
||||
})}
|
||||
</Typography>
|
||||
{progressDetail && !isMultiPrediction(p) && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 600, display: 'block' }}>
|
||||
@ -497,7 +512,9 @@ export function RecentPredictionsPanel({
|
||||
);
|
||||
})}
|
||||
{!items.length && (
|
||||
<Typography sx={{ opacity: 0.6, py: 2, textAlign: 'center' }}>No predictions yet</Typography>
|
||||
<Typography sx={{ opacity: 0.6, py: 2, textAlign: 'center' }}>
|
||||
{t('candlePredict.recentPredictions.empty')}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
@ -519,23 +536,23 @@ export function RecentPredictionsPanel({
|
||||
<Table size="small" sx={predictionsTableSx}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell sx={{ width: '1%', pr: 2 }}>Mode</TableCell>
|
||||
<TableCell sx={{ minWidth: 160 }}>Prediction</TableCell>
|
||||
<TableCell sx={{ minWidth: 220 }}>Period</TableCell>
|
||||
<TableCell sx={{ width: '1%', pr: 2 }}>{t(`${cols}.mode`)}</TableCell>
|
||||
<TableCell sx={{ minWidth: 160 }}>{t(`${cols}.prediction`)}</TableCell>
|
||||
<TableCell sx={{ minWidth: 220 }}>{t(`${cols}.period`)}</TableCell>
|
||||
<TableCell align="right" sx={{ width: 72 }}>
|
||||
Stake
|
||||
{t(`${cols}.stake`)}
|
||||
</TableCell>
|
||||
<TableCell sx={{ width: 88 }}>Account</TableCell>
|
||||
<TableCell sx={{ minWidth: 110 }}>Status</TableCell>
|
||||
<TableCell sx={{ width: 88 }}>{t(`${cols}.account`)}</TableCell>
|
||||
<TableCell sx={{ minWidth: 110 }}>{t(`${cols}.status`)}</TableCell>
|
||||
<TableCell align="right" sx={{ width: 72 }}>
|
||||
Payout
|
||||
{t(`${cols}.payout`)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{items.map((p) => {
|
||||
const period = formatCandlePeriod(p);
|
||||
const progressDetail = multiProgressDetail(p);
|
||||
const period = formatCandlePeriod(t, p);
|
||||
const progressDetail = multiProgressDetail(t, p);
|
||||
return (
|
||||
<TableRow
|
||||
key={p.id}
|
||||
@ -546,10 +563,10 @@ export function RecentPredictionsPanel({
|
||||
}
|
||||
>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
<ModeChip prediction={p} />
|
||||
<ModeChip prediction={p} t={t} />
|
||||
</TableCell>
|
||||
<TableCell sx={{ minWidth: 160 }}>
|
||||
<PredictionCell prediction={p} />
|
||||
<PredictionCell prediction={p} t={t} />
|
||||
</TableCell>
|
||||
<TableCell sx={{ minWidth: 220 }}>
|
||||
<PeriodCell prediction={p} period={period} />
|
||||
@ -559,7 +576,7 @@ export function RecentPredictionsPanel({
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
<Chip
|
||||
label={formatStakeAccount(p.stakeAccountKind ?? 'main')}
|
||||
label={formatStakeAccount(t, p.stakeAccountKind ?? 'main')}
|
||||
size="small"
|
||||
color={stakeAccountChipColor(p.stakeAccountKind ?? 'main')}
|
||||
variant={p.stakeAccountKind === 'main' ? 'outlined' : 'filled'}
|
||||
@ -569,7 +586,7 @@ export function RecentPredictionsPanel({
|
||||
<TableCell>
|
||||
<Stack spacing={0.25} sx={{ minWidth: 0 }}>
|
||||
<Box sx={{ whiteSpace: 'nowrap' }}>
|
||||
<StatusLabel status={p.status} />
|
||||
<StatusLabel status={p.status} t={t} />
|
||||
</Box>
|
||||
{progressDetail && (
|
||||
<Typography
|
||||
@ -590,7 +607,7 @@ export function RecentPredictionsPanel({
|
||||
{!items.length && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} sx={{ opacity: 0.6 }}>
|
||||
No predictions yet
|
||||
{t('candlePredict.recentPredictions.empty')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@ -614,7 +631,7 @@ export function RecentPredictionsPanel({
|
||||
|
||||
{predictionsQ.isError && (
|
||||
<Alert severity="warning" sx={{ mt: 1.5 }}>
|
||||
Could not load predictions. Try refreshing the page.
|
||||
{t('candlePredict.recentPredictions.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
Typography,
|
||||
alpha,
|
||||
} from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { StakeAccountKind } from '../types';
|
||||
|
||||
const MASK = '••••••';
|
||||
@ -94,6 +95,11 @@ export function StakeWalletBalanceBar({
|
||||
onToggleVisibility,
|
||||
loading,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const visibilityLabel = balancesVisible
|
||||
? t('candlePredict.stakeWallet.hideBalances')
|
||||
: t('candlePredict.stakeWallet.showBalances');
|
||||
|
||||
return (
|
||||
<Paper
|
||||
elevation={0}
|
||||
@ -112,13 +118,13 @@ export function StakeWalletBalanceBar({
|
||||
sx={{ alignItems: 'center', justifyContent: 'space-between', mb: 1.5, flexWrap: 'nowrap' }}
|
||||
>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, flex: 1, minWidth: 0 }}>
|
||||
Vos portefeuilles de mise
|
||||
{t('candlePredict.stakeWallet.barTitle')}
|
||||
</Typography>
|
||||
<Tooltip title={balancesVisible ? 'Masquer les soldes' : 'Afficher les soldes'}>
|
||||
<Tooltip title={visibilityLabel}>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={onToggleVisibility}
|
||||
aria-label={balancesVisible ? 'Masquer les soldes' : 'Afficher les soldes'}
|
||||
aria-label={visibilityLabel}
|
||||
sx={{ flexShrink: 0 }}
|
||||
>
|
||||
{balancesVisible ? (
|
||||
@ -151,7 +157,7 @@ export function StakeWalletBalanceBar({
|
||||
}}
|
||||
>
|
||||
<WalletCard
|
||||
title="Wallet principal"
|
||||
title={t('candlePredict.stakeWallet.mainWallet')}
|
||||
amount={mainLabel}
|
||||
icon={<AccountBalanceWalletRoundedIcon fontSize="small" />}
|
||||
accent="#D6B25E"
|
||||
@ -159,7 +165,7 @@ export function StakeWalletBalanceBar({
|
||||
hidden={!balancesVisible}
|
||||
/>
|
||||
<WalletCard
|
||||
title="Wallet bonus"
|
||||
title={t('candlePredict.stakeWallet.bonusWallet')}
|
||||
amount={bonusLabel}
|
||||
icon={<CardGiftcardRoundedIcon fontSize="small" />}
|
||||
accent="#7C5CFF"
|
||||
@ -167,7 +173,7 @@ export function StakeWalletBalanceBar({
|
||||
hidden={!balancesVisible}
|
||||
/>
|
||||
<WalletCard
|
||||
title="Wallet de test"
|
||||
title={t('candlePredict.stakeWallet.testWallet')}
|
||||
amount={testLabel}
|
||||
icon={<ScienceRoundedIcon fontSize="small" />}
|
||||
accent="#4CAF50"
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { FormControl, InputLabel, MenuItem, Select, Typography } from '@mui/material';
|
||||
import { FormControl, InputLabel, MenuItem, Select } from '@mui/material';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
|
||||
export type StakeAccountKind = 'main' | 'bonus' | 'test';
|
||||
|
||||
@ -22,28 +23,36 @@ export function StakeWalletSelector({
|
||||
disabled,
|
||||
size = 'small',
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<FormControl fullWidth size={size} disabled={disabled}>
|
||||
<InputLabel>Stake wallet</InputLabel>
|
||||
<InputLabel>{t('candlePredict.stakeWalletSelector.label')}</InputLabel>
|
||||
<Select
|
||||
label="Stake wallet"
|
||||
label={t('candlePredict.stakeWalletSelector.label')}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value as StakeAccountKind)}
|
||||
>
|
||||
<MenuItem value="main">
|
||||
<Typography variant="body2">
|
||||
Main wallet · <strong>{mainBalanceLabel}</strong>
|
||||
</Typography>
|
||||
<Trans
|
||||
i18nKey="candlePredict.stakeWalletSelector.mainWallet"
|
||||
values={{ balance: mainBalanceLabel }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</MenuItem>
|
||||
<MenuItem value="bonus">
|
||||
<Typography variant="body2">
|
||||
Bonus wallet · <strong>{bonusBalanceLabel}</strong>
|
||||
</Typography>
|
||||
<Trans
|
||||
i18nKey="candlePredict.stakeWalletSelector.bonusWallet"
|
||||
values={{ balance: bonusBalanceLabel }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</MenuItem>
|
||||
<MenuItem value="test">
|
||||
<Typography variant="body2">
|
||||
Test wallet · <strong>{testBalanceLabel}</strong>
|
||||
</Typography>
|
||||
<Trans
|
||||
i18nKey="candlePredict.stakeWalletSelector.testWallet"
|
||||
values={{ balance: testBalanceLabel }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import ScienceRoundedIcon from '@mui/icons-material/ScienceRounded';
|
||||
import { Alert, Stack, Typography } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/** Prominent banner when stakes use the play-money test wallet. */
|
||||
export function TestModeBanner() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Alert
|
||||
severity="success"
|
||||
@ -16,11 +18,10 @@ export function TestModeBanner() {
|
||||
}}
|
||||
>
|
||||
<Stack spacing={0.25}>
|
||||
<Typography sx={{ fontWeight: 900, letterSpacing: 0.3 }}>Mode test</Typography>
|
||||
<Typography variant="body2">
|
||||
You are playing with test credits only. Winnings and losses stay in your test wallet — they
|
||||
cannot be withdrawn or transferred to your main wallet.
|
||||
<Typography sx={{ fontWeight: 900, letterSpacing: 0.3 }}>
|
||||
{t('candlePredict.testMode.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2">{t('candlePredict.testMode.hint')}</Typography>
|
||||
</Stack>
|
||||
</Alert>
|
||||
);
|
||||
|
||||
@ -41,6 +41,37 @@ export function parseStakeAmountInput(
|
||||
return { ok: true, value };
|
||||
}
|
||||
|
||||
export function stakeAmountFormatErrorCode(
|
||||
raw: string,
|
||||
options?: { whileTyping?: boolean }
|
||||
): 'required' | 'invalidFormat' | 'zero' | 'invalid' | null {
|
||||
const s = raw.trim();
|
||||
const whileTyping = options?.whileTyping ?? false;
|
||||
|
||||
if (!s) return whileTyping ? null : 'required';
|
||||
|
||||
if (!isPartialStakeAmountInput(s)) return 'invalidFormat';
|
||||
|
||||
if (isValidStakeAmountFormat(s)) return null;
|
||||
|
||||
if (whileTyping && isIncompleteStakeAmountInput(s)) return null;
|
||||
|
||||
if (/^0(\.0*)?$/.test(s)) return 'zero';
|
||||
|
||||
return 'invalid';
|
||||
}
|
||||
|
||||
export function stakeAmountRangeErrorCode(
|
||||
raw: string,
|
||||
minStake: number,
|
||||
maxStake: number
|
||||
): 'outOfRange' | null {
|
||||
const parsed = parseStakeAmountInput(raw);
|
||||
if (!parsed.ok) return null;
|
||||
if (parsed.value < minStake || parsed.value > maxStake) return 'outOfRange';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function stakeAmountFormatError(
|
||||
raw: string,
|
||||
options?: { whileTyping?: boolean }
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import SaveRoundedIcon from '@mui/icons-material/SaveRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
useAdminCandleConfig,
|
||||
useUpdateAdminCandleConfig,
|
||||
@ -21,11 +22,10 @@ import {
|
||||
import { CandlePredictIntervalsPanel } from './CandlePredictIntervalsPanel';
|
||||
import { CandlePredictMultiLevelsPanel } from './CandlePredictMultiLevelsPanel';
|
||||
import type { PoolWinnerRule } from '../candle-predict/types';
|
||||
import { NEUTRAL_ROUND_BEHAVIOR } from '../candle-predict/utils/poolNeutrality';
|
||||
import { poolWinnerRuleDescription } from '../candle-predict/utils/poolWinnerRule';
|
||||
|
||||
/** Admin panel to configure Candle Predict global rules and time intervals. */
|
||||
export function CandlePredictConfigPanel() {
|
||||
const { t } = useTranslation();
|
||||
const configQ = useAdminCandleConfig();
|
||||
const saveMut = useUpdateAdminCandleConfig();
|
||||
const [form, setForm] = useState({
|
||||
@ -47,7 +47,9 @@ export function CandlePredictConfigPanel() {
|
||||
predictionAutoEnabled: true,
|
||||
predictionMultiEnabled: true,
|
||||
});
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState<{ severity: 'success' | 'error'; text: string } | null>(
|
||||
null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (configQ.data) {
|
||||
@ -97,7 +99,7 @@ export function CandlePredictConfigPanel() {
|
||||
.filter((n) => !Number.isNaN(n) && n > 0);
|
||||
|
||||
const save = async () => {
|
||||
setMessage(null);
|
||||
setFeedback(null);
|
||||
try {
|
||||
await saveMut.mutateAsync({
|
||||
stakeAmounts: parseNums(form.stakeAmounts),
|
||||
@ -120,23 +122,35 @@ export function CandlePredictConfigPanel() {
|
||||
multiCandle: form.predictionMultiEnabled,
|
||||
},
|
||||
});
|
||||
setMessage('Configuration saved');
|
||||
setFeedback({
|
||||
severity: 'success',
|
||||
text: t('admin.catalog.candlePredict.config.configSaved'),
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
setMessage(err?.response?.data?.error ?? 'Save failed');
|
||||
setFeedback({
|
||||
severity: 'error',
|
||||
text: err?.response?.data?.error ?? t('admin.catalog.candlePredict.config.saveFailed'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (configQ.isLoading) return <Alert severity="info">Loading game config…</Alert>;
|
||||
const poolWinnerDesc =
|
||||
form.poolWinnerRule === 'majority'
|
||||
? t('admin.catalog.candlePredict.config.poolWinnerMajorityDesc')
|
||||
: t('admin.catalog.candlePredict.config.poolWinnerMinorityDesc');
|
||||
|
||||
if (configQ.isLoading) {
|
||||
return <Alert severity="info">{t('admin.catalog.candlePredict.config.loading')}</Alert>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
Global settings
|
||||
{t('admin.catalog.candlePredict.config.globalTitle')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Synthetic candles are generated from player stake pools — no real market data. Interval-specific
|
||||
overrides are managed below; empty fields inherit these defaults.
|
||||
{t('admin.catalog.candlePredict.config.globalIntro')}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
@ -146,30 +160,30 @@ export function CandlePredictConfigPanel() {
|
||||
mb: 4,
|
||||
}}
|
||||
>
|
||||
{message && (
|
||||
<Alert severity={message.includes('failed') ? 'error' : 'success'} sx={{ gridColumn: '1 / -1' }}>
|
||||
{message}
|
||||
{feedback && (
|
||||
<Alert severity={feedback.severity} sx={{ gridColumn: '1 / -1' }}>
|
||||
{feedback.text}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
label="Stake amounts (comma-separated)"
|
||||
label={t('admin.catalog.candlePredict.config.stakeAmounts')}
|
||||
value={form.stakeAmounts}
|
||||
onChange={(e) => setForm({ ...form, stakeAmounts: e.target.value })}
|
||||
fullWidth
|
||||
helperText="Quick-pick buttons for players — each value must be within min/max below"
|
||||
helperText={t('admin.catalog.candlePredict.config.stakeAmountsHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Minimum stake (custom input)"
|
||||
label={t('admin.catalog.candlePredict.config.minStake')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 0.01, min: 0.01 } }}
|
||||
value={form.minStakeAmount}
|
||||
onChange={(e) => setForm({ ...form, minStakeAmount: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Lowest amount allowed in free-form stake field (e.g. 0.01 for cents)"
|
||||
helperText={t('admin.catalog.candlePredict.config.minStakeHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Maximum stake"
|
||||
label={t('admin.catalog.candlePredict.config.maxStake')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 1, min: 0.01 } }}
|
||||
value={form.maxStakeAmount}
|
||||
@ -177,28 +191,27 @@ export function CandlePredictConfigPanel() {
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Default prediction window (seconds)"
|
||||
label={t('admin.catalog.candlePredict.config.predictionWindow')}
|
||||
type="number"
|
||||
value={form.predictionWindowSeconds}
|
||||
onChange={(e) => setForm({ ...form, predictionWindowSeconds: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Default seconds before each candle close to place predictions"
|
||||
helperText={t('admin.catalog.candlePredict.config.predictionWindowHint')}
|
||||
/>
|
||||
<Typography variant="subtitle2" sx={{ gridColumn: '1 / -1', fontWeight: 800, mt: 1 }}>
|
||||
Neutral round rules
|
||||
{t('admin.catalog.candlePredict.config.neutralTitle')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ gridColumn: '1 / -1', opacity: 0.75, mb: -1 }}>
|
||||
{NEUTRAL_ROUND_BEHAVIOR} Use the rules below to declare a round neutral when pools are
|
||||
too balanced or too one-sided.
|
||||
{t('admin.catalog.candlePredict.config.neutralBehavior')}
|
||||
</Typography>
|
||||
<TextField
|
||||
label="Min tolerance — close pools (%)"
|
||||
label={t('admin.catalog.candlePredict.config.minTolerance')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 0.5, min: 0, max: 50 } }}
|
||||
value={form.tieTolerancePercent}
|
||||
onChange={(e) => setForm({ ...form, tieTolerancePercent: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Neutral when |Long% − Short%| ≤ this value (e.g. 49/51 at 2%)"
|
||||
helperText={t('admin.catalog.candlePredict.config.minToleranceHint')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -207,16 +220,16 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, tieToleranceMinEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Enable min tolerance rule"
|
||||
label={t('admin.catalog.candlePredict.config.enableMinTolerance')}
|
||||
/>
|
||||
<TextField
|
||||
label="Max tolerance — extreme imbalance (%)"
|
||||
label={t('admin.catalog.candlePredict.config.maxTolerance')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 1, min: 51, max: 100 } }}
|
||||
value={form.tieToleranceMaxPercent}
|
||||
onChange={(e) => setForm({ ...form, tieToleranceMaxPercent: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Neutral when largest pool ≥ this value (e.g. 95/5 at 95%)"
|
||||
helperText={t('admin.catalog.candlePredict.config.maxToleranceHint')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -225,52 +238,58 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, tieToleranceMaxEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Enable max tolerance rule"
|
||||
label={t('admin.catalog.candlePredict.config.enableMaxTolerance')}
|
||||
/>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel id="pool-winner-rule-label">Pool winner rule</InputLabel>
|
||||
<InputLabel id="pool-winner-rule-label">
|
||||
{t('admin.catalog.candlePredict.config.poolWinnerRule')}
|
||||
</InputLabel>
|
||||
<Select
|
||||
labelId="pool-winner-rule-label"
|
||||
label="Pool winner rule"
|
||||
label={t('admin.catalog.candlePredict.config.poolWinnerRule')}
|
||||
value={form.poolWinnerRule}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, poolWinnerRule: e.target.value as PoolWinnerRule })
|
||||
}
|
||||
>
|
||||
<MenuItem value="minority">Minority pool wins (smaller total stake)</MenuItem>
|
||||
<MenuItem value="majority">Majority pool wins (larger total stake)</MenuItem>
|
||||
<MenuItem value="minority">
|
||||
{t('admin.catalog.candlePredict.config.poolWinnerMinority')}
|
||||
</MenuItem>
|
||||
<MenuItem value="majority">
|
||||
{t('admin.catalog.candlePredict.config.poolWinnerMajority')}
|
||||
</MenuItem>
|
||||
</Select>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, mt: 0.75, display: 'block' }}>
|
||||
{poolWinnerRuleDescription(form.poolWinnerRule)} Applied immediately to new settlements.
|
||||
{poolWinnerDesc} {t('admin.catalog.candlePredict.config.poolWinnerApplied')}
|
||||
</Typography>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label="Default base chart price"
|
||||
label={t('admin.catalog.candlePredict.config.basePrice')}
|
||||
type="number"
|
||||
value={form.basePrice}
|
||||
onChange={(e) => setForm({ ...form, basePrice: Number(e.target.value) })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Default pool multiplier"
|
||||
label={t('admin.catalog.candlePredict.config.poolMultiplier')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 0.05, min: 0.01 } }}
|
||||
value={form.poolMultiplier}
|
||||
onChange={(e) => setForm({ ...form, poolMultiplier: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Stake weight in Long/Short pools (single, auto, multi final candle)"
|
||||
helperText={t('admin.catalog.candlePredict.config.poolMultiplierHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Default payout multiplier"
|
||||
label={t('admin.catalog.candlePredict.config.payoutMultiplier')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { step: 0.05, min: 1 } }}
|
||||
value={form.payoutMultiplier}
|
||||
onChange={(e) => setForm({ ...form, payoutMultiplier: Number(e.target.value) })}
|
||||
fullWidth
|
||||
helperText="Win payout for correct predictions — independent from pool weight"
|
||||
helperText={t('admin.catalog.candlePredict.config.payoutMultiplierHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Wallet type code"
|
||||
label={t('admin.catalog.candlePredict.config.walletTypeCode')}
|
||||
value={form.walletTypeCode}
|
||||
onChange={(e) => setForm({ ...form, walletTypeCode: e.target.value })}
|
||||
fullWidth
|
||||
@ -282,15 +301,15 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Game active"
|
||||
label={t('admin.catalog.candlePredict.config.gameActive')}
|
||||
sx={{ gridColumn: { md: '1 / -1' } }}
|
||||
/>
|
||||
|
||||
<Typography variant="subtitle2" sx={{ gridColumn: '1 / -1', fontWeight: 800, mt: 1 }}>
|
||||
Prediction modes
|
||||
{t('admin.catalog.candlePredict.config.modesTitle')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ gridColumn: '1 / -1', opacity: 0.75, mb: -1 }}>
|
||||
Enable or disable each prediction type independently. Disabled modes are hidden from players.
|
||||
{t('admin.catalog.candlePredict.config.modesIntro')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -299,7 +318,7 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, predictionSingleEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Single-candle predictions"
|
||||
label={t('admin.catalog.candlePredict.config.singleEnabled')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -308,7 +327,7 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, predictionAutoEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Auto predictions"
|
||||
label={t('admin.catalog.candlePredict.config.autoEnabled')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -317,18 +336,23 @@ export function CandlePredictConfigPanel() {
|
||||
onChange={(e) => setForm({ ...form, predictionMultiEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Multi-candle predictions"
|
||||
label={t('admin.catalog.candlePredict.config.multiEnabled')}
|
||||
/>
|
||||
|
||||
<Stack direction="row" sx={{ gridColumn: '1 / -1' }}>
|
||||
<Button variant="contained" startIcon={<SaveRoundedIcon />} onClick={() => void save()} disabled={saveMut.isPending}>
|
||||
Save global config
|
||||
<Button
|
||||
variant="contained"
|
||||
startIcon={<SaveRoundedIcon />}
|
||||
onClick={() => void save()}
|
||||
disabled={saveMut.isPending}
|
||||
>
|
||||
{t('admin.catalog.candlePredict.config.saveGlobal')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
Prediction intervals
|
||||
{t('admin.catalog.candlePredict.config.intervalsTitle')}
|
||||
</Typography>
|
||||
<CandlePredictIntervalsPanel />
|
||||
|
||||
|
||||
@ -27,6 +27,7 @@ import AddRoundedIcon from '@mui/icons-material/AddRounded';
|
||||
import DeleteOutlineRoundedIcon from '@mui/icons-material/DeleteOutlineRounded';
|
||||
import EditRoundedIcon from '@mui/icons-material/EditRounded';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import {
|
||||
useAdminCandleIntervals,
|
||||
@ -105,6 +106,7 @@ function triToBody(value: TriBool): boolean | null | undefined {
|
||||
|
||||
/** Admin CRUD for Candle Predict time intervals (rounds + chart candles per period). */
|
||||
export function CandlePredictIntervalsPanel() {
|
||||
const { t } = useTranslation();
|
||||
const intervalsQ = useAdminCandleIntervals();
|
||||
const createMut = useCreateAdminCandleInterval();
|
||||
const updateMut = useUpdateAdminCandleInterval();
|
||||
@ -114,7 +116,9 @@ export function CandlePredictIntervalsPanel() {
|
||||
open: false,
|
||||
});
|
||||
const [form, setForm] = useState<FormState>(emptyForm());
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState<{ severity: 'success' | 'error'; text: string } | null>(
|
||||
null
|
||||
);
|
||||
|
||||
const openCreate = () => {
|
||||
setForm(emptyForm());
|
||||
@ -133,18 +137,25 @@ export function CandlePredictIntervalsPanel() {
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setMessage(null);
|
||||
setFeedback(null);
|
||||
const windowVal = parseOptional(form.predictionWindowSeconds);
|
||||
if (windowVal != null) {
|
||||
if (windowVal < 5) {
|
||||
setMessage('Prediction window must be at least 5 seconds');
|
||||
setFeedback({
|
||||
severity: 'error',
|
||||
text: t('admin.catalog.candlePredict.intervals.windowMinError'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const max = maxPredictionWindowSeconds(form.intervalMinutes);
|
||||
if (windowVal > max) {
|
||||
setMessage(
|
||||
`Prediction window cannot exceed ${formatWindowLimit(form.intervalMinutes)} for a ${form.intervalMinutes}-minute interval`
|
||||
);
|
||||
setFeedback({
|
||||
severity: 'error',
|
||||
text: t('admin.catalog.candlePredict.intervals.windowMaxError', {
|
||||
max: formatWindowLimit(form.intervalMinutes),
|
||||
minutes: form.intervalMinutes,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -169,30 +180,47 @@ export function CandlePredictIntervalsPanel() {
|
||||
try {
|
||||
if (dialog.editing) {
|
||||
await updateMut.mutateAsync({ id: dialog.editing.id, body });
|
||||
setMessage('Interval updated');
|
||||
setFeedback({
|
||||
severity: 'success',
|
||||
text: t('admin.catalog.candlePredict.intervals.intervalUpdated'),
|
||||
});
|
||||
} else {
|
||||
await createMut.mutateAsync(body);
|
||||
setMessage('Interval created');
|
||||
setFeedback({
|
||||
severity: 'success',
|
||||
text: t('admin.catalog.candlePredict.intervals.intervalCreated'),
|
||||
});
|
||||
}
|
||||
setDialog({ open: false });
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
setMessage(err?.response?.data?.error ?? 'Save failed');
|
||||
setFeedback({
|
||||
severity: 'error',
|
||||
text: err?.response?.data?.error ?? t('admin.catalog.candlePredict.config.saveFailed'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (row: CandlePredictInterval) => {
|
||||
setMessage(null);
|
||||
setFeedback(null);
|
||||
try {
|
||||
await deleteMut.mutateAsync(row.id);
|
||||
setMessage('Interval deleted');
|
||||
setFeedback({
|
||||
severity: 'success',
|
||||
text: t('admin.catalog.candlePredict.intervals.intervalDeleted'),
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
setMessage(err?.response?.data?.error ?? 'Delete failed');
|
||||
setFeedback({
|
||||
severity: 'error',
|
||||
text: err?.response?.data?.error ?? t('admin.catalog.candlePredict.intervals.deleteFailed'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (intervalsQ.isLoading) return <Alert severity="info">Loading intervals…</Alert>;
|
||||
if (intervalsQ.isLoading) {
|
||||
return <Alert severity="info">{t('admin.catalog.candlePredict.intervals.loading')}</Alert>;
|
||||
}
|
||||
|
||||
const rows = intervalsQ.data ?? [];
|
||||
const windowMaxLabel = formatWindowLimit(form.intervalMinutes);
|
||||
@ -210,9 +238,7 @@ export function CandlePredictIntervalsPanel() {
|
||||
sx={{ alignItems: { sm: 'center' }, mb: 2 }}
|
||||
>
|
||||
<Typography sx={{ flex: 1, opacity: 0.75 }}>
|
||||
Each interval has its own rounds and candle chart. Players pick a period; predictions are
|
||||
deferred to the matching round at candle close. Leave override fields empty to inherit
|
||||
global defaults.
|
||||
{t('admin.catalog.candlePredict.intervals.intro')}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
@ -220,16 +246,13 @@ export function CandlePredictIntervalsPanel() {
|
||||
onClick={openCreate}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'auto' }, flexShrink: 0 }}
|
||||
>
|
||||
Add interval
|
||||
{t('admin.catalog.candlePredict.intervals.addInterval')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{message && (
|
||||
<Alert
|
||||
severity={message.includes('failed') || message.includes('Cannot') ? 'error' : 'success'}
|
||||
sx={{ mb: 2 }}
|
||||
>
|
||||
{message}
|
||||
{feedback && (
|
||||
<Alert severity={feedback.severity} sx={{ mb: 2 }}>
|
||||
{feedback.text}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -238,17 +261,17 @@ export function CandlePredictIntervalsPanel() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Order</TableCell>
|
||||
<TableCell>Label</TableCell>
|
||||
<TableCell>Minutes</TableCell>
|
||||
<TableCell>Window (s)</TableCell>
|
||||
<TableCell>Min tie %</TableCell>
|
||||
<TableCell>Max tie %</TableCell>
|
||||
<TableCell>Pool</TableCell>
|
||||
<TableCell>Payout</TableCell>
|
||||
<TableCell>Initial batch</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">Actions</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.order')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.label')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.minutes')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.window')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.minTie')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.maxTie')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.pool')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.payout')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.initialBatch')}</TableCell>
|
||||
<TableCell>{t('admin.catalog.candlePredict.intervals.columns.status')}</TableCell>
|
||||
<TableCell align="right">{t('admin.catalog.candlePredict.intervals.columns.actions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -258,7 +281,12 @@ export function CandlePredictIntervalsPanel() {
|
||||
<TableCell>
|
||||
{row.label}
|
||||
{row.isDefault && (
|
||||
<Chip size="small" label="Default" color="primary" sx={{ ml: 1 }} />
|
||||
<Chip
|
||||
size="small"
|
||||
label={t('admin.catalog.candlePredict.intervals.default')}
|
||||
color="primary"
|
||||
sx={{ ml: 1 }}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>{row.intervalMinutes}</TableCell>
|
||||
@ -271,7 +299,11 @@ export function CandlePredictIntervalsPanel() {
|
||||
<TableCell>
|
||||
<Chip
|
||||
size="small"
|
||||
label={row.isActive ? 'Active' : 'Disabled'}
|
||||
label={
|
||||
row.isActive
|
||||
? t('admin.catalog.candlePredict.intervals.active')
|
||||
: t('admin.catalog.candlePredict.intervals.disabled')
|
||||
}
|
||||
color={row.isActive ? 'success' : 'default'}
|
||||
/>
|
||||
</TableCell>
|
||||
@ -288,7 +320,7 @@ export function CandlePredictIntervalsPanel() {
|
||||
{!rows.length && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={11} sx={{ opacity: 0.6 }}>
|
||||
No intervals configured
|
||||
{t('admin.catalog.candlePredict.intervals.noIntervals')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@ -298,11 +330,15 @@ export function CandlePredictIntervalsPanel() {
|
||||
</Box>
|
||||
|
||||
<Dialog open={dialog.open} onClose={() => setDialog({ open: false })} fullWidth maxWidth="sm">
|
||||
<DialogTitle>{dialog.editing ? 'Edit interval' : 'New interval'}</DialogTitle>
|
||||
<DialogTitle>
|
||||
{dialog.editing
|
||||
? t('admin.catalog.candlePredict.intervals.editTitle')
|
||||
: t('admin.catalog.candlePredict.intervals.newTitle')}
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
<TextField
|
||||
label="Interval (minutes)"
|
||||
label={t('admin.catalog.candlePredict.intervals.intervalMinutes')}
|
||||
type="number"
|
||||
value={form.intervalMinutes}
|
||||
onChange={(e) => setForm({ ...form, intervalMinutes: Number(e.target.value) })}
|
||||
@ -310,98 +346,109 @@ export function CandlePredictIntervalsPanel() {
|
||||
disabled={!!dialog.editing}
|
||||
/>
|
||||
<TextField
|
||||
label="Display label"
|
||||
label={t('admin.catalog.candlePredict.intervals.displayLabel')}
|
||||
value={form.label}
|
||||
onChange={(e) => setForm({ ...form, label: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Sort order"
|
||||
label={t('admin.catalog.candlePredict.intervals.sortOrder')}
|
||||
type="number"
|
||||
value={form.sortOrder}
|
||||
onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Prediction window override (seconds, optional)"
|
||||
label={t('admin.catalog.candlePredict.intervals.windowOverride')}
|
||||
value={form.predictionWindowSeconds}
|
||||
onChange={(e) => setForm({ ...form, predictionWindowSeconds: e.target.value })}
|
||||
fullWidth
|
||||
error={windowInvalid}
|
||||
helperText={`Max ${windowMaxLabel} for ${form.intervalMinutes} min — leave empty for global default`}
|
||||
helperText={t('admin.catalog.candlePredict.intervals.windowOverrideHint', {
|
||||
max: windowMaxLabel,
|
||||
minutes: form.intervalMinutes,
|
||||
})}
|
||||
/>
|
||||
<TextField
|
||||
label="Min tie tolerance override (%)"
|
||||
label={t('admin.catalog.candlePredict.intervals.minTieOverride')}
|
||||
value={form.tieTolerancePercent}
|
||||
onChange={(e) => setForm({ ...form, tieTolerancePercent: e.target.value })}
|
||||
fullWidth
|
||||
helperText="Leave empty to inherit global default"
|
||||
helperText={t('admin.catalog.candlePredict.intervals.minTieOverrideHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Max tie tolerance override (%)"
|
||||
label={t('admin.catalog.candlePredict.intervals.maxTieOverride')}
|
||||
value={form.tieToleranceMaxPercent}
|
||||
onChange={(e) => setForm({ ...form, tieToleranceMaxPercent: e.target.value })}
|
||||
fullWidth
|
||||
helperText="Neutral when largest pool ≥ this % — empty inherits global"
|
||||
helperText={t('admin.catalog.candlePredict.intervals.maxTieOverrideHint')}
|
||||
/>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel id="min-tie-enabled-label">Min tolerance rule</InputLabel>
|
||||
<InputLabel id="min-tie-enabled-label">
|
||||
{t('admin.catalog.candlePredict.intervals.minToleranceRule')}
|
||||
</InputLabel>
|
||||
<Select
|
||||
labelId="min-tie-enabled-label"
|
||||
label="Min tolerance rule"
|
||||
label={t('admin.catalog.candlePredict.intervals.minToleranceRule')}
|
||||
value={form.tieToleranceMinEnabled}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, tieToleranceMinEnabled: e.target.value as TriBool })
|
||||
}
|
||||
>
|
||||
<MenuItem value="inherit">Inherit global</MenuItem>
|
||||
<MenuItem value="on">Enabled</MenuItem>
|
||||
<MenuItem value="off">Disabled</MenuItem>
|
||||
<MenuItem value="inherit">
|
||||
{t('admin.catalog.candlePredict.intervals.inheritGlobal')}
|
||||
</MenuItem>
|
||||
<MenuItem value="on">{t('admin.catalog.candlePredict.intervals.enabled')}</MenuItem>
|
||||
<MenuItem value="off">{t('admin.catalog.candlePredict.intervals.disabled')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel id="max-tie-enabled-label">Max tolerance rule</InputLabel>
|
||||
<InputLabel id="max-tie-enabled-label">
|
||||
{t('admin.catalog.candlePredict.intervals.maxToleranceRule')}
|
||||
</InputLabel>
|
||||
<Select
|
||||
labelId="max-tie-enabled-label"
|
||||
label="Max tolerance rule"
|
||||
label={t('admin.catalog.candlePredict.intervals.maxToleranceRule')}
|
||||
value={form.tieToleranceMaxEnabled}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, tieToleranceMaxEnabled: e.target.value as TriBool })
|
||||
}
|
||||
>
|
||||
<MenuItem value="inherit">Inherit global</MenuItem>
|
||||
<MenuItem value="on">Enabled</MenuItem>
|
||||
<MenuItem value="off">Disabled</MenuItem>
|
||||
<MenuItem value="inherit">
|
||||
{t('admin.catalog.candlePredict.intervals.inheritGlobal')}
|
||||
</MenuItem>
|
||||
<MenuItem value="on">{t('admin.catalog.candlePredict.intervals.enabled')}</MenuItem>
|
||||
<MenuItem value="off">{t('admin.catalog.candlePredict.intervals.disabled')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label="Pool multiplier override"
|
||||
label={t('admin.catalog.candlePredict.intervals.poolMultiplierOverride')}
|
||||
value={form.poolMultiplier}
|
||||
onChange={(e) => setForm({ ...form, poolMultiplier: e.target.value })}
|
||||
fullWidth
|
||||
helperText="Weight in Long/Short pools — leave empty to inherit global default"
|
||||
helperText={t('admin.catalog.candlePredict.intervals.poolMultiplierOverrideHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Payout multiplier override"
|
||||
label={t('admin.catalog.candlePredict.intervals.payoutMultiplierOverride')}
|
||||
value={form.payoutMultiplier}
|
||||
onChange={(e) => setForm({ ...form, payoutMultiplier: e.target.value })}
|
||||
fullWidth
|
||||
helperText="Win payout for correct predictions — leave empty to inherit global default"
|
||||
helperText={t('admin.catalog.candlePredict.intervals.payoutMultiplierOverrideHint')}
|
||||
/>
|
||||
<TextField
|
||||
label="Base price override"
|
||||
label={t('admin.catalog.candlePredict.intervals.basePriceOverride')}
|
||||
value={form.basePrice}
|
||||
onChange={(e) => setForm({ ...form, basePrice: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Initial chart batch size"
|
||||
label={t('admin.catalog.candlePredict.intervals.chartBatchSize')}
|
||||
type="number"
|
||||
value={form.chartCandleLimit}
|
||||
onChange={(e) => setForm({ ...form, chartCandleLimit: Number(e.target.value) })}
|
||||
fullWidth
|
||||
slotProps={{ htmlInput: { min: 20, max: 200 } }}
|
||||
helperText="Candles loaded on open (20–200). Scroll left on the chart to load older history in batches."
|
||||
helperText={t('admin.catalog.candlePredict.intervals.chartBatchSizeHint')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -410,7 +457,7 @@ export function CandlePredictIntervalsPanel() {
|
||||
onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Active"
|
||||
label={t('admin.catalog.candlePredict.intervals.active')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -419,14 +466,14 @@ export function CandlePredictIntervalsPanel() {
|
||||
onChange={(e) => setForm({ ...form, isDefault: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Default interval for new players"
|
||||
label={t('admin.catalog.candlePredict.intervals.defaultForNewPlayers')}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDialog({ open: false })}>Cancel</Button>
|
||||
<Button onClick={() => setDialog({ open: false })}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={() => void save()} disabled={createMut.isPending || updateMut.isPending}>
|
||||
Save
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -15,6 +15,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import SaveRoundedIcon from '@mui/icons-material/SaveRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
useAdminMultiLevels,
|
||||
useUpdateAdminMultiLevels,
|
||||
@ -24,10 +25,13 @@ import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
|
||||
/** Admin panel for multi-candle level configuration. */
|
||||
export function CandlePredictMultiLevelsPanel() {
|
||||
const { t } = useTranslation();
|
||||
const levelsQ = useAdminMultiLevels();
|
||||
const saveMut = useUpdateAdminMultiLevels();
|
||||
const [rows, setRows] = useState<MultiCandleLevel[]>([]);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [feedback, setFeedback] = useState<{ severity: 'success' | 'error'; text: string } | null>(
|
||||
null
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (levelsQ.data) setRows(levelsQ.data);
|
||||
@ -38,13 +42,16 @@ export function CandlePredictMultiLevelsPanel() {
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setMessage(null);
|
||||
setFeedback(null);
|
||||
try {
|
||||
await saveMut.mutateAsync(rows);
|
||||
setMessage('Multi-candle levels saved.');
|
||||
setFeedback({
|
||||
severity: 'success',
|
||||
text: t('admin.catalog.candlePredict.multiLevels.saved'),
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Save failed';
|
||||
setMessage(msg);
|
||||
const msg = e instanceof Error ? e.message : t('admin.catalog.candlePredict.multiLevels.saveFailed');
|
||||
setFeedback({ severity: 'error', text: msg });
|
||||
}
|
||||
};
|
||||
|
||||
@ -53,18 +60,16 @@ export function CandlePredictMultiLevelsPanel() {
|
||||
<Stack spacing={2}>
|
||||
<Box>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Multi-candle levels
|
||||
{t('admin.catalog.candlePredict.multiLevels.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Configure levels from 2 upward. Pool multiplier weights bets in Long/Short pools at the
|
||||
final candle; payout multiplier applies only to the player's win when the full
|
||||
sequence is correct.
|
||||
{t('admin.catalog.candlePredict.multiLevels.intro')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{message && (
|
||||
<Alert severity={message.includes('saved') ? 'success' : 'error'} onClose={() => setMessage(null)}>
|
||||
{message}
|
||||
{feedback && (
|
||||
<Alert severity={feedback.severity} onClose={() => setFeedback(null)}>
|
||||
{feedback.text}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -72,12 +77,24 @@ export function CandlePredictMultiLevelsPanel() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Level</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Candles</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Enabled</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Pool multiplier</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Payout multiplier</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Sort</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.level')}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.candles')}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.enabled')}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.poolMultiplier')}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.payoutMultiplier')}
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>
|
||||
{t('admin.catalog.candlePredict.multiLevels.columns.sort')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -138,7 +155,7 @@ export function CandlePredictMultiLevelsPanel() {
|
||||
onClick={() => void handleSave()}
|
||||
disabled={saveMut.isPending || levelsQ.isLoading}
|
||||
>
|
||||
Save levels
|
||||
{t('admin.catalog.candlePredict.multiLevels.saveLevels')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
@ -33,6 +33,7 @@ import SportsEsportsRoundedIcon from '@mui/icons-material/SportsEsportsRounded';
|
||||
import CandlestickChartRoundedIcon from '@mui/icons-material/CandlestickChartRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import type { Advertisement, AdvertisementInput, Game, GameImplementationOption, GameInput } from '../home/types';
|
||||
@ -66,6 +67,7 @@ const emptyAd: AdvertisementInput = {
|
||||
|
||||
/** Admin page to CRUD games and home-page advertisements. */
|
||||
export function CatalogAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState<TabKey>('games');
|
||||
const qc = useQueryClient();
|
||||
|
||||
@ -115,7 +117,7 @@ export function CatalogAdminPage() {
|
||||
},
|
||||
onError: (e: unknown) => {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
setError(err?.response?.data?.error ?? 'Failed to save game');
|
||||
setError(err?.response?.data?.error ?? t('admin.catalog.saveGameFailed'));
|
||||
},
|
||||
});
|
||||
|
||||
@ -143,7 +145,7 @@ export function CatalogAdminPage() {
|
||||
},
|
||||
onError: (e: unknown) => {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
setError(err?.response?.data?.error ?? 'Failed to save advertisement');
|
||||
setError(err?.response?.data?.error ?? t('admin.catalog.saveAdFailed'));
|
||||
},
|
||||
});
|
||||
|
||||
@ -229,15 +231,15 @@ export function CatalogAdminPage() {
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
title="Catalog"
|
||||
subtitle="Manage games and dynamic home-page promotions."
|
||||
actions={<RefreshIconButton label="Refresh catalog" onClick={refresh} />}
|
||||
title={t('admin.catalog.title')}
|
||||
subtitle={t('admin.catalog.subtitle')}
|
||||
actions={<RefreshIconButton label={t('admin.catalog.refresh')} onClick={refresh} />}
|
||||
/>
|
||||
|
||||
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }} variant="scrollable" scrollButtons="auto">
|
||||
<Tab value="games" icon={<SportsEsportsRoundedIcon />} iconPosition="start" label="Games" />
|
||||
<Tab value="ads" icon={<CampaignRoundedIcon />} iconPosition="start" label="Advertisements" />
|
||||
<Tab value="candle" icon={<CandlestickChartRoundedIcon />} iconPosition="start" label="Candle Predict" />
|
||||
<Tab value="games" icon={<SportsEsportsRoundedIcon />} iconPosition="start" label={t('admin.catalog.tabs.games')} />
|
||||
<Tab value="ads" icon={<CampaignRoundedIcon />} iconPosition="start" label={t('admin.catalog.tabs.ads')} />
|
||||
<Tab value="candle" icon={<CandlestickChartRoundedIcon />} iconPosition="start" label={t('admin.catalog.tabs.candle')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 'games' && (
|
||||
@ -248,10 +250,10 @@ export function CatalogAdminPage() {
|
||||
onClick={openCreateGame}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}
|
||||
>
|
||||
Add game
|
||||
{t('admin.catalog.addGame')}
|
||||
</Button>
|
||||
{gamesQ.isLoading ? (
|
||||
<Alert severity="info">Loading games…</Alert>
|
||||
<Alert severity="info">{t('admin.catalog.loadingGames')}</Alert>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
@ -281,7 +283,7 @@ export function CatalogAdminPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center' }}>
|
||||
<IconButton size="small" onClick={() => openEditGame(game)} aria-label="Edit game">
|
||||
<IconButton size="small" onClick={() => openEditGame(game)} aria-label={t('admin.catalog.editGame')}>
|
||||
<EditRoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<Button
|
||||
@ -291,7 +293,7 @@ export function CatalogAdminPage() {
|
||||
disabled={game.status === 'maintenance' || deactivateGameMut.isPending}
|
||||
onClick={() => deactivateGameMut.mutate(game.id)}
|
||||
>
|
||||
Désactiver
|
||||
{t('admin.catalog.deactivate')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
@ -306,12 +308,12 @@ export function CatalogAdminPage() {
|
||||
variant="outlined"
|
||||
/>
|
||||
) : (
|
||||
<Chip size="small" label="No implementation" variant="outlined" />
|
||||
<Chip size="small" label={t('admin.catalog.noImplementation')} variant="outlined" />
|
||||
)}
|
||||
{game.implementationKey && !hasWebImplementation(game.implementationKey) && (
|
||||
<Chip size="small" label="No web UI" color="warning" variant="outlined" />
|
||||
<Chip size="small" label={t('admin.catalog.noWebUi')} color="warning" variant="outlined" />
|
||||
)}
|
||||
{game.isFeatured && <Chip size="small" label="Featured" color="primary" />}
|
||||
{game.isFeatured && <Chip size="small" label={t('admin.catalog.featured')} color="primary" />}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
@ -330,10 +332,10 @@ export function CatalogAdminPage() {
|
||||
onClick={openCreateAd}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}
|
||||
>
|
||||
Add advertisement
|
||||
{t('admin.catalog.addAd')}
|
||||
</Button>
|
||||
{adsQ.isLoading ? (
|
||||
<Alert severity="info">Loading advertisements…</Alert>
|
||||
<Alert severity="info">{t('admin.catalog.loadingAds')}</Alert>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
@ -378,10 +380,10 @@ export function CatalogAdminPage() {
|
||||
<Stack direction="row" spacing={0.75} useFlexGap sx={{ flexWrap: 'wrap' }}>
|
||||
<Chip
|
||||
size="small"
|
||||
label={ad.isActive ? 'Active' : 'Inactive'}
|
||||
label={ad.isActive ? t('admin.catalog.active') : t('admin.catalog.inactive')}
|
||||
color={ad.isActive ? 'success' : 'default'}
|
||||
/>
|
||||
<Chip size="small" label={`Order ${ad.sortOrder}`} variant="outlined" />
|
||||
<Chip size="small" label={t('admin.catalog.order', { order: ad.sortOrder })} variant="outlined" />
|
||||
</Stack>
|
||||
{ad.subtitle && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
@ -405,19 +407,19 @@ export function CatalogAdminPage() {
|
||||
fullWidth
|
||||
maxWidth="sm"
|
||||
>
|
||||
<DialogTitle>{gameDialog.editing ? 'Edit game' : 'New game'}</DialogTitle>
|
||||
<DialogTitle>{gameDialog.editing ? t('admin.catalog.gameDialog.edit') : t('admin.catalog.gameDialog.new')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
<TextField
|
||||
label="Slug"
|
||||
label={t('admin.catalog.fields.slug')}
|
||||
value={gameForm.slug}
|
||||
onChange={(e) => setGameForm({ ...gameForm, slug: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
helperText={
|
||||
showDefaultSlugAction
|
||||
? `Recommended slug for this implementation: ${selectedImplementation?.defaultSlug}`
|
||||
? t('admin.catalog.fields.slugRecommended', { slug: selectedImplementation?.defaultSlug })
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
@ -433,18 +435,18 @@ export function CatalogAdminPage() {
|
||||
}
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
>
|
||||
Use default slug ({selectedImplementation.defaultSlug})
|
||||
{t('admin.catalog.fields.useDefaultSlug', { slug: selectedImplementation.defaultSlug })}
|
||||
</Button>
|
||||
)}
|
||||
<TextField
|
||||
label="Title"
|
||||
label={t('admin.catalog.fields.title')}
|
||||
value={gameForm.title}
|
||||
onChange={(e) => setGameForm({ ...gameForm, title: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Description"
|
||||
label={t('admin.catalog.fields.description')}
|
||||
value={gameForm.description ?? ''}
|
||||
onChange={(e) => setGameForm({ ...gameForm, description: e.target.value })}
|
||||
fullWidth
|
||||
@ -452,27 +454,27 @@ export function CatalogAdminPage() {
|
||||
minRows={2}
|
||||
/>
|
||||
<TextField
|
||||
label="Category"
|
||||
label={t('admin.catalog.fields.category')}
|
||||
value={gameForm.category ?? ''}
|
||||
onChange={(e) => setGameForm({ ...gameForm, category: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Thumbnail URL"
|
||||
label={t('admin.catalog.fields.thumbnailUrl')}
|
||||
value={gameForm.thumbnailUrl ?? ''}
|
||||
onChange={(e) => setGameForm({ ...gameForm, thumbnailUrl: e.target.value || null })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Accent color"
|
||||
label={t('admin.catalog.fields.accentColor')}
|
||||
value={gameForm.accentColor ?? ''}
|
||||
onChange={(e) => setGameForm({ ...gameForm, accentColor: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Implementation</InputLabel>
|
||||
<InputLabel>{t('admin.catalog.fields.implementation')}</InputLabel>
|
||||
<Select
|
||||
label="Implementation"
|
||||
label={t('admin.catalog.fields.implementation')}
|
||||
value={gameForm.implementationKey ?? ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
@ -483,7 +485,7 @@ export function CatalogAdminPage() {
|
||||
}}
|
||||
>
|
||||
<MenuItem value="">
|
||||
<em>None (catalog only)</em>
|
||||
<em>{t('admin.catalog.fields.implementationNone')}</em>
|
||||
</MenuItem>
|
||||
{(implementationsQ.data ?? []).map((impl) => (
|
||||
<MenuItem key={impl.key} value={impl.key}>
|
||||
@ -493,30 +495,29 @@ export function CatalogAdminPage() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, mt: -1 }}>
|
||||
Links this catalog entry to a backend game module. Required for playable games.
|
||||
{t('admin.catalog.fields.implementationHint')}
|
||||
</Typography>
|
||||
{gameForm.implementationKey && !hasWebImplementation(gameForm.implementationKey) && (
|
||||
<Alert severity="warning" sx={{ py: 0.5 }}>
|
||||
This implementation has no web UI module yet. Players on web will see a "not
|
||||
supported" message until you register it in the frontend.
|
||||
{t('admin.catalog.fields.implementationNoWeb')}
|
||||
</Alert>
|
||||
)}
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Status</InputLabel>
|
||||
<InputLabel>{t('admin.catalog.fields.status')}</InputLabel>
|
||||
<Select
|
||||
label="Status"
|
||||
label={t('admin.catalog.fields.status')}
|
||||
value={gameForm.status ?? 'active'}
|
||||
onChange={(e) =>
|
||||
setGameForm({ ...gameForm, status: e.target.value as GameInput['status'] })
|
||||
}
|
||||
>
|
||||
<MenuItem value="active">Active</MenuItem>
|
||||
<MenuItem value="coming_soon">Coming soon</MenuItem>
|
||||
<MenuItem value="maintenance">Maintenance</MenuItem>
|
||||
<MenuItem value="active">{t('admin.catalog.fields.statusActive')}</MenuItem>
|
||||
<MenuItem value="coming_soon">{t('admin.catalog.fields.statusComingSoon')}</MenuItem>
|
||||
<MenuItem value="maintenance">{t('admin.catalog.fields.statusMaintenance')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label="Sort order"
|
||||
label={t('admin.catalog.fields.sortOrder')}
|
||||
type="number"
|
||||
value={gameForm.sortOrder ?? 0}
|
||||
onChange={(e) => setGameForm({ ...gameForm, sortOrder: Number(e.target.value) })}
|
||||
@ -529,46 +530,46 @@ export function CatalogAdminPage() {
|
||||
onChange={(e) => setGameForm({ ...gameForm, isFeatured: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Featured"
|
||||
label={t('admin.catalog.fields.featured')}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2, flexWrap: 'wrap', gap: 1 }}>
|
||||
<Button onClick={() => setGameDialog({ open: false })}>Cancel</Button>
|
||||
<Button onClick={() => setGameDialog({ open: false })}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={() => saveGameMut.mutate()} disabled={saveGameMut.isPending}>
|
||||
Save
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={adDialog.open} onClose={() => setAdDialog({ open: false })} fullWidth maxWidth="sm">
|
||||
<DialogTitle>{adDialog.editing ? 'Edit advertisement' : 'New advertisement'}</DialogTitle>
|
||||
<DialogTitle>{adDialog.editing ? t('admin.catalog.adDialog.edit') : t('admin.catalog.adDialog.new')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Placement</InputLabel>
|
||||
<InputLabel>{t('admin.catalog.fields.placement')}</InputLabel>
|
||||
<Select
|
||||
label="Placement"
|
||||
label={t('admin.catalog.fields.placement')}
|
||||
value={adForm.placement ?? 'home_hero'}
|
||||
onChange={(e) =>
|
||||
setAdForm({ ...adForm, placement: e.target.value as AdvertisementInput['placement'] })
|
||||
}
|
||||
>
|
||||
<MenuItem value="home_hero">Home hero (carousel)</MenuItem>
|
||||
<MenuItem value="home_strip">Home strip</MenuItem>
|
||||
<MenuItem value="home_sidebar">Home sidebar</MenuItem>
|
||||
<MenuItem value="home_hero">{t('admin.catalog.fields.placementHomeHero')}</MenuItem>
|
||||
<MenuItem value="home_strip">{t('admin.catalog.fields.placementHomeStrip')}</MenuItem>
|
||||
<MenuItem value="home_sidebar">{t('admin.catalog.fields.placementHomeSidebar')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label="Title"
|
||||
label={t('admin.catalog.fields.title')}
|
||||
value={adForm.title}
|
||||
onChange={(e) => setAdForm({ ...adForm, title: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Subtitle"
|
||||
label={t('admin.catalog.fields.subtitle')}
|
||||
value={adForm.subtitle ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, subtitle: e.target.value })}
|
||||
fullWidth
|
||||
@ -576,39 +577,39 @@ export function CatalogAdminPage() {
|
||||
minRows={2}
|
||||
/>
|
||||
<TextField
|
||||
label="CTA label"
|
||||
label={t('admin.catalog.fields.ctaLabel')}
|
||||
value={adForm.ctaLabel ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, ctaLabel: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Link URL"
|
||||
label={t('admin.catalog.fields.linkUrl')}
|
||||
value={adForm.linkUrl ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, linkUrl: e.target.value })}
|
||||
fullWidth
|
||||
placeholder="/wallet or https://..."
|
||||
/>
|
||||
<TextField
|
||||
label="Image URL"
|
||||
label={t('admin.catalog.fields.imageUrl')}
|
||||
value={adForm.imageUrl ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, imageUrl: e.target.value || null })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Background gradient (CSS)"
|
||||
label={t('admin.catalog.fields.backgroundGradient')}
|
||||
value={adForm.backgroundGradient ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, backgroundGradient: e.target.value || null })}
|
||||
fullWidth
|
||||
placeholder="linear-gradient(135deg, ...)"
|
||||
/>
|
||||
<TextField
|
||||
label="Accent color"
|
||||
label={t('admin.catalog.fields.accentColor')}
|
||||
value={adForm.accentColor ?? ''}
|
||||
onChange={(e) => setAdForm({ ...adForm, accentColor: e.target.value })}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Sort order"
|
||||
label={t('admin.catalog.fields.sortOrder')}
|
||||
type="number"
|
||||
value={adForm.sortOrder ?? 0}
|
||||
onChange={(e) => setAdForm({ ...adForm, sortOrder: Number(e.target.value) })}
|
||||
@ -621,14 +622,14 @@ export function CatalogAdminPage() {
|
||||
onChange={(e) => setAdForm({ ...adForm, isActive: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Active"
|
||||
label={t('admin.catalog.active')}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2, flexWrap: 'wrap', gap: 1 }}>
|
||||
<Button onClick={() => setAdDialog({ open: false })}>Cancel</Button>
|
||||
<Button onClick={() => setAdDialog({ open: false })}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={() => saveAdMut.mutate()} disabled={saveAdMut.isPending}>
|
||||
Save
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -22,6 +22,7 @@ import PublicRoundedIcon from '@mui/icons-material/PublicRounded';
|
||||
import SyncRoundedIcon from '@mui/icons-material/SyncRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
|
||||
@ -32,6 +33,7 @@ type CountryRow = {
|
||||
};
|
||||
|
||||
export function CountriesAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [search, setSearch] = useState('');
|
||||
const [showBlockedOnly, setShowBlockedOnly] = useState(false);
|
||||
@ -83,7 +85,7 @@ export function CountriesAdminPage() {
|
||||
>
|
||||
<PublicRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
Countries
|
||||
{t('admin.countries.title')}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@ -92,43 +94,47 @@ export function CountriesAdminPage() {
|
||||
onClick={() => syncMut.mutate()}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'auto' } }}
|
||||
>
|
||||
Sync from API
|
||||
{t('admin.countries.sync')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Catalog synced from ISO 3166 by default, or from{' '}
|
||||
{t('admin.countries.descriptionBeforeLink')}{' '}
|
||||
<a href="https://restcountries.com" target="_blank" rel="noreferrer">
|
||||
REST Countries v5
|
||||
</a>{' '}
|
||||
when <code>REST_COUNTRIES_API_KEY</code> is configured on the backend. Disable registration
|
||||
for specific countries of residence.
|
||||
{t('admin.countries.descriptionAfterLink')}
|
||||
</Typography>
|
||||
|
||||
{syncMut.isSuccess && (
|
||||
<Alert severity="success" sx={{ mb: 2 }} onClose={() => syncMut.reset()}>
|
||||
Synced {syncMut.data.synced} countries
|
||||
{syncMut.data.source === 'restcountries-v5' ? ' from REST Countries' : ' from ISO 3166'}.
|
||||
Total in database: {syncMut.data.total}.
|
||||
{t('admin.countries.syncSuccess', {
|
||||
synced: syncMut.data.synced,
|
||||
total: syncMut.data.total,
|
||||
source:
|
||||
syncMut.data.source === 'restcountries-v5'
|
||||
? t('admin.countries.syncSourceRest')
|
||||
: t('admin.countries.syncSourceIso'),
|
||||
})}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{syncMut.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }} onClose={() => syncMut.reset()}>
|
||||
{(syncMut.error as { response?: { data?: { error?: string } } })?.response?.data?.error ??
|
||||
'Country sync failed'}
|
||||
t('admin.countries.syncFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Failed to load countries from the server.
|
||||
{t('admin.countries.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.data?.total === 0 && (
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
No countries in database. Click "Sync from API" to load the catalog.
|
||||
{t('admin.countries.emptyDb')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -137,14 +143,17 @@ export function CountriesAdminPage() {
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ mb: 2 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Search country"
|
||||
label={t('admin.countries.search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<Chip label={`${blockedCount} blocked`} color={blockedCount > 0 ? 'warning' : 'default'} />
|
||||
<Chip
|
||||
label={t('admin.countries.blockedCount', { count: blockedCount })}
|
||||
color={blockedCount > 0 ? 'warning' : 'default'}
|
||||
/>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<Typography variant="body2">Blocked only</Typography>
|
||||
<Typography variant="body2">{t('admin.countries.blockedOnly')}</Typography>
|
||||
<Switch checked={showBlockedOnly} onChange={(e) => setShowBlockedOnly(e.target.checked)} />
|
||||
</Stack>
|
||||
</Stack>
|
||||
@ -153,9 +162,9 @@ export function CountriesAdminPage() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Code</TableCell>
|
||||
<TableCell>Name</TableCell>
|
||||
<TableCell>Registration</TableCell>
|
||||
<TableCell>{t('admin.countries.code')}</TableCell>
|
||||
<TableCell>{t('admin.countries.name')}</TableCell>
|
||||
<TableCell>{t('admin.countries.registration')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -177,7 +186,7 @@ export function CountriesAdminPage() {
|
||||
{filtered.length === 0 && !q.isLoading && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} align="center">
|
||||
No countries match your filters
|
||||
{t('admin.countries.noMatch')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
import { Alert, Box, CircularProgress, Skeleton } from '@mui/material';
|
||||
import dayjs from 'dayjs';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { DashboardFiltersBar } from './components/DashboardFiltersBar';
|
||||
import {
|
||||
@ -28,6 +29,7 @@ const defaultFilters: DashboardFilters = {
|
||||
};
|
||||
|
||||
export function DashboardPage() {
|
||||
const { t } = useTranslation();
|
||||
const [filters, setFilters] = useState<DashboardFilters>(defaultFilters);
|
||||
const [forceRefresh, setForceRefresh] = useState(false);
|
||||
const [hiddenSections, setHiddenSections] = useState<DashboardSectionId[]>(
|
||||
@ -65,22 +67,23 @@ export function DashboardPage() {
|
||||
const exportData = useCallback(() => {
|
||||
if (!q.data) return;
|
||||
const d = q.data;
|
||||
const exp = 'admin.dashboard.export';
|
||||
const rows = [
|
||||
{ Catégorie: 'Utilisateurs', Indicateur: 'Total inscrits', Valeur: d.kpis.users.totalUsers },
|
||||
{ Catégorie: 'Utilisateurs', Indicateur: 'Nouveaux', Valeur: d.kpis.users.newUsers },
|
||||
{ Catégorie: 'Dépôts', Indicateur: 'Montant total (raw)', Valeur: d.kpis.deposits.totalAmountRaw },
|
||||
{ Catégorie: 'Dépôts', Indicateur: 'Montant total USDT', Valeur: formatRawUsdt(d.kpis.deposits.totalAmountRaw) },
|
||||
{ Catégorie: 'Retraits', Indicateur: 'Montant total (raw)', Valeur: d.kpis.withdrawals.totalAmountRaw },
|
||||
{ Catégorie: 'Jeux', Indicateur: 'Prédictions', Valeur: d.games.participation.totalPredictions },
|
||||
{ Catégorie: 'Financier', Indicateur: 'Net P/L plateforme (réel)', Valeur: formatRawUsdt(d.financial.performance.platformNetPnlRaw) },
|
||||
{ Catégorie: 'Financier', Indicateur: 'Net P/L test', Valeur: formatRawUsdt(d.financial.performance.platformNetPnlTestRaw) },
|
||||
{ Catégorie: 'Alertes', Indicateur: 'Ouvertes', Valeur: d.alerts.openAlertsCount },
|
||||
{ Catégorie: t(`${exp}.categories.users`), Indicateur: t(`${exp}.indicators.totalUsers`), Valeur: d.kpis.users.totalUsers },
|
||||
{ Catégorie: t(`${exp}.categories.users`), Indicateur: t(`${exp}.indicators.newUsers`), Valeur: d.kpis.users.newUsers },
|
||||
{ Catégorie: t(`${exp}.categories.deposits`), Indicateur: t(`${exp}.indicators.depositTotalRaw`), Valeur: d.kpis.deposits.totalAmountRaw },
|
||||
{ Catégorie: t(`${exp}.categories.deposits`), Indicateur: t(`${exp}.indicators.depositTotalUsdt`), Valeur: formatRawUsdt(d.kpis.deposits.totalAmountRaw) },
|
||||
{ Catégorie: t(`${exp}.categories.withdrawals`), Indicateur: t(`${exp}.indicators.withdrawalTotalRaw`), Valeur: d.kpis.withdrawals.totalAmountRaw },
|
||||
{ Catégorie: t(`${exp}.categories.games`), Indicateur: t(`${exp}.indicators.predictions`), Valeur: d.games.participation.totalPredictions },
|
||||
{ Catégorie: t(`${exp}.categories.financial`), Indicateur: t(`${exp}.indicators.platformNetPnl`), Valeur: formatRawUsdt(d.financial.performance.platformNetPnlRaw) },
|
||||
{ Catégorie: t(`${exp}.categories.financial`), Indicateur: t(`${exp}.indicators.testNetPnl`), Valeur: formatRawUsdt(d.financial.performance.platformNetPnlTestRaw) },
|
||||
{ Catégorie: t(`${exp}.categories.alerts`), Indicateur: t(`${exp}.indicators.openAlerts`), Valeur: d.alerts.openAlertsCount },
|
||||
];
|
||||
const ws = XLSX.utils.json_to_sheet(rows);
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Dashboard');
|
||||
XLSX.utils.book_append_sheet(wb, ws, t(`${exp}.sheetName`));
|
||||
XLSX.writeFile(wb, `prediqo-dashboard-${d.filters.preset}-${dayjs().format('YYYYMMDD-HHmm')}.xlsx`);
|
||||
}, [q.data]);
|
||||
}, [q.data, t]);
|
||||
|
||||
const show = (id: DashboardSectionId) => !hiddenSections.includes(id);
|
||||
|
||||
@ -116,39 +119,41 @@ export function DashboardPage() {
|
||||
|
||||
{customRangePending && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
Sélectionnez les dates « Du » et « Au » pour charger les analytics de l’intervalle personnalisé.
|
||||
{t('admin.dashboard.customRangePending')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{customRangeInvalid && (
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
La date « Du » doit être antérieure ou égale à la date « Au ».
|
||||
{t('admin.dashboard.customRangeInvalid')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.isError && !customRangePending && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Impossible de charger les analytics. Vérifiez que le backend est démarré et que vous êtes administrateur.
|
||||
{t('admin.dashboard.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.data?.meta?.chartsFromMaterializedViews && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
KPIs, graphiques financiers, paris, géographie et démographie alimentés par les vues matérialisées PostgreSQL (rafraîchies périodiquement, sans service externe).
|
||||
{t('admin.dashboard.materializedViews')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.data?.meta?.cached && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
Données servies depuis le cache ({q.data.meta.cachedAt ? dayjs(q.data.meta.cachedAt).format('HH:mm:ss') : 'récentes'}).
|
||||
Utilisez « Actualiser » pour forcer un recalcul complet.
|
||||
{t('admin.dashboard.cached', {
|
||||
time: q.data.meta.cachedAt
|
||||
? dayjs(q.data.meta.cachedAt).format('HH:mm:ss')
|
||||
: t('admin.dashboard.cachedRecent'),
|
||||
})}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{q.data?.meta?.degraded && (
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
Certaines sections n’ont pas pu être calculées à temps (volume de données élevé). Les indicateurs
|
||||
affichés peuvent être partiels.
|
||||
{t('admin.dashboard.degraded')}
|
||||
{q.data.meta.warnings?.length ? (
|
||||
<Box component="ul" sx={{ mt: 1, mb: 0, pl: 2 }}>
|
||||
{q.data.meta.warnings.map((w) => (
|
||||
@ -162,7 +167,7 @@ export function DashboardPage() {
|
||||
{q.isFetching && !q.isLoading && (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2, opacity: 0.7 }}>
|
||||
<CircularProgress size={16} />
|
||||
<span>Mise à jour des données…</span>
|
||||
<span>{t('admin.dashboard.updating')}</span>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
|
||||
@ -18,6 +18,7 @@ import {
|
||||
} from 'recharts';
|
||||
import type { DailyPoint } from '../types';
|
||||
import { formatCount, formatRawUsdt } from '../utils/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const CHART_COLORS = ['#D6B25E', '#7C5CFF', '#29B6F6', '#4CAF50', '#FF7043', '#AB47BC'];
|
||||
|
||||
@ -231,6 +232,7 @@ export function SimplePieChart({
|
||||
}
|
||||
|
||||
export function FinancialTrendChart({ deposits, withdrawals }: { deposits: DailyPoint[]; withdrawals: DailyPoint[] }) {
|
||||
const { t } = useTranslation();
|
||||
const byDate = new Map<string, { date: string; deposits: number; withdrawals: number }>();
|
||||
for (const d of deposits) {
|
||||
byDate.set(d.date, { date: d.date, deposits: d.value, withdrawals: 0 });
|
||||
@ -243,12 +245,12 @@ export function FinancialTrendChart({ deposits, withdrawals }: { deposits: Daily
|
||||
const merged = [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));
|
||||
return (
|
||||
<TrendLineChart
|
||||
title="Flux financiers — dépôts vs retraits"
|
||||
title={t('admin.dashboard.charts.financialFlow')}
|
||||
data={merged}
|
||||
valueFormatter={formatUsdtTooltip}
|
||||
lines={[
|
||||
{ key: 'deposits', label: 'Dépôts', color: '#4CAF50' },
|
||||
{ key: 'withdrawals', label: 'Retraits', color: '#FF7043' },
|
||||
{ key: 'deposits', label: t('admin.dashboard.charts.deposits'), color: '#4CAF50' },
|
||||
{ key: 'withdrawals', label: t('admin.dashboard.charts.withdrawals'), color: '#FF7043' },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
@ -10,24 +10,22 @@ import {
|
||||
TextField,
|
||||
} from '@mui/material';
|
||||
import FileDownloadRoundedIcon from '@mui/icons-material/FileDownloadRounded';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PageHeader, RefreshIconButton } from '../../../shared/components/PageHeader';
|
||||
import type { DashboardFilters, DatePreset, GameKey } from '../types';
|
||||
|
||||
const DATE_PRESETS: { value: DatePreset; label: string }[] = [
|
||||
{ value: 'today', label: "Aujourd'hui" },
|
||||
{ value: 'yesterday', label: 'Hier' },
|
||||
{ value: 'this_week', label: 'Cette semaine' },
|
||||
{ value: 'this_month', label: 'Mois en cours' },
|
||||
{ value: 'last_30_days', label: '30 derniers jours' },
|
||||
{ value: 'last_90_days', label: '90 derniers jours' },
|
||||
{ value: 'this_year', label: 'Cette année' },
|
||||
{ value: 'custom', label: 'Intervalle personnalisé' },
|
||||
const DATE_PRESET_KEYS: DatePreset[] = [
|
||||
'today',
|
||||
'yesterday',
|
||||
'this_week',
|
||||
'this_month',
|
||||
'last_30_days',
|
||||
'last_90_days',
|
||||
'this_year',
|
||||
'custom',
|
||||
];
|
||||
|
||||
const GAME_OPTIONS: { value: GameKey; label: string }[] = [
|
||||
{ value: 'all', label: 'Tous les jeux' },
|
||||
{ value: 'candle-predict', label: 'Candle Predict' },
|
||||
];
|
||||
const GAME_KEYS: GameKey[] = ['all', 'candle-predict'];
|
||||
|
||||
type DashboardFiltersBarProps = {
|
||||
filters: DashboardFilters;
|
||||
@ -48,6 +46,8 @@ export function DashboardFiltersBar({
|
||||
periodLabel,
|
||||
disableActions,
|
||||
}: DashboardFiltersBarProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
@ -59,13 +59,15 @@ export function DashboardFiltersBar({
|
||||
}}
|
||||
>
|
||||
<PageHeader
|
||||
title="Dashboard Administrateur"
|
||||
subtitle={`Vue analytique de la plateforme — ${periodLabel ?? 'période sélectionnée'}`}
|
||||
title={t('admin.dashboard.title')}
|
||||
subtitle={t('admin.dashboard.subtitle', {
|
||||
period: periodLabel ?? t('admin.dashboard.selectedPeriod'),
|
||||
})}
|
||||
mb={0}
|
||||
actions={
|
||||
<>
|
||||
<RefreshIconButton
|
||||
label="Actualiser le dashboard"
|
||||
label={t('admin.dashboard.refresh')}
|
||||
onClick={onRefresh}
|
||||
disabled={loading || disableActions}
|
||||
/>
|
||||
@ -77,7 +79,7 @@ export function DashboardFiltersBar({
|
||||
disabled={loading || disableActions}
|
||||
sx={{ flexShrink: 0 }}
|
||||
>
|
||||
Exporter
|
||||
{t('admin.dashboard.exportAction')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
@ -85,15 +87,15 @@ export function DashboardFiltersBar({
|
||||
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ mt: 2.5, flexWrap: 'wrap' }}>
|
||||
<FormControl size="small" sx={{ minWidth: { xs: '100%', sm: 200 }, width: { xs: '100%', sm: 'auto' } }}>
|
||||
<InputLabel>Période</InputLabel>
|
||||
<InputLabel>{t('admin.dashboard.period')}</InputLabel>
|
||||
<Select
|
||||
label="Période"
|
||||
label={t('admin.dashboard.period')}
|
||||
value={filters.preset}
|
||||
onChange={(e) => onChange({ ...filters, preset: e.target.value as DatePreset })}
|
||||
>
|
||||
{DATE_PRESETS.map((p) => (
|
||||
<MenuItem key={p.value} value={p.value}>
|
||||
{p.label}
|
||||
{DATE_PRESET_KEYS.map((value) => (
|
||||
<MenuItem key={value} value={value}>
|
||||
{t(`admin.dashboard.presets.${value}`)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
@ -102,7 +104,7 @@ export function DashboardFiltersBar({
|
||||
{filters.preset === 'custom' && (
|
||||
<>
|
||||
<TextField
|
||||
label="Du"
|
||||
label={t('admin.dashboard.from')}
|
||||
type="date"
|
||||
size="small"
|
||||
value={filters.from ?? ''}
|
||||
@ -110,7 +112,7 @@ export function DashboardFiltersBar({
|
||||
slotProps={{ inputLabel: { shrink: true } }}
|
||||
/>
|
||||
<TextField
|
||||
label="Au"
|
||||
label={t('admin.dashboard.to')}
|
||||
type="date"
|
||||
size="small"
|
||||
value={filters.to ?? ''}
|
||||
@ -121,22 +123,28 @@ export function DashboardFiltersBar({
|
||||
)}
|
||||
|
||||
<FormControl size="small" sx={{ minWidth: { xs: '100%', sm: 180 }, width: { xs: '100%', sm: 'auto' } }}>
|
||||
<InputLabel>Jeu</InputLabel>
|
||||
<InputLabel>{t('admin.dashboard.game')}</InputLabel>
|
||||
<Select
|
||||
label="Jeu"
|
||||
label={t('admin.dashboard.game')}
|
||||
value={filters.gameKey}
|
||||
onChange={(e) => onChange({ ...filters, gameKey: e.target.value as GameKey })}
|
||||
>
|
||||
{GAME_OPTIONS.map((g) => (
|
||||
<MenuItem key={g.value} value={g.value}>
|
||||
{g.label}
|
||||
{GAME_KEYS.map((value) => (
|
||||
<MenuItem key={value} value={value}>
|
||||
{value === 'all'
|
||||
? t('admin.dashboard.games.all')
|
||||
: t('admin.dashboard.games.candlePredict')}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<Chip
|
||||
label={filters.gameKey === 'all' ? 'Tous les jeux' : 'Candle Predict'}
|
||||
label={
|
||||
filters.gameKey === 'all'
|
||||
? t('admin.dashboard.games.all')
|
||||
: t('admin.dashboard.games.candlePredict')
|
||||
}
|
||||
color="primary"
|
||||
variant="outlined"
|
||||
sx={{ alignSelf: 'center', fontWeight: 700 }}
|
||||
|
||||
@ -15,6 +15,7 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useCountryNames } from '../../countries/useCountryNames';
|
||||
import type { AdminDashboardData, BetSegment } from '../types';
|
||||
import { REPORT_PATHS, reportUrl } from '../reportLinks';
|
||||
@ -29,13 +30,7 @@ import {
|
||||
import { KpiCard, SectionPanel } from './KpiCard';
|
||||
import { ReportDetailLink } from './ReportDetailLink';
|
||||
import { TreasuryDashboardCards } from './TreasuryDashboardCards';
|
||||
import {
|
||||
AGE_BUCKET_LABELS,
|
||||
GENDER_DASHBOARD_LABELS,
|
||||
formatCount,
|
||||
formatPercent,
|
||||
formatRawUsdt,
|
||||
} from '../utils/format';
|
||||
import { formatCount, formatPercent, formatRawUsdt } from '../utils/format';
|
||||
import { ScrollableTable } from '../../../shared/components/ScrollableTable';
|
||||
|
||||
function gridItem(xs = 12, sm = 6, md = 3) {
|
||||
@ -108,49 +103,51 @@ function FixedTableCard({
|
||||
}
|
||||
|
||||
export function KpiSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const { users, deposits, withdrawals, bonuses, adjustments, withdrawalsEnabled } = data.kpis;
|
||||
const dateQ = {
|
||||
from: data.filters.from,
|
||||
to: data.filters.to,
|
||||
};
|
||||
const c = 'admin.dashboard.sections.kpi.cards';
|
||||
return (
|
||||
<SectionPanel
|
||||
title="Indicateurs clés"
|
||||
subtitle="Vue synthétique — cliquez sur une carte pour le rapport détaillé"
|
||||
action={<ReportDetailLink to={REPORT_PATHS.reportsHub} label="Tous les rapports" />}
|
||||
title={t('admin.dashboard.sections.kpi.title')}
|
||||
subtitle={t('admin.dashboard.sections.kpi.subtitle')}
|
||||
action={<ReportDetailLink to={REPORT_PATHS.reportsHub} label={t('admin.dashboard.allReports')} />}
|
||||
>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Utilisateurs
|
||||
{t('admin.dashboard.sections.kpi.groups.users')}
|
||||
</Typography>
|
||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Total inscrits"
|
||||
title={t(`${c}.totalUsers`)}
|
||||
value={formatCount(users.totalUsers)}
|
||||
tone="info"
|
||||
subtitle="Tous les comptes"
|
||||
subtitle={t(`${c}.totalUsersSub`)}
|
||||
to={REPORT_PATHS.usersAll}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Nouveaux (période)"
|
||||
title={t(`${c}.newUsers`)}
|
||||
value={formatCount(users.newUsers)}
|
||||
tone="positive"
|
||||
subtitle="Inscriptions sur la période"
|
||||
subtitle={t(`${c}.newUsersSub`)}
|
||||
to={reportUrl(REPORT_PATHS.usersNewPeriod, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Actifs (période)"
|
||||
title={t(`${c}.activeUsers`)}
|
||||
value={formatCount(users.activeUsers)}
|
||||
to={reportUrl(REPORT_PATHS.usersActivePeriod, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Inactifs"
|
||||
title={t(`${c}.inactiveUsers`)}
|
||||
value={formatCount(users.inactiveUsers)}
|
||||
tone="warning"
|
||||
to={reportUrl(REPORT_PATHS.usersInactivePeriod, dateQ)}
|
||||
@ -158,77 +155,85 @@ export function KpiSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Croissance inscriptions"
|
||||
title={t(`${c}.signupGrowth`)}
|
||||
value={formatPercent(users.signupGrowthRate)}
|
||||
tone={users.signupGrowthRate >= 0 ? 'positive' : 'danger'}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Sur le jeu"
|
||||
title={t(`${c}.onlineGame`)}
|
||||
value={formatCount(users.onlineNow)}
|
||||
tone="info"
|
||||
subtitle="WebSocket Candle Predict"
|
||||
subtitle={t(`${c}.onlineGameSub`)}
|
||||
to={REPORT_PATHS.usersOnlineNow}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Connectés (app)"
|
||||
title={t(`${c}.onlineApp`)}
|
||||
value={formatCount(users.onlineInApp)}
|
||||
tone="info"
|
||||
subtitle="Session active, sans prédiction requise"
|
||||
subtitle={t(`${c}.onlineAppSub`)}
|
||||
to={REPORT_PATHS.usersOnlineApp}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard title="Administrateurs" value={formatCount(users.adminCount)} to={REPORT_PATHS.usersStaff} />
|
||||
<KpiCard title={t(`${c}.admins`)} value={formatCount(users.adminCount)} to={REPORT_PATHS.usersStaff} />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Dépôts
|
||||
{t('admin.dashboard.sections.kpi.groups.deposits')}
|
||||
</Typography>
|
||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Montant total"
|
||||
title={t(`${c}.depositTotal`)}
|
||||
value={`${formatRawUsdt(deposits.totalAmountRaw)} USDT`}
|
||||
to={reportUrl(REPORT_PATHS.deposits, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard title="Nombre de dépôts" value={formatCount(deposits.totalCount)} to={reportUrl(REPORT_PATHS.deposits, dateQ)} />
|
||||
<KpiCard
|
||||
title={t(`${c}.depositCount`)}
|
||||
value={formatCount(deposits.totalCount)}
|
||||
to={reportUrl(REPORT_PATHS.deposits, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Utilisateurs déposants"
|
||||
title={t(`${c}.depositUsers`)}
|
||||
value={formatCount(deposits.uniqueUsers)}
|
||||
to={reportUrl(REPORT_PATHS.depositUsers, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard title="Dépôt moyen" value={`${formatRawUsdt(deposits.averagePerUserRaw)} USDT`} />
|
||||
<KpiCard title={t(`${c}.depositAvg`)} value={`${formatRawUsdt(deposits.averagePerUserRaw)} USDT`} />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Retraits & bonus
|
||||
{t('admin.dashboard.sections.kpi.groups.withdrawalsBonus')}
|
||||
</Typography>
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Retraits (total)"
|
||||
title={t(`${c}.withdrawalTotal`)}
|
||||
value={`${formatRawUsdt(withdrawals.totalAmountRaw)} USDT`}
|
||||
to={reportUrl(REPORT_PATHS.withdrawals, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard title="Retraits (nombre)" value={formatCount(withdrawals.totalCount)} to={reportUrl(REPORT_PATHS.withdrawals, dateQ)} />
|
||||
<KpiCard
|
||||
title={t(`${c}.withdrawalCount`)}
|
||||
value={formatCount(withdrawals.totalCount)}
|
||||
to={reportUrl(REPORT_PATHS.withdrawals, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Bonus accordés"
|
||||
title={t(`${c}.bonusesGranted`)}
|
||||
value={`${formatRawUsdt(bonuses.totalAmountRaw)} USDT`}
|
||||
tone="positive"
|
||||
to={reportUrl(REPORT_PATHS.bonuses, dateQ)}
|
||||
@ -236,16 +241,16 @@ export function KpiSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Admin adjustments"
|
||||
title={t(`${c}.adminAdjustments`)}
|
||||
value={`${formatRawUsdt(adjustments.totalAmountRaw)} USDT`}
|
||||
subtitle={`${formatCount(adjustments.uniqueUsers)} utilisateurs`}
|
||||
subtitle={t('admin.dashboard.usersCount', { count: adjustments.uniqueUsers })}
|
||||
to={reportUrl(REPORT_PATHS.adjustments, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={gridItem()}>
|
||||
<KpiCard
|
||||
title="Retraits plateforme"
|
||||
value={withdrawalsEnabled ? 'ACTIVÉS' : 'DÉSACTIVÉS'}
|
||||
title={t(`${c}.platformWithdrawals`)}
|
||||
value={withdrawalsEnabled ? t('admin.dashboard.enabled') : t('admin.dashboard.disabled')}
|
||||
tone={withdrawalsEnabled ? 'positive' : 'danger'}
|
||||
/>
|
||||
</Grid>
|
||||
@ -255,34 +260,36 @@ export function KpiSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const { balances, performance } = data.financial;
|
||||
const fc = 'admin.dashboard.sections.financial.cards';
|
||||
const walletPie = balances.distribution.map((d) => ({
|
||||
name: d.kind === 'main' ? 'Principal' : d.kind === 'bonus' ? 'Bonus' : 'Test',
|
||||
name: t(`admin.dashboard.walletKind.${d.kind}`),
|
||||
value: d.amountRaw,
|
||||
}));
|
||||
return (
|
||||
<SectionPanel
|
||||
title="Analyse financière"
|
||||
subtitle="Soldes actuels et tendances sur la période"
|
||||
title={t('admin.dashboard.sections.financial.title')}
|
||||
subtitle={t('admin.dashboard.sections.financial.subtitle')}
|
||||
action={<ReportDetailLink to={REPORT_PATHS.walletBalances} />}
|
||||
>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Wallets principaux" value={`${formatRawUsdt(balances.mainWalletRaw)} USDT`} to={REPORT_PATHS.walletBalances} />
|
||||
<KpiCard title={t(`${fc}.mainWallets`)} value={`${formatRawUsdt(balances.mainWalletRaw)} USDT`} to={REPORT_PATHS.walletBalances} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Wallets bonus" value={`${formatRawUsdt(balances.bonusWalletRaw)} USDT`} to={REPORT_PATHS.walletBalances} />
|
||||
<KpiCard title={t(`${fc}.bonusWallets`)} value={`${formatRawUsdt(balances.bonusWalletRaw)} USDT`} to={REPORT_PATHS.walletBalances} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Wallets test" value={`${formatRawUsdt(balances.testWalletRaw)} USDT`} to={REPORT_PATHS.predictionsTest} />
|
||||
<KpiCard title={t(`${fc}.testWallets`)} value={`${formatRawUsdt(balances.testWalletRaw)} USDT`} to={REPORT_PATHS.predictionsTest} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Solde cumulé" value={`${formatRawUsdt(balances.totalRaw)} USDT`} tone="info" to={REPORT_PATHS.walletBalances} />
|
||||
<KpiCard title={t(`${fc}.cumulativeBalance`)} value={`${formatRawUsdt(balances.totalRaw)} USDT`} tone="info" to={REPORT_PATHS.walletBalances} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Net P/L plateforme"
|
||||
subtitle="Wallets réels (hors test)"
|
||||
title={t(`${fc}.platformNetPnl`)}
|
||||
subtitle={t(`${fc}.platformNetPnlSub`)}
|
||||
value={`${formatRawUsdt(performance.platformNetPnlRaw)} USDT`}
|
||||
tone={performance.platformNetPnlRaw >= 0 ? 'positive' : 'danger'}
|
||||
to={REPORT_PATHS.predictionsReal}
|
||||
@ -290,8 +297,8 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Net P/L test"
|
||||
subtitle="Wallet de test uniquement"
|
||||
title={t(`${fc}.testNetPnl`)}
|
||||
subtitle={t(`${fc}.testNetPnlSub`)}
|
||||
value={`${formatRawUsdt(performance.platformNetPnlTestRaw)} USDT`}
|
||||
tone={performance.platformNetPnlTestRaw >= 0 ? 'positive' : 'danger'}
|
||||
to={REPORT_PATHS.predictionsTest}
|
||||
@ -299,16 +306,16 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Ratio Dépôts / Retraits"
|
||||
title={t(`${fc}.depositWithdrawalRatio`)}
|
||||
value={performance.depositWithdrawalRatio == null ? '—' : performance.depositWithdrawalRatio.toFixed(2)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Coût bonus" value={`${formatRawUsdt(performance.bonusCostRaw)} USDT`} to={REPORT_PATHS.bonuses} />
|
||||
<KpiCard title={t(`${fc}.bonusCost`)} value={`${formatRawUsdt(performance.bonusCostRaw)} USDT`} to={REPORT_PATHS.bonuses} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Coût ajustements"
|
||||
title={t(`${fc}.adjustmentCost`)}
|
||||
value={`${formatRawUsdt(performance.adjustmentCostRaw)} USDT`}
|
||||
to={REPORT_PATHS.adjustments}
|
||||
/>
|
||||
@ -316,14 +323,20 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Trésorerie on-chain
|
||||
{t('admin.dashboard.sections.financial.onChainTreasury')}
|
||||
</Typography>
|
||||
<TreasuryDashboardCards />
|
||||
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2, height: '100%' }}>
|
||||
<SimplePieChart data={walletPie} title="Répartition des soldes" nameKey="name" valueKey="value" valueFormatter={formatUsdtTooltip} />
|
||||
<SimplePieChart
|
||||
data={walletPie}
|
||||
title={t('admin.dashboard.sections.financial.balanceDistribution')}
|
||||
nameKey="name"
|
||||
valueKey="value"
|
||||
valueFormatter={formatUsdtTooltip}
|
||||
/>
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
@ -335,7 +348,7 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart
|
||||
data={data.charts.netPnl}
|
||||
title="Évolution du Net P/L (réel)"
|
||||
title={t('admin.dashboard.sections.financial.netPnlTrend')}
|
||||
valueFormatter={(v) => `${formatRawUsdt(v)} USDT`}
|
||||
/>
|
||||
<ReportDetailLink to={REPORT_PATHS.predictionsReal} />
|
||||
@ -345,7 +358,7 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart
|
||||
data={data.charts.bonuses}
|
||||
title="Évolution des bonus"
|
||||
title={t('admin.dashboard.sections.financial.bonusTrend')}
|
||||
valueFormatter={(v) => `${formatRawUsdt(v)} USDT`}
|
||||
/>
|
||||
<ReportDetailLink to={REPORT_PATHS.bonuses} />
|
||||
@ -357,25 +370,33 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const g = data.games;
|
||||
const dateQ = {
|
||||
from: data.filters.from,
|
||||
to: data.filters.to,
|
||||
};
|
||||
const gc = 'admin.dashboard.sections.game.cards';
|
||||
const seg = 'admin.dashboard.sections.game.segments';
|
||||
const tbl = 'admin.dashboard.tables';
|
||||
return (
|
||||
<SectionPanel title="Analyse des jeux" subtitle="Synthèse par segment (vue fixe)" action={<ReportDetailLink to={reportUrl(REPORT_PATHS.predictions, dateQ)} />}>
|
||||
<SectionPanel
|
||||
title={t('admin.dashboard.sections.game.title')}
|
||||
subtitle={t('admin.dashboard.sections.game.subtitle')}
|
||||
action={<ReportDetailLink to={reportUrl(REPORT_PATHS.predictions, dateQ)} />}
|
||||
>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Participants" value={formatCount(g.participation.uniqueParticipants)} to={reportUrl(REPORT_PATHS.predictionsParticipants, dateQ)} />
|
||||
<KpiCard title={t(`${gc}.participants`)} value={formatCount(g.participation.uniqueParticipants)} to={reportUrl(REPORT_PATHS.predictionsParticipants, dateQ)} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Prédictions" value={formatCount(g.participation.totalPredictions)} to={reportUrl(REPORT_PATHS.predictions, dateQ)} />
|
||||
<KpiCard title={t(`${gc}.predictions`)} value={formatCount(g.participation.totalPredictions)} to={reportUrl(REPORT_PATHS.predictions, dateQ)} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Moy. / joueur" value={g.participation.avgPredictionsPerUser} />
|
||||
<KpiCard title={t(`${gc}.avgPerPlayer`)} value={g.participation.avgPredictionsPerUser} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Total misé" value={`${formatRawUsdt(g.participation.totalStakeRaw)} USDT`} to={reportUrl(REPORT_PATHS.predictions, dateQ)} />
|
||||
<KpiCard title={t(`${gc}.totalStaked`)} value={`${formatRawUsdt(g.participation.totalStakeRaw)} USDT`} to={reportUrl(REPORT_PATHS.predictions, dateQ)} />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
@ -384,34 +405,24 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>Segment</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
|
||||
Utilisateurs
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
|
||||
Prédictions
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
|
||||
Misé
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
|
||||
Net P/L
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
|
||||
Taux réussite
|
||||
</TableCell>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.segment`)}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.users`)}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.predictions`)}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.stake`)}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.netPnl`)}</TableCell>
|
||||
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>{t(`${tbl}.winRate`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
<SegmentRow label="Prédictions normales" seg={g.manual} to={reportUrl(REPORT_PATHS.predictionsManual, dateQ)} />
|
||||
<SegmentRow label="Auto Prediction" seg={g.auto} to={reportUrl(REPORT_PATHS.predictionsAuto, dateQ)} />
|
||||
<SegmentRow label="Multi-candles" seg={g.multiCandle} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
<SegmentRow label="Réel + manuel" seg={g.cross.realManual} to={reportUrl(REPORT_PATHS.predictionsManual, dateQ)} />
|
||||
<SegmentRow label="Réel + auto" seg={g.cross.realAuto} to={reportUrl(REPORT_PATHS.predictionsAuto, dateQ)} />
|
||||
<SegmentRow label="Réel + multi-candles" seg={g.cross.realMulti} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
<SegmentRow label="Test + manuel" seg={g.cross.testManual} to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)} />
|
||||
<SegmentRow label="Test + auto" seg={g.cross.testAuto} to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)} />
|
||||
<SegmentRow label="Test + multi-candles" seg={g.cross.testMulti} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.manual`)} seg={g.manual} to={reportUrl(REPORT_PATHS.predictionsManual, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.auto`)} seg={g.auto} to={reportUrl(REPORT_PATHS.predictionsAuto, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.multiCandle`)} seg={g.multiCandle} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.realManual`)} seg={g.cross.realManual} to={reportUrl(REPORT_PATHS.predictionsManual, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.realAuto`)} seg={g.cross.realAuto} to={reportUrl(REPORT_PATHS.predictionsAuto, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.realMulti`)} seg={g.cross.realMulti} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.testManual`)} seg={g.cross.testManual} to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.testAuto`)} seg={g.cross.testAuto} to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)} />
|
||||
<SegmentRow label={t(`${seg}.testMulti`)} seg={g.cross.testMulti} to={reportUrl(REPORT_PATHS.predictionsMultiCandle, dateQ)} />
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
@ -420,15 +431,15 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
<Grid container spacing={2} sx={{ mt: 2 }}>
|
||||
<Grid size={{ xs: 12, md: 4 }}>
|
||||
<KpiCard
|
||||
title="Wallet test — utilisateurs"
|
||||
title={t(`${gc}.testWalletUsers`)}
|
||||
value={formatCount(g.testWallet.uniqueUsers)}
|
||||
subtitle={`Joué : ${formatRawUsdt(g.testWallet.totalStakeRaw)} USDT`}
|
||||
subtitle={t('admin.dashboard.played', { amount: formatRawUsdt(g.testWallet.totalStakeRaw) })}
|
||||
to={reportUrl(REPORT_PATHS.predictionsTestUsers, dateQ)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 4 }}>
|
||||
<KpiCard
|
||||
title="P/L test"
|
||||
title={t(`${gc}.testPnl`)}
|
||||
value={`${formatRawUsdt(g.testWallet.netPnlRaw)} USDT`}
|
||||
tone={g.testWallet.netPnlRaw >= 0 ? 'positive' : 'danger'}
|
||||
to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)}
|
||||
@ -437,23 +448,25 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mt: 3, mb: 1 }}>
|
||||
Répartitions (taille fixe)
|
||||
{t('admin.dashboard.sections.game.distributionsFixed')}
|
||||
</Typography>
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<FixedTableCard title="Short vs Long" reportTo={reportUrl(REPORT_PATHS.predictions, dateQ)}>
|
||||
<FixedTableCard title={t('admin.dashboard.sections.game.shortVsLong')} reportTo={reportUrl(REPORT_PATHS.predictions, dateQ)}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Direction</TableCell>
|
||||
<TableCell align="right">Prédictions</TableCell>
|
||||
<TableCell align="right">Misé</TableCell>
|
||||
<TableCell>{t(`${tbl}.direction`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.predictions`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.stake`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.charts.shortVsLong.map((r) => (
|
||||
<TableRow key={r.direction}>
|
||||
<TableCell sx={{ fontWeight: 600 }}>{r.direction === 'long' ? 'Long' : 'Short'}</TableCell>
|
||||
<TableCell sx={{ fontWeight: 600 }}>
|
||||
{r.direction === 'long' ? t('admin.dashboard.sections.game.long') : t('admin.dashboard.sections.game.short')}
|
||||
</TableCell>
|
||||
<TableCell align="right">{formatCount(r.count)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(r.stakeRaw)}</TableCell>
|
||||
</TableRow>
|
||||
@ -463,20 +476,20 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
</FixedTableCard>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<FixedTableCard title="Par intervalle de jeu" reportTo={reportUrl(REPORT_PATHS.predictions, dateQ)}>
|
||||
<FixedTableCard title={t('admin.dashboard.sections.game.byInterval')} reportTo={reportUrl(REPORT_PATHS.predictions, dateQ)}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Intervalle</TableCell>
|
||||
<TableCell align="right">Participants</TableCell>
|
||||
<TableCell align="right">Misé</TableCell>
|
||||
<TableCell align="right">P/L maison</TableCell>
|
||||
<TableCell>{t(`${tbl}.interval`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.participants`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.stake`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.housePnl`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.charts.byInterval.map((r) => (
|
||||
<TableRow key={r.intervalMinutes}>
|
||||
<TableCell sx={{ fontWeight: 600 }}>{r.intervalMinutes} min</TableCell>
|
||||
<TableCell sx={{ fontWeight: 600 }}>{t('admin.dashboard.minSuffix', { n: r.intervalMinutes })}</TableCell>
|
||||
<TableCell align="right">{formatCount(r.participants)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(r.stakeRaw)}</TableCell>
|
||||
<TableCell
|
||||
@ -497,6 +510,7 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function UserSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const s = data.users.security;
|
||||
const a = data.users.activity;
|
||||
const periodFrom = data.filters.from.slice(0, 10);
|
||||
@ -504,71 +518,81 @@ export function UserSection({ data }: { data: AdminDashboardData }) {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
const weekStart = dayjs().startOf('week').format('YYYY-MM-DD');
|
||||
const monthStart = dayjs().startOf('month').format('YYYY-MM-DD');
|
||||
const sec = 'admin.dashboard.sections.users.security';
|
||||
const act = 'admin.dashboard.sections.users.activityLabels';
|
||||
const securityItems = [
|
||||
{ label: 'E-mails vérifiés', value: s.emailVerified, to: REPORT_PATHS.usersAll },
|
||||
{ label: 'E-mails non vérifiés', value: s.emailUnverified, to: REPORT_PATHS.usersEmailUnverified, tone: 'warning' as const },
|
||||
{ label: '2FA activé', value: s.totpEnabled, to: REPORT_PATHS.users2faOn, tone: 'positive' as const },
|
||||
{ label: 'Sans 2FA', value: s.totpDisabled, to: REPORT_PATHS.users2faOff },
|
||||
{ label: 'Suspendus', value: s.suspendedAccounts, to: REPORT_PATHS.usersSuspended, tone: 'danger' as const },
|
||||
{ label: 'Désactivés', value: s.disabledAccounts, to: REPORT_PATHS.usersSuspended },
|
||||
{ label: 'Comptes expirés', value: s.expiredAccounts, to: REPORT_PATHS.usersInactive },
|
||||
{ label: 'Credentials expirés', value: s.credentialsExpired, to: REPORT_PATHS.usersInactive },
|
||||
{ label: 'Sous enquête', value: s.underSurveillance, to: REPORT_PATHS.usersSurveillance, tone: 'warning' as const },
|
||||
{ label: 'Retraits bloqués', value: s.withdrawalsBlocked, to: REPORT_PATHS.usersSuspended },
|
||||
{ key: 'emailVerified', value: s.emailVerified, to: REPORT_PATHS.usersAll },
|
||||
{ key: 'emailUnverified', value: s.emailUnverified, to: REPORT_PATHS.usersEmailUnverified, tone: 'warning' as const },
|
||||
{ key: 'totpEnabled', value: s.totpEnabled, to: REPORT_PATHS.users2faOn, tone: 'positive' as const },
|
||||
{ key: 'totpDisabled', value: s.totpDisabled, to: REPORT_PATHS.users2faOff },
|
||||
{ key: 'suspended', value: s.suspendedAccounts, to: REPORT_PATHS.usersSuspended, tone: 'danger' as const },
|
||||
{ key: 'disabled', value: s.disabledAccounts, to: REPORT_PATHS.usersSuspended },
|
||||
{ key: 'expired', value: s.expiredAccounts, to: REPORT_PATHS.usersInactive },
|
||||
{ key: 'credentialsExpired', value: s.credentialsExpired, to: REPORT_PATHS.usersInactive },
|
||||
{ key: 'underSurveillance', value: s.underSurveillance, to: REPORT_PATHS.usersSurveillance, tone: 'warning' as const },
|
||||
{ key: 'withdrawalsBlocked', value: s.withdrawalsBlocked, to: REPORT_PATHS.usersSuspended },
|
||||
];
|
||||
const activityItems = [
|
||||
{
|
||||
label: 'Actifs aujourd\'hui',
|
||||
key: 'activeToday',
|
||||
value: a.activeToday,
|
||||
to: reportUrl(REPORT_PATHS.usersActivePeriod, { from: today, to: today }),
|
||||
},
|
||||
{
|
||||
label: 'Actifs cette semaine',
|
||||
key: 'activeThisWeek',
|
||||
value: a.activeThisWeek,
|
||||
to: reportUrl(REPORT_PATHS.usersActivePeriod, { from: weekStart, to: today }),
|
||||
},
|
||||
{
|
||||
label: 'Actifs ce mois',
|
||||
key: 'activeThisMonth',
|
||||
value: a.activeThisMonth,
|
||||
to: reportUrl(REPORT_PATHS.usersActivePeriod, { from: monthStart, to: today }),
|
||||
},
|
||||
{
|
||||
label: 'Inactifs (période)',
|
||||
key: 'inactivePeriod',
|
||||
value: a.inactiveInPeriod,
|
||||
to: reportUrl(REPORT_PATHS.usersInactivePeriod, { from: periodFrom, to: periodTo }),
|
||||
tone: 'warning' as const,
|
||||
},
|
||||
];
|
||||
const recentLogins = data.users.recentLogins.slice(0, 5);
|
||||
const tbl = 'admin.dashboard.tables';
|
||||
return (
|
||||
<SectionPanel title="Utilisateurs & sécurité" subtitle="Compteurs et activité récente" action={<ReportDetailLink to={REPORT_PATHS.usersAll} />}>
|
||||
<SectionPanel
|
||||
title={t('admin.dashboard.sections.users.title')}
|
||||
subtitle={t('admin.dashboard.sections.users.subtitle')}
|
||||
action={<ReportDetailLink to={REPORT_PATHS.usersAll} />}
|
||||
>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Sécurité & conformité
|
||||
{t('admin.dashboard.sections.users.securityCompliance')}
|
||||
</Typography>
|
||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||
{securityItems.map((item) => (
|
||||
<Grid key={item.label} size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title={item.label} value={formatCount(item.value)} tone={item.tone} to={item.to} />
|
||||
<Grid key={item.key} size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title={t(`${sec}.${item.key}`)} value={formatCount(item.value)} tone={item.tone} to={item.to} />
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, display: 'block', mb: 1 }}>
|
||||
Activité
|
||||
{t('admin.dashboard.sections.users.activity')}
|
||||
</Typography>
|
||||
<Grid container spacing={2} sx={{ mb: recentLogins.length > 0 ? 3 : 0 }}>
|
||||
{activityItems.map((item) => (
|
||||
<Grid key={item.label} size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title={item.label} value={formatCount(item.value)} tone={item.tone} to={item.to} />
|
||||
<Grid key={item.key} size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title={t(`${act}.${item.key}`)} value={formatCount(item.value)} tone={item.tone} to={item.to} />
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
{recentLogins.length > 0 && (
|
||||
<FixedTableCard title="Dernières connexions (top 5)" reportTo={reportUrl(REPORT_PATHS.usersActivePeriod, { from: today, to: today })}>
|
||||
<FixedTableCard
|
||||
title={t('admin.dashboard.sections.users.recentLogins')}
|
||||
reportTo={reportUrl(REPORT_PATHS.usersActivePeriod, { from: today, to: today })}
|
||||
>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Utilisateur</TableCell>
|
||||
<TableCell align="right">Date</TableCell>
|
||||
<TableCell>{t(`${tbl}.user`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.date`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -587,17 +611,20 @@ export function UserSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function GeographySection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const { label: countryLabel } = useCountryNames();
|
||||
const top = data.geography.slice(0, 8);
|
||||
const topWithNames = top.map((r) => ({ ...r, countryName: countryLabel(r.country) }));
|
||||
const tbl = 'admin.dashboard.tables';
|
||||
const geo = 'admin.dashboard.sections.geography';
|
||||
return (
|
||||
<SectionPanel title="Géographie" subtitle="Top 8 pays — vue fixe" action={<ReportDetailLink to={REPORT_PATHS.geoUsers} />}>
|
||||
<SectionPanel title={t(`${geo}.title`)} subtitle={t(`${geo}.subtitle`)} action={<ReportDetailLink to={REPORT_PATHS.geoUsers} />}>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart
|
||||
data={topWithNames.map((r) => ({ country: r.countryName, users: r.users }))}
|
||||
title="Utilisateurs (top 8)"
|
||||
title={t(`${geo}.usersTop8`)}
|
||||
dataKey="users"
|
||||
labelKey="country"
|
||||
/>
|
||||
@ -608,7 +635,7 @@ export function GeographySection({ data }: { data: AdminDashboardData }) {
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart
|
||||
data={topWithNames.map((r) => ({ country: r.countryName, deposits: r.depositsRaw }))}
|
||||
title="Dépôts (top 8)"
|
||||
title={t(`${geo}.depositsTop8`)}
|
||||
dataKey="deposits"
|
||||
labelKey="country"
|
||||
valueFormatter={(v) => `${formatRawUsdt(v)} USDT`}
|
||||
@ -617,16 +644,16 @@ export function GeographySection({ data }: { data: AdminDashboardData }) {
|
||||
</Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<FixedTableCard title="Synthèse top 8 pays" reportTo={REPORT_PATHS.geoUsers} tableMinWidth={760}>
|
||||
<FixedTableCard title={t(`${geo}.summaryTop8`)} reportTo={REPORT_PATHS.geoUsers} tableMinWidth={760}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Pays</TableCell>
|
||||
<TableCell align="right">Utilisateurs</TableCell>
|
||||
<TableCell align="right">Dépôts</TableCell>
|
||||
<TableCell align="right">Retraits</TableCell>
|
||||
<TableCell align="right">Net P/L</TableCell>
|
||||
<TableCell align="right">Actifs</TableCell>
|
||||
<TableCell>{t(`${tbl}.country`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.users`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.deposits`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.withdrawals`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.netPnl`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.active`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -648,45 +675,52 @@ export function GeographySection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function DemographicsSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const genderLabel = (gender: string) =>
|
||||
t(`admin.dashboard.gender.${gender}`, { defaultValue: gender });
|
||||
const ageLabel = (bucket: string) =>
|
||||
t(`admin.dashboard.ageBucket.${bucket}`, { defaultValue: bucket });
|
||||
const genderData = data.demographics.byGender.map((g) => ({
|
||||
label: GENDER_DASHBOARD_LABELS[g.gender] ?? g.gender,
|
||||
label: genderLabel(g.gender),
|
||||
users: g.users,
|
||||
}));
|
||||
const ageData = data.demographics.byAge.map((a) => ({
|
||||
label: AGE_BUCKET_LABELS[a.ageBucket] ?? a.ageBucket,
|
||||
label: ageLabel(a.ageBucket),
|
||||
users: a.users,
|
||||
}));
|
||||
const demo = 'admin.dashboard.sections.demographics';
|
||||
const tbl = 'admin.dashboard.tables';
|
||||
return (
|
||||
<SectionPanel title="Démographie" subtitle="Répartitions à taille fixe">
|
||||
<SectionPanel title={t(`${demo}.title`)} subtitle={t(`${demo}.subtitle`)}>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimplePieChart data={genderData} title="Par sexe" nameKey="label" valueKey="users" />
|
||||
<SimplePieChart data={genderData} title={t(`${demo}.byGender`)} nameKey="label" valueKey="users" />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart data={ageData} title="Par tranche d'âge" dataKey="users" labelKey="label" />
|
||||
<SimpleBarChart data={ageData} title={t(`${demo}.byAge`)} dataKey="users" labelKey="label" />
|
||||
</Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<FixedTableCard title="Détail par sexe" tableMinWidth={680}>
|
||||
<FixedTableCard title={t(`${demo}.genderDetail`)} tableMinWidth={680}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Sexe</TableCell>
|
||||
<TableCell align="right">Utilisateurs</TableCell>
|
||||
<TableCell align="right">Misé</TableCell>
|
||||
<TableCell align="right">Net P/L</TableCell>
|
||||
<TableCell align="right">Dépôts</TableCell>
|
||||
<TableCell>{t(`${tbl}.gender`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.users`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.stake`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.netPnl`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.deposits`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.demographics.byGender.map((g) => (
|
||||
<TableRow key={g.gender}>
|
||||
<TableCell>{GENDER_DASHBOARD_LABELS[g.gender] ?? g.gender}</TableCell>
|
||||
<TableCell>{genderLabel(g.gender)}</TableCell>
|
||||
<TableCell align="right">{formatCount(g.users)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(g.stakeRaw)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(g.netPnlRaw)}</TableCell>
|
||||
@ -698,21 +732,21 @@ export function DemographicsSection({ data }: { data: AdminDashboardData }) {
|
||||
</FixedTableCard>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<FixedTableCard title="Détail par tranche d'âge" tableMinWidth={680}>
|
||||
<FixedTableCard title={t(`${demo}.ageDetail`)} tableMinWidth={680}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Tranche</TableCell>
|
||||
<TableCell align="right">Utilisateurs</TableCell>
|
||||
<TableCell align="right">Misé</TableCell>
|
||||
<TableCell align="right">Net P/L</TableCell>
|
||||
<TableCell align="right">Dépôts</TableCell>
|
||||
<TableCell>{t(`${tbl}.ageBucket`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.users`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.stake`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.netPnl`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.deposits`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{data.demographics.byAge.map((a) => (
|
||||
<TableRow key={a.ageBucket}>
|
||||
<TableCell>{AGE_BUCKET_LABELS[a.ageBucket] ?? a.ageBucket}</TableCell>
|
||||
<TableCell>{ageLabel(a.ageBucket)}</TableCell>
|
||||
<TableCell align="right">{formatCount(a.users)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(a.stakeRaw)}</TableCell>
|
||||
<TableCell align="right">{formatRawUsdt(a.netPnlRaw)}</TableCell>
|
||||
@ -729,10 +763,12 @@ export function DemographicsSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const dateQ = {
|
||||
from: data.filters.from,
|
||||
to: data.filters.to,
|
||||
};
|
||||
const ch = 'admin.dashboard.sections.charts';
|
||||
const manualAutoMulti = data.charts.predictionsManual.map((m, i) => ({
|
||||
date: m.date,
|
||||
manual: m.value,
|
||||
@ -740,52 +776,52 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
multi: data.charts.predictionsMultiCandle[i]?.value ?? 0,
|
||||
}));
|
||||
const shortLong = data.charts.shortVsLong.map((r) => ({
|
||||
direction: r.direction === 'long' ? 'Long' : 'Short',
|
||||
direction: r.direction === 'long' ? t('admin.dashboard.sections.game.long') : t('admin.dashboard.sections.game.short'),
|
||||
count: r.count,
|
||||
}));
|
||||
const intervalData = data.charts.byInterval.map((r) => ({
|
||||
label: `${r.intervalMinutes} min`,
|
||||
label: t('admin.dashboard.minSuffix', { n: r.intervalMinutes }),
|
||||
stake: r.stakeRaw,
|
||||
participants: r.participants,
|
||||
}));
|
||||
const hourLogin = data.charts.loginHours.map((h) => ({ hour: `${h.hour}h`, count: h.count }));
|
||||
const hourBet = data.charts.betHours.map((h) => ({ hour: `${h.hour}h`, count: h.count }));
|
||||
const hourLogin = data.charts.loginHours.map((h) => ({ hour: t('admin.dashboard.hourSuffix', { h: h.hour }), count: h.count }));
|
||||
const hourBet = data.charts.betHours.map((h) => ({ hour: t('admin.dashboard.hourSuffix', { h: h.hour }), count: h.count }));
|
||||
return (
|
||||
<SectionPanel title="Tendances & répartitions" subtitle="Graphiques sur la période (vues à taille fixe)">
|
||||
<SectionPanel title={t(`${ch}.title`)} subtitle={t(`${ch}.subtitle`)}>
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart data={data.charts.signups} title="Inscriptions" />
|
||||
<TrendAreaChart data={data.charts.signups} title={t(`${ch}.signups`)} />
|
||||
<ReportDetailLink to={reportUrl(REPORT_PATHS.usersNewPeriod, dateQ)} />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart data={data.charts.activeUsers} title="Connexions" />
|
||||
<TrendAreaChart data={data.charts.activeUsers} title={t(`${ch}.logins`)} />
|
||||
<ReportDetailLink to={reportUrl(REPORT_PATHS.usersActivePeriod, dateQ)} />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart data={data.charts.verifiedUsers} title="E-mails vérifiés" />
|
||||
<TrendAreaChart data={data.charts.verifiedUsers} title={t(`${ch}.verifiedEmails`)} />
|
||||
<ReportDetailLink to={REPORT_PATHS.usersAll} />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendAreaChart data={data.charts.totpEnabled} title="2FA activé" />
|
||||
<TrendAreaChart data={data.charts.totpEnabled} title={t(`${ch}.totpEnabled`)} />
|
||||
<ReportDetailLink to={REPORT_PATHS.users2faOn} />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<TrendLineChart
|
||||
title="Manuel vs Auto vs Multi-candles"
|
||||
title={t(`${ch}.manualAutoMulti`)}
|
||||
data={manualAutoMulti}
|
||||
lines={[
|
||||
{ key: 'manual', label: 'Manuel', color: '#D6B25E' },
|
||||
{ key: 'auto', label: 'Auto', color: '#7C5CFF' },
|
||||
{ key: 'multi', label: 'Multi-candles', color: '#22C55E' },
|
||||
{ key: 'manual', label: t(`${ch}.manual`), color: '#D6B25E' },
|
||||
{ key: 'auto', label: t(`${ch}.auto`), color: '#7C5CFF' },
|
||||
{ key: 'multi', label: t(`${ch}.multiCandle`), color: '#22C55E' },
|
||||
]}
|
||||
/>
|
||||
<ReportDetailLink to={REPORT_PATHS.predictions} />
|
||||
@ -793,7 +829,7 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimplePieChart data={shortLong} title="Short vs Long" nameKey="direction" valueKey="count" />
|
||||
<SimplePieChart data={shortLong} title={t(`${ch}.shortVsLong`)} nameKey="direction" valueKey="count" />
|
||||
<ReportDetailLink to={REPORT_PATHS.predictions} />
|
||||
</Card>
|
||||
</Grid>
|
||||
@ -801,7 +837,7 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart
|
||||
data={intervalData}
|
||||
title="Mises par intervalle"
|
||||
title={t(`${ch}.stakeByInterval`)}
|
||||
dataKey="stake"
|
||||
labelKey="label"
|
||||
valueFormatter={(v) => `${formatRawUsdt(v)} USDT`}
|
||||
@ -811,13 +847,13 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart data={hourLogin} title="Heures de connexion (24h)" dataKey="count" labelKey="hour" />
|
||||
<SimpleBarChart data={hourLogin} title={t(`${ch}.loginHours`)} dataKey="count" labelKey="hour" />
|
||||
<ReportDetailLink to={reportUrl(REPORT_PATHS.usersActivePeriod, dateQ)} />
|
||||
</Card>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimpleBarChart data={hourBet} title="Heures de jeu (24h)" dataKey="count" labelKey="hour" />
|
||||
<SimpleBarChart data={hourBet} title={t(`${ch}.betHours`)} dataKey="count" labelKey="hour" />
|
||||
<ReportDetailLink to={REPORT_PATHS.predictions} />
|
||||
</Card>
|
||||
</Grid>
|
||||
@ -825,10 +861,10 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
<Card sx={{ p: 2 }}>
|
||||
<SimplePieChart
|
||||
data={[
|
||||
{ label: 'Nouveaux', value: data.charts.retention.newUsers },
|
||||
{ label: 'Récurrents', value: data.charts.retention.returningUsers },
|
||||
{ label: t(`${ch}.newUsers`), value: data.charts.retention.newUsers },
|
||||
{ label: t(`${ch}.returningUsers`), value: data.charts.retention.returningUsers },
|
||||
]}
|
||||
title="Nouveaux vs récurrents"
|
||||
title={t(`${ch}.newVsReturning`)}
|
||||
nameKey="label"
|
||||
valueKey="value"
|
||||
/>
|
||||
@ -841,21 +877,28 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) {
|
||||
}
|
||||
|
||||
export function AlertsSection({ data }: { data: AdminDashboardData }) {
|
||||
const { t } = useTranslation();
|
||||
const al = data.alerts;
|
||||
const recentAlerts = al.recentAlerts.slice(0, 10);
|
||||
const alert = 'admin.dashboard.sections.alerts';
|
||||
const tbl = 'admin.dashboard.tables';
|
||||
return (
|
||||
<SectionPanel title="Alertes" subtitle="Surveillance en temps réel" action={<ReportDetailLink to={REPORT_PATHS.securityAlerts} label="Centre sécurité" />}>
|
||||
<SectionPanel
|
||||
title={t(`${alert}.title`)}
|
||||
subtitle={t(`${alert}.subtitle`)}
|
||||
action={<ReportDetailLink to={REPORT_PATHS.securityAlerts} label={t('admin.dashboard.securityCenter')} />}
|
||||
>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Alertes ouvertes" value={formatCount(al.openAlertsCount)} tone="danger" to={REPORT_PATHS.securityAlerts} />
|
||||
<KpiCard title={t(`${alert}.openAlerts`)} value={formatCount(al.openAlertsCount)} tone="danger" to={REPORT_PATHS.securityAlerts} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard title="Alertes connexion" value={formatCount(al.failedLoginAlerts)} tone="warning" to={REPORT_PATHS.securityAlerts} />
|
||||
<KpiCard title={t(`${alert}.loginAlerts`)} value={formatCount(al.failedLoginAlerts)} tone="warning" to={REPORT_PATHS.securityAlerts} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Hausse dépôts"
|
||||
value={al.depositSpike.isUnusual ? 'Inhabituelle' : 'Normale'}
|
||||
title={t(`${alert}.depositSpike`)}
|
||||
value={al.depositSpike.isUnusual ? t('admin.dashboard.unusual') : t('admin.dashboard.normal')}
|
||||
subtitle={formatPercent(al.depositSpike.spikePercent)}
|
||||
tone={al.depositSpike.isUnusual ? 'warning' : 'default'}
|
||||
to={REPORT_PATHS.deposits}
|
||||
@ -863,8 +906,8 @@ export function AlertsSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<KpiCard
|
||||
title="Hausse retraits"
|
||||
value={al.withdrawalSpike.isUnusual ? 'Inhabituelle' : 'Normale'}
|
||||
title={t(`${alert}.withdrawalSpike`)}
|
||||
value={al.withdrawalSpike.isUnusual ? t('admin.dashboard.unusual') : t('admin.dashboard.normal')}
|
||||
subtitle={formatPercent(al.withdrawalSpike.spikePercent)}
|
||||
tone={al.withdrawalSpike.isUnusual ? 'warning' : 'default'}
|
||||
to={REPORT_PATHS.withdrawals}
|
||||
@ -872,16 +915,16 @@ export function AlertsSection({ data }: { data: AdminDashboardData }) {
|
||||
</Grid>
|
||||
</Grid>
|
||||
{recentAlerts.length === 0 ? (
|
||||
<Alert severity="success">Aucune alerte récente sur la période.</Alert>
|
||||
<Alert severity="success">{t('admin.dashboard.noRecentAlerts')}</Alert>
|
||||
) : (
|
||||
<FixedTableCard title={`Alertes récentes (max ${recentAlerts.length})`} reportTo={REPORT_PATHS.securityAlerts}>
|
||||
<FixedTableCard title={t('admin.dashboard.recentAlertsMax', { count: recentAlerts.length })} reportTo={REPORT_PATHS.securityAlerts}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Type</TableCell>
|
||||
<TableCell>Sévérité</TableCell>
|
||||
<TableCell>Statut</TableCell>
|
||||
<TableCell align="right">Date</TableCell>
|
||||
<TableCell>{t(`${tbl}.type`)}</TableCell>
|
||||
<TableCell>{t(`${tbl}.severity`)}</TableCell>
|
||||
<TableCell>{t(`${tbl}.status`)}</TableCell>
|
||||
<TableCell align="right">{t(`${tbl}.date`)}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import ViewModuleRoundedIcon from '@mui/icons-material/ViewModuleRounded';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { DashboardFilters, DashboardSectionId } from '../types';
|
||||
import { DASHBOARD_SECTIONS } from '../types';
|
||||
import { loadDashboardLayout, saveDashboardLayout, type SavedDashboardView } from '../utils/layoutStorage';
|
||||
@ -29,10 +30,12 @@ export function PersonalizationToolbar({
|
||||
hiddenSections,
|
||||
onHiddenChange,
|
||||
}: PersonalizationToolbarProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [viewName, setViewName] = useState('');
|
||||
const [savedViews, setSavedViews] = useState(() => loadDashboardLayout().savedViews);
|
||||
const [emailReport, setEmailReport] = useState('');
|
||||
const p = 'admin.dashboard.personalize';
|
||||
|
||||
const toggleSection = (id: DashboardSectionId) => {
|
||||
if (hiddenSections.includes(id)) {
|
||||
@ -74,7 +77,7 @@ export function PersonalizationToolbar({
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<Button size="small" variant="outlined" startIcon={<ViewModuleRoundedIcon />} onClick={() => setOpen(true)}>
|
||||
Personnaliser
|
||||
{t(`${p}.button`)}
|
||||
</Button>
|
||||
{savedViews.slice(0, 3).map((v) => (
|
||||
<Chip
|
||||
@ -87,15 +90,15 @@ export function PersonalizationToolbar({
|
||||
/>
|
||||
))}
|
||||
<Typography variant="caption" sx={{ opacity: 0.55, ml: 1 }}>
|
||||
Masquer/afficher des sections · vues sauvegardées (local)
|
||||
{t(`${p}.hint`)}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<Dialog open={open} onClose={() => setOpen(false)} fullWidth maxWidth="sm">
|
||||
<DialogTitle>Personnalisation du dashboard</DialogTitle>
|
||||
<DialogTitle>{t(`${p}.dialogTitle`)}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, mt: 1, mb: 1 }}>
|
||||
Sections visibles
|
||||
{t(`${p}.visibleSections`)}
|
||||
</Typography>
|
||||
<Stack>
|
||||
{DASHBOARD_SECTIONS.map((s) => (
|
||||
@ -107,31 +110,31 @@ export function PersonalizationToolbar({
|
||||
onChange={() => toggleSection(s.id)}
|
||||
/>
|
||||
}
|
||||
label={s.label}
|
||||
label={t(`admin.dashboard.sectionLabels.${s.id}`)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, mt: 2, mb: 1 }}>
|
||||
Sauvegarder la vue actuelle
|
||||
{t(`${p}.saveCurrentView`)}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
placeholder="Nom de la vue"
|
||||
placeholder={t(`${p}.viewNamePlaceholder`)}
|
||||
value={viewName}
|
||||
onChange={(e) => setViewName(e.target.value)}
|
||||
/>
|
||||
<Button variant="contained" onClick={saveView} disabled={!viewName.trim()}>
|
||||
Sauver
|
||||
{t(`${p}.save`)}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{savedViews.length > 0 && (
|
||||
<Stack spacing={0.5} sx={{ mt: 2 }}>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
Vues enregistrées
|
||||
{t(`${p}.savedViews`)}
|
||||
</Typography>
|
||||
{savedViews.map((v) => (
|
||||
<Chip
|
||||
@ -147,21 +150,21 @@ export function PersonalizationToolbar({
|
||||
)}
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, mt: 3, mb: 1 }}>
|
||||
Rapports par e-mail (bientôt)
|
||||
{t(`${p}.emailReportsSoon`)}
|
||||
</Typography>
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
placeholder={t(`${p}.emailPlaceholder`)}
|
||||
value={emailReport}
|
||||
onChange={(e) => setEmailReport(e.target.value)}
|
||||
helperText="La programmation automatique de rapports sera disponible dans une prochaine version."
|
||||
helperText={t(`${p}.emailHelper`)}
|
||||
disabled
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpen(false)}>Fermer</Button>
|
||||
<Button onClick={() => setOpen(false)}>{t(`${p}.close`)}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { Button } from '@mui/material';
|
||||
import OpenInNewRoundedIcon from '@mui/icons-material/OpenInNewRounded';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/** Compact link to open the detailed report for a dashboard KPI. */
|
||||
export function ReportDetailLink({ to, label = 'Voir le rapport détaillé' }: { to: string; label?: string }) {
|
||||
export function ReportDetailLink({ to, label }: { to: string; label?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Button
|
||||
component={RouterLink}
|
||||
@ -12,7 +14,7 @@ export function ReportDetailLink({ to, label = 'Voir le rapport détaillé' }: {
|
||||
endIcon={<OpenInNewRoundedIcon />}
|
||||
sx={{ mt: 1, px: 0, minWidth: 0, fontWeight: 700 }}
|
||||
>
|
||||
{label}
|
||||
{label ?? t('admin.dashboard.reportDetail')}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { Alert, Grid, Skeleton } from '@mui/material';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import { REPORT_PATHS } from '../reportLinks';
|
||||
import { formatRawUsdt } from '../utils/format';
|
||||
@ -25,6 +26,7 @@ function formatOnChainBalance(raw: string | null, decimals: number): string {
|
||||
|
||||
/** On-chain hot/cold balances and in-progress deposit sweeps for the admin dashboard. */
|
||||
export function TreasuryDashboardCards() {
|
||||
const { t } = useTranslation();
|
||||
const q = useQuery({
|
||||
queryKey: ['admin-treasury-overview'],
|
||||
queryFn: async () => {
|
||||
@ -50,7 +52,7 @@ export function TreasuryDashboardCards() {
|
||||
if (q.isError) {
|
||||
return (
|
||||
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Impossible de charger la trésorerie on-chain (hot/cold). Consultez la page Treasury pour le détail.
|
||||
{t('admin.dashboard.treasury.loadError')}
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
@ -64,7 +66,7 @@ export function TreasuryDashboardCards() {
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 4 }}>
|
||||
<KpiCard
|
||||
title="Hot wallet (on-chain)"
|
||||
title={t('admin.dashboard.treasury.hotWallet')}
|
||||
subtitle={asset?.walletType.name ?? 'USDT'}
|
||||
value={formatOnChainBalance(asset?.hotOnChainBalance ?? null, decimals)}
|
||||
tone="info"
|
||||
@ -73,7 +75,7 @@ export function TreasuryDashboardCards() {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 4 }}>
|
||||
<KpiCard
|
||||
title="Cold wallet (on-chain)"
|
||||
title={t('admin.dashboard.treasury.coldWallet')}
|
||||
subtitle={asset?.walletType.name ?? 'USDT'}
|
||||
value={formatOnChainBalance(asset?.coldOnChainBalance ?? null, decimals)}
|
||||
tone="info"
|
||||
@ -82,11 +84,11 @@ export function TreasuryDashboardCards() {
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 4 }}>
|
||||
<KpiCard
|
||||
title="Deposit sweeps en cours"
|
||||
title={t('admin.dashboard.treasury.sweepsInProgress')}
|
||||
subtitle={
|
||||
sweeps.count > 0
|
||||
? `${sweeps.count} opération${sweeps.count > 1 ? 's' : ''} · pending / gas / broadcast`
|
||||
: 'Aucun sweep actif'
|
||||
? t('admin.dashboard.treasury.operations', { count: sweeps.count })
|
||||
: t('admin.dashboard.treasury.noActiveSweep')
|
||||
}
|
||||
value={
|
||||
sweeps.count > 0
|
||||
|
||||
@ -13,20 +13,3 @@ export function formatPercent(value: number): string {
|
||||
export function formatCount(value: number): string {
|
||||
return value.toLocaleString();
|
||||
}
|
||||
|
||||
export const AGE_BUCKET_LABELS: Record<string, string> = {
|
||||
unknown: 'Unknown',
|
||||
under_18: 'Under 18',
|
||||
'18_24': '18–24',
|
||||
'25_34': '25–34',
|
||||
'35_44': '35–44',
|
||||
'45_54': '45–54',
|
||||
'55_plus': '55+',
|
||||
};
|
||||
|
||||
export const GENDER_DASHBOARD_LABELS: Record<string, string> = {
|
||||
male: 'Masculin',
|
||||
female: 'Féminin',
|
||||
other: 'Autre',
|
||||
unknown: 'Non renseigné',
|
||||
};
|
||||
|
||||
@ -28,6 +28,7 @@ import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
|
||||
import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
adminCreateFaq,
|
||||
adminCreateFaqCategory,
|
||||
@ -66,6 +67,7 @@ const emptyCategory = (): { name: string; slug: string; sortOrder: number; isAct
|
||||
|
||||
/** Admin / moderator FAQ management. */
|
||||
export function FaqAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [tab, setTab] = useState<TabKey>('entries');
|
||||
const [search, setSearch] = useState('');
|
||||
@ -109,7 +111,7 @@ export function FaqAdminPage() {
|
||||
const saveEntryM = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (entryForm.categoryId === '' || !entryForm.question.trim()) {
|
||||
throw new Error('Catégorie et question requises');
|
||||
throw new Error(t('admin.faqAdmin.categoryRequired'));
|
||||
}
|
||||
const body = {
|
||||
categoryId: entryForm.categoryId,
|
||||
@ -136,7 +138,7 @@ export function FaqAdminPage() {
|
||||
|
||||
const saveCatM = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!catForm.name.trim()) throw new Error('Nom requis');
|
||||
if (!catForm.name.trim()) throw new Error(t('admin.faqAdmin.nameRequired'));
|
||||
const body = {
|
||||
name: catForm.name.trim(),
|
||||
slug: catForm.slug.trim() || undefined,
|
||||
@ -209,21 +211,19 @@ export function FaqAdminPage() {
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<HelpOutlineRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
Gestion FAQ
|
||||
{t('admin.faqAdmin.title')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.7 }}>
|
||||
Créez et organisez les questions fréquentes affichées aux utilisateurs.
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.faqAdmin.subtitle')}</Typography>
|
||||
</Stack>
|
||||
<Button startIcon={<RefreshRoundedIcon />} onClick={() => invalidate()} variant="outlined" size="small">
|
||||
Actualiser
|
||||
{t('admin.faqAdmin.refresh')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<Tabs value={tab} onChange={(_, v: TabKey) => setTab(v)} sx={{ mb: 2 }}>
|
||||
<Tab value="entries" label="Questions" />
|
||||
<Tab value="categories" label="Catégories" />
|
||||
<Tab value="entries" label={t('admin.faqAdmin.tabEntries')} />
|
||||
<Tab value="categories" label={t('admin.faqAdmin.tabCategories')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 'entries' && (
|
||||
@ -231,19 +231,19 @@ export function FaqAdminPage() {
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={1.5} sx={{ mb: 2 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
placeholder="Rechercher…"
|
||||
placeholder={t('admin.faqAdmin.searchPlaceholder')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<FormControl size="small" sx={{ minWidth: 160 }}>
|
||||
<InputLabel>Catégorie</InputLabel>
|
||||
<InputLabel>{t('admin.faqAdmin.category')}</InputLabel>
|
||||
<Select
|
||||
label="Catégorie"
|
||||
label={t('admin.faqAdmin.category')}
|
||||
value={categoryFilter}
|
||||
onChange={(e) => setCategoryFilter(e.target.value as number | '')}
|
||||
>
|
||||
<MenuItem value="">Toutes</MenuItem>
|
||||
<MenuItem value="">{t('admin.faqAdmin.allCategories')}</MenuItem>
|
||||
{categories.map((c) => (
|
||||
<MenuItem key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
@ -252,25 +252,25 @@ export function FaqAdminPage() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: 140 }}>
|
||||
<InputLabel>Statut</InputLabel>
|
||||
<InputLabel>{t('admin.faqAdmin.status')}</InputLabel>
|
||||
<Select
|
||||
label="Statut"
|
||||
label={t('admin.faqAdmin.status')}
|
||||
value={activeFilter}
|
||||
onChange={(e) => setActiveFilter(e.target.value as typeof activeFilter)}
|
||||
>
|
||||
<MenuItem value="all">Tous</MenuItem>
|
||||
<MenuItem value="active">Actives</MenuItem>
|
||||
<MenuItem value="inactive">Inactives</MenuItem>
|
||||
<MenuItem value="all">{t('admin.faqAdmin.allStatuses')}</MenuItem>
|
||||
<MenuItem value="active">{t('admin.faqAdmin.activeEntries')}</MenuItem>
|
||||
<MenuItem value="inactive">{t('admin.faqAdmin.inactiveEntries')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Button startIcon={<AddRoundedIcon />} variant="contained" onClick={openCreateEntry}>
|
||||
Nouvelle FAQ
|
||||
{t('admin.faqAdmin.newEntry')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{(entriesQ.error || saveEntryM.error) && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
{(saveEntryM.error as Error)?.message ?? 'Erreur de chargement'}
|
||||
{(saveEntryM.error as Error)?.message ?? t('admin.faqAdmin.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -284,14 +284,20 @@ export function FaqAdminPage() {
|
||||
<Chip size="small" label={entry.categoryName} variant="outlined" />
|
||||
<Chip
|
||||
size="small"
|
||||
label={entry.isActive ? 'Active' : 'Inactive'}
|
||||
label={entry.isActive ? t('admin.faqAdmin.entryActive') : t('admin.faqAdmin.entryInactive')}
|
||||
color={entry.isActive ? 'success' : 'default'}
|
||||
/>
|
||||
<Chip size="small" label={`Ordre: ${entry.sortOrder}`} variant="outlined" />
|
||||
<Chip size="small" label={t('admin.faqAdmin.order', { order: entry.sortOrder })} variant="outlined" />
|
||||
</Stack>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65, display: 'block', mt: 0.5 }}>
|
||||
Vues: {entry.viewCount} · Utile: {entry.helpfulYes} / {entry.helpfulNo}
|
||||
{entry.updatedByName ? ` · Modifié par ${entry.updatedByName}` : ''}
|
||||
{t('admin.faqAdmin.views', {
|
||||
views: entry.viewCount,
|
||||
yes: entry.helpfulYes,
|
||||
no: entry.helpfulNo,
|
||||
})}
|
||||
{entry.updatedByName
|
||||
? t('admin.faqAdmin.updatedBy', { name: entry.updatedByName })
|
||||
: ''}
|
||||
{entry.updatedAt ? ` · ${new Date(entry.updatedAt).toLocaleString()}` : ''}
|
||||
</Typography>
|
||||
</Box>
|
||||
@ -302,7 +308,7 @@ export function FaqAdminPage() {
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => {
|
||||
if (window.confirm('Supprimer cette FAQ ?')) deleteEntryM.mutate(entry.id);
|
||||
if (window.confirm(t('admin.faqAdmin.deleteEntryConfirm'))) deleteEntryM.mutate(entry.id);
|
||||
}}
|
||||
>
|
||||
<DeleteOutlineRoundedIcon fontSize="small" />
|
||||
@ -311,7 +317,7 @@ export function FaqAdminPage() {
|
||||
</Paper>
|
||||
))}
|
||||
{!entriesQ.isLoading && sortedEntries.length === 0 && (
|
||||
<Alert severity="info">Aucune FAQ trouvée.</Alert>
|
||||
<Alert severity="info">{t('admin.faqAdmin.noEntries')}</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</>
|
||||
@ -321,7 +327,7 @@ export function FaqAdminPage() {
|
||||
<>
|
||||
<Stack direction="row" sx={{ mb: 2, justifyContent: 'flex-end' }}>
|
||||
<Button startIcon={<AddRoundedIcon />} variant="contained" onClick={openCreateCat}>
|
||||
Nouvelle catégorie
|
||||
{t('admin.faqAdmin.newCategory')}
|
||||
</Button>
|
||||
</Stack>
|
||||
<Stack spacing={1}>
|
||||
@ -331,8 +337,8 @@ export function FaqAdminPage() {
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography sx={{ fontWeight: 800 }}>{cat.name}</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
Slug: {cat.slug} · Ordre: {cat.sortOrder}
|
||||
{cat.isActive === false ? ' · Inactive' : ''}
|
||||
{t('admin.faqAdmin.slug', { slug: cat.slug, order: cat.sortOrder })}
|
||||
{cat.isActive === false ? t('admin.faqAdmin.categoryInactive') : ''}
|
||||
</Typography>
|
||||
</Box>
|
||||
<IconButton size="small" onClick={() => openEditCat(cat)}>
|
||||
@ -342,7 +348,7 @@ export function FaqAdminPage() {
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => {
|
||||
if (window.confirm('Supprimer cette catégorie ? Les FAQ associées doivent être déplacées.')) {
|
||||
if (window.confirm(t('admin.faqAdmin.deleteCategoryConfirm'))) {
|
||||
deleteCatM.mutate(cat.id);
|
||||
}
|
||||
}}
|
||||
@ -357,13 +363,13 @@ export function FaqAdminPage() {
|
||||
)}
|
||||
|
||||
<Dialog open={entryDialogOpen} onClose={() => setEntryDialogOpen(false)} maxWidth="md" fullWidth>
|
||||
<DialogTitle>{editingEntry ? 'Modifier la FAQ' : 'Nouvelle FAQ'}</DialogTitle>
|
||||
<DialogTitle>{editingEntry ? t('admin.faqAdmin.entryDialogEdit') : t('admin.faqAdmin.entryDialogNew')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Catégorie</InputLabel>
|
||||
<InputLabel>{t('admin.faqAdmin.category')}</InputLabel>
|
||||
<Select
|
||||
label="Catégorie"
|
||||
label={t('admin.faqAdmin.category')}
|
||||
value={entryForm.categoryId}
|
||||
onChange={(e) => setEntryForm((f) => ({ ...f, categoryId: e.target.value as number }))}
|
||||
>
|
||||
@ -375,19 +381,19 @@ export function FaqAdminPage() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label="Question"
|
||||
label={t('admin.faqAdmin.question')}
|
||||
fullWidth
|
||||
value={entryForm.question}
|
||||
onChange={(e) => setEntryForm((f) => ({ ...f, question: e.target.value }))}
|
||||
/>
|
||||
<Typography variant="subtitle2">Réponse</Typography>
|
||||
<Typography variant="subtitle2">{t('admin.faqAdmin.answer')}</Typography>
|
||||
<FaqRichEditor
|
||||
value={entryForm.answerHtml}
|
||||
onChange={(html) => setEntryForm((f) => ({ ...f, answerHtml: html }))}
|
||||
/>
|
||||
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
|
||||
<TextField
|
||||
label="Ordre d'affichage"
|
||||
label={t('admin.faqAdmin.sortOrder')}
|
||||
type="number"
|
||||
size="small"
|
||||
value={entryForm.sortOrder}
|
||||
@ -401,7 +407,7 @@ export function FaqAdminPage() {
|
||||
onChange={(e) => setEntryForm((f) => ({ ...f, isActive: e.target.checked }))}
|
||||
/>
|
||||
}
|
||||
label="Active"
|
||||
label={t('admin.faqAdmin.entryActive')}
|
||||
/>
|
||||
</Stack>
|
||||
{saveEntryM.error && (
|
||||
@ -410,32 +416,32 @@ export function FaqAdminPage() {
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setEntryDialogOpen(false)}>Annuler</Button>
|
||||
<Button onClick={() => setEntryDialogOpen(false)}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={() => saveEntryM.mutate()} disabled={saveEntryM.isPending}>
|
||||
Enregistrer
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={catDialogOpen} onClose={() => setCatDialogOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{editingCat ? 'Modifier la catégorie' : 'Nouvelle catégorie'}</DialogTitle>
|
||||
<DialogTitle>{editingCat ? t('admin.faqAdmin.categoryDialogEdit') : t('admin.faqAdmin.categoryDialogNew')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
<TextField
|
||||
label="Nom"
|
||||
label={t('admin.faqAdmin.name')}
|
||||
fullWidth
|
||||
value={catForm.name}
|
||||
onChange={(e) => setCatForm((f) => ({ ...f, name: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Slug (optionnel)"
|
||||
label={t('admin.faqAdmin.slugOptional')}
|
||||
fullWidth
|
||||
value={catForm.slug}
|
||||
onChange={(e) => setCatForm((f) => ({ ...f, slug: e.target.value }))}
|
||||
helperText="Généré automatiquement si vide"
|
||||
helperText={t('admin.faqAdmin.slugAuto')}
|
||||
/>
|
||||
<TextField
|
||||
label="Ordre"
|
||||
label={t('admin.faqAdmin.orderField')}
|
||||
type="number"
|
||||
value={catForm.sortOrder}
|
||||
onChange={(e) => setCatForm((f) => ({ ...f, sortOrder: Number(e.target.value) || 0 }))}
|
||||
@ -447,15 +453,15 @@ export function FaqAdminPage() {
|
||||
onChange={(e) => setCatForm((f) => ({ ...f, isActive: e.target.checked }))}
|
||||
/>
|
||||
}
|
||||
label="Active"
|
||||
label={t('admin.faqAdmin.entryActive')}
|
||||
/>
|
||||
{saveCatM.error && <Alert severity="error">{(saveCatM.error as Error).message}</Alert>}
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setCatDialogOpen(false)}>Annuler</Button>
|
||||
<Button onClick={() => setCatDialogOpen(false)}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={() => saveCatM.mutate()} disabled={saveCatM.isPending}>
|
||||
Enregistrer
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -21,6 +21,7 @@ import TrendingUpRoundedIcon from '@mui/icons-material/TrendingUpRounded';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
fetchFaqCategories,
|
||||
fetchFaqs,
|
||||
@ -58,6 +59,7 @@ function HelpfulButtons({
|
||||
entry: FaqEntry;
|
||||
onUpdate: (yes: number, no: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const voted = readSet(VOTED_KEY).has(entry.id);
|
||||
const mutation = useMutation({
|
||||
mutationFn: (helpful: boolean) => recordFaqHelpful(entry.id, helpful),
|
||||
@ -70,7 +72,7 @@ function HelpfulButtons({
|
||||
if (voted) {
|
||||
return (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
Merci pour votre retour !
|
||||
{t('faq.thankYou')}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@ -78,7 +80,7 @@ function HelpfulButtons({
|
||||
return (
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.8 }}>
|
||||
Cette réponse vous a-t-elle été utile ?
|
||||
{t('faq.helpfulQuestion')}
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
@ -87,7 +89,7 @@ function HelpfulButtons({
|
||||
disabled={mutation.isPending}
|
||||
onClick={() => mutation.mutate(true)}
|
||||
>
|
||||
Oui ({entry.helpfulYes})
|
||||
{t('faq.yes', { count: entry.helpfulYes })}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
@ -96,7 +98,7 @@ function HelpfulButtons({
|
||||
disabled={mutation.isPending}
|
||||
onClick={() => mutation.mutate(false)}
|
||||
>
|
||||
Non ({entry.helpfulNo})
|
||||
{t('faq.no', { count: entry.helpfulNo })}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
@ -108,6 +110,7 @@ type FaqPageProps = {
|
||||
|
||||
/** Public FAQ page with search, categories, accordion, and helpful votes. */
|
||||
export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
const { t } = useTranslation();
|
||||
const [search, setSearch] = useState('');
|
||||
const [categorySlug, setCategorySlug] = useState<string | null>(null);
|
||||
const [expandedId, setExpandedId] = useState<string | false>(false);
|
||||
@ -172,16 +175,16 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
{!isLoggedIn && (
|
||||
<>
|
||||
<Button component={RouterLink} to="/login" size="small" variant="outlined">
|
||||
Connexion
|
||||
{t('faq.publicHeader.login')}
|
||||
</Button>
|
||||
<Button component={RouterLink} to="/register" size="small" variant="contained">
|
||||
Inscription
|
||||
{t('faq.publicHeader.register')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isLoggedIn && (
|
||||
<Button component={RouterLink} to="/home" size="small" variant="contained">
|
||||
Accueil
|
||||
{t('faq.publicHeader.home')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
@ -192,17 +195,15 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<HelpOutlineRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
Foire aux questions
|
||||
{t('faq.title')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.7 }}>
|
||||
Trouvez rapidement des réponses aux questions les plus fréquentes.
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('faq.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
placeholder="Rechercher une question…"
|
||||
placeholder={t('faq.searchPlaceholder')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
slotProps={{
|
||||
@ -219,7 +220,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2, flexWrap: 'wrap', gap: 1 }}>
|
||||
<Chip
|
||||
label="Toutes"
|
||||
label={t('faq.allCategories')}
|
||||
color={categorySlug === null ? 'primary' : 'default'}
|
||||
onClick={() => setCategorySlug(null)}
|
||||
variant={categorySlug === null ? 'filled' : 'outlined'}
|
||||
@ -240,7 +241,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 1, alignItems: 'center' }}>
|
||||
<TrendingUpRoundedIcon fontSize="small" color="primary" />
|
||||
<Typography variant="subtitle1" sx={{ fontWeight: 800 }}>
|
||||
Questions populaires
|
||||
{t('faq.popular')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>
|
||||
@ -267,7 +268,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
|
||||
{(categoriesQ.error || faqsQ.error) && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Impossible de charger les FAQ. Réessayez plus tard.
|
||||
{t('faq.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -276,7 +277,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : entries.length === 0 ? (
|
||||
<Alert severity="info">Aucune question ne correspond à votre recherche.</Alert>
|
||||
<Alert severity="info">{t('faq.noResults')}</Alert>
|
||||
) : (
|
||||
<Stack spacing={1}>
|
||||
{entries.map((entry) => (
|
||||
@ -292,7 +293,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) {
|
||||
<Typography sx={{ fontWeight: 700 }}>{entry.question}</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6 }}>
|
||||
{entry.categoryName}
|
||||
{entry.viewCount > 0 ? ` · ${entry.viewCount} consultation(s)` : ''}
|
||||
{entry.viewCount > 0 ? ` · ${t('faq.views', { count: entry.viewCount })}` : ''}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</AccordionSummary>
|
||||
|
||||
@ -18,6 +18,7 @@ import EmojiEventsRoundedIcon from '@mui/icons-material/EmojiEventsRounded';
|
||||
import GridViewRoundedIcon from '@mui/icons-material/GridViewRounded';
|
||||
import { useMemo, useState, type ReactNode } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { GameCard } from './components/GameCard';
|
||||
import { PromoCarousel } from './components/PromoCarousel';
|
||||
import { PromoStrip } from './components/PromoStrip';
|
||||
@ -29,6 +30,7 @@ const ALL = 'all';
|
||||
|
||||
/** Main landing page with hero promos, strip ads, and filterable games grid. */
|
||||
export function HomePage() {
|
||||
const { t } = useTranslation();
|
||||
const nav = useNavigate();
|
||||
const gamesQ = useGames();
|
||||
const heroQ = useHeroAdvertisements();
|
||||
@ -52,7 +54,7 @@ export function HomePage() {
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([gamesQ.refetch(), heroQ.refetch(), stripQ.refetch()]);
|
||||
setToast('Catalog refreshed');
|
||||
setToast(t('common.catalogRefreshed'));
|
||||
};
|
||||
|
||||
const onPlay = (game: Game) => {
|
||||
@ -66,12 +68,12 @@ export function HomePage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<HomeRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Play & Predict"
|
||||
subtitle="Explore live prediction games, grab limited-time promos, and compete for rewards."
|
||||
title={t('home.title')}
|
||||
subtitle={t('home.subtitle')}
|
||||
mb={2.5}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh catalog"
|
||||
label={t('home.refreshCatalog')}
|
||||
onClick={() => void refreshAll()}
|
||||
disabled={loading}
|
||||
/>
|
||||
@ -80,7 +82,7 @@ export function HomePage() {
|
||||
|
||||
{(gamesQ.isError || heroQ.isError) && (
|
||||
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Some content failed to load. Run database migrations and ensure the API is running.
|
||||
{t('home.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -105,19 +107,19 @@ export function HomePage() {
|
||||
>
|
||||
<StatPill
|
||||
icon={<BoltRoundedIcon fontSize="small" />}
|
||||
label="Live games"
|
||||
label={t('home.liveGames')}
|
||||
value={String(liveCount)}
|
||||
color="#D6B25E"
|
||||
/>
|
||||
<StatPill
|
||||
icon={<EmojiEventsRoundedIcon fontSize="small" />}
|
||||
label="Featured"
|
||||
label={t('home.featured')}
|
||||
value={String(featuredCount)}
|
||||
color="#7C5CFF"
|
||||
/>
|
||||
<StatPill
|
||||
icon={<GridViewRoundedIcon fontSize="small" />}
|
||||
label="Total"
|
||||
label={t('home.total')}
|
||||
value={String(games.length)}
|
||||
color="#4CAF50"
|
||||
sx={{ gridColumn: { xs: '1 / -1', sm: 'auto' } }}
|
||||
@ -127,7 +129,7 @@ export function HomePage() {
|
||||
|
||||
<Box sx={{ display: { xs: 'none', lg: 'block' } }}>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, letterSpacing: 1.2, mb: 1, display: 'block' }}>
|
||||
Promotions
|
||||
{t('home.promotions')}
|
||||
</Typography>
|
||||
<PromoStrip ads={stripQ.data ?? []} />
|
||||
</Box>
|
||||
@ -135,7 +137,7 @@ export function HomePage() {
|
||||
|
||||
<Box sx={{ display: { xs: 'block', lg: 'none' }, mb: 3 }}>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6, letterSpacing: 1.2, mb: 1, display: 'block' }}>
|
||||
Promotions
|
||||
{t('home.promotions')}
|
||||
</Typography>
|
||||
<PromoStrip ads={stripQ.data ?? []} />
|
||||
</Box>
|
||||
@ -158,12 +160,12 @@ export function HomePage() {
|
||||
sx={{ flexWrap: 'wrap', alignItems: 'center' }}
|
||||
>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mr: 0.5 }}>
|
||||
Categories
|
||||
{t('home.categories')}
|
||||
</Typography>
|
||||
{categories.map((cat) => (
|
||||
<Chip
|
||||
key={cat}
|
||||
label={cat === ALL ? 'All games' : cat}
|
||||
label={cat === ALL ? t('home.allGames') : cat}
|
||||
clickable
|
||||
color={category === cat ? 'primary' : 'default'}
|
||||
variant={category === cat ? 'filled' : 'outlined'}
|
||||
@ -176,7 +178,7 @@ export function HomePage() {
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 2 }}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900 }}>
|
||||
Available games
|
||||
{t('home.availableGames')}
|
||||
</Typography>
|
||||
<Chip size="small" label={filtered.length} variant="outlined" />
|
||||
</Stack>
|
||||
@ -200,7 +202,7 @@ export function HomePage() {
|
||||
</Box>
|
||||
) : filtered.length === 0 ? (
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
No games in this category yet.
|
||||
{t('home.noGamesInCategory')}
|
||||
</Alert>
|
||||
) : (
|
||||
<Box
|
||||
|
||||
@ -3,6 +3,8 @@ import SportsEsportsRoundedIcon from '@mui/icons-material/SportsEsportsRounded';
|
||||
import LockClockRoundedIcon from '@mui/icons-material/LockClockRounded';
|
||||
import BuildCircleRoundedIcon from '@mui/icons-material/BuildCircleRounded';
|
||||
import PlayArrowRoundedIcon from '@mui/icons-material/PlayArrowRounded';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { Game, GameStatus } from '../types';
|
||||
|
||||
const categoryIcons: Record<string, string> = {
|
||||
@ -12,14 +14,22 @@ const categoryIcons: Record<string, string> = {
|
||||
politics: '🗳️',
|
||||
};
|
||||
|
||||
function statusMeta(status: GameStatus) {
|
||||
function statusMeta(status: GameStatus, t: TFunction) {
|
||||
if (status === 'active') {
|
||||
return { label: 'Live', color: 'success' as const, icon: null };
|
||||
return { label: t('home.gameStatus.live'), color: 'success' as const, icon: null };
|
||||
}
|
||||
if (status === 'coming_soon') {
|
||||
return { label: 'Soon', color: 'warning' as const, icon: <LockClockRoundedIcon sx={{ fontSize: 14 }} /> };
|
||||
return {
|
||||
label: t('home.gameStatus.soon'),
|
||||
color: 'warning' as const,
|
||||
icon: <LockClockRoundedIcon sx={{ fontSize: 14 }} />,
|
||||
};
|
||||
}
|
||||
return { label: 'Maintenance', color: 'default' as const, icon: <BuildCircleRoundedIcon sx={{ fontSize: 14 }} /> };
|
||||
return {
|
||||
label: t('home.gameStatus.maintenance'),
|
||||
color: 'default' as const,
|
||||
icon: <BuildCircleRoundedIcon sx={{ fontSize: 14 }} />,
|
||||
};
|
||||
}
|
||||
|
||||
type Props = {
|
||||
@ -29,7 +39,8 @@ type Props = {
|
||||
|
||||
/** Visual card for a catalog game entry. */
|
||||
export function GameCard({ game, onPlay }: Props) {
|
||||
const meta = statusMeta(game.status);
|
||||
const { t } = useTranslation();
|
||||
const meta = statusMeta(game.status, t);
|
||||
const accent = game.accentColor || '#D6B25E';
|
||||
const playable = game.status === 'active';
|
||||
const emoji = categoryIcons[game.category] ?? '🎮';
|
||||
@ -81,7 +92,12 @@ export function GameCard({ game, onPlay }: Props) {
|
||||
)}
|
||||
<Stack direction="row" spacing={0.75} sx={{ position: 'absolute', top: 10, left: 10 }}>
|
||||
{game.isFeatured && (
|
||||
<Chip size="small" label="Featured" color="primary" sx={{ fontWeight: 700 }} />
|
||||
<Chip
|
||||
size="small"
|
||||
label={t('home.gameStatus.featured')}
|
||||
color="primary"
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
)}
|
||||
<Chip
|
||||
size="small"
|
||||
@ -145,7 +161,7 @@ export function GameCard({ game, onPlay }: Props) {
|
||||
: {}),
|
||||
}}
|
||||
>
|
||||
{playable ? 'Play now' : meta.label}
|
||||
{playable ? t('home.gameStatus.playNow') : meta.label}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
|
||||
@ -2,20 +2,20 @@
|
||||
* Admin-only page for backend network and environment status.
|
||||
*/
|
||||
import { Box, Stack, Typography } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { NetworkBanner } from '../../shared/network/NetworkBanner';
|
||||
|
||||
/** Dedicated admin view for TRON network, withdrawals, and server environment. */
|
||||
export function NetworkStatusPage() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
Réseau & environnement
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7, maxWidth: 720 }}>
|
||||
Configuration serveur réservée aux administrateurs : réseau blockchain, retraits et environnement
|
||||
d'exécution.
|
||||
{t('admin.network.title')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7, maxWidth: 720 }}>{t('admin.network.subtitle')}</Typography>
|
||||
</Stack>
|
||||
<NetworkBanner />
|
||||
</Box>
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
* Admin options hub page.
|
||||
* Presents navigation cards to user management and application settings.
|
||||
*/
|
||||
import type { ElementType } from 'react';
|
||||
import { Box, Card, CardActionArea, CardContent, Chip, Stack, Typography } from '@mui/material';
|
||||
import PeopleOutlineRoundedIcon from '@mui/icons-material/PeopleOutlineRounded';
|
||||
import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
|
||||
@ -16,19 +17,156 @@ import ShieldRoundedIcon from '@mui/icons-material/ShieldRounded';
|
||||
import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded';
|
||||
import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
type OptionCardKey =
|
||||
| 'users'
|
||||
| 'settings'
|
||||
| 'catalog'
|
||||
| 'treasury'
|
||||
| 'referral'
|
||||
| 'referralFraud'
|
||||
| 'testWallet'
|
||||
| 'security'
|
||||
| 'network'
|
||||
| 'faq'
|
||||
| 'support'
|
||||
| 'countries';
|
||||
|
||||
type OptionCardConfig = {
|
||||
key: OptionCardKey;
|
||||
path: string;
|
||||
icon: ElementType;
|
||||
badgeKey: string;
|
||||
badgeColor?: 'primary' | 'success' | 'info' | 'secondary' | 'error' | 'warning';
|
||||
bg: string;
|
||||
border: string;
|
||||
iconColor?: 'error';
|
||||
};
|
||||
|
||||
const OPTION_CARDS: OptionCardConfig[] = [
|
||||
{
|
||||
key: 'users',
|
||||
path: '/admin/users',
|
||||
icon: PeopleOutlineRoundedIcon,
|
||||
badgeKey: 'admin',
|
||||
badgeColor: 'primary',
|
||||
bg: 'rgba(214,178,94,0.16)',
|
||||
border: 'rgba(214,178,94,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'settings',
|
||||
path: '/admin/settings',
|
||||
icon: SettingsOutlinedIcon,
|
||||
badgeKey: 'dynamic',
|
||||
bg: 'rgba(124,92,255,0.16)',
|
||||
border: 'rgba(124,92,255,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'catalog',
|
||||
path: '/admin/catalog',
|
||||
icon: CampaignRoundedIcon,
|
||||
badgeKey: 'catalog',
|
||||
badgeColor: 'success',
|
||||
bg: 'rgba(76,175,80,0.16)',
|
||||
border: 'rgba(76,175,80,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'treasury',
|
||||
path: '/admin/treasury',
|
||||
icon: AccountBalanceWalletRoundedIcon,
|
||||
badgeKey: 'coldHot',
|
||||
badgeColor: 'info',
|
||||
bg: 'rgba(41,182,246,0.16)',
|
||||
border: 'rgba(41,182,246,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'referral',
|
||||
path: '/admin/referral',
|
||||
icon: GroupAddRoundedIcon,
|
||||
badgeKey: 'levelsBonus',
|
||||
badgeColor: 'secondary',
|
||||
bg: 'rgba(124,92,255,0.16)',
|
||||
border: 'rgba(124,92,255,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'referralFraud',
|
||||
path: '/admin/referral/fraud',
|
||||
icon: ShieldRoundedIcon,
|
||||
badgeKey: 'sybilReview',
|
||||
badgeColor: 'error',
|
||||
bg: 'rgba(244,67,54,0.12)',
|
||||
border: 'rgba(244,67,54,0.22)',
|
||||
iconColor: 'error',
|
||||
},
|
||||
{
|
||||
key: 'testWallet',
|
||||
path: '/admin/test-wallet',
|
||||
icon: ScienceRoundedIcon,
|
||||
badgeKey: 'playMoney',
|
||||
badgeColor: 'success',
|
||||
bg: 'rgba(76,175,80,0.16)',
|
||||
border: 'rgba(76,175,80,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'security',
|
||||
path: '/admin/security',
|
||||
icon: SecurityRoundedIcon,
|
||||
badgeKey: 'alertsLedger',
|
||||
badgeColor: 'warning',
|
||||
bg: 'rgba(255,152,0,0.16)',
|
||||
border: 'rgba(255,152,0,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'network',
|
||||
path: '/admin/network',
|
||||
icon: LanRoundedIcon,
|
||||
badgeKey: 'admin',
|
||||
badgeColor: 'primary',
|
||||
bg: 'rgba(76,175,80,0.16)',
|
||||
border: 'rgba(76,175,80,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'faq',
|
||||
path: '/admin/faq',
|
||||
icon: HelpOutlineRoundedIcon,
|
||||
badgeKey: 'staff',
|
||||
badgeColor: 'success',
|
||||
bg: 'rgba(255,193,7,0.16)',
|
||||
border: 'rgba(255,193,7,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'support',
|
||||
path: '/admin/support',
|
||||
icon: HeadsetMicRoundedIcon,
|
||||
badgeKey: 'staff',
|
||||
badgeColor: 'success',
|
||||
bg: 'rgba(76,175,80,0.16)',
|
||||
border: 'rgba(76,175,80,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'countries',
|
||||
path: '/admin/countries',
|
||||
icon: PublicRoundedIcon,
|
||||
badgeKey: 'registration',
|
||||
badgeColor: 'info',
|
||||
bg: 'rgba(33,150,243,0.16)',
|
||||
border: 'rgba(33,150,243,0.22)',
|
||||
},
|
||||
];
|
||||
|
||||
/** Landing page for administrative tools and configuration shortcuts. */
|
||||
export function OptionsPage() {
|
||||
const { t } = useTranslation();
|
||||
const nav = useNavigate();
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, letterSpacing: 0.2, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
Options
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>
|
||||
Administrative tools and configuration.
|
||||
{t('admin.options.title')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.options.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<Box
|
||||
@ -39,403 +177,49 @@ export function OptionsPage() {
|
||||
gridTemplateColumns: { xs: '1fr', md: 'repeat(12, 1fr)' },
|
||||
}}
|
||||
>
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/users')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(214,178,94,0.16)',
|
||||
border: '1px solid rgba(214,178,94,0.22)',
|
||||
}}
|
||||
>
|
||||
<PeopleOutlineRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
User Management
|
||||
</Typography>
|
||||
<Chip size="small" label="Admin" color="primary" variant="outlined" />
|
||||
{OPTION_CARDS.map((card) => {
|
||||
const Icon = card.icon;
|
||||
return (
|
||||
<Card key={card.key} sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav(card.path)} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: card.bg,
|
||||
border: `1px solid ${card.border}`,
|
||||
}}
|
||||
>
|
||||
<Icon fontSize="small" color={card.iconColor} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
{t(`admin.options.cards.${card.key}.title`)}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={t(`admin.badge.${card.badgeKey}`)}
|
||||
color={card.badgeColor}
|
||||
variant="outlined"
|
||||
/>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
{t(`admin.options.cards.${card.key}.description`)}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Search users, open details, and manage account flags safely.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/settings')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(124,92,255,0.16)',
|
||||
border: '1px solid rgba(124,92,255,0.22)',
|
||||
}}
|
||||
>
|
||||
<SettingsOutlinedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Settings
|
||||
</Typography>
|
||||
<Chip size="small" label="Dynamic" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Configure password policy and access/refresh token expiration without code changes.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/catalog')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(76,175,80,0.16)',
|
||||
border: '1px solid rgba(76,175,80,0.22)',
|
||||
}}
|
||||
>
|
||||
<CampaignRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Games & Ads
|
||||
</Typography>
|
||||
<Chip size="small" label="Catalog" color="success" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Publish games and home-page promotions dynamically — no deploy required.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/treasury')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(41,182,246,0.16)',
|
||||
border: '1px solid rgba(41,182,246,0.22)',
|
||||
}}
|
||||
>
|
||||
<AccountBalanceWalletRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Treasury
|
||||
</Typography>
|
||||
<Chip size="small" label="Cold / Hot" color="info" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Cold wallet addresses, deposit sweeps, and hot wallet funding from cold storage.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/referral')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(124,92,255,0.16)',
|
||||
border: '1px solid rgba(124,92,255,0.22)',
|
||||
}}
|
||||
>
|
||||
<GroupAddRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Referral program
|
||||
</Typography>
|
||||
<Chip size="small" label="Levels / Bonus" color="secondary" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Multi-level commissions, bonus pool, eligibility rules, and signup analytics.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/referral/fraud')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(244,67,54,0.12)',
|
||||
border: '1px solid rgba(244,67,54,0.22)',
|
||||
}}
|
||||
>
|
||||
<ShieldRoundedIcon fontSize="small" color="error" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Referral fraud dashboard
|
||||
</Typography>
|
||||
<Chip size="small" label="Sybil / Review / Clawback" color="error" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Review queue, high-risk referrers, monthly caps, and commission clawbacks.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/test-wallet')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(76,175,80,0.16)',
|
||||
border: '1px solid rgba(76,175,80,0.22)',
|
||||
}}
|
||||
>
|
||||
<ScienceRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Test wallet
|
||||
</Typography>
|
||||
<Chip size="small" label="Play money" color="success" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Credit amounts, request limits, cooldowns, and grant history for practice play.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/security')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(255,152,0,0.16)',
|
||||
border: '1px solid rgba(255,152,0,0.22)',
|
||||
}}
|
||||
>
|
||||
<SecurityRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Security
|
||||
</Typography>
|
||||
<Chip size="small" label="Alerts / Ledger" color="warning" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Integrity checks, security alerts, in-app notifications, and approved ledger credits.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/network')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(76,175,80,0.16)',
|
||||
border: '1px solid rgba(76,175,80,0.22)',
|
||||
}}
|
||||
>
|
||||
<LanRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Réseau & environnement
|
||||
</Typography>
|
||||
<Chip size="small" label="Admin" color="primary" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Testnet, état des retraits USDT (TRC20) et environnement serveur.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/faq')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(255,193,7,0.16)',
|
||||
border: '1px solid rgba(255,193,7,0.22)',
|
||||
}}
|
||||
>
|
||||
<HelpOutlineRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Foire aux questions
|
||||
</Typography>
|
||||
<Chip size="small" label="Staff" color="success" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Gérer les questions, catégories, médias et statistiques FAQ.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/support')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(76,175,80,0.16)',
|
||||
border: '1px solid rgba(76,175,80,0.22)',
|
||||
}}
|
||||
>
|
||||
<HeadsetMicRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Centre d'assistance
|
||||
</Typography>
|
||||
<Chip size="small" label="Staff" color="success" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Conversations utilisateurs et visiteurs, réponses en temps réel.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
|
||||
<Card sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' }, borderRadius: 3 }}>
|
||||
<CardActionArea onClick={() => nav('/admin/countries')} sx={{ height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
backgroundColor: 'rgba(33,150,243,0.16)',
|
||||
border: '1px solid rgba(33,150,243,0.22)',
|
||||
}}
|
||||
>
|
||||
<PublicRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }}>
|
||||
Countries
|
||||
</Typography>
|
||||
<Chip size="small" label="Registration" color="info" variant="outlined" />
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.75, mt: 0.5 }}>
|
||||
Sync country catalog and block registration by country of residence.
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -25,6 +25,7 @@ import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded';
|
||||
import BadgeRoundedIcon from '@mui/icons-material/BadgeRounded';
|
||||
import dayjs from 'dayjs';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import { PageHeader, PageSectionHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import { ProfileEditForm } from './components/ProfileEditForm';
|
||||
@ -36,6 +37,7 @@ import { displayName, useProfile } from './hooks/useProfile';
|
||||
|
||||
/** Profile route with personal info, account metadata, and security settings. */
|
||||
export function ProfilePage() {
|
||||
const { t } = useTranslation();
|
||||
const { auth } = useAuth();
|
||||
const profileQ = useProfile();
|
||||
const [tab, setTab] = useState(0);
|
||||
@ -47,19 +49,19 @@ export function ProfilePage() {
|
||||
|
||||
const refresh = async () => {
|
||||
await profileQ.refetch();
|
||||
setToast('Profile refreshed');
|
||||
setToast(t('common.profileRefreshed'));
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<PersonRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Profile"
|
||||
subtitle="View and manage your personal information and account security."
|
||||
title={t('profile.title')}
|
||||
subtitle={t('profile.subtitle')}
|
||||
mb={2.5}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh profile"
|
||||
label={t('profile.refreshProfile')}
|
||||
onClick={() => void refresh()}
|
||||
disabled={profileQ.isLoading}
|
||||
/>
|
||||
@ -68,7 +70,7 @@ export function ProfilePage() {
|
||||
|
||||
{profileQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Failed to load profile. Make sure you are logged in and the API is running.
|
||||
{t('profile.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -115,16 +117,16 @@ export function ProfilePage() {
|
||||
useFlexGap
|
||||
sx={{ mt: 1.5, flexWrap: 'wrap', justifyContent: { xs: 'center', sm: 'flex-start' } }}
|
||||
>
|
||||
<Chip size="small" label={`Role: ${profile.role}`} color="primary" variant="outlined" />
|
||||
<Chip size="small" label={`${t('common.role')}: ${profile.role}`} color="primary" variant="outlined" />
|
||||
<Chip
|
||||
size="small"
|
||||
label={profile.emailVerified ? 'Email verified' : 'Email not verified'}
|
||||
label={profile.emailVerified ? t('profile.emailVerified') : t('profile.emailNotVerified')}
|
||||
color={profile.emailVerified ? 'success' : 'default'}
|
||||
variant="outlined"
|
||||
/>
|
||||
<Chip
|
||||
size="small"
|
||||
label={profile.totpEnabled ? '2FA enabled' : '2FA off'}
|
||||
label={profile.totpEnabled ? t('profile.twoFaEnabled') : t('profile.twoFaOff')}
|
||||
color={profile.totpEnabled ? 'success' : 'warning'}
|
||||
variant="outlined"
|
||||
/>
|
||||
@ -145,8 +147,8 @@ export function ProfilePage() {
|
||||
allowScrollButtonsMobile
|
||||
sx={{ mb: 2, borderBottom: '1px solid rgba(255,255,255,0.08)' }}
|
||||
>
|
||||
<Tab icon={<BadgeRoundedIcon />} iconPosition="start" label="Personal" />
|
||||
<Tab icon={<SecurityRoundedIcon />} iconPosition="start" label="Security" />
|
||||
<Tab icon={<BadgeRoundedIcon />} iconPosition="start" label={t('profile.tabPersonal')} />
|
||||
<Tab icon={<SecurityRoundedIcon />} iconPosition="start" label={t('profile.tabSecurity')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 0 && (
|
||||
@ -160,7 +162,7 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<PageSectionHeader
|
||||
title="Personal information"
|
||||
title={t('profile.personalInfo')}
|
||||
actions={
|
||||
profile && !editing ? (
|
||||
<Button
|
||||
@ -169,7 +171,7 @@ export function ProfilePage() {
|
||||
onClick={() => setEditing(true)}
|
||||
sx={{ flexShrink: 0 }}
|
||||
>
|
||||
Edit
|
||||
{t('common.edit')}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
@ -199,7 +201,7 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Email verification
|
||||
{t('profile.emailVerification')}
|
||||
</Typography>
|
||||
{profileQ.isLoading ? (
|
||||
<Skeleton height={80} />
|
||||
@ -216,7 +218,7 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Referral program
|
||||
{t('profile.referralProgram')}
|
||||
</Typography>
|
||||
<ReferralPanel onNotify={setToast} />
|
||||
</CardContent>
|
||||
@ -225,7 +227,7 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Account details
|
||||
{t('profile.accountDetails')}
|
||||
</Typography>
|
||||
{profileQ.isLoading ? (
|
||||
<Stack spacing={1.5}>
|
||||
@ -235,17 +237,23 @@ export function ProfilePage() {
|
||||
</Stack>
|
||||
) : profile ? (
|
||||
<Stack spacing={2} divider={<Divider sx={{ opacity: 0.1 }} />}>
|
||||
<MetaRow label="User ID" value={profile.id} mono />
|
||||
<MetaRow label="Role" value={profile.role} />
|
||||
<MetaRow label={t('profile.userId')} value={profile.id} mono />
|
||||
<MetaRow label={t('common.role')} value={profile.role} />
|
||||
<MetaRow
|
||||
label="Member since"
|
||||
label={t('profile.memberSince')}
|
||||
value={dayjs(profile.createdAt).format('YYYY-MM-DD HH:mm')}
|
||||
/>
|
||||
<MetaRow label="Email verified" value={profile.emailVerified ? 'Yes' : 'No'} />
|
||||
<MetaRow label="2FA" value={profile.totpEnabled ? 'Enabled' : 'Disabled'} />
|
||||
<MetaRow
|
||||
label={t('profile.emailVerification')}
|
||||
value={profile.emailVerified ? t('common.yes') : t('common.no')}
|
||||
/>
|
||||
<MetaRow
|
||||
label="2FA"
|
||||
value={profile.totpEnabled ? t('profile.enabled') : t('profile.disabled')}
|
||||
/>
|
||||
</Stack>
|
||||
) : (
|
||||
<MetaRow label="User ID" value={auth.userId ?? '—'} mono />
|
||||
<MetaRow label={t('profile.userId')} value={auth.userId ?? '—'} mono />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@ -264,10 +272,10 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 0.5 }}>
|
||||
Change password
|
||||
{t('profile.changePassword')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mb: 2 }}>
|
||||
Update your password. You will need your current password to confirm.
|
||||
{t('profile.changePasswordHint')}
|
||||
</Typography>
|
||||
<ChangePasswordForm onSuccess={setToast} onError={setToast} />
|
||||
</CardContent>
|
||||
@ -276,10 +284,10 @@ export function ProfilePage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 0.5 }}>
|
||||
Two-factor authentication
|
||||
{t('profile.twoFactorAuth')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mb: 2 }}>
|
||||
Add an extra layer of security for transfers and sensitive actions.
|
||||
{t('profile.twoFactorHint')}
|
||||
</Typography>
|
||||
{profile ? (
|
||||
<TwoFactorPanel
|
||||
|
||||
@ -13,6 +13,7 @@ import {
|
||||
import VisibilityOffRoundedIcon from '@mui/icons-material/VisibilityOffRounded';
|
||||
import VisibilityRoundedIcon from '@mui/icons-material/VisibilityRounded';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
|
||||
type ChangePasswordFormProps = {
|
||||
@ -20,10 +21,8 @@ type ChangePasswordFormProps = {
|
||||
onError: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Submits current and new password to POST /api/v1/auth/change-password.
|
||||
*/
|
||||
export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const [currentPassword, setCurrentPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
@ -33,15 +32,15 @@ export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormPro
|
||||
|
||||
const submit = async () => {
|
||||
if (!currentPassword) {
|
||||
onError('Enter your current password');
|
||||
onError(t('profilePassword.enterCurrent'));
|
||||
return;
|
||||
}
|
||||
if (!newPassword) {
|
||||
onError('Enter a new password');
|
||||
onError(t('profilePassword.enterNew'));
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
onError('New password and confirmation do not match');
|
||||
onError(t('profilePassword.mismatch'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
@ -53,10 +52,10 @@ export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormPro
|
||||
setCurrentPassword('');
|
||||
setNewPassword('');
|
||||
setConfirmPassword('');
|
||||
onSuccess('Password updated successfully');
|
||||
onSuccess(t('profilePassword.updated'));
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError(err?.response?.data?.error ?? err?.message ?? 'Password change failed');
|
||||
onError(err?.response?.data?.error ?? err?.message ?? t('profilePassword.failed'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@ -65,7 +64,7 @@ export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormPro
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<TextField
|
||||
label="Current password"
|
||||
label={t('profilePassword.current')}
|
||||
type={showCurrent ? 'text' : 'password'}
|
||||
fullWidth
|
||||
value={currentPassword}
|
||||
@ -83,7 +82,7 @@ export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormPro
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
label="New password"
|
||||
label={t('profilePassword.new')}
|
||||
type={showNew ? 'text' : 'password'}
|
||||
fullWidth
|
||||
value={newPassword}
|
||||
@ -101,18 +100,18 @@ export function ChangePasswordForm({ onSuccess, onError }: ChangePasswordFormPro
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
label="Confirm new password"
|
||||
label={t('profilePassword.confirm')}
|
||||
type="password"
|
||||
fullWidth
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
/>
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
Choose a strong password. Server policy (length, complexity) is enforced on save.
|
||||
{t('profilePassword.strengthHint')}
|
||||
</Alert>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<Button variant="contained" onClick={submit} disabled={saving}>
|
||||
{saving ? 'Updating…' : 'Update password'}
|
||||
{saving ? t('auth.updating') : t('auth.updatePassword')}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
/**
|
||||
* Email verification panel on the profile page.
|
||||
* Sends verification emails and surfaces dev verify links in console transport mode.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -14,6 +13,7 @@ import {
|
||||
import MarkEmailReadRoundedIcon from '@mui/icons-material/MarkEmailReadRounded';
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
|
||||
type EmailVerificationPanelProps = {
|
||||
@ -22,14 +22,12 @@ type EmailVerificationPanelProps = {
|
||||
onNotify: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lets unverified users request a verification email and copy the dev link when returned.
|
||||
*/
|
||||
export function EmailVerificationPanel({
|
||||
email,
|
||||
emailVerified,
|
||||
onNotify,
|
||||
}: EmailVerificationPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [sending, setSending] = useState(false);
|
||||
const [devLink, setDevLink] = useState<string | null>(null);
|
||||
@ -38,7 +36,11 @@ export function EmailVerificationPanel({
|
||||
if (emailVerified) {
|
||||
return (
|
||||
<Alert severity="success" icon={<MarkEmailReadRoundedIcon />} sx={{ borderRadius: 2 }}>
|
||||
Your email <b>{email}</b> is verified.
|
||||
<Trans
|
||||
i18nKey="profileEmailVerify.verified"
|
||||
values={{ email: email ?? '—' }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
@ -53,12 +55,10 @@ export function EmailVerificationPanel({
|
||||
);
|
||||
await qc.invalidateQueries({ queryKey: ['user-profile'] });
|
||||
onNotify(res.data.message);
|
||||
if (res.data.devVerifyUrl) {
|
||||
setDevLink(res.data.devVerifyUrl);
|
||||
}
|
||||
if (res.data.devVerifyUrl) setDevLink(res.data.devVerifyUrl);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
const msg = err?.response?.data?.error ?? err?.message ?? 'Failed to send email';
|
||||
const msg = err?.response?.data?.error ?? err?.message ?? t('profileEmailVerify.sendFailed');
|
||||
setError(msg);
|
||||
onNotify(msg);
|
||||
} finally {
|
||||
@ -70,17 +70,20 @@ export function EmailVerificationPanel({
|
||||
if (!devLink) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(devLink);
|
||||
onNotify('Dev verify link copied');
|
||||
onNotify(t('profileEmailVerify.devLinkCopied'));
|
||||
} catch {
|
||||
onNotify('Copy failed');
|
||||
onNotify(t('common.copyFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
Your email <b>{email ?? '—'}</b> is not verified yet. Verify it to secure withdrawals and
|
||||
account recovery.
|
||||
<Trans
|
||||
i18nKey="profileEmailVerify.notVerified"
|
||||
values={{ email: email ?? '—' }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
{error && (
|
||||
@ -90,25 +93,26 @@ export function EmailVerificationPanel({
|
||||
)}
|
||||
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
We will send a secure one-time link valid for 24 hours. Changing your email requires
|
||||
verification again.
|
||||
{t('profileEmailVerify.hint')}
|
||||
</Typography>
|
||||
|
||||
<Box>
|
||||
<Button
|
||||
variant="contained"
|
||||
startIcon={sending ? <CircularProgress size={18} color="inherit" /> : <MarkEmailReadRoundedIcon />}
|
||||
startIcon={
|
||||
sending ? <CircularProgress size={18} color="inherit" /> : <MarkEmailReadRoundedIcon />
|
||||
}
|
||||
onClick={send}
|
||||
disabled={sending || !email}
|
||||
>
|
||||
{sending ? 'Sending…' : 'Send verification email'}
|
||||
{sending ? t('common.sending') : t('profileEmailVerify.sendEmail')}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{devLink && (
|
||||
<Stack spacing={1}>
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
<b>Dev mode:</b> SMTP is not used. Open or copy this link to verify locally.
|
||||
<Trans i18nKey="profileEmailVerify.devMode" components={{ b: <b /> }} />
|
||||
</Alert>
|
||||
<TextField
|
||||
fullWidth
|
||||
@ -117,7 +121,7 @@ export function EmailVerificationPanel({
|
||||
slotProps={{ htmlInput: { readOnly: true, style: { fontFamily: 'monospace', fontSize: 12 } } }}
|
||||
/>
|
||||
<Button size="small" variant="outlined" onClick={copyDevLink}>
|
||||
Copy dev link
|
||||
{t('profileEmailVerify.copyDevLink')}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
@ -1,15 +1,10 @@
|
||||
/**
|
||||
* Editable personal information form for the profile page.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Stack,
|
||||
TextField,
|
||||
} from '@mui/material';
|
||||
import { Alert, Box, Button, Stack, TextField } from '@mui/material';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import { CountryAutocomplete, type CountryOption } from '../../../shared/components/CountryAutocomplete';
|
||||
import { GenderSelect } from '../../../shared/components/GenderSelect';
|
||||
@ -30,9 +25,6 @@ function countryLabel(code: string | null | undefined, countries: CountryOption[
|
||||
return match ? `${match.name} (${match.code})` : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form to update name, date of birth, email, phone, country, and nationality via PATCH /api/v1/me.
|
||||
*/
|
||||
export function ProfileEditForm({
|
||||
profile,
|
||||
editing,
|
||||
@ -40,6 +32,7 @@ export function ProfileEditForm({
|
||||
onSaved,
|
||||
onError,
|
||||
}: ProfileEditFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [middleName, setMiddleName] = useState('');
|
||||
@ -82,15 +75,15 @@ export function ProfileEditForm({
|
||||
|
||||
const save = async () => {
|
||||
if (!email.trim()) {
|
||||
onError('Email cannot be empty');
|
||||
onError(t('profileForm.emailEmpty'));
|
||||
return;
|
||||
}
|
||||
if (!countryOfResidence.trim()) {
|
||||
onError('Country of residence is required');
|
||||
onError(t('profileForm.countryRequired'));
|
||||
return;
|
||||
}
|
||||
if (!gender) {
|
||||
onError('Gender is required');
|
||||
onError(t('profileForm.genderRequired'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
@ -108,10 +101,10 @@ export function ProfileEditForm({
|
||||
};
|
||||
await api.patch('/api/v1/me', payload);
|
||||
await qc.invalidateQueries({ queryKey: ['user-profile'] });
|
||||
onSaved('Profile updated successfully');
|
||||
onSaved(t('profileForm.updated'));
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError(err?.response?.data?.error ?? err?.message ?? 'Update failed');
|
||||
onError(err?.response?.data?.error ?? err?.message ?? t('profileForm.updateFailed'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@ -120,19 +113,19 @@ export function ProfileEditForm({
|
||||
if (!editing) {
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<InfoRow label="First name" value={profile.firstName} />
|
||||
<InfoRow label="Middle name" value={profile.middleName} />
|
||||
<InfoRow label="Last name" value={profile.lastName} />
|
||||
<InfoRow label="Date of birth" value={profile.dateOfBirth?.slice(0, 10)} />
|
||||
<InfoRow label="Gender" value={genderLabel(profile.gender)} />
|
||||
<InfoRow label="Email" value={profile.email} />
|
||||
<InfoRow label="Phone" value={profile.phone} />
|
||||
<InfoRow label={t('profileForm.firstName')} value={profile.firstName} />
|
||||
<InfoRow label={t('profileForm.middleName')} value={profile.middleName} />
|
||||
<InfoRow label={t('profileForm.lastName')} value={profile.lastName} />
|
||||
<InfoRow label={t('profileForm.dateOfBirth')} value={profile.dateOfBirth?.slice(0, 10)} />
|
||||
<InfoRow label={t('gender.label')} value={genderLabel(profile.gender)} />
|
||||
<InfoRow label={t('common.email')} value={profile.email} />
|
||||
<InfoRow label={t('auth.phoneOptional').replace(' (optional)', '')} value={profile.phone} />
|
||||
<InfoRow
|
||||
label="Country of residence"
|
||||
label={t('auth.countryOfResidence')}
|
||||
value={countryLabel(profile.countryOfResidence, countries)}
|
||||
/>
|
||||
<InfoRow
|
||||
label="Nationality"
|
||||
label={t('auth.nationalityOptional').replace(' (optional)', '')}
|
||||
value={
|
||||
profile.nationality
|
||||
? countryNameByCode.get(profile.nationality)
|
||||
@ -148,28 +141,28 @@ export function ProfileEditForm({
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Fields show your current information. Edit only what you want to change, then save.
|
||||
{t('profileForm.editHint')}
|
||||
</Alert>
|
||||
<TextField
|
||||
label="First name"
|
||||
label={t('profileForm.firstName')}
|
||||
fullWidth
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Middle name"
|
||||
label={t('profileForm.middleName')}
|
||||
fullWidth
|
||||
value={middleName}
|
||||
onChange={(e) => setMiddleName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Last name"
|
||||
label={t('profileForm.lastName')}
|
||||
fullWidth
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Date of birth"
|
||||
label={t('profileForm.dateOfBirth')}
|
||||
type="date"
|
||||
fullWidth
|
||||
value={dateOfBirth}
|
||||
@ -178,7 +171,7 @@ export function ProfileEditForm({
|
||||
/>
|
||||
<GenderSelect value={gender} onChange={setGender} required />
|
||||
<TextField
|
||||
label="Email"
|
||||
label={t('common.email')}
|
||||
type="email"
|
||||
fullWidth
|
||||
required
|
||||
@ -186,43 +179,43 @@ export function ProfileEditForm({
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Phone (optional)"
|
||||
label={t('profileForm.phoneOptional')}
|
||||
fullWidth
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
/>
|
||||
|
||||
<CountryAutocomplete
|
||||
label="Country of residence"
|
||||
label={t('auth.countryOfResidence')}
|
||||
value={countryOfResidence}
|
||||
onChange={setCountryOfResidence}
|
||||
options={countries}
|
||||
loading={countriesQ.isLoading}
|
||||
required
|
||||
helperText="Search by country name or ISO code (e.g. France or FR)"
|
||||
helperText={t('profileForm.countryHelper')}
|
||||
/>
|
||||
|
||||
<CountryAutocomplete
|
||||
label="Nationality (optional)"
|
||||
label={t('auth.nationalityOptional')}
|
||||
value={nationality}
|
||||
onChange={setNationality}
|
||||
options={countries}
|
||||
loading={countriesQ.isLoading}
|
||||
placeholder="Search nationality…"
|
||||
placeholder={t('profileForm.nationalityPlaceholder')}
|
||||
/>
|
||||
|
||||
{countriesQ.isError && (
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
Could not load country list. Try again later or contact support.
|
||||
{t('profileForm.countriesLoadFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: 'flex', gap: 1.5, justifyContent: 'flex-end', pt: 1 }}>
|
||||
<Button onClick={onCancel} disabled={saving}>
|
||||
Cancel
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={save} disabled={saving || countriesQ.isLoading}>
|
||||
{saving ? 'Saving…' : 'Save profile'}
|
||||
{saving ? t('profileForm.saving') : t('profileForm.saveProfile')}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
@ -17,6 +17,7 @@ import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
|
||||
import OpenInNewRoundedIcon from '@mui/icons-material/OpenInNewRounded';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
|
||||
type ReferralInfo = {
|
||||
@ -31,6 +32,7 @@ type ReferralPanelProps = {
|
||||
};
|
||||
|
||||
export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const q = useQuery({
|
||||
queryKey: ['referral-me'],
|
||||
queryFn: async () => {
|
||||
@ -41,14 +43,14 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
|
||||
const copy = async (text: string, label: string) => {
|
||||
if (!text) {
|
||||
onNotify('Nothing to copy');
|
||||
onNotify(t('common.nothingToCopy'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
onNotify(`${label} copied`);
|
||||
onNotify(t('common.copied', { label }));
|
||||
} catch {
|
||||
onNotify('Copy failed');
|
||||
onNotify(t('common.copyFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@ -57,17 +59,12 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
}
|
||||
|
||||
if (q.isError) {
|
||||
return <Alert severity="warning">Could not load referral information.</Alert>;
|
||||
return <Alert severity="warning">{t('profileReferral.loadFailed')}</Alert>;
|
||||
}
|
||||
|
||||
const info = q.data;
|
||||
if (!info?.referralCode) {
|
||||
return (
|
||||
<Alert severity="info">
|
||||
Your referral code is not available yet. Contact support if you registered before the
|
||||
referral program launched.
|
||||
</Alert>
|
||||
);
|
||||
return <Alert severity="info">{t('profileReferral.notAvailable')}</Alert>;
|
||||
}
|
||||
|
||||
return (
|
||||
@ -75,7 +72,7 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<GroupAddRoundedIcon fontSize="small" color="primary" />
|
||||
<Typography variant="body2" sx={{ opacity: 0.75, flex: 1 }}>
|
||||
Share your link to invite friends and earn commissions on their activity.
|
||||
{t('profileReferral.shareHint')}
|
||||
</Typography>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
@ -84,20 +81,20 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
variant="text"
|
||||
endIcon={<OpenInNewRoundedIcon />}
|
||||
>
|
||||
Full network
|
||||
{t('profileReferral.fullNetwork')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<Chip
|
||||
size="small"
|
||||
label={`${info.directReferrals} direct referral${info.directReferrals === 1 ? '' : 's'}`}
|
||||
label={t('profileReferral.directReferrals', { count: info.directReferrals })}
|
||||
variant="outlined"
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
/>
|
||||
|
||||
<Box>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6 }}>
|
||||
Referral code
|
||||
{t('profileReferral.referralCode')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.5} sx={{ mt: 0.5 }}>
|
||||
<TextField
|
||||
@ -108,8 +105,8 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
sx={{ '& input': { fontFamily: 'monospace', fontWeight: 700, letterSpacing: 1 } }}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="Copy referral code"
|
||||
onClick={() => void copy(info.referralCode!, 'Referral code')}
|
||||
aria-label={t('profileReferral.copyCodeAria')}
|
||||
onClick={() => void copy(info.referralCode!, t('profileReferral.referralCode'))}
|
||||
>
|
||||
<ContentCopyRoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
@ -118,7 +115,7 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
|
||||
<Box>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6 }}>
|
||||
Referral link
|
||||
{t('profileReferral.referralLink')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.5} sx={{ mt: 0.5 }}>
|
||||
<TextField
|
||||
@ -129,8 +126,8 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
sx={{ '& input': { fontSize: 12 } }}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="Copy referral link"
|
||||
onClick={() => void copy(info.referralLink, 'Referral link')}
|
||||
aria-label={t('profileReferral.copyLinkAria')}
|
||||
onClick={() => void copy(info.referralLink, t('profileReferral.referralLink'))}
|
||||
>
|
||||
<ContentCopyRoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
@ -141,10 +138,10 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<ContentCopyRoundedIcon />}
|
||||
onClick={() => void copy(info.referralLink, 'Referral link')}
|
||||
onClick={() => void copy(info.referralLink, t('profileReferral.referralLink'))}
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
>
|
||||
Copy invite link
|
||||
{t('profileReferral.copyInvite')}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import type { TotpSetupResponse } from '../types';
|
||||
|
||||
@ -21,10 +22,8 @@ type TwoFactorPanelProps = {
|
||||
onError: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Guides the user through TOTP 2FA setup or shows enabled status.
|
||||
*/
|
||||
export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [setupData, setSetupData] = useState<TotpSetupResponse | null>(null);
|
||||
const [loadingSetup, setLoadingSetup] = useState(false);
|
||||
@ -39,7 +38,7 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
setSetupData(res.data);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError(err?.response?.data?.error ?? err?.message ?? '2FA setup failed');
|
||||
onError(err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.setupFailed'));
|
||||
} finally {
|
||||
setLoadingSetup(false);
|
||||
}
|
||||
@ -47,7 +46,7 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
|
||||
const enable = async () => {
|
||||
if (code.trim().length !== 6) {
|
||||
onError('Enter the 6-digit code from your authenticator app');
|
||||
onError(t('profileTwoFactor.enterCode'));
|
||||
return;
|
||||
}
|
||||
setEnabling(true);
|
||||
@ -56,13 +55,11 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
setSetupData(null);
|
||||
setCode('');
|
||||
await qc.invalidateQueries({ queryKey: ['user-profile'] });
|
||||
onSuccess('Two-factor authentication enabled');
|
||||
onSuccess(t('profileTwoFactor.enabledSuccess'));
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError(
|
||||
err?.response?.data?.error ??
|
||||
err?.message ??
|
||||
'Invalid code. Scan the QR again and enter the current 6-digit code.'
|
||||
err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.invalidCode')
|
||||
);
|
||||
} finally {
|
||||
setEnabling(false);
|
||||
@ -72,8 +69,7 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
if (totpEnabled) {
|
||||
return (
|
||||
<Alert severity="success" sx={{ borderRadius: 2 }}>
|
||||
Two-factor authentication is <b>enabled</b> on your account. A TOTP code is required for
|
||||
transfers when 2FA is active.
|
||||
<Trans i18nKey="profileTwoFactor.enabled" components={{ b: <b /> }} />
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
@ -81,23 +77,22 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Protect your account with Google Authenticator or any TOTP app. Scan the QR code, then
|
||||
enter a verification code to enable 2FA.
|
||||
{t('profileTwoFactor.setupHint')}
|
||||
</Typography>
|
||||
|
||||
{!setupData ? (
|
||||
<Button variant="outlined" onClick={startSetup} disabled={loadingSetup}>
|
||||
{loadingSetup ? <CircularProgress size={22} /> : 'Set up 2FA'}
|
||||
{loadingSetup ? <CircularProgress size={22} /> : t('profileTwoFactor.setupButton')}
|
||||
</Button>
|
||||
) : (
|
||||
<Stack spacing={2} sx={{ alignItems: 'center' }}>
|
||||
<Typography variant="subtitle2" sx={{ alignSelf: 'flex-start' }}>
|
||||
Scan with your authenticator app
|
||||
{t('profileTwoFactor.scanQr')}
|
||||
</Typography>
|
||||
<Box
|
||||
component="img"
|
||||
src={setupData.qrCodeUrl}
|
||||
alt="2FA QR code"
|
||||
alt={t('profileTwoFactor.qrAlt')}
|
||||
sx={{
|
||||
width: 200,
|
||||
height: 200,
|
||||
@ -116,10 +111,10 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
Manual key: {setupData.secret}
|
||||
{t('profileTwoFactor.manualKey', { secret: setupData.secret })}
|
||||
</Typography>
|
||||
<TextField
|
||||
label="6-digit verification code"
|
||||
label={t('profileTwoFactor.verificationCode')}
|
||||
fullWidth
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
@ -127,9 +122,9 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan
|
||||
placeholder="000000"
|
||||
/>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button onClick={() => setSetupData(null)}>Cancel</Button>
|
||||
<Button onClick={() => setSetupData(null)}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" onClick={enable} disabled={enabling}>
|
||||
{enabling ? 'Enabling…' : 'Enable 2FA'}
|
||||
{enabling ? t('profileTwoFactor.enabling') : t('profileTwoFactor.enable')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@ -23,6 +23,7 @@ import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
|
||||
@ -89,6 +90,7 @@ type ReviewQueueItem = {
|
||||
};
|
||||
|
||||
export function ReferralAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [levelForm, setLevelForm] = useState({
|
||||
levelNumber: '',
|
||||
@ -212,7 +214,7 @@ export function ReferralAdminPage() {
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
setFundPendingMsg(
|
||||
res.data.message ?? 'Bonus pool funding submitted — pending super-admin approval'
|
||||
res.data.message ?? t('admin.referralAdmin.fundPending')
|
||||
);
|
||||
void qc.invalidateQueries({ queryKey: ['admin-referral-config'] });
|
||||
},
|
||||
@ -227,10 +229,10 @@ export function ReferralAdminPage() {
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 2 }}>
|
||||
<GroupAddRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
Referral program
|
||||
{t('admin.referralAdmin.title')}
|
||||
</Typography>
|
||||
<Button component={RouterLink} to="/admin/referral/fraud" variant="outlined" size="small" color="warning">
|
||||
Fraud dashboard
|
||||
{t('admin.referralAdmin.fraudDashboard')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
@ -240,13 +242,13 @@ export function ReferralAdminPage() {
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{configQ.isError && <Alert severity="error">Failed to load referral configuration.</Alert>}
|
||||
{configQ.isError && <Alert severity="error">{t('admin.referralAdmin.loadError')}</Alert>}
|
||||
|
||||
{s && (
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Program settings
|
||||
{t('admin.referralAdmin.programSettings')}
|
||||
</Typography>
|
||||
<Stack spacing={2}>
|
||||
<FormControlLabel
|
||||
@ -256,7 +258,7 @@ export function ReferralAdminPage() {
|
||||
onChange={(e) => setSettingsForm({ ...s, enabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Program enabled"
|
||||
label={t('admin.referralAdmin.programEnabled')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -265,7 +267,7 @@ export function ReferralAdminPage() {
|
||||
onChange={(e) => setSettingsForm({ ...s, bonusWithdrawable: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Bonus withdrawable (transfer bonus → main)"
|
||||
label={t('admin.referralAdmin.bonusWithdrawable')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -276,7 +278,7 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Referrer must have verified email"
|
||||
label={t('admin.referralAdmin.referrerVerified')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -287,7 +289,7 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Referrer must have deposited"
|
||||
label={t('admin.referralAdmin.referrerDeposited')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -298,20 +300,20 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Referred user must have verified email (before payout)"
|
||||
label={t('admin.referralAdmin.referredVerified')}
|
||||
/>
|
||||
<TextField
|
||||
label="Commission hold (days)"
|
||||
label={t('admin.referralAdmin.commissionHold')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.commissionHoldDays}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, commissionHoldDays: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText="Delay after first deposit before commission can be paid"
|
||||
helperText={t('admin.referralAdmin.commissionHoldHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Min real-money predictions (referred user)"
|
||||
label={t('admin.referralAdmin.minPredictions')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.minReferredPredictions}
|
||||
@ -320,17 +322,17 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label="Max pending days"
|
||||
label={t('admin.referralAdmin.maxPendingDays')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.commissionMaxPendingDays}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, commissionMaxPendingDays: Number(e.target.value) || 1 })
|
||||
}
|
||||
helperText="Expire unpaid commissions if eligibility is still not met"
|
||||
helperText={t('admin.referralAdmin.maxPendingHelper')}
|
||||
/>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, pt: 1 }}>
|
||||
Commission modes
|
||||
{t('admin.referralAdmin.commissionModes')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -341,7 +343,7 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Deposit commissions (first deposit of referred users)"
|
||||
label={t('admin.referralAdmin.depositCommissions')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -352,10 +354,10 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Withdrawal commissions (prediction gains from main account only)"
|
||||
label={t('admin.referralAdmin.withdrawalCommissions')}
|
||||
/>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, pt: 1 }}>
|
||||
Alertes Slack
|
||||
{t('admin.referralAdmin.slackAlerts')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -366,15 +368,13 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Slack alerts enabled (referral channel: cap blocks, clawbacks, Sybil review)"
|
||||
label={t('admin.referralAdmin.slackEnabled')}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: -1, mb: 1 }}>
|
||||
Configure <code>SLACK_REFERRAL_WEBHOOK_URL</code> for #referral-fraud and{' '}
|
||||
<code>SLACK_SECURITY_WEBHOOK_URL</code> for #security.{' '}
|
||||
<code>SLACK_WEBHOOK_URL</code> is used as fallback for both.
|
||||
{t('admin.referralAdmin.slackHint')}
|
||||
</Typography>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, pt: 1 }}>
|
||||
Anti-fraude Sybil (P2)
|
||||
{t('admin.referralAdmin.sybilSection')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -385,39 +385,39 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Sybil detection enabled"
|
||||
label={t('admin.referralAdmin.sybilEnabled')}
|
||||
/>
|
||||
<TextField
|
||||
label="Sybil review threshold (score)"
|
||||
label={t('admin.referralAdmin.sybilReview')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.sybilReviewThreshold}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, sybilReviewThreshold: Number(e.target.value) || 0 })
|
||||
}
|
||||
helperText="Score ≥ this → manual review queue"
|
||||
helperText={t('admin.referralAdmin.sybilReviewHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Sybil block threshold (score)"
|
||||
label={t('admin.referralAdmin.sybilBlock')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.sybilBlockThreshold}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, sybilBlockThreshold: Number(e.target.value) || 1 })
|
||||
}
|
||||
helperText="Score ≥ this → auto-block (no commission)"
|
||||
helperText={t('admin.referralAdmin.sybilBlockHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Max commission amount / referrer / month (raw)"
|
||||
label={t('admin.referralAdmin.maxAmountMonth')}
|
||||
fullWidth
|
||||
value={s.maxCommissionAmountPerReferrerMonthRaw}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, maxCommissionAmountPerReferrerMonthRaw: e.target.value })
|
||||
}
|
||||
helperText="500000000 = 500 USDT (6 decimals). 0 = unlimited."
|
||||
helperText={t('admin.referralAdmin.maxAmountHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Max commissions / referrer / month (count)"
|
||||
label={t('admin.referralAdmin.maxCountMonth')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.maxCommissionsPerReferrerMonth}
|
||||
@ -427,10 +427,10 @@ export function ReferralAdminPage() {
|
||||
maxCommissionsPerReferrerMonth: Number(e.target.value) || 0,
|
||||
})
|
||||
}
|
||||
helperText="0 = unlimited"
|
||||
helperText={t('admin.referralAdmin.unlimitedHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Max referrals per referrer / 24h"
|
||||
label={t('admin.referralAdmin.maxReferralsDay')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.maxReferralsPerDay}
|
||||
@ -439,36 +439,36 @@ export function ReferralAdminPage() {
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label="Default referrer user ID (admin UUID)"
|
||||
label={t('admin.referralAdmin.defaultReferrer')}
|
||||
fullWidth
|
||||
value={s.defaultReferrerUserId ?? ''}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, defaultReferrerUserId: e.target.value || null })
|
||||
}
|
||||
helperText="Used when no referral code is provided at signup"
|
||||
helperText={t('admin.referralAdmin.defaultReferrerHelper')}
|
||||
/>
|
||||
<TextField
|
||||
label="Min first deposit (raw units)"
|
||||
label={t('admin.referralAdmin.minFirstDeposit')}
|
||||
fullWidth
|
||||
value={s.minFirstDepositRaw}
|
||||
onChange={(e) => setSettingsForm({ ...s, minFirstDepositRaw: e.target.value })}
|
||||
/>
|
||||
<TextField
|
||||
label="Commission wallet type ID"
|
||||
label={t('admin.referralAdmin.commissionWalletType')}
|
||||
type="number"
|
||||
fullWidth
|
||||
value={s.commissionWalletTypeId}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, commissionWalletTypeId: Number(e.target.value) })
|
||||
}
|
||||
helperText="2 = USDT_TRC20 by default"
|
||||
helperText={t('admin.referralAdmin.commissionWalletHelper')}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => saveSettingsMut.mutate(s)}
|
||||
disabled={saveSettingsMut.isPending}
|
||||
>
|
||||
Save settings
|
||||
{t('admin.referralAdmin.saveSettings')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
@ -478,17 +478,17 @@ export function ReferralAdminPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Commission levels
|
||||
{t('admin.referralAdmin.levelsTitle')}
|
||||
</Typography>
|
||||
<ScrollableTable>
|
||||
<Table size="small" sx={{ mb: 2 }}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Level</TableCell>
|
||||
<TableCell>% of first deposit</TableCell>
|
||||
<TableCell>Max amount / month (raw)</TableCell>
|
||||
<TableCell>Max count / month</TableCell>
|
||||
<TableCell>Active</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.level')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.percentDeposit')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.maxAmountMonthCol')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.maxCountMonthCol')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.active')}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@ -497,10 +497,10 @@ export function ReferralAdminPage() {
|
||||
<TableRow key={l.levelNumber}>
|
||||
<TableCell>{l.levelNumber}</TableCell>
|
||||
<TableCell>{l.commissionPercent}%</TableCell>
|
||||
<TableCell>{l.monthlyMaxAmountRaw === '0' ? 'Global' : l.monthlyMaxAmountRaw}</TableCell>
|
||||
<TableCell>{l.monthlyMaxCount === 0 ? 'Global' : l.monthlyMaxCount}</TableCell>
|
||||
<TableCell>{l.monthlyMaxAmountRaw === '0' ? t('admin.referralAdmin.global') : l.monthlyMaxAmountRaw}</TableCell>
|
||||
<TableCell>{l.monthlyMaxCount === 0 ? t('admin.referralAdmin.global') : l.monthlyMaxCount}</TableCell>
|
||||
<TableCell>
|
||||
<Chip size="small" label={l.isActive ? 'Yes' : 'No'} color={l.isActive ? 'success' : 'default'} />
|
||||
<Chip size="small" label={l.isActive ? t('common.yes') : t('common.no')} color={l.isActive ? 'success' : 'default'} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Stack direction="row" spacing={1}>
|
||||
@ -515,14 +515,14 @@ export function ReferralAdminPage() {
|
||||
})
|
||||
}
|
||||
>
|
||||
Edit
|
||||
{t('admin.referralAdmin.edit')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => deleteLevelMut.mutate(l.levelNumber)}
|
||||
>
|
||||
Delete
|
||||
{t('admin.referralAdmin.delete')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
@ -533,27 +533,27 @@ export function ReferralAdminPage() {
|
||||
</ScrollableTable>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
|
||||
<TextField
|
||||
label="Level #"
|
||||
label={t('admin.referralAdmin.levelNumber')}
|
||||
type="number"
|
||||
value={levelForm.levelNumber}
|
||||
onChange={(e) => setLevelForm((f) => ({ ...f, levelNumber: e.target.value }))}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Commission %"
|
||||
label={t('admin.referralAdmin.commissionPercent')}
|
||||
type="number"
|
||||
value={levelForm.commissionPercent}
|
||||
onChange={(e) => setLevelForm((f) => ({ ...f, commissionPercent: e.target.value }))}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Max amount / month (raw, 0=global)"
|
||||
label={t('admin.referralAdmin.maxAmountField')}
|
||||
value={levelForm.monthlyMaxAmountRaw}
|
||||
onChange={(e) => setLevelForm((f) => ({ ...f, monthlyMaxAmountRaw: e.target.value }))}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Max count / month (0=global)"
|
||||
label={t('admin.referralAdmin.maxCountField')}
|
||||
type="number"
|
||||
value={levelForm.monthlyMaxCount}
|
||||
onChange={(e) => setLevelForm((f) => ({ ...f, monthlyMaxCount: e.target.value }))}
|
||||
@ -573,7 +573,7 @@ export function ReferralAdminPage() {
|
||||
});
|
||||
}}
|
||||
>
|
||||
Add / update level
|
||||
{t('admin.referralAdmin.addUpdateLevel')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
@ -582,30 +582,30 @@ export function ReferralAdminPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Bonus pool (treasury for referral payouts)
|
||||
{t('admin.referralAdmin.bonusPoolTitle')}
|
||||
</Typography>
|
||||
<Stack spacing={1} sx={{ mb: 2 }}>
|
||||
{(config?.pools ?? []).map((p) => (
|
||||
<Typography key={p.walletTypeId} variant="body2">
|
||||
Wallet type {p.walletTypeId}: <strong>{p.availableBalance}</strong> raw units
|
||||
{t('admin.referralAdmin.walletTypeBalance', { id: p.walletTypeId, balance: p.availableBalance })}
|
||||
</Typography>
|
||||
))}
|
||||
</Stack>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
|
||||
<TextField
|
||||
label="Wallet type ID"
|
||||
label={t('admin.referralAdmin.walletTypeId')}
|
||||
value={fundForm.walletTypeId}
|
||||
onChange={(e) => setFundForm((f) => ({ ...f, walletTypeId: e.target.value }))}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
label="Amount (display)"
|
||||
label={t('admin.referralAdmin.amountDisplay')}
|
||||
value={fundForm.amountDisplay}
|
||||
onChange={(e) => setFundForm((f) => ({ ...f, amountDisplay: e.target.value }))}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
<Button variant="contained" onClick={() => fundMut.mutate()} disabled={fundMut.isPending}>
|
||||
Fund pool
|
||||
{t('admin.referralAdmin.fundPool')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
@ -614,28 +614,28 @@ export function ReferralAdminPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Manual review queue
|
||||
{t('admin.referralAdmin.reviewTitle')}
|
||||
</Typography>
|
||||
{reviewQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Failed to load review queue.
|
||||
{t('admin.referralAdmin.reviewLoadError')}
|
||||
</Alert>
|
||||
)}
|
||||
{(reviewQ.data?.items.length ?? 0) === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No commissions awaiting review.
|
||||
{t('admin.referralAdmin.noReview')}
|
||||
</Typography>
|
||||
) : (
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Score</TableCell>
|
||||
<TableCell>Signals</TableCell>
|
||||
<TableCell>Level</TableCell>
|
||||
<TableCell>Commission</TableCell>
|
||||
<TableCell>Beneficiary</TableCell>
|
||||
<TableCell>Referred</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.score')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.signals')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.level')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.commission')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.beneficiary')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.referred')}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@ -667,11 +667,11 @@ export function ReferralAdminPage() {
|
||||
onClick={() => approveMut.mutate(item.id)}
|
||||
disabled={approveMut.isPending}
|
||||
>
|
||||
Approve
|
||||
{t('admin.referralAdmin.approve')}
|
||||
</Button>
|
||||
<TextField
|
||||
size="small"
|
||||
placeholder="Reject reason"
|
||||
placeholder={t('admin.referralAdmin.rejectReason')}
|
||||
value={rejectReasons[item.id] ?? ''}
|
||||
onChange={(e) =>
|
||||
setRejectReasons((prev) => ({ ...prev, [item.id]: e.target.value }))
|
||||
@ -688,7 +688,7 @@ export function ReferralAdminPage() {
|
||||
}}
|
||||
disabled={rejectMut.isPending}
|
||||
>
|
||||
Reject
|
||||
{t('admin.referralAdmin.reject')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
@ -705,25 +705,31 @@ export function ReferralAdminPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Statistics
|
||||
{t('admin.referralAdmin.statsTitle')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2, flexWrap: 'wrap' }} useFlexGap>
|
||||
<Chip label={`Referred users: ${stats.referralSummary.totalReferred}`} />
|
||||
<Chip label={`Commissions paid: ${stats.referralSummary.totalCommissionsPaid} raw`} />
|
||||
<Chip label={`Payout events: ${stats.referralSummary.payoutCount}`} />
|
||||
<Chip label={t('admin.referralAdmin.referredUsers', { count: stats.referralSummary.totalReferred })} />
|
||||
<Chip label={t('admin.referralAdmin.commissionsPaid', { raw: stats.referralSummary.totalCommissionsPaid })} />
|
||||
<Chip label={t('admin.referralAdmin.payoutEvents', { count: stats.referralSummary.payoutCount })} />
|
||||
<Chip
|
||||
label={`Pending: ${stats.referralSummary.pendingCount} (${stats.referralSummary.pendingCommissions} raw)`}
|
||||
label={t('admin.referralAdmin.pending', {
|
||||
count: stats.referralSummary.pendingCount,
|
||||
raw: stats.referralSummary.pendingCommissions,
|
||||
})}
|
||||
color="warning"
|
||||
variant="outlined"
|
||||
/>
|
||||
<Chip
|
||||
label={`Review: ${stats.referralSummary.reviewCount} (${stats.referralSummary.reviewCommissions} raw)`}
|
||||
label={t('admin.referralAdmin.review', {
|
||||
count: stats.referralSummary.reviewCount,
|
||||
raw: stats.referralSummary.reviewCommissions,
|
||||
})}
|
||||
color="error"
|
||||
variant="outlined"
|
||||
/>
|
||||
</Stack>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
|
||||
Users by country
|
||||
{t('admin.referralAdmin.byCountry')}
|
||||
</Typography>
|
||||
<ScrollableTable>
|
||||
<Table size="small" sx={{ mb: 2 }}>
|
||||
@ -738,15 +744,15 @@ export function ReferralAdminPage() {
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
|
||||
Top referrers
|
||||
{t('admin.referralAdmin.topReferrers')}
|
||||
</Typography>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Code</TableCell>
|
||||
<TableCell>Direct referrals</TableCell>
|
||||
<TableCell>Earned (raw)</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.code')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.directReferrals')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.totalEarned')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
|
||||
@ -23,6 +23,7 @@ import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useState } from 'react';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
|
||||
@ -107,6 +108,7 @@ function StatCard({ label, value, sub }: { label: string; value: string | number
|
||||
}
|
||||
|
||||
export function ReferralFraudDashboardPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [clawbackReasons, setClawbackReasons] = useState<Record<string, string>>({});
|
||||
const [exportFrom, setExportFrom] = useState('');
|
||||
@ -163,7 +165,9 @@ export function ReferralFraudDashboardPage() {
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
setExportError(e instanceof Error ? e.message : 'Export failed');
|
||||
setExportError(
|
||||
e instanceof Error ? e.message : t('admin.referralFraud.recentClawbacks.exportFailed')
|
||||
);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
@ -174,49 +178,69 @@ export function ReferralFraudDashboardPage() {
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 2, flexWrap: 'wrap' }} useFlexGap>
|
||||
<ShieldRoundedIcon color="error" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
Referral fraud dashboard
|
||||
{t('admin.referralFraud.title')}
|
||||
</Typography>
|
||||
<Button component={RouterLink} to="/admin/referral" variant="outlined" size="small">
|
||||
Program settings
|
||||
{t('admin.referralFraud.programSettings')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{dashQ.isError && <Alert severity="error">Failed to load fraud dashboard.</Alert>}
|
||||
{dashQ.isError && <Alert severity="error">{t('admin.referralFraud.loadError')}</Alert>}
|
||||
|
||||
{data && (
|
||||
<>
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard label="Review queue" value={data.summary.reviewCount} sub={`${data.summary.reviewAmount} raw`} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard label="Pending" value={data.summary.pendingCount} sub={`${data.summary.pendingAmount} raw`} />
|
||||
<StatCard
|
||||
label={t('admin.referralFraud.stats.reviewQueue')}
|
||||
value={data.summary.reviewCount}
|
||||
sub={t('admin.referralFraud.rawAmount', { amount: data.summary.reviewAmount })}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard
|
||||
label="Paid this month"
|
||||
label={t('admin.referralFraud.stats.pending')}
|
||||
value={data.summary.pendingCount}
|
||||
sub={t('admin.referralFraud.rawAmount', { amount: data.summary.pendingAmount })}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard
|
||||
label={t('admin.referralFraud.stats.paidThisMonth')}
|
||||
value={data.summary.paidThisMonthCount}
|
||||
sub={`${data.summary.paidThisMonthAmount} raw`}
|
||||
sub={t('admin.referralFraud.rawAmount', { amount: data.summary.paidThisMonthAmount })}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard
|
||||
label="Clawed back (month)"
|
||||
label={t('admin.referralFraud.stats.clawedBackMonth')}
|
||||
value={data.summary.clawedBackThisMonthCount}
|
||||
sub={`${data.summary.clawedBackThisMonthAmount} raw`}
|
||||
sub={t('admin.referralFraud.rawAmount', {
|
||||
amount: data.summary.clawedBackThisMonthAmount,
|
||||
})}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard label="Sybil blocked (month)" value={data.summary.blockedThisMonthCount} />
|
||||
<StatCard
|
||||
label={t('admin.referralFraud.stats.sybilBlockedMonth')}
|
||||
value={data.summary.blockedThisMonthCount}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 6, md: 3 }}>
|
||||
<StatCard label="Cap blocked (month)" value={data.summary.capBlockedThisMonthCount} />
|
||||
<StatCard
|
||||
label={t('admin.referralFraud.stats.capBlockedMonth')}
|
||||
value={data.summary.capBlockedThisMonthCount}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<StatCard
|
||||
label="Monthly caps (per referrer)"
|
||||
value={`${data.settings.maxCommissionsPerReferrerMonth} commissions`}
|
||||
sub={`max ${data.settings.maxCommissionAmountPerReferrerMonthRaw} raw / month`}
|
||||
label={t('admin.referralFraud.stats.monthlyCaps')}
|
||||
value={t('admin.referralFraud.stats.commissionsCount', {
|
||||
count: data.settings.maxCommissionsPerReferrerMonth,
|
||||
})}
|
||||
sub={t('admin.referralFraud.stats.maxRawMonth', {
|
||||
amount: data.settings.maxCommissionAmountPerReferrerMonthRaw,
|
||||
})}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
@ -224,21 +248,21 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Review queue
|
||||
{t('admin.referralFraud.reviewQueue.title')}
|
||||
</Typography>
|
||||
{data.reviewQueuePreview.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No commissions awaiting review.
|
||||
{t('admin.referralFraud.reviewQueue.empty')}
|
||||
</Typography>
|
||||
) : (
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Score</TableCell>
|
||||
<TableCell>Signals</TableCell>
|
||||
<TableCell>Amount</TableCell>
|
||||
<TableCell>Beneficiary</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.score')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.signals')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.reviewQueue.amount')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.beneficiary')}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@ -249,16 +273,20 @@ export function ReferralFraudDashboardPage() {
|
||||
<Chip size="small" color="warning" label={item.sybilScore} />
|
||||
</TableCell>
|
||||
<TableCell sx={{ maxWidth: 200 }}>
|
||||
<Typography variant="caption">{item.sybilSignals.join(', ') || '—'}</Typography>
|
||||
<Typography variant="caption">
|
||||
{item.sybilSignals.join(', ') || '—'}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>{item.commissionAmount}</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="caption">{item.beneficiaryUserId.slice(0, 8)}…</Typography>
|
||||
<Typography variant="caption">
|
||||
{item.beneficiaryUserId.slice(0, 8)}…
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button size="small" color="success" onClick={() => approveMut.mutate(item.id)}>
|
||||
Approve
|
||||
{t('admin.referralAdmin.approve')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
@ -266,11 +294,11 @@ export function ReferralFraudDashboardPage() {
|
||||
onClick={() =>
|
||||
rejectMut.mutate({
|
||||
payoutId: item.id,
|
||||
reason: 'Rejected from fraud dashboard',
|
||||
reason: t('admin.referralFraud.reviewQueue.rejectReason'),
|
||||
})
|
||||
}
|
||||
>
|
||||
Reject
|
||||
{t('admin.referralAdmin.reject')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
@ -288,17 +316,17 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3, height: '100%' }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
High-risk referrers
|
||||
{t('admin.referralFraud.highRisk.title')}
|
||||
</Typography>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Code</TableCell>
|
||||
<TableCell>Avg Sybil</TableCell>
|
||||
<TableCell>Review</TableCell>
|
||||
<TableCell>Inactive</TableCell>
|
||||
<TableCell>Month raw</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.code')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.highRisk.avgSybil')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.highRisk.review')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.highRisk.inactive')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.highRisk.monthRaw')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -321,12 +349,12 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3, height: '100%' }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Sybil signals (this month)
|
||||
{t('admin.referralFraud.sybilSignals.title')}
|
||||
</Typography>
|
||||
<Stack spacing={1}>
|
||||
{data.sybilSignalBreakdown.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No signals recorded this month.
|
||||
{t('admin.referralFraud.sybilSignals.empty')}
|
||||
</Typography>
|
||||
) : (
|
||||
data.sybilSignalBreakdown.map((s) => (
|
||||
@ -345,16 +373,16 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 2 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Clawback (paid commissions)
|
||||
{t('admin.referralFraud.clawback.title')}
|
||||
</Typography>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Score</TableCell>
|
||||
<TableCell>Amount</TableCell>
|
||||
<TableCell>Beneficiary</TableCell>
|
||||
<TableCell>Reason + action</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.score')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.reviewQueue.amount')}</TableCell>
|
||||
<TableCell>{t('admin.referralAdmin.beneficiary')}</TableCell>
|
||||
<TableCell>{t('admin.referralFraud.clawback.reasonAction')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -369,7 +397,7 @@ export function ReferralFraudDashboardPage() {
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
placeholder="Clawback reason"
|
||||
placeholder={t('admin.referralFraud.clawback.reasonPlaceholder')}
|
||||
value={clawbackReasons[p.id] ?? ''}
|
||||
onChange={(e) =>
|
||||
setClawbackReasons((prev) => ({ ...prev, [p.id]: e.target.value }))
|
||||
@ -388,7 +416,7 @@ export function ReferralFraudDashboardPage() {
|
||||
})
|
||||
}
|
||||
>
|
||||
Clawback
|
||||
{t('admin.referralFraud.clawback.action')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
@ -405,12 +433,12 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Recent clawbacks
|
||||
{t('admin.referralFraud.recentClawbacks.title')}
|
||||
</Typography>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} sx={{ mb: 2 }} useFlexGap>
|
||||
<TextField
|
||||
size="small"
|
||||
label="From"
|
||||
label={t('admin.referralFraud.recentClawbacks.from')}
|
||||
type="date"
|
||||
slotProps={{ inputLabel: { shrink: true } }}
|
||||
value={exportFrom}
|
||||
@ -418,7 +446,7 @@ export function ReferralFraudDashboardPage() {
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="To"
|
||||
label={t('admin.referralFraud.recentClawbacks.to')}
|
||||
type="date"
|
||||
slotProps={{ inputLabel: { shrink: true } }}
|
||||
value={exportTo}
|
||||
@ -431,7 +459,9 @@ export function ReferralFraudDashboardPage() {
|
||||
onClick={() => void downloadClawbacksCsv()}
|
||||
disabled={exporting}
|
||||
>
|
||||
Export CSV
|
||||
{exporting
|
||||
? t('common.exporting')
|
||||
: t('admin.referralFraud.recentClawbacks.exportCsv')}
|
||||
</Button>
|
||||
</Stack>
|
||||
{exportError && (
|
||||
@ -441,13 +471,17 @@ export function ReferralFraudDashboardPage() {
|
||||
)}
|
||||
{data.recentClawbacks.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
None yet.
|
||||
{t('admin.referralFraud.recentClawbacks.empty')}
|
||||
</Typography>
|
||||
) : (
|
||||
data.recentClawbacks.map((c) => (
|
||||
<Box key={c.id} sx={{ mb: 1.5 }}>
|
||||
<Typography variant="body2">
|
||||
<strong>{c.amount}</strong> raw — {c.reason}
|
||||
<Typography variant="body2" component="div">
|
||||
<Trans
|
||||
i18nKey="admin.referralFraud.recentClawbacks.line"
|
||||
values={{ amount: c.amount, reason: c.reason }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{new Date(c.createdAt).toLocaleString()}
|
||||
@ -462,11 +496,11 @@ export function ReferralFraudDashboardPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Recent blocks (Sybil / cap)
|
||||
{t('admin.referralFraud.recentBlocks.title')}
|
||||
</Typography>
|
||||
{data.recentCapBlocks.length === 0 ? (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
None recorded.
|
||||
{t('admin.referralFraud.recentBlocks.empty')}
|
||||
</Typography>
|
||||
) : (
|
||||
data.recentCapBlocks.map((b, i) => (
|
||||
|
||||
@ -22,6 +22,7 @@ import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
|
||||
import TableChartRoundedIcon from '@mui/icons-material/TableChartRounded';
|
||||
import AccountTreeRoundedIcon from '@mui/icons-material/AccountTreeRounded';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import { rawToHuman } from '../wallet/utils/walletFormat';
|
||||
import { ReferralTableView } from './components/ReferralTableView';
|
||||
@ -53,6 +54,7 @@ function StatCard({ label, value, sub }: { label: string; value: string | number
|
||||
}
|
||||
|
||||
export function ReferralPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { auth } = useAuth();
|
||||
const [tab, setTab] = useState(0);
|
||||
const [maxDepth, setMaxDepth] = useState(5);
|
||||
@ -65,47 +67,47 @@ export function ReferralPage() {
|
||||
|
||||
const copy = async (text: string, label: string) => {
|
||||
if (!text) {
|
||||
setToast('Nothing to copy');
|
||||
setToast(t('common.nothingToCopy'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setToast(`${label} copied`);
|
||||
setToast(t('common.copied', { label }));
|
||||
} catch {
|
||||
setToast('Copy failed');
|
||||
setToast(t('common.copyFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([dashQ.refetch(), commissionsQ.refetch()]);
|
||||
setToast('Referral data refreshed');
|
||||
setToast(t('referralPage.refreshed'));
|
||||
};
|
||||
|
||||
const commissionModeLabel = () => {
|
||||
if (!data) return '';
|
||||
const { depositEnabled, withdrawalEnabled } = data.commissionModes;
|
||||
if (depositEnabled && withdrawalEnabled) return 'Deposits + withdrawal gains';
|
||||
if (depositEnabled) return 'First deposits';
|
||||
if (withdrawalEnabled) return 'Withdrawal gains (prediction profits)';
|
||||
return 'Commissions paused';
|
||||
if (depositEnabled && withdrawalEnabled) return t('referralPage.modes.both');
|
||||
if (depositEnabled) return t('referralPage.modes.deposit');
|
||||
if (withdrawalEnabled) return t('referralPage.modes.withdrawal');
|
||||
return t('referralPage.modes.paused');
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<GroupAddRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Referral program"
|
||||
subtitle="Build your network and earn commissions on your referrals' activity."
|
||||
title={t('referralPage.title')}
|
||||
subtitle={t('referralPage.subtitle')}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh referral data"
|
||||
label={t('referralPage.refresh')}
|
||||
onClick={() => void refreshAll()}
|
||||
disabled={dashQ.isFetching}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
{dashQ.isError && <Alert severity="error">Failed to load referral dashboard.</Alert>}
|
||||
{dashQ.isError && <Alert severity="error">{t('referralPage.loadError')}</Alert>}
|
||||
|
||||
{dashQ.isLoading && (
|
||||
<Stack spacing={2}>
|
||||
@ -118,31 +120,35 @@ export function ReferralPage() {
|
||||
<>
|
||||
{!data.programEnabled && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
The referral program is temporarily disabled. Your network data is still visible below.
|
||||
{t('referralPage.programDisabled')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 2, flexWrap: 'wrap' }} useFlexGap>
|
||||
<Box sx={{ flex: '1 1 140px', minWidth: 140 }}>
|
||||
<StatCard label="Network size" value={data.summary.networkSize} sub={`${data.directReferrals} direct`} />
|
||||
</Box>
|
||||
<Box sx={{ flex: '1 1 140px', minWidth: 140 }}>
|
||||
<StatCard
|
||||
label="Total earned"
|
||||
value={`${rawToHuman(data.summary.totalEarnedRaw, USDT_DECIMALS)}`}
|
||||
sub="USDT (all statuses)"
|
||||
label={t('referralPage.stats.networkSize')}
|
||||
value={data.summary.networkSize}
|
||||
sub={t('referralPage.stats.direct', { count: data.directReferrals })}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ flex: '1 1 140px', minWidth: 140 }}>
|
||||
<StatCard
|
||||
label="Paid out"
|
||||
label={t('referralPage.stats.totalEarned')}
|
||||
value={`${rawToHuman(data.summary.totalEarnedRaw, USDT_DECIMALS)}`}
|
||||
sub={t('referralPage.stats.allStatuses')}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ flex: '1 1 140px', minWidth: 140 }}>
|
||||
<StatCard
|
||||
label={t('referralPage.stats.paidOut')}
|
||||
value={`${rawToHuman(data.summary.paidRaw, USDT_DECIMALS)}`}
|
||||
sub="USDT"
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ flex: '1 1 140px', minWidth: 140 }}>
|
||||
<StatCard
|
||||
label="Pending / review"
|
||||
label={t('referralPage.stats.pendingReview')}
|
||||
value={`${rawToHuman(
|
||||
(BigInt(data.summary.pendingRaw) + BigInt(data.summary.reviewRaw)).toString(),
|
||||
USDT_DECIMALS
|
||||
@ -157,26 +163,33 @@ export function ReferralPage() {
|
||||
<Card sx={{ borderRadius: 3, height: '100%' }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1.5 }}>
|
||||
Your invite link
|
||||
{t('referralPage.invite.title')}
|
||||
</Typography>
|
||||
{data.referralCode ? (
|
||||
<Stack spacing={2}>
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }} useFlexGap>
|
||||
<Chip label={commissionModeLabel()} color="primary" variant="outlined" />
|
||||
{data.bonusWithdrawable && (
|
||||
<Chip label="Bonus withdrawable" size="small" color="success" variant="outlined" />
|
||||
<Chip
|
||||
label={t('referralPage.invite.bonusWithdrawable')}
|
||||
size="small"
|
||||
color="success"
|
||||
variant="outlined"
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
<Stack direction="row" spacing={0.5}>
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
label="Referral code"
|
||||
label={t('profileReferral.referralCode')}
|
||||
value={data.referralCode}
|
||||
slotProps={{ input: { readOnly: true } }}
|
||||
sx={{ '& input': { fontFamily: 'monospace', fontWeight: 700 } }}
|
||||
/>
|
||||
<IconButton onClick={() => void copy(data.referralCode!, 'Code')}>
|
||||
<IconButton
|
||||
onClick={() => void copy(data.referralCode!, t('profileReferral.referralCode'))}
|
||||
>
|
||||
<ContentCopyRoundedIcon />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
@ -184,25 +197,27 @@ export function ReferralPage() {
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
label="Invite link"
|
||||
label={t('profileReferral.referralLink')}
|
||||
value={data.referralLink}
|
||||
slotProps={{ input: { readOnly: true } }}
|
||||
/>
|
||||
<IconButton onClick={() => void copy(data.referralLink, 'Link')}>
|
||||
<IconButton
|
||||
onClick={() => void copy(data.referralLink, t('profileReferral.referralLink'))}
|
||||
>
|
||||
<ContentCopyRoundedIcon />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
<Button
|
||||
variant="contained"
|
||||
startIcon={<ContentCopyRoundedIcon />}
|
||||
onClick={() => void copy(data.referralLink, 'Invite link')}
|
||||
onClick={() => void copy(data.referralLink, t('profileReferral.copyInvite'))}
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
>
|
||||
Copy invite link
|
||||
{t('profileReferral.copyInvite')}
|
||||
</Button>
|
||||
</Stack>
|
||||
) : (
|
||||
<Alert severity="info">Your referral code is not available yet.</Alert>
|
||||
<Alert severity="info">{t('referralPage.invite.codeNotAvailable')}</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@ -212,7 +227,7 @@ export function ReferralPage() {
|
||||
<Card sx={{ borderRadius: 3, height: '100%' }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1.5 }}>
|
||||
Your referrer
|
||||
{t('referralPage.referrer.title')}
|
||||
</Typography>
|
||||
{data.referrer ? (
|
||||
<Stack spacing={1}>
|
||||
@ -221,36 +236,40 @@ export function ReferralPage() {
|
||||
</Typography>
|
||||
{data.referrer.referralCode && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Code: <strong>{data.referrer.referralCode}</strong>
|
||||
{t('referralPage.invite.codePrefix')}{' '}
|
||||
<strong>{data.referrer.referralCode}</strong>
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Member since {new Date(data.referrer.memberSince).toLocaleDateString()}
|
||||
{t('referralPage.referrer.memberSince', {
|
||||
date: new Date(data.referrer.memberSince).toLocaleDateString(i18n.language),
|
||||
})}
|
||||
</Typography>
|
||||
</Stack>
|
||||
) : (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
You joined without a referral code, or your referrer is not linked.
|
||||
{t('referralPage.referrer.noReferrer')}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, mt: 3, mb: 1 }}>
|
||||
Commission levels
|
||||
{t('referralPage.referrer.commissionLevels')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }} useFlexGap>
|
||||
{data.levels.map((l: { levelNumber: number; commissionPercent: number }) => (
|
||||
<Chip
|
||||
key={l.levelNumber}
|
||||
label={`Level ${l.levelNumber}: ${l.commissionPercent}%`}
|
||||
label={t('referralPage.referrer.levelChip', {
|
||||
level: l.levelNumber,
|
||||
percent: l.commissionPercent,
|
||||
})}
|
||||
variant="outlined"
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5 }}>
|
||||
{data.commissionModes.depositEnabled &&
|
||||
'Deposit commissions apply on eligible first deposits. '}
|
||||
{data.commissionModes.withdrawalEnabled &&
|
||||
'Withdrawal commissions apply only on prediction gains withdrawn from the main account (not deposited principal).'}
|
||||
{data.commissionModes.depositEnabled && t('referralPage.referrer.depositHint')}
|
||||
{data.commissionModes.withdrawalEnabled && t('referralPage.referrer.withdrawalHint')}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@ -265,16 +284,16 @@ export function ReferralPage() {
|
||||
sx={{ alignItems: { sm: 'center' }, mb: 2 }}
|
||||
>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, flex: 1 }}>
|
||||
Your referral network
|
||||
{t('referralPage.network.title')}
|
||||
</Typography>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Max depth"
|
||||
label={t('referralPage.network.maxDepth')}
|
||||
type="number"
|
||||
value={maxDepth}
|
||||
onChange={(e) => setMaxDepth(Math.min(10, Math.max(1, Number(e.target.value) || 5)))}
|
||||
sx={{ width: 120 }}
|
||||
helperText={`Showing ${data.maxNetworkDepth} levels`}
|
||||
helperText={t('referralPage.network.showingLevels', { count: data.maxNetworkDepth })}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
@ -285,8 +304,8 @@ export function ReferralPage() {
|
||||
scrollButtons="auto"
|
||||
sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}
|
||||
>
|
||||
<Tab icon={<TableChartRoundedIcon />} iconPosition="start" label="Table view" />
|
||||
<Tab icon={<AccountTreeRoundedIcon />} iconPosition="start" label="Tree view" />
|
||||
<Tab icon={<TableChartRoundedIcon />} iconPosition="start" label={t('referralPage.network.tableView')} />
|
||||
<Tab icon={<AccountTreeRoundedIcon />} iconPosition="start" label={t('referralPage.network.treeView')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 0 && <ReferralTableView members={data.network} />}
|
||||
@ -299,7 +318,7 @@ export function ReferralPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
|
||||
Commission history
|
||||
{t('referralPage.network.commissionHistory')}
|
||||
</Typography>
|
||||
{commissionsQ.isLoading ? (
|
||||
<Skeleton height={160} />
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ScrollableTable } from '../../../shared/components/ScrollableTable';
|
||||
import { rawToHuman } from '../../wallet/utils/walletFormat';
|
||||
import type { ReferralCommissionItem } from '../types';
|
||||
@ -26,10 +27,12 @@ type ReferralCommissionsPanelProps = {
|
||||
};
|
||||
|
||||
export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No commission events yet.
|
||||
{t('referralPage.commissions.empty')}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@ -39,12 +42,12 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Member</TableCell>
|
||||
<TableCell>Level</TableCell>
|
||||
<TableCell>Source</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">Commission</TableCell>
|
||||
<TableCell>Date</TableCell>
|
||||
<TableCell>{t('referralPage.commissions.member')}</TableCell>
|
||||
<TableCell>{t('referralPage.commissions.level')}</TableCell>
|
||||
<TableCell>{t('referralPage.commissions.source')}</TableCell>
|
||||
<TableCell>{t('common.status')}</TableCell>
|
||||
<TableCell align="right">{t('referralPage.commissions.commission')}</TableCell>
|
||||
<TableCell>{t('referralPage.commissions.date')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -56,7 +59,11 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp
|
||||
<Chip
|
||||
size="small"
|
||||
variant="outlined"
|
||||
label={c.commissionSource === 'deposit' ? 'Deposit' : 'Withdrawal gains'}
|
||||
label={
|
||||
c.commissionSource === 'deposit'
|
||||
? t('referralPage.commissions.deposit')
|
||||
: t('referralPage.commissions.withdrawal')
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
@ -65,7 +72,10 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp
|
||||
<TableCell align="right">
|
||||
{rawToHuman(c.commissionAmountRaw, USDT_DECIMALS)} USDT
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
|
||||
{c.commissionPercent}% of {rawToHuman(c.baseAmountRaw, USDT_DECIMALS)}
|
||||
{t('referralPage.commissions.percentOf', {
|
||||
percent: c.commissionPercent,
|
||||
amount: rawToHuman(c.baseAmountRaw, USDT_DECIMALS),
|
||||
})}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
|
||||
@ -9,18 +9,13 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ScrollableTable } from '../../../shared/components/ScrollableTable';
|
||||
import { rawToHuman } from '../../wallet/utils/walletFormat';
|
||||
import type { ReferralNetworkMember } from '../types';
|
||||
|
||||
const USDT_DECIMALS = 6;
|
||||
|
||||
function statusChip(status: ReferralNetworkMember['status']) {
|
||||
if (status === 'active') return <Chip size="small" label="Active" color="success" />;
|
||||
if (status === 'unverified') return <Chip size="small" label="Unverified" color="warning" variant="outlined" />;
|
||||
return <Chip size="small" label="Registered" variant="outlined" />;
|
||||
}
|
||||
|
||||
function formatRaw(raw: string) {
|
||||
return `${rawToHuman(raw, USDT_DECIMALS)} USDT`;
|
||||
}
|
||||
@ -30,10 +25,24 @@ type ReferralTableViewProps = {
|
||||
};
|
||||
|
||||
export function ReferralTableView({ members }: ReferralTableViewProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
function statusChip(status: ReferralNetworkMember['status']) {
|
||||
if (status === 'active') {
|
||||
return <Chip size="small" label={t('referralPage.table.status.active')} color="success" />;
|
||||
}
|
||||
if (status === 'unverified') {
|
||||
return (
|
||||
<Chip size="small" label={t('referralPage.table.status.unverified')} color="warning" variant="outlined" />
|
||||
);
|
||||
}
|
||||
return <Chip size="small" label={t('referralPage.table.status.registered')} variant="outlined" />;
|
||||
}
|
||||
|
||||
if (members.length === 0) {
|
||||
return (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ py: 3, textAlign: 'center' }}>
|
||||
No referrals in your network yet. Share your invite link to grow your team.
|
||||
{t('referralPage.table.empty')}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@ -43,15 +52,15 @@ export function ReferralTableView({ members }: ReferralTableViewProps) {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Member</TableCell>
|
||||
<TableCell>Country</TableCell>
|
||||
<TableCell>Level</TableCell>
|
||||
<TableCell>Registered</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">Direct refs</TableCell>
|
||||
<TableCell align="right">Predictions</TableCell>
|
||||
<TableCell align="right">Commissions</TableCell>
|
||||
<TableCell align="right">Pending</TableCell>
|
||||
<TableCell>{t('referralPage.table.member')}</TableCell>
|
||||
<TableCell>{t('referralPage.table.country')}</TableCell>
|
||||
<TableCell>{t('referralPage.table.level')}</TableCell>
|
||||
<TableCell>{t('referralPage.table.registered')}</TableCell>
|
||||
<TableCell>{t('common.status')}</TableCell>
|
||||
<TableCell align="right">{t('referralPage.table.directRefs')}</TableCell>
|
||||
<TableCell align="right">{t('referralPage.table.predictions')}</TableCell>
|
||||
<TableCell align="right">{t('referralPage.table.commissions')}</TableCell>
|
||||
<TableCell align="right">{t('referralPage.table.pending')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -70,9 +79,7 @@ export function ReferralTableView({ members }: ReferralTableViewProps) {
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2">
|
||||
{m.countryName ?? '—'}
|
||||
</Typography>
|
||||
<Typography variant="body2">{m.countryName ?? '—'}</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip size="small" label={`L${m.levelNumber}`} variant="outlined" />
|
||||
@ -89,7 +96,7 @@ export function ReferralTableView({ members }: ReferralTableViewProps) {
|
||||
</Typography>
|
||||
{BigInt(m.commissionsGeneratedRaw) > BigInt(m.commissionsPaidRaw) && (
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
|
||||
total {formatRaw(m.commissionsGeneratedRaw)}
|
||||
{t('referralPage.table.total', { amount: formatRaw(m.commissionsGeneratedRaw) })}
|
||||
</Typography>
|
||||
)}
|
||||
</TableCell>
|
||||
|
||||
@ -11,6 +11,7 @@ import {
|
||||
import ExpandMoreRoundedIcon from '@mui/icons-material/ExpandMoreRounded';
|
||||
import ChevronRightRoundedIcon from '@mui/icons-material/ChevronRightRounded';
|
||||
import PersonRoundedIcon from '@mui/icons-material/PersonRounded';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { rawToHuman } from '../../wallet/utils/walletFormat';
|
||||
import type { ReferralNetworkMember } from '../types';
|
||||
|
||||
@ -24,12 +25,20 @@ type TreeNodeProps = {
|
||||
};
|
||||
|
||||
function TreeNode({ member, children, childMap, defaultExpanded = false }: TreeNodeProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(defaultExpanded);
|
||||
const hasChildren = children.length > 0;
|
||||
|
||||
const statusColor =
|
||||
member.status === 'active' ? 'success' : member.status === 'unverified' ? 'warning' : 'default';
|
||||
|
||||
const statusLabel =
|
||||
member.status === 'active'
|
||||
? t('referralPage.table.status.active')
|
||||
: member.status === 'unverified'
|
||||
? t('referralPage.table.status.unverified')
|
||||
: t('referralPage.table.status.registered');
|
||||
|
||||
return (
|
||||
<Box sx={{ pl: { xs: 1, sm: 2 } }}>
|
||||
<Paper
|
||||
@ -56,18 +65,31 @@ function TreeNode({ member, children, childMap, defaultExpanded = false }: TreeN
|
||||
<Typography variant="body2" sx={{ fontWeight: 800 }}>
|
||||
{member.displayName}
|
||||
</Typography>
|
||||
<Chip size="small" label={`Level ${member.levelNumber}`} variant="outlined" />
|
||||
<Chip size="small" label={member.status} color={statusColor} variant="outlined" />
|
||||
<Chip
|
||||
size="small"
|
||||
label={t('referralPage.tree.level', { level: member.levelNumber })}
|
||||
variant="outlined"
|
||||
/>
|
||||
<Chip size="small" label={statusLabel} color={statusColor} variant="outlined" />
|
||||
{member.directReferralsCount > 0 && (
|
||||
<Chip size="small" label={`${member.directReferralsCount} direct`} />
|
||||
<Chip
|
||||
size="small"
|
||||
label={t('referralPage.tree.direct', { count: member.directReferralsCount })}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
|
||||
{member.countryName ? `${member.countryName} · ` : ''}
|
||||
Paid: {rawToHuman(member.commissionsPaidRaw, USDT_DECIMALS)} USDT
|
||||
{t('referralPage.tree.paid', {
|
||||
amount: rawToHuman(member.commissionsPaidRaw, USDT_DECIMALS),
|
||||
})}
|
||||
{BigInt(member.commissionsPendingRaw) > 0n &&
|
||||
` · Pending: ${rawToHuman(member.commissionsPendingRaw, USDT_DECIMALS)} USDT`}
|
||||
{member.referralCode ? ` · Code: ${member.referralCode}` : ''}
|
||||
` · ${t('referralPage.tree.pending', {
|
||||
amount: rawToHuman(member.commissionsPendingRaw, USDT_DECIMALS),
|
||||
})}`}
|
||||
{member.referralCode
|
||||
? ` · ${t('referralPage.tree.code', { code: member.referralCode })}`
|
||||
: ''}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
@ -105,6 +127,8 @@ type ReferralTreeViewProps = {
|
||||
};
|
||||
|
||||
export function ReferralTreeView({ members, rootUserId }: ReferralTreeViewProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const childMap = useMemo(() => {
|
||||
const map = new Map<string, ReferralNetworkMember[]>();
|
||||
for (const m of members) {
|
||||
@ -123,7 +147,7 @@ export function ReferralTreeView({ members, rootUserId }: ReferralTreeViewProps)
|
||||
if (directChildren.length === 0) {
|
||||
return (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ py: 3, textAlign: 'center' }}>
|
||||
Your referral tree is empty. Invite members to see the hierarchy here.
|
||||
{t('referralPage.tree.empty')}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
@ -59,7 +59,7 @@ import {
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { useTranslation, Trans } from 'react-i18next';
|
||||
import { Link as RouterLink, useParams, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { useCountryNames } from '../countries/useCountryNames';
|
||||
@ -74,15 +74,10 @@ function toDateInputValue(value: string): string {
|
||||
}
|
||||
|
||||
import {
|
||||
|
||||
BULK_ACTION_CONFIRM,
|
||||
|
||||
BULK_ACTION_LABELS,
|
||||
|
||||
bulkActionConfirm,
|
||||
bulkActionLabel,
|
||||
type BulkActionResult,
|
||||
|
||||
type ReportBulkAction,
|
||||
|
||||
} from './reportBulkActions';
|
||||
|
||||
|
||||
@ -143,12 +138,10 @@ type ReportExportJob = {
|
||||
|
||||
|
||||
|
||||
function apiErrorMessage(err: unknown, fallback: string): string {
|
||||
function apiErrorMessage(err: unknown, fallback: string, timeoutMsg: string): string {
|
||||
const e = err as { response?: { data?: { error?: string }; status?: number }; message?: string };
|
||||
if (e?.response?.data?.error) return String(e.response.data.error);
|
||||
if (e?.response?.status === 503) {
|
||||
return 'La requête a pris trop de temps (volume de données élevé). Réduisez la période ou affinez les filtres.';
|
||||
}
|
||||
if (e?.response?.status === 503) return timeoutMsg;
|
||||
return e?.message ?? fallback;
|
||||
}
|
||||
|
||||
@ -226,6 +219,7 @@ function downloadBlob(blob: Blob, filename: string) {
|
||||
|
||||
export function ReportDetailPage() {
|
||||
|
||||
const { t, i18n } = useTranslation();
|
||||
const theme = useTheme();
|
||||
|
||||
const isCompact = useMediaQuery(theme.breakpoints.down('md'));
|
||||
@ -435,11 +429,13 @@ export function ReportDetailPage() {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-report', reportKey] });
|
||||
|
||||
setToast({
|
||||
|
||||
message: `${data.succeeded.length} réussi(s)${data.failed.length ? ` · ${data.failed.length} échec(s)` : ''}`,
|
||||
|
||||
message: t('admin.reports.detail.bulkResult', {
|
||||
succeeded: data.succeeded.length,
|
||||
suffix: data.failed.length
|
||||
? t('admin.reports.detail.bulkFailedSuffix', { failed: data.failed.length })
|
||||
: '',
|
||||
}),
|
||||
severity: data.failed.length ? 'error' : 'success',
|
||||
|
||||
});
|
||||
|
||||
},
|
||||
@ -450,13 +446,13 @@ export function ReportDetailPage() {
|
||||
|
||||
err && typeof err === 'object' && 'response' in err
|
||||
|
||||
? String((err as { response?: { data?: { error?: string } } }).response?.data?.error ?? 'Action échouée')
|
||||
? String((err as { response?: { data?: { error?: string } } }).response?.data?.error ?? t('admin.reports.detail.actionFailed'))
|
||||
|
||||
: err instanceof Error
|
||||
|
||||
? err.message
|
||||
|
||||
: 'Action de masse échouée';
|
||||
: t('admin.reports.detail.bulkFailed');
|
||||
|
||||
setToast({ message, severity: 'error' });
|
||||
|
||||
@ -524,7 +520,7 @@ export function ReportDetailPage() {
|
||||
|
||||
if (job.status === 'failed') {
|
||||
|
||||
throw new Error(job.error ?? 'Export échoué');
|
||||
throw new Error(job.error ?? t('admin.reports.detail.exportFailed'));
|
||||
|
||||
}
|
||||
|
||||
@ -554,11 +550,19 @@ export function ReportDetailPage() {
|
||||
|
||||
);
|
||||
|
||||
setToast({ message: `Export terminé (${job.rowCount.toLocaleString('fr-FR')} lignes)`, severity: 'success' });
|
||||
setToast({
|
||||
message: t('admin.reports.detail.exportDone', {
|
||||
count: job.rowCount.toLocaleString(i18n.language),
|
||||
}),
|
||||
severity: 'success',
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
|
||||
setToast({ message: apiErrorMessage(err, 'Export échoué'), severity: 'error' });
|
||||
setToast({
|
||||
message: apiErrorMessage(err, t('admin.reports.detail.exportFailed'), t('admin.reports.detail.timeoutError')),
|
||||
severity: 'error',
|
||||
});
|
||||
|
||||
} finally {
|
||||
|
||||
@ -613,7 +617,10 @@ export function ReportDetailPage() {
|
||||
|
||||
downloadBlob(new Blob([res.data], { type: mime }), `${reportKey}${ids?.length ? '-selection' : ''}.${format}`);
|
||||
} catch (err) {
|
||||
setToast({ message: apiErrorMessage(err, 'Export échoué'), severity: 'error' });
|
||||
setToast({
|
||||
message: apiErrorMessage(err, t('admin.reports.detail.exportFailed'), t('admin.reports.detail.timeoutError')),
|
||||
severity: 'error',
|
||||
});
|
||||
}
|
||||
|
||||
},
|
||||
@ -756,7 +763,7 @@ export function ReportDetailPage() {
|
||||
|
||||
{selectionCount(selection) > 0 && (
|
||||
|
||||
<Chip size="small" color="primary" label={`${selectionCount(selection)} sélectionné(s)`} />
|
||||
<Chip size="small" color="primary" label={t('admin.reports.detail.selected', { count: selectionCount(selection) })} />
|
||||
|
||||
)}
|
||||
|
||||
@ -784,7 +791,7 @@ export function ReportDetailPage() {
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'flex-start', flexWrap: 'wrap' }}>
|
||||
|
||||
<IconButton component={RouterLink} to="/admin/reports" aria-label="Retour">
|
||||
<IconButton component={RouterLink} to="/admin/reports" aria-label={t('admin.reports.detail.back')}>
|
||||
|
||||
<ArrowBackRoundedIcon />
|
||||
|
||||
@ -816,25 +823,25 @@ export function ReportDetailPage() {
|
||||
|
||||
<Button size="small" variant="outlined" startIcon={<FilterListRoundedIcon />} onClick={() => setFiltersOpen((v) => !v)}>
|
||||
|
||||
Filtres
|
||||
{t('admin.reports.detail.filters')}
|
||||
|
||||
</Button>
|
||||
|
||||
<Button size="small" variant="outlined" startIcon={<DownloadRoundedIcon />} disabled={exporting} onClick={() => void exportServerAsync('xlsx')}>
|
||||
|
||||
Excel (filtres)
|
||||
{t('admin.reports.detail.exportExcelFilters')}
|
||||
|
||||
</Button>
|
||||
|
||||
<Button size="small" variant="outlined" disabled={exporting} onClick={() => void exportServerAsync('csv')}>
|
||||
|
||||
CSV (filtres)
|
||||
{t('admin.reports.detail.exportCsvFilters')}
|
||||
|
||||
</Button>
|
||||
|
||||
<Button size="small" variant="outlined" disabled={exporting} onClick={() => void exportServerAsync('pdf')}>
|
||||
|
||||
PDF (serveur)
|
||||
{t('admin.reports.detail.exportPdfServer')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -850,7 +857,7 @@ export function ReportDetailPage() {
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 1 }}>
|
||||
|
||||
Actions de masse
|
||||
{t('admin.reports.detail.bulkActionsTitle')}
|
||||
|
||||
</Typography>
|
||||
|
||||
@ -858,19 +865,19 @@ export function ReportDetailPage() {
|
||||
|
||||
<Button size="small" variant="contained" onClick={() => void exportSelection('xlsx')}>
|
||||
|
||||
Exporter sélection (Excel)
|
||||
{t('admin.reports.detail.exportSelectionExcel')}
|
||||
|
||||
</Button>
|
||||
|
||||
<Button size="small" variant="outlined" onClick={() => void exportSelection('csv')}>
|
||||
|
||||
CSV
|
||||
{t('admin.reports.detail.csv')}
|
||||
|
||||
</Button>
|
||||
|
||||
<Button size="small" variant="outlined" onClick={() => void exportSelection('pdf')}>
|
||||
|
||||
PDF
|
||||
{t('admin.reports.detail.pdf')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -890,7 +897,7 @@ export function ReportDetailPage() {
|
||||
|
||||
>
|
||||
|
||||
{BULK_ACTION_LABELS[action]}
|
||||
{bulkActionLabel(t, action)}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -898,7 +905,7 @@ export function ReportDetailPage() {
|
||||
|
||||
<Button size="small" onClick={() => setSelection(emptySelection)}>
|
||||
|
||||
Tout désélectionner
|
||||
{t('admin.reports.detail.deselectAll')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -916,15 +923,15 @@ export function ReportDetailPage() {
|
||||
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2} sx={{ flexWrap: 'wrap' }}>
|
||||
|
||||
<TextField size="small" label="Recherche" value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||
<TextField size="small" label={t('admin.reports.detail.search')} value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||
|
||||
<TextField size="small" label="Du" type="date" value={from} onChange={(e) => setFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
|
||||
<TextField size="small" label={t('admin.reports.detail.from')} type="date" value={from} onChange={(e) => setFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
|
||||
|
||||
<TextField size="small" label="Au" type="date" value={to} onChange={(e) => setTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
|
||||
<TextField size="small" label={t('admin.reports.detail.to')} type="date" value={to} onChange={(e) => setTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
|
||||
|
||||
<Button variant="contained" onClick={applyFilters}>
|
||||
|
||||
Appliquer
|
||||
{t('admin.reports.detail.apply')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -932,11 +939,11 @@ export function ReportDetailPage() {
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ mt: 2, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
|
||||
<TextField size="small" placeholder="Nom du filtre favori" value={favoriteName} onChange={(e) => setFavoriteName(e.target.value)} />
|
||||
<TextField size="small" placeholder={t('admin.reports.detail.favoriteNamePlaceholder')} value={favoriteName} onChange={(e) => setFavoriteName(e.target.value)} />
|
||||
|
||||
<Button size="small" startIcon={<StarRoundedIcon />} onClick={saveFavorite} disabled={!favoriteName.trim()}>
|
||||
|
||||
Sauver filtre
|
||||
{t('admin.reports.detail.saveFilter')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -978,7 +985,7 @@ export function ReportDetailPage() {
|
||||
|
||||
{q.isError && (
|
||||
<Alert severity="error">
|
||||
{apiErrorMessage(q.error, 'Impossible de charger ce rapport.')}
|
||||
{apiErrorMessage(q.error, t('admin.reports.detail.loadError'), t('admin.reports.detail.timeoutError'))}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -996,17 +1003,29 @@ export function ReportDetailPage() {
|
||||
<Alert severity="success" sx={{ mb: 2 }}>
|
||||
{q.data.summary.totalAmountRaw != null && (
|
||||
<Box component="div">
|
||||
Montant total : <strong>{formatRawUsdtCell(String(q.data.summary.totalAmountRaw))} USDT</strong>
|
||||
<Trans
|
||||
i18nKey="admin.reports.detail.summaryTotal"
|
||||
values={{ amount: formatRawUsdtCell(String(q.data.summary.totalAmountRaw)) }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{q.data.summary.totalCount != null && (
|
||||
<Box component="div">
|
||||
Nombre d'opérations : <strong>{q.data.summary.totalCount.toLocaleString('fr-FR')}</strong>
|
||||
<Trans
|
||||
i18nKey="admin.reports.detail.summaryCount"
|
||||
values={{ count: q.data.summary.totalCount.toLocaleString(i18n.language) }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{q.data.summary.uniqueUsers != null && (
|
||||
<Box component="div">
|
||||
Utilisateurs distincts : <strong>{q.data.summary.uniqueUsers.toLocaleString('fr-FR')}</strong>
|
||||
<Trans
|
||||
i18nKey="admin.reports.detail.summaryUsers"
|
||||
values={{ count: q.data.summary.uniqueUsers.toLocaleString(i18n.language) }}
|
||||
components={{ strong: <strong /> }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Alert>
|
||||
@ -1016,7 +1035,9 @@ export function ReportDetailPage() {
|
||||
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
|
||||
Export serveur en cours… {exportProgress.toLocaleString('fr-FR')} ligne(s) traitées
|
||||
{t('admin.reports.detail.exportInProgress', {
|
||||
count: exportProgress.toLocaleString(i18n.language),
|
||||
})}
|
||||
|
||||
</Alert>
|
||||
|
||||
@ -1090,13 +1111,14 @@ export function ReportDetailPage() {
|
||||
|
||||
<Dialog open={!!pendingAction} onClose={() => setPendingAction(null)} maxWidth="xs" fullWidth>
|
||||
|
||||
<DialogTitle>{pendingAction ? BULK_ACTION_LABELS[pendingAction] : ''}</DialogTitle>
|
||||
<DialogTitle>{pendingAction ? bulkActionLabel(t, pendingAction) : ''}</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
|
||||
<Typography variant="body2" sx={{ mb: 2 }}>
|
||||
|
||||
{pendingAction ? BULK_ACTION_CONFIRM[pendingAction] : ''} ({selectedIds.length} ligne(s))
|
||||
{pendingAction ? bulkActionConfirm(t, pendingAction) : ''}{' '}
|
||||
({t('admin.reports.detail.selectedRows', { count: selectedIds.length })})
|
||||
|
||||
</Typography>
|
||||
|
||||
@ -1108,7 +1130,7 @@ export function ReportDetailPage() {
|
||||
|
||||
size="small"
|
||||
|
||||
label="Motif (optionnel)"
|
||||
label={t('admin.reports.detail.reasonOptional')}
|
||||
|
||||
value={actionReason}
|
||||
|
||||
@ -1128,7 +1150,7 @@ export function ReportDetailPage() {
|
||||
|
||||
<Button onClick={() => setPendingAction(null)} disabled={bulkMut.isPending}>
|
||||
|
||||
Annuler
|
||||
{t('common.cancel')}
|
||||
|
||||
</Button>
|
||||
|
||||
@ -1144,7 +1166,7 @@ export function ReportDetailPage() {
|
||||
|
||||
>
|
||||
|
||||
Confirmer
|
||||
{t('admin.reports.detail.confirm')}
|
||||
|
||||
</Button>
|
||||
|
||||
|
||||
@ -14,6 +14,7 @@ import SearchRoundedIcon from '@mui/icons-material/SearchRounded';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
|
||||
type CatalogResponse = {
|
||||
@ -25,6 +26,7 @@ type CatalogResponse = {
|
||||
};
|
||||
|
||||
export function ReportsHubPage() {
|
||||
const { t } = useTranslation();
|
||||
const [search, setSearch] = useState('');
|
||||
const q = useQuery({
|
||||
queryKey: ['admin-reports-catalog'],
|
||||
@ -60,16 +62,14 @@ export function ReportsHubPage() {
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, mb: 0.5 }}>
|
||||
Rapports
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Données détaillées, tableaux paginés, filtres avancés et exports. Le dashboard affiche uniquement les synthèses.
|
||||
{t('admin.reports.title')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.75, mb: 2 }}>{t('admin.reports.subtitle')}</Typography>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
size="small"
|
||||
placeholder="Rechercher un rapport (titre, description, catégorie…)"
|
||||
placeholder={t('admin.reports.searchPlaceholder')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
sx={{ mb: 3, maxWidth: 560 }}
|
||||
@ -84,11 +84,11 @@ export function ReportsHubPage() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{q.isLoading && <Typography sx={{ opacity: 0.7 }}>Chargement du catalogue…</Typography>}
|
||||
{q.isLoading && <Typography sx={{ opacity: 0.7 }}>{t('admin.reports.loading')}</Typography>}
|
||||
|
||||
{!q.isLoading && search.trim() && totalVisible === 0 && (
|
||||
<Typography sx={{ opacity: 0.7, py: 4, textAlign: 'center' }}>
|
||||
Aucun rapport ne correspond à « {search.trim()} ».
|
||||
{t('admin.reports.noResults', { query: search.trim() })}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
export type ReportBulkAction =
|
||||
| 'export-selection'
|
||||
| 'suspend'
|
||||
@ -8,26 +10,13 @@ export type ReportBulkAction =
|
||||
| 'surveillance-off'
|
||||
| 'suspend-users';
|
||||
|
||||
export const BULK_ACTION_LABELS: Record<ReportBulkAction, string> = {
|
||||
'export-selection': 'Exporter la sélection',
|
||||
suspend: 'Suspendre',
|
||||
reactivate: 'Réactiver',
|
||||
enable: 'Activer',
|
||||
disable: 'Désactiver',
|
||||
'surveillance-on': 'Mettre sous enquête',
|
||||
'surveillance-off': 'Retirer de l’enquête',
|
||||
'suspend-users': 'Suspendre les utilisateurs',
|
||||
};
|
||||
export function bulkActionLabel(t: TFunction, action: ReportBulkAction): string {
|
||||
return t(`admin.reports.detail.bulkActions.${action}`);
|
||||
}
|
||||
|
||||
export const BULK_ACTION_CONFIRM: Partial<Record<ReportBulkAction, string>> = {
|
||||
suspend: 'Suspendre les comptes sélectionnés (retraits bloqués + sous enquête) ?',
|
||||
reactivate: 'Réactiver les comptes sélectionnés ?',
|
||||
enable: 'Activer les comptes sélectionnés ?',
|
||||
disable: 'Désactiver les comptes sélectionnés ?',
|
||||
'surveillance-on': 'Mettre les comptes sélectionnés sous enquête ?',
|
||||
'surveillance-off': 'Retirer les comptes sélectionnés de l’enquête ?',
|
||||
'suspend-users': 'Suspendre les utilisateurs liés aux lignes sélectionnées ?',
|
||||
};
|
||||
export function bulkActionConfirm(t: TFunction, action: ReportBulkAction): string {
|
||||
return t(`admin.reports.detail.bulkConfirm.${action}`);
|
||||
}
|
||||
|
||||
export type BulkActionResult = {
|
||||
succeeded: string[];
|
||||
|
||||
@ -36,7 +36,8 @@ import PlayArrowRoundedIcon from '@mui/icons-material/PlayArrowRounded';
|
||||
import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
|
||||
import NotificationsActiveRoundedIcon from '@mui/icons-material/NotificationsActiveRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
@ -120,6 +121,7 @@ function ListPagination({
|
||||
total: number;
|
||||
onPageChange: (page: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
||||
const from = total === 0 ? 0 : page * pageSize + 1;
|
||||
const to = Math.min(total, (page + 1) * pageSize);
|
||||
@ -133,7 +135,9 @@ function ListPagination({
|
||||
sx={{ alignItems: 'center', justifyContent: 'space-between', mt: 2 }}
|
||||
>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{total > 0 ? `${from}–${to} of ${total}` : 'No results'}
|
||||
{total > 0
|
||||
? t('common.pagination', { from, to, total })
|
||||
: t('common.noResults')}
|
||||
</Typography>
|
||||
<Pagination
|
||||
count={pageCount}
|
||||
@ -148,6 +152,7 @@ function ListPagination({
|
||||
}
|
||||
|
||||
export function SecurityAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [searchParams] = useSearchParams();
|
||||
const [tab, setTab] = useState(0);
|
||||
@ -167,7 +172,10 @@ export function SecurityAdminPage() {
|
||||
amountDisplay: '',
|
||||
reason: '',
|
||||
});
|
||||
const [integrityResult, setIntegrityResult] = useState<string | null>(null);
|
||||
const [integrityAlert, setIntegrityAlert] = useState<{
|
||||
severity: 'success' | 'error';
|
||||
message: string;
|
||||
} | null>(null);
|
||||
const [tamperExporting, setTamperExporting] = useState(false);
|
||||
const [alertsPage, setAlertsPage] = useState(0);
|
||||
const [notificationsPage, setNotificationsPage] = useState(0);
|
||||
@ -276,8 +284,8 @@ export function SecurityAdminPage() {
|
||||
|
||||
const creditDestinationLabel =
|
||||
creditForm.adjustmentType === 'bonus'
|
||||
? 'Credits the user bonus wallet (account_kind = bonus).'
|
||||
: 'Credits the user main wallet (account_kind = main) — used for gameplay and withdrawals.';
|
||||
? t('admin.security.credits.bonusHint')
|
||||
: t('admin.security.credits.mainHint');
|
||||
|
||||
const openResolveDialog = (alertId: string) => {
|
||||
setResolveId(alertId);
|
||||
@ -299,8 +307,8 @@ export function SecurityAdminPage() {
|
||||
setResolveError(null);
|
||||
setResolveToast(
|
||||
variables.reactivateWithdrawals
|
||||
? 'Alert resolved and user security hold cleared.'
|
||||
: 'Alert resolved.'
|
||||
? t('admin.security.resolve.successReactivate')
|
||||
: t('admin.security.resolve.success')
|
||||
);
|
||||
void qc.invalidateQueries({ queryKey: ['admin-security-alerts'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-notifications'] });
|
||||
@ -311,7 +319,7 @@ export function SecurityAdminPage() {
|
||||
},
|
||||
onError: (e: unknown) => {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
setResolveError(err?.response?.data?.error ?? err?.message ?? 'Failed to resolve alert');
|
||||
setResolveError(err?.response?.data?.error ?? err?.message ?? t('admin.security.resolve.failed'));
|
||||
},
|
||||
});
|
||||
|
||||
@ -324,11 +332,13 @@ export function SecurityAdminPage() {
|
||||
const integrityMut = useMutation({
|
||||
mutationFn: () => api.post<{ issuesFound: number; issues: unknown[] }>('/api/v1/admin/security/integrity-check'),
|
||||
onSuccess: (res) => {
|
||||
setIntegrityResult(
|
||||
res.data.issuesFound === 0
|
||||
? 'Integrity check passed — no issues found.'
|
||||
: `Found ${res.data.issuesFound} issue(s). Affected users were placed under security hold.`
|
||||
);
|
||||
setIntegrityAlert({
|
||||
severity: res.data.issuesFound === 0 ? 'success' : 'error',
|
||||
message:
|
||||
res.data.issuesFound === 0
|
||||
? t('admin.security.integrity.passed')
|
||||
: t('admin.security.integrity.issuesFound', { count: res.data.issuesFound }),
|
||||
});
|
||||
void qc.invalidateQueries({ queryKey: ['admin-security-alerts'] });
|
||||
},
|
||||
});
|
||||
@ -336,11 +346,13 @@ export function SecurityAdminPage() {
|
||||
const tamperCheckMut = useMutation({
|
||||
mutationFn: () => api.post<{ processed: number }>('/api/v1/admin/security/db-tamper-check'),
|
||||
onSuccess: (res) => {
|
||||
setIntegrityResult(
|
||||
res.data.processed === 0
|
||||
? 'DB tamper check — no pending unauthorized changes.'
|
||||
: `Processed ${res.data.processed} unauthorized DB change(s) and raised alerts.`
|
||||
);
|
||||
setIntegrityAlert({
|
||||
severity: res.data.processed === 0 ? 'success' : 'error',
|
||||
message:
|
||||
res.data.processed === 0
|
||||
? t('admin.security.integrity.tamperNone')
|
||||
: t('admin.security.integrity.tamperProcessed', { count: res.data.processed }),
|
||||
});
|
||||
void qc.invalidateQueries({ queryKey: ['admin-db-tamper-events'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-security-alerts'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-notifications'] });
|
||||
@ -354,7 +366,7 @@ export function SecurityAdminPage() {
|
||||
'/api/v1/admin/security/dismiss-spurious-tamper-alerts'
|
||||
),
|
||||
onSuccess: (res) => {
|
||||
setIntegrityResult(res.data.message);
|
||||
setIntegrityAlert({ severity: 'success', message: res.data.message });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-security-alerts'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-notifications'] });
|
||||
setAlertsPage(0);
|
||||
@ -397,7 +409,7 @@ export function SecurityAdminPage() {
|
||||
const decimals = wt?.decimals ?? USDT_DECIMALS;
|
||||
const amountRaw = humanToRaw(creditForm.amountDisplay, decimals);
|
||||
if (amountRaw === '0') {
|
||||
throw new Error('Enter a valid amount greater than zero');
|
||||
throw new Error(t('admin.security.credits.invalidAmount'));
|
||||
}
|
||||
const res = await api.post<{ message?: string }>(
|
||||
`/api/v1/admin/users/${creditForm.userId.trim()}/ledger-credit`,
|
||||
@ -412,8 +424,7 @@ export function SecurityAdminPage() {
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
setCreditSuccess(
|
||||
data.message ??
|
||||
'Credit request submitted — pending super-admin approval.'
|
||||
data.message ?? t('admin.security.credits.pendingApproval')
|
||||
);
|
||||
setCreditOpen(false);
|
||||
setCreditForm({
|
||||
@ -438,10 +449,10 @@ export function SecurityAdminPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<SecurityRoundedIcon color="warning" sx={{ fontSize: 36 }} />}
|
||||
title="Security"
|
||||
title={t('admin.security.title')}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh security data"
|
||||
label={t('admin.security.refresh')}
|
||||
onClick={() => {
|
||||
void alertsQ.refetch();
|
||||
void notificationsQ.refetch();
|
||||
@ -468,7 +479,7 @@ export function SecurityAdminPage() {
|
||||
onClick={() => integrityMut.mutate()}
|
||||
sx={{ width: { xs: '100%', sm: 'auto' } }}
|
||||
>
|
||||
Run integrity check
|
||||
{t('admin.security.actions.runIntegrity')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
@ -479,7 +490,7 @@ export function SecurityAdminPage() {
|
||||
onClick={() => tamperCheckMut.mutate()}
|
||||
sx={{ width: { xs: '100%', sm: 'auto' } }}
|
||||
>
|
||||
Process DB tamper events
|
||||
{t('admin.security.actions.processTamper')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@ -489,13 +500,13 @@ export function SecurityAdminPage() {
|
||||
onClick={() => dismissSpuriousMut.mutate()}
|
||||
sx={{ width: { xs: '100%', sm: 'auto' } }}
|
||||
>
|
||||
Dismiss false alerts
|
||||
{t('admin.security.actions.dismissFalse')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{integrityResult && (
|
||||
<Alert severity={integrityResult.includes('passed') ? 'success' : 'error'} sx={{ mb: 2 }}>
|
||||
{integrityResult}
|
||||
{integrityAlert && (
|
||||
<Alert severity={integrityAlert.severity} sx={{ mb: 2 }}>
|
||||
{integrityAlert.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -507,20 +518,20 @@ export function SecurityAdminPage() {
|
||||
allowScrollButtonsMobile
|
||||
sx={{ mb: 2 }}
|
||||
>
|
||||
<Tab label={`Alerts (${alertsQ.data?.total ?? 0})`} />
|
||||
<Tab label={t('admin.security.tabs.alerts', { count: alertsQ.data?.total ?? 0 })} />
|
||||
<Tab
|
||||
label={
|
||||
<Stack direction="row" spacing={0.5} sx={{ alignItems: 'center' }}>
|
||||
<span>Notifications</span>
|
||||
<span>{t('admin.security.tabs.notifications')}</span>
|
||||
{(notificationsQ.data?.unreadCount ?? 0) > 0 && (
|
||||
<Chip size="small" color="error" label={notificationsQ.data?.unreadCount} />
|
||||
)}
|
||||
</Stack>
|
||||
}
|
||||
/>
|
||||
<Tab label="Ledger credits" />
|
||||
<Tab label={`DB audit (${tamperEventsQ.data?.total ?? 0})`} />
|
||||
<Tab label="Alert emails" />
|
||||
<Tab label={t('admin.security.tabs.ledgerCredits')} />
|
||||
<Tab label={t('admin.security.tabs.dbAudit', { count: tamperEventsQ.data?.total ?? 0 })} />
|
||||
<Tab label={t('admin.security.tabs.alertEmails')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 0 && (
|
||||
@ -528,27 +539,27 @@ export function SecurityAdminPage() {
|
||||
<CardContent>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2 }}>
|
||||
<Chip
|
||||
label="Open"
|
||||
label={t('admin.security.alerts.open')}
|
||||
color={alertFilter === 'open' ? 'primary' : 'default'}
|
||||
onClick={() => setAlertFilter('open')}
|
||||
/>
|
||||
<Chip
|
||||
label="All"
|
||||
label={t('admin.security.alerts.all')}
|
||||
color={alertFilter === 'all' ? 'primary' : 'default'}
|
||||
onClick={() => setAlertFilter('all')}
|
||||
/>
|
||||
</Stack>
|
||||
{alertsQ.isError && <Alert severity="error">Failed to load alerts.</Alert>}
|
||||
{alertsQ.isError && <Alert severity="error">{t('admin.security.alerts.loadError')}</Alert>}
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Severity</TableCell>
|
||||
<TableCell>Title</TableCell>
|
||||
<TableCell>Type</TableCell>
|
||||
<TableCell>User</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Created</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.severity')}</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.title')}</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.type')}</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.user')}</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.status')}</TableCell>
|
||||
<TableCell>{t('admin.security.alerts.created')}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@ -578,7 +589,7 @@ export function SecurityAdminPage() {
|
||||
<TableCell>
|
||||
{a.status === 'open' && (
|
||||
<Button size="small" onClick={() => openResolveDialog(a.id)}>
|
||||
Resolve
|
||||
{t('admin.security.alerts.resolve')}
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
@ -587,7 +598,7 @@ export function SecurityAdminPage() {
|
||||
{alerts.length === 0 && !alertsQ.isLoading && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} align="center">
|
||||
No alerts
|
||||
{t('admin.security.alerts.empty')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@ -613,7 +624,7 @@ export function SecurityAdminPage() {
|
||||
sx={{ mb: 2, justifyContent: 'space-between', alignItems: { sm: 'center' } }}
|
||||
>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800 }}>
|
||||
In-app notifications
|
||||
{t('admin.security.notifications.title')}
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
@ -621,7 +632,7 @@ export function SecurityAdminPage() {
|
||||
disabled={(notificationsQ.data?.unreadCount ?? 0) === 0}
|
||||
onClick={() => markAllReadMut.mutate()}
|
||||
>
|
||||
Mark all read
|
||||
{t('admin.security.notifications.markAllRead')}
|
||||
</Button>
|
||||
</Stack>
|
||||
<Stack spacing={1}>
|
||||
@ -641,7 +652,7 @@ export function SecurityAdminPage() {
|
||||
<Typography sx={{ fontWeight: 700, flex: 1 }}>{n.title}</Typography>
|
||||
{!n.readAt && (
|
||||
<Button size="small" onClick={() => markReadMut.mutate(n.id)}>
|
||||
Mark read
|
||||
{t('admin.security.notifications.markRead')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
@ -656,7 +667,7 @@ export function SecurityAdminPage() {
|
||||
</Box>
|
||||
))}
|
||||
{notifications.length === 0 && !notificationsQ.isLoading && (
|
||||
<Typography sx={{ opacity: 0.6, textAlign: 'center', py: 3 }}>No notifications</Typography>
|
||||
<Typography sx={{ opacity: 0.6, textAlign: 'center', py: 3 }}>{t('admin.security.notifications.empty')}</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
<ListPagination
|
||||
@ -678,21 +689,21 @@ export function SecurityAdminPage() {
|
||||
sx={{ mb: 2, justifyContent: 'space-between', alignItems: { sm: 'center' } }}
|
||||
>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800 }}>
|
||||
Approved ledger credits
|
||||
{t('admin.security.credits.title')}
|
||||
</Typography>
|
||||
<Button variant="contained" onClick={() => setCreditOpen(true)} sx={{ alignSelf: { xs: 'stretch', sm: 'auto' } }}>
|
||||
Grant credit
|
||||
{t('admin.security.credits.grant')}
|
||||
</Button>
|
||||
</Stack>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Type</TableCell>
|
||||
<TableCell>User</TableCell>
|
||||
<TableCell>Amount</TableCell>
|
||||
<TableCell>Approved by</TableCell>
|
||||
<TableCell>Date</TableCell>
|
||||
<TableCell>{t('common.type')}</TableCell>
|
||||
<TableCell>{t('admin.security.credits.user')}</TableCell>
|
||||
<TableCell>{t('admin.security.credits.amount')}</TableCell>
|
||||
<TableCell>{t('admin.security.credits.approvedBy')}</TableCell>
|
||||
<TableCell>{t('admin.security.credits.date')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -717,7 +728,7 @@ export function SecurityAdminPage() {
|
||||
{credits.length === 0 && !creditsQ.isLoading && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} align="center">
|
||||
No credits yet
|
||||
{t('admin.security.credits.empty')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@ -738,10 +749,10 @@ export function SecurityAdminPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Direct database changes (audit trail)
|
||||
{t('admin.security.dbAudit.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mb: 2 }}>
|
||||
Modifications detected outside the application layer (psql, pgAdmin, scripts, etc.).
|
||||
{t('admin.security.dbAudit.subtitle')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2, flexWrap: 'wrap' }}>
|
||||
<Button
|
||||
@ -751,21 +762,21 @@ export function SecurityAdminPage() {
|
||||
disabled={tamperExporting}
|
||||
onClick={() => void downloadTamperCsv()}
|
||||
>
|
||||
Export CSV
|
||||
{t('admin.security.dbAudit.exportCsv')}
|
||||
</Button>
|
||||
</Stack>
|
||||
{tamperEventsQ.isError && <Alert severity="error">Failed to load DB audit events.</Alert>}
|
||||
{tamperEventsQ.isError && <Alert severity="error">{t('admin.security.dbAudit.loadError')}</Alert>}
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Severity</TableCell>
|
||||
<TableCell>Table</TableCell>
|
||||
<TableCell>Op</TableCell>
|
||||
<TableCell>Columns</TableCell>
|
||||
<TableCell>Source</TableCell>
|
||||
<TableCell>Processed</TableCell>
|
||||
<TableCell>When</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.severity')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.table')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.op')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.columns')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.source')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.processed')}</TableCell>
|
||||
<TableCell>{t('admin.security.dbAudit.when')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -782,14 +793,14 @@ export function SecurityAdminPage() {
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>{ev.sourceHint}</TableCell>
|
||||
<TableCell>{ev.processedAt ? 'Yes' : 'Pending'}</TableCell>
|
||||
<TableCell>{ev.processedAt ? t('admin.security.dbAudit.processedYes') : t('admin.security.dbAudit.processedPending')}</TableCell>
|
||||
<TableCell>{new Date(ev.createdAt).toLocaleString()}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{(tamperEventsQ.data?.items ?? []).length === 0 && !tamperEventsQ.isLoading && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} align="center">
|
||||
No direct DB changes recorded
|
||||
{t('admin.security.dbAudit.empty')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
@ -810,10 +821,10 @@ export function SecurityAdminPage() {
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Security alert emails
|
||||
{t('admin.security.alertEmails.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mb: 2 }}>
|
||||
One email per line. Encrypted at rest in the database.
|
||||
{t('admin.security.alertEmails.subtitle')}
|
||||
</Typography>
|
||||
<TextField
|
||||
multiline
|
||||
@ -821,7 +832,7 @@ export function SecurityAdminPage() {
|
||||
fullWidth
|
||||
value={emailsText}
|
||||
onChange={(e) => setEmailsText(e.target.value)}
|
||||
placeholder="admin@example.com"
|
||||
placeholder={t('admin.security.alertEmails.placeholder')}
|
||||
/>
|
||||
<Button
|
||||
sx={{ mt: 2 }}
|
||||
@ -835,11 +846,11 @@ export function SecurityAdminPage() {
|
||||
settingsMut.mutate(alertEmails);
|
||||
}}
|
||||
>
|
||||
Save emails
|
||||
{t('admin.security.alertEmails.save')}
|
||||
</Button>
|
||||
{settingsMut.isSuccess && (
|
||||
<Alert severity="success" sx={{ mt: 2 }}>
|
||||
Settings saved
|
||||
{t('admin.security.alertEmails.saved')}
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
@ -868,10 +879,10 @@ export function SecurityAdminPage() {
|
||||
});
|
||||
}}
|
||||
>
|
||||
<DialogTitle>Resolve alert</DialogTitle>
|
||||
<DialogTitle>{t('admin.security.resolve.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
label="Resolution note"
|
||||
label={t('admin.security.resolve.note')}
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={3}
|
||||
@ -887,7 +898,7 @@ export function SecurityAdminPage() {
|
||||
onChange={(e) => setReactivate(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Reactivate withdrawals and clear security hold for user"
|
||||
label={t('admin.security.resolve.reactivate')}
|
||||
/>
|
||||
{resolveError && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
@ -904,10 +915,10 @@ export function SecurityAdminPage() {
|
||||
}}
|
||||
disabled={resolveMut.isPending}
|
||||
>
|
||||
Cancel
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="submit" variant="contained" disabled={resolveMut.isPending}>
|
||||
{resolveMut.isPending ? 'Resolving…' : 'Resolve'}
|
||||
{resolveMut.isPending ? t('admin.security.resolve.resolving') : t('admin.security.resolve.resolve')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Box>
|
||||
@ -921,19 +932,19 @@ export function SecurityAdminPage() {
|
||||
/>
|
||||
|
||||
<Dialog open={creditOpen} onClose={() => setCreditOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Grant ledger credit</DialogTitle>
|
||||
<DialogTitle>{t('admin.security.credits.dialogTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
<TextField
|
||||
label="User ID (UUID)"
|
||||
label={t('admin.security.credits.userId')}
|
||||
fullWidth
|
||||
value={creditForm.userId}
|
||||
onChange={(e) => setCreditForm((f) => ({ ...f, userId: e.target.value }))}
|
||||
/>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Wallet</InputLabel>
|
||||
<InputLabel>{t('admin.security.credits.wallet')}</InputLabel>
|
||||
<Select
|
||||
label="Wallet"
|
||||
label={t('admin.security.credits.wallet')}
|
||||
value={creditForm.walletTypeId}
|
||||
onChange={(e) =>
|
||||
setCreditForm((f) => ({ ...f, walletTypeId: Number(e.target.value) }))
|
||||
@ -947,9 +958,9 @@ export function SecurityAdminPage() {
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Type</InputLabel>
|
||||
<InputLabel>{t('common.type')}</InputLabel>
|
||||
<Select
|
||||
label="Type"
|
||||
label={t('common.type')}
|
||||
value={creditForm.adjustmentType}
|
||||
onChange={(e) =>
|
||||
setCreditForm((f) => ({
|
||||
@ -958,21 +969,21 @@ export function SecurityAdminPage() {
|
||||
}))
|
||||
}
|
||||
>
|
||||
<MenuItem value="bonus">Bonus (bonus wallet)</MenuItem>
|
||||
<MenuItem value="admin_adjustment">Admin adjustment (main wallet)</MenuItem>
|
||||
<MenuItem value="bonus">{t('admin.security.credits.bonusWallet')}</MenuItem>
|
||||
<MenuItem value="admin_adjustment">{t('admin.security.credits.mainWallet')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Typography variant="caption" sx={{ opacity: 0.75, mt: -1 }}>
|
||||
{creditDestinationLabel}
|
||||
</Typography>
|
||||
<TextField
|
||||
label="Amount (display units)"
|
||||
label={t('admin.security.credits.amountDisplay')}
|
||||
fullWidth
|
||||
value={creditForm.amountDisplay}
|
||||
onChange={(e) => setCreditForm((f) => ({ ...f, amountDisplay: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
label="Reason (required, audited)"
|
||||
label={t('admin.security.credits.reason')}
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
@ -984,13 +995,13 @@ export function SecurityAdminPage() {
|
||||
{(creditMut.error as { response?: { data?: { error?: string } }; message?: string })
|
||||
?.response?.data?.error ??
|
||||
(creditMut.error as Error)?.message ??
|
||||
'Credit failed'}
|
||||
t('admin.security.credits.failed')}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setCreditOpen(false)}>Cancel</Button>
|
||||
<Button onClick={() => setCreditOpen(false)}>{t('common.cancel')}</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={
|
||||
@ -1001,7 +1012,7 @@ export function SecurityAdminPage() {
|
||||
}
|
||||
onClick={() => creditMut.mutate()}
|
||||
>
|
||||
Approve credit
|
||||
{t('admin.security.credits.approve')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -22,10 +22,12 @@ import SaveRoundedIcon from '@mui/icons-material/SaveRounded';
|
||||
import RestartAltRoundedIcon from '@mui/icons-material/RestartAltRounded';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
|
||||
/** Editable password policy and token expiration settings form. */
|
||||
export function SettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
type Settings = {
|
||||
password_min_length: number;
|
||||
password_require_uppercase: boolean;
|
||||
@ -88,7 +90,7 @@ export function SettingsPage() {
|
||||
setForm(null);
|
||||
setSaved(true);
|
||||
} catch (e: any) {
|
||||
setSaveError(e?.response?.data?.error ?? e?.message ?? 'Failed to save settings');
|
||||
setSaveError(e?.response?.data?.error ?? e?.message ?? t('admin.settings.saveFailed'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@ -98,18 +100,16 @@ export function SettingsPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, letterSpacing: 0.2 }}>
|
||||
Settings
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>
|
||||
Password policy, security, rate limits, withdrawals, and Candle Predict engine tuning.
|
||||
{t('admin.settings.title')}
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.settings.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<Card sx={{ mt: 2.5, borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
{q.isLoading ? (
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Loading settings…
|
||||
{t('admin.settings.loading')}
|
||||
</Alert>
|
||||
) : q.isError ? (
|
||||
<Alert
|
||||
@ -117,15 +117,15 @@ export function SettingsPage() {
|
||||
sx={{ borderRadius: 2 }}
|
||||
action={
|
||||
<Button color="inherit" size="small" onClick={() => q.refetch()}>
|
||||
Retry
|
||||
{t('admin.settings.retry')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Failed to load settings.
|
||||
{t('admin.settings.loadError')}
|
||||
</Alert>
|
||||
) : !effective ? (
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
No settings loaded.
|
||||
{t('admin.settings.noSettings')}
|
||||
</Alert>
|
||||
) : (
|
||||
<Stack spacing={2}>
|
||||
@ -136,16 +136,16 @@ export function SettingsPage() {
|
||||
)}
|
||||
{saved && (
|
||||
<Alert severity="success" sx={{ borderRadius: 2 }}>
|
||||
Settings saved.
|
||||
{t('admin.settings.saved')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Password policy</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.passwordPolicy.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Enforce complexity rules for all new passwords.
|
||||
{t('admin.settings.sections.passwordPolicy.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -160,7 +160,7 @@ export function SettingsPage() {
|
||||
>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 4' } }}>
|
||||
<TextField
|
||||
label="Minimum length"
|
||||
label={t('admin.settings.sections.passwordPolicy.minLength')}
|
||||
value={effective.password_min_length}
|
||||
onChange={(e) => set('password_min_length', parseInt(e.target.value || '0', 10) || 0)}
|
||||
type="number"
|
||||
@ -180,7 +180,7 @@ export function SettingsPage() {
|
||||
onChange={(e) => set('password_require_uppercase', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Uppercase"
|
||||
label={t('admin.settings.sections.passwordPolicy.uppercase')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -189,7 +189,7 @@ export function SettingsPage() {
|
||||
onChange={(e) => set('password_require_lowercase', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Lowercase"
|
||||
label={t('admin.settings.sections.passwordPolicy.lowercase')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -198,7 +198,7 @@ export function SettingsPage() {
|
||||
onChange={(e) => set('password_require_number', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Number"
|
||||
label={t('admin.settings.sections.passwordPolicy.number')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
@ -207,7 +207,7 @@ export function SettingsPage() {
|
||||
onChange={(e) => set('password_require_special', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Special"
|
||||
label={t('admin.settings.sections.passwordPolicy.special')}
|
||||
/>
|
||||
</Stack>
|
||||
</Box>
|
||||
@ -218,9 +218,9 @@ export function SettingsPage() {
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Email verification</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.emailVerification.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Require confirmed email before users can sign in.
|
||||
{t('admin.settings.sections.emailVerification.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -234,7 +234,7 @@ export function SettingsPage() {
|
||||
}
|
||||
/>
|
||||
}
|
||||
label="Block login until email is verified"
|
||||
label={t('admin.settings.sections.emailVerification.blockLogin')}
|
||||
/>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
@ -242,9 +242,9 @@ export function SettingsPage() {
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Token expiration</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.tokenExpiration.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Change expiry without redeploying the backend.
|
||||
{t('admin.settings.sections.tokenExpiration.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -258,8 +258,8 @@ export function SettingsPage() {
|
||||
>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Access token expiry"
|
||||
helperText="Examples: 15m, 1h"
|
||||
label={t('admin.settings.sections.tokenExpiration.accessToken')}
|
||||
helperText={t('admin.settings.sections.tokenExpiration.examplesShort')}
|
||||
value={effective.access_token_expiry}
|
||||
onChange={(e) => set('access_token_expiry', e.target.value)}
|
||||
fullWidth
|
||||
@ -267,8 +267,8 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Refresh token expiry"
|
||||
helperText="Examples: 7d, 30d"
|
||||
label={t('admin.settings.sections.tokenExpiration.refreshToken')}
|
||||
helperText={t('admin.settings.sections.tokenExpiration.examplesLong')}
|
||||
value={effective.refresh_token_expiry}
|
||||
onChange={(e) => set('refresh_token_expiry', e.target.value)}
|
||||
fullWidth
|
||||
@ -281,9 +281,9 @@ export function SettingsPage() {
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Withdrawals & safety</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.withdrawals.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Kill-switch and withdrawal limits (applied immediately after save).
|
||||
{t('admin.settings.sections.withdrawals.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -296,7 +296,7 @@ export function SettingsPage() {
|
||||
onChange={(e) => set('allow_withdrawals', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Allow on-chain withdrawals"
|
||||
label={t('admin.settings.sections.withdrawals.allowOnChain')}
|
||||
/>
|
||||
<Box
|
||||
sx={{
|
||||
@ -307,7 +307,7 @@ export function SettingsPage() {
|
||||
>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Daily withdrawal limit (USD)"
|
||||
label={t('admin.settings.sections.withdrawals.dailyLimit')}
|
||||
type="number"
|
||||
value={effective.daily_withdrawal_limit_usd}
|
||||
onChange={(e) =>
|
||||
@ -318,7 +318,7 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Large withdrawal threshold (USD)"
|
||||
label={t('admin.settings.sections.withdrawals.largeThreshold')}
|
||||
type="number"
|
||||
value={effective.large_withdrawal_threshold_usd}
|
||||
onChange={(e) =>
|
||||
@ -329,7 +329,7 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Withdrawal network fee (USDT)"
|
||||
label={t('admin.settings.sections.withdrawals.networkFee')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { min: 0, step: 0.01 } }}
|
||||
value={(effective.withdrawal_network_fee_usdt_micro / 1_000_000).toFixed(2)}
|
||||
@ -342,7 +342,7 @@ export function SettingsPage() {
|
||||
: 0
|
||||
);
|
||||
}}
|
||||
helperText="Deducted from the user's USDT balance per withdrawal (covers on-chain TRON gas)."
|
||||
helperText={t('admin.settings.sections.withdrawals.networkFeeHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
</Box>
|
||||
@ -354,9 +354,9 @@ export function SettingsPage() {
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Rate limiting</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.rateLimiting.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
API and login throttling. Max limits apply within seconds; window size needs a restart.
|
||||
{t('admin.settings.sections.rateLimiting.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -370,8 +370,8 @@ export function SettingsPage() {
|
||||
>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 4' } }}>
|
||||
<TextField
|
||||
label="API window (ms)"
|
||||
helperText="Restart server to apply"
|
||||
label={t('admin.settings.sections.rateLimiting.apiWindow')}
|
||||
helperText={t('admin.settings.sections.rateLimiting.restartHint')}
|
||||
type="number"
|
||||
value={effective.rate_limit_window_ms}
|
||||
onChange={(e) => set('rate_limit_window_ms', parseNum(e.target.value))}
|
||||
@ -380,7 +380,7 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 4' } }}>
|
||||
<TextField
|
||||
label="API max requests / window"
|
||||
label={t('admin.settings.sections.rateLimiting.apiMax')}
|
||||
type="number"
|
||||
value={effective.rate_limit_max}
|
||||
onChange={(e) => set('rate_limit_max', parseNum(e.target.value))}
|
||||
@ -389,7 +389,7 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 4' } }}>
|
||||
<TextField
|
||||
label="Login max attempts / 15 min"
|
||||
label={t('admin.settings.sections.rateLimiting.loginMax')}
|
||||
type="number"
|
||||
value={effective.login_rate_limit_max}
|
||||
onChange={(e) => set('login_rate_limit_max', parseNum(e.target.value))}
|
||||
@ -403,9 +403,9 @@ export function SettingsPage() {
|
||||
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
|
||||
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
|
||||
<Box>
|
||||
<Typography sx={{ fontWeight: 900 }}>Candle Predict engine</Typography>
|
||||
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.candlePredict.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
Tick interval and backfill pacing (lower backfill = less DB load at scale).
|
||||
{t('admin.settings.sections.candlePredict.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</AccordionSummary>
|
||||
@ -419,8 +419,8 @@ export function SettingsPage() {
|
||||
>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Engine tick (ms)"
|
||||
helperText="How often rounds are settled"
|
||||
label={t('admin.settings.sections.candlePredict.engineTick')}
|
||||
helperText={t('admin.settings.sections.candlePredict.engineTickHelper')}
|
||||
type="number"
|
||||
value={effective.candle_predict_engine_tick_ms}
|
||||
onChange={(e) =>
|
||||
@ -431,8 +431,8 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Backfill interval (ms)"
|
||||
helperText="Min delay between backfill runs"
|
||||
label={t('admin.settings.sections.candlePredict.backfillInterval')}
|
||||
helperText={t('admin.settings.sections.candlePredict.backfillIntervalHelper')}
|
||||
type="number"
|
||||
value={effective.candle_predict_backfill_interval_ms}
|
||||
onChange={(e) =>
|
||||
@ -443,8 +443,8 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Backfill max per tick"
|
||||
helperText="Candles filled per interval per run"
|
||||
label={t('admin.settings.sections.candlePredict.backfillMax')}
|
||||
helperText={t('admin.settings.sections.candlePredict.backfillMaxHelper')}
|
||||
type="number"
|
||||
value={effective.candle_predict_backfill_max_per_tick}
|
||||
onChange={(e) =>
|
||||
@ -455,8 +455,8 @@ export function SettingsPage() {
|
||||
</Box>
|
||||
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
|
||||
<TextField
|
||||
label="Backfill seed max"
|
||||
helperText="Historical candles on first run"
|
||||
label={t('admin.settings.sections.candlePredict.backfillSeed')}
|
||||
helperText={t('admin.settings.sections.candlePredict.backfillSeedHelper')}
|
||||
type="number"
|
||||
value={effective.candle_predict_backfill_seed_max}
|
||||
onChange={(e) =>
|
||||
@ -475,7 +475,7 @@ export function SettingsPage() {
|
||||
disabled={saving}
|
||||
startIcon={<RestartAltRoundedIcon />}
|
||||
>
|
||||
Reset
|
||||
{t('admin.settings.reset')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
@ -483,7 +483,7 @@ export function SettingsPage() {
|
||||
disabled={saving}
|
||||
startIcon={<SaveRoundedIcon />}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save settings'}
|
||||
{saving ? t('admin.settings.saving') : t('admin.settings.save')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@ -22,6 +22,7 @@ import SendRoundedIcon from '@mui/icons-material/SendRounded';
|
||||
import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import {
|
||||
adminFetchMessages,
|
||||
@ -39,12 +40,7 @@ import { notifySupportMessage, requestSupportNotificationPermission } from './ut
|
||||
import type { SupportConversation, SupportMessage } from './types';
|
||||
import type { SupportWsServerMessage } from './ws/protocol';
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
open: 'Ouverte',
|
||||
pending: 'En attente',
|
||||
resolved: 'Résolue',
|
||||
closed: 'Fermée',
|
||||
};
|
||||
const STATUS_KEYS = ['open', 'pending', 'resolved', 'closed'] as const;
|
||||
|
||||
const STATUS_COLORS: Record<string, 'success' | 'warning' | 'default' | 'info'> = {
|
||||
open: 'success',
|
||||
@ -56,9 +52,11 @@ const STATUS_COLORS: Record<string, 'success' | 'warning' | 'default' | 'info'>
|
||||
function AdminMessageList({
|
||||
messages,
|
||||
staffTyping,
|
||||
t,
|
||||
}: {
|
||||
messages: SupportMessage[];
|
||||
staffTyping?: boolean;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<Box sx={{ flex: 1, overflowY: 'auto', p: 2 }}>
|
||||
@ -77,7 +75,7 @@ function AdminMessageList({
|
||||
>
|
||||
{!isStaff && (
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, opacity: 0.7 }}>
|
||||
{msg.senderType === 'visitor' ? 'Visiteur' : 'Utilisateur'}
|
||||
{msg.senderType === 'visitor' ? t('admin.supportAdmin.visitor') : t('admin.supportAdmin.user')}
|
||||
</Typography>
|
||||
)}
|
||||
{msg.body && (
|
||||
@ -99,7 +97,7 @@ function AdminMessageList({
|
||||
)}
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, display: 'block', textAlign: 'right' }}>
|
||||
{new Date(msg.createdAt).toLocaleString()}
|
||||
{msg.readAt ? ' · Lu' : ''}
|
||||
{msg.readAt ? t('admin.supportAdmin.read') : ''}
|
||||
</Typography>
|
||||
</Paper>
|
||||
</Box>
|
||||
@ -107,7 +105,7 @@ function AdminMessageList({
|
||||
})}
|
||||
{staffTyping && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, fontStyle: 'italic' }}>
|
||||
Le visiteur écrit…
|
||||
{t('admin.supportAdmin.visitorTyping')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
@ -116,6 +114,7 @@ function AdminMessageList({
|
||||
|
||||
/** Admin / moderator support inbox. */
|
||||
export function SupportAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const { auth } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
@ -142,8 +141,8 @@ export function SupportAdminPage() {
|
||||
});
|
||||
} else if (msg.message && msg.message.senderType !== 'staff') {
|
||||
notifySupportMessage({
|
||||
title: 'Nouveau message support',
|
||||
body: msg.message.body ?? 'Message reçu',
|
||||
title: t('admin.supportAdmin.newMessageTitle'),
|
||||
body: msg.message.body ?? t('admin.supportAdmin.newMessageBody'),
|
||||
tag: `admin-support-${msg.conversationId}`,
|
||||
});
|
||||
}
|
||||
@ -248,7 +247,7 @@ export function SupportAdminPage() {
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 2 }}>
|
||||
<HeadsetMicRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
Centre d'assistance
|
||||
{t('admin.supportAdmin.title')}
|
||||
</Typography>
|
||||
<IconButton onClick={() => void listQ.refetch()}>
|
||||
<RefreshRoundedIcon />
|
||||
@ -267,7 +266,7 @@ export function SupportAdminPage() {
|
||||
<Paper sx={{ p: 2, borderRadius: 3, display: 'flex', flexDirection: 'column', minHeight: 400 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
placeholder="Rechercher…"
|
||||
placeholder={t('admin.supportAdmin.searchPlaceholder')}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
@ -276,20 +275,20 @@ export function SupportAdminPage() {
|
||||
sx={{ mb: 1.5 }}
|
||||
/>
|
||||
<FormControl size="small" sx={{ mb: 1.5 }}>
|
||||
<InputLabel>Statut</InputLabel>
|
||||
<InputLabel>{t('admin.supportAdmin.status')}</InputLabel>
|
||||
<Select
|
||||
label="Statut"
|
||||
label={t('admin.supportAdmin.status')}
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<MenuItem value="">Tous</MenuItem>
|
||||
<MenuItem value="open">Ouverte</MenuItem>
|
||||
<MenuItem value="pending">En attente</MenuItem>
|
||||
<MenuItem value="resolved">Résolue</MenuItem>
|
||||
<MenuItem value="closed">Fermée</MenuItem>
|
||||
<MenuItem value="">{t('admin.supportAdmin.allStatuses')}</MenuItem>
|
||||
<MenuItem value="open">{t('admin.supportAdmin.statuses.open')}</MenuItem>
|
||||
<MenuItem value="pending">{t('admin.supportAdmin.statuses.pending')}</MenuItem>
|
||||
<MenuItem value="resolved">{t('admin.supportAdmin.statuses.resolved')}</MenuItem>
|
||||
<MenuItem value="closed">{t('admin.supportAdmin.statuses.closed')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
@ -311,7 +310,7 @@ export function SupportAdminPage() {
|
||||
>
|
||||
<Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
|
||||
{c.isAnonymous ? 'Visiteur anonyme' : `Utilisateur ${c.userId?.slice(0, 8)}…`}
|
||||
{c.isAnonymous ? t('admin.supportAdmin.anonymousVisitor') : t('admin.supportAdmin.userPrefix', { id: c.userId?.slice(0, 8) })}
|
||||
</Typography>
|
||||
{c.unreadStaff > 0 && (
|
||||
<Chip size="small" color="error" label={c.unreadStaff} />
|
||||
@ -322,7 +321,11 @@ export function SupportAdminPage() {
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={STATUS_LABELS[c.status] ?? c.status}
|
||||
label={
|
||||
(STATUS_KEYS as readonly string[]).includes(c.status)
|
||||
? t(`admin.supportAdmin.statuses.${c.status as (typeof STATUS_KEYS)[number]}`)
|
||||
: c.status
|
||||
}
|
||||
color={STATUS_COLORS[c.status] ?? 'default'}
|
||||
sx={{ mt: 0.5 }}
|
||||
/>
|
||||
@ -330,7 +333,7 @@ export function SupportAdminPage() {
|
||||
))}
|
||||
{!listQ.data?.items.length && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.6, py: 2 }}>
|
||||
Aucune conversation
|
||||
{t('admin.supportAdmin.noConversations')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
@ -349,21 +352,21 @@ export function SupportAdminPage() {
|
||||
{/* Chat */}
|
||||
<Paper sx={{ borderRadius: 3, display: 'flex', flexDirection: 'column', minHeight: 400 }}>
|
||||
{!selectedId ? (
|
||||
<Typography sx={{ p: 3, opacity: 0.6 }}>Sélectionnez une conversation</Typography>
|
||||
<Typography sx={{ p: 3, opacity: 0.6 }}>{t('admin.supportAdmin.selectConversation')}</Typography>
|
||||
) : (
|
||||
<>
|
||||
<Stack direction="row" spacing={1} sx={{ p: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
|
||||
<FormControl size="small" sx={{ minWidth: 130 }}>
|
||||
<InputLabel>Statut</InputLabel>
|
||||
<InputLabel>{t('admin.supportAdmin.status')}</InputLabel>
|
||||
<Select
|
||||
label="Statut"
|
||||
label={t('admin.supportAdmin.status')}
|
||||
value={conv?.status ?? 'open'}
|
||||
onChange={(e) => updateMut.mutate({ status: e.target.value })}
|
||||
>
|
||||
<MenuItem value="open">Ouverte</MenuItem>
|
||||
<MenuItem value="pending">En attente</MenuItem>
|
||||
<MenuItem value="resolved">Résolue</MenuItem>
|
||||
<MenuItem value="closed">Fermée</MenuItem>
|
||||
<MenuItem value="open">{t('admin.supportAdmin.statuses.open')}</MenuItem>
|
||||
<MenuItem value="pending">{t('admin.supportAdmin.statuses.pending')}</MenuItem>
|
||||
<MenuItem value="resolved">{t('admin.supportAdmin.statuses.resolved')}</MenuItem>
|
||||
<MenuItem value="closed">{t('admin.supportAdmin.statuses.closed')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Button
|
||||
@ -371,18 +374,18 @@ export function SupportAdminPage() {
|
||||
variant="outlined"
|
||||
onClick={() => updateMut.mutate({ assignedTo: auth.userId })}
|
||||
>
|
||||
M'assigner
|
||||
{t('admin.supportAdmin.assignSelf')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={() => updateMut.mutate({ status: 'resolved' })}
|
||||
>
|
||||
Résolu
|
||||
{t('admin.supportAdmin.markResolved')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<AdminMessageList messages={messages} staffTyping={userTyping} />
|
||||
<AdminMessageList messages={messages} staffTyping={userTyping} t={t} />
|
||||
|
||||
<Box sx={{ p: 1.5, borderTop: '1px solid', borderColor: 'divider' }}>
|
||||
<input
|
||||
@ -401,7 +404,7 @@ export function SupportAdminPage() {
|
||||
size="small"
|
||||
multiline
|
||||
maxRows={3}
|
||||
placeholder="Répondre…"
|
||||
placeholder={t('admin.supportAdmin.replyPlaceholder')}
|
||||
value={draft}
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
@ -443,54 +446,54 @@ export function SupportAdminPage() {
|
||||
{/* User context */}
|
||||
<Paper sx={{ p: 2, borderRadius: 3, display: { xs: 'none', lg: 'block' } }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
Contexte
|
||||
{t('admin.supportAdmin.contextTitle')}
|
||||
</Typography>
|
||||
<Divider sx={{ mb: 2, opacity: 0.2 }} />
|
||||
{conv?.isAnonymous && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
Conversation anonyme — aucun compte associé.
|
||||
{t('admin.supportAdmin.anonymousAlert')}
|
||||
</Alert>
|
||||
)}
|
||||
{user ? (
|
||||
<Stack spacing={1}>
|
||||
<Typography variant="body2">
|
||||
<strong>Nom :</strong> {user.displayName ?? '—'}
|
||||
<strong>{t('admin.supportAdmin.name')}</strong> {user.displayName ?? '—'}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
<strong>ID :</strong> {user.id}
|
||||
<strong>{t('admin.supportAdmin.id')}</strong> {user.id}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
<strong>E-mail :</strong> {user.email ?? '—'}
|
||||
<strong>{t('admin.supportAdmin.email')}</strong> {user.email ?? '—'}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
<strong>Rôle :</strong> {user.role}
|
||||
<strong>{t('admin.supportAdmin.role')}</strong> {user.role}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
<strong>Statut :</strong>{' '}
|
||||
<strong>{t('admin.supportAdmin.accountStatus')}</strong>{' '}
|
||||
{user.isEnabled ? (
|
||||
<Chip size="small" color="success" label="Actif" />
|
||||
<Chip size="small" color="success" label={t('admin.supportAdmin.accountActive')} />
|
||||
) : (
|
||||
<Chip size="small" color="default" label="Désactivé" />
|
||||
<Chip size="small" color="default" label={t('admin.supportAdmin.accountDisabled')} />
|
||||
)}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
<strong>E-mail vérifié :</strong> {user.emailVerified ? 'Oui' : 'Non'}
|
||||
<strong>{t('admin.supportAdmin.emailVerified')}</strong> {user.emailVerified ? t('common.yes') : t('common.no')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
Inscrit le {new Date(user.createdAt).toLocaleDateString()}
|
||||
{t('admin.supportAdmin.registeredOn', { date: new Date(user.createdAt).toLocaleDateString() })}
|
||||
</Typography>
|
||||
</Stack>
|
||||
) : (
|
||||
!conv?.isAnonymous && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.6 }}>
|
||||
Chargement…
|
||||
{t('common.loading')}
|
||||
</Typography>
|
||||
)
|
||||
)}
|
||||
{conv && (
|
||||
<Box sx={{ mt: 3 }}>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6 }}>
|
||||
Conversation créée le {new Date(conv.createdAt).toLocaleString()}
|
||||
{t('admin.supportAdmin.conversationCreated', { date: new Date(conv.createdAt).toLocaleString() })}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@ -14,6 +14,7 @@ import DoneRoundedIcon from '@mui/icons-material/DoneRounded';
|
||||
import SendRoundedIcon from '@mui/icons-material/SendRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
attachmentFullUrl,
|
||||
fetchCurrentConversation,
|
||||
@ -33,13 +34,13 @@ function formatMessageTime(iso: string): string {
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function formatDayLabel(iso: string): string {
|
||||
function formatDayLabel(iso: string, t: (key: string) => string): string {
|
||||
const d = new Date(iso);
|
||||
const today = new Date();
|
||||
if (d.toDateString() === today.toDateString()) return "Aujourd'hui";
|
||||
if (d.toDateString() === today.toDateString()) return t('support.chat.today');
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(today.getDate() - 1);
|
||||
if (d.toDateString() === yesterday.toDateString()) return 'Hier';
|
||||
if (d.toDateString() === yesterday.toDateString()) return t('support.chat.yesterday');
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
@ -50,7 +51,15 @@ function ReadIndicator({ readAt }: { readAt: string | null }) {
|
||||
return <DoneRoundedIcon sx={{ fontSize: 14, opacity: 0.5 }} />;
|
||||
}
|
||||
|
||||
function MessageBubble({ msg, isMine }: { msg: SupportMessage; isMine: boolean }) {
|
||||
function MessageBubble({
|
||||
msg,
|
||||
isMine,
|
||||
t,
|
||||
}: {
|
||||
msg: SupportMessage;
|
||||
isMine: boolean;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const isImage = msg.attachmentMime?.startsWith('image/');
|
||||
return (
|
||||
<Box
|
||||
@ -89,7 +98,7 @@ function MessageBubble({ msg, isMine }: { msg: SupportMessage; isMine: boolean }
|
||||
<Box
|
||||
component="img"
|
||||
src={attachmentFullUrl(msg.attachmentUrl)}
|
||||
alt={msg.attachmentName ?? 'attachment'}
|
||||
alt={msg.attachmentName ?? t('support.chat.attachment')}
|
||||
sx={{ maxWidth: '100%', borderRadius: 2, display: 'block' }}
|
||||
/>
|
||||
) : (
|
||||
@ -101,7 +110,7 @@ function MessageBubble({ msg, isMine }: { msg: SupportMessage; isMine: boolean }
|
||||
variant="body2"
|
||||
sx={{ color: 'inherit', fontWeight: 600 }}
|
||||
>
|
||||
📎 {msg.attachmentName ?? 'Fichier'}
|
||||
📎 {msg.attachmentName ?? t('support.chat.file')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
@ -124,6 +133,7 @@ type Props = {
|
||||
|
||||
/** WhatsApp-style support chat panel for users and anonymous visitors. */
|
||||
export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [draft, setDraft] = useState('');
|
||||
const [messages, setMessages] = useState<SupportMessage[]>([]);
|
||||
@ -153,8 +163,8 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
});
|
||||
if (msg.message.senderType === 'staff' && !widgetOpen) {
|
||||
notifySupportMessage({
|
||||
title: 'Assistance Prediqo',
|
||||
body: msg.message.body ?? 'Nouveau message',
|
||||
title: t('support.widget.title'),
|
||||
body: msg.message.body ?? t('support.chat.newMessage'),
|
||||
tag: `support-${conversationId}`,
|
||||
onClick: onOpenWidget,
|
||||
});
|
||||
@ -173,7 +183,7 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
);
|
||||
}
|
||||
},
|
||||
[conversationId, widgetOpen, onOpenWidget, qc]
|
||||
[conversationId, widgetOpen, onOpenWidget, qc, t]
|
||||
);
|
||||
|
||||
const { connected: wsConnected } = useSupportSocket({
|
||||
@ -266,11 +276,11 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
)}
|
||||
{!convQ.isLoading && messages.length === 0 && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, textAlign: 'center', py: 3 }}>
|
||||
Bonjour ! Comment pouvons-nous vous aider ?
|
||||
{t('support.chat.greeting')}
|
||||
</Typography>
|
||||
)}
|
||||
{messages.map((msg) => {
|
||||
const day = formatDayLabel(msg.createdAt);
|
||||
const day = formatDayLabel(msg.createdAt, t);
|
||||
const showDay = day !== lastDay;
|
||||
lastDay = day;
|
||||
const isMine = msg.senderType === 'user' || msg.senderType === 'visitor';
|
||||
@ -290,13 +300,13 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
{day}
|
||||
</Typography>
|
||||
)}
|
||||
<MessageBubble msg={msg} isMine={isMine} />
|
||||
<MessageBubble msg={msg} isMine={isMine} t={t} />
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{staffTyping && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, fontStyle: 'italic', pl: 1 }}>
|
||||
L'équipe est en train d'écrire…
|
||||
{t('support.chat.typing')}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
@ -318,7 +328,7 @@ export function SupportChatPanel({ widgetOpen = true, onOpenWidget }: Props) {
|
||||
size="small"
|
||||
multiline
|
||||
maxRows={4}
|
||||
placeholder="Écrivez votre message…"
|
||||
placeholder={t('support.chat.placeholder')}
|
||||
value={draft}
|
||||
onChange={(e) => onDraftChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
|
||||
@ -11,11 +11,13 @@ import {
|
||||
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
|
||||
import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { SupportChatPanel } from './SupportChatPanel';
|
||||
import { requestSupportNotificationPermission, shouldAskNotificationPermission } from '../utils/notifications';
|
||||
|
||||
/** Floating support button — visible on all pages including login/register. */
|
||||
export function SupportWidget() {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
@ -35,7 +37,7 @@ export function SupportWidget() {
|
||||
<Zoom in={!open}>
|
||||
<Fab
|
||||
color="primary"
|
||||
aria-label="Assistance"
|
||||
aria-label={t('support.widget.ariaLabel')}
|
||||
onClick={openWidget}
|
||||
sx={{
|
||||
position: 'fixed',
|
||||
@ -83,10 +85,10 @@ export function SupportWidget() {
|
||||
<HeadsetMicRoundedIcon sx={{ mr: 1 }} />
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography variant="subtitle1" sx={{ fontWeight: 800, lineHeight: 1.2 }}>
|
||||
Assistance Prediqo
|
||||
{t('support.widget.title')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.9 }}>
|
||||
Réponse en temps réel de notre équipe
|
||||
{t('support.widget.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
<IconButton size="small" onClick={() => setOpen(false)} sx={{ color: 'inherit' }}>
|
||||
|
||||
@ -22,6 +22,7 @@ import {
|
||||
import ScienceRoundedIcon from '@mui/icons-material/ScienceRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import { humanToRaw, rawToHuman } from '../wallet/utils/walletFormat';
|
||||
@ -48,6 +49,7 @@ type CreditHistoryItem = {
|
||||
const USDT_DECIMALS = 6;
|
||||
|
||||
export function TestWalletAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [form, setForm] = useState<TestWalletConfig | null>(null);
|
||||
const [creditDisplay, setCreditDisplay] = useState('1000');
|
||||
@ -102,7 +104,7 @@ export function TestWalletAdminPage() {
|
||||
});
|
||||
|
||||
if (configQ.isLoading || !form) {
|
||||
return <Typography sx={{ p: 2 }}>Loading test wallet settings…</Typography>;
|
||||
return <Typography sx={{ p: 2 }}>{t('admin.testWallet.loading')}</Typography>;
|
||||
}
|
||||
|
||||
return (
|
||||
@ -111,17 +113,15 @@ export function TestWalletAdminPage() {
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<ScienceRoundedIcon color="success" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
Test wallet
|
||||
{t('admin.testWallet.title')}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={form.enabled ? 'Enabled' : 'Disabled'}
|
||||
label={form.enabled ? t('admin.testWallet.enabled') : t('admin.testWallet.disabled')}
|
||||
color={form.enabled ? 'success' : 'default'}
|
||||
/>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.7 }}>
|
||||
Configure play-money credits so new users can practice predictions before using real funds.
|
||||
</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.testWallet.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<Card sx={{ borderRadius: 3, mb: 3 }}>
|
||||
@ -134,57 +134,57 @@ export function TestWalletAdminPage() {
|
||||
onChange={(e) => setForm({ ...form, enabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label="Allow users to request test credits"
|
||||
label={t('admin.testWallet.allowRequests')}
|
||||
/>
|
||||
<TextField
|
||||
label="Credit amount per request (USDT)"
|
||||
label={t('admin.testWallet.creditAmount')}
|
||||
type="number"
|
||||
value={creditDisplay}
|
||||
onChange={(e) => setCreditDisplay(e.target.value)}
|
||||
helperText="Amount credited automatically when a user requests test funds"
|
||||
helperText={t('admin.testWallet.creditHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Max requests per user"
|
||||
label={t('admin.testWallet.maxRequests')}
|
||||
type="number"
|
||||
value={form.maxRequestsPerUser}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, maxRequestsPerUser: Math.max(0, Number(e.target.value) || 0) })
|
||||
}
|
||||
helperText="0 = unlimited"
|
||||
helperText={t('admin.testWallet.maxRequestsHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Cooldown between requests (hours)"
|
||||
label={t('admin.testWallet.cooldown')}
|
||||
type="number"
|
||||
value={form.cooldownHours}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, cooldownHours: Math.max(0, Number(e.target.value) || 0) })
|
||||
}
|
||||
helperText="0 = no waiting period"
|
||||
helperText={t('admin.testWallet.cooldownHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
{saveMut.isError && (
|
||||
<Alert severity="error">
|
||||
{(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error ?? 'Save failed'}
|
||||
?.error ?? t('admin.testWallet.saveFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
{saveMut.isSuccess && <Alert severity="success">Settings saved.</Alert>}
|
||||
{saveMut.isSuccess && <Alert severity="success">{t('admin.testWallet.saved')}</Alert>}
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => saveMut.mutate()}
|
||||
disabled={saveMut.isPending}
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
>
|
||||
{saveMut.isPending ? 'Saving…' : 'Save settings'}
|
||||
{saveMut.isPending ? t('admin.testWallet.saving') : t('admin.testWallet.save')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1.5 }}>
|
||||
Credit history
|
||||
{t('admin.testWallet.history')}
|
||||
</Typography>
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
|
||||
@ -192,9 +192,9 @@ export function TestWalletAdminPage() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Date</TableCell>
|
||||
<TableCell>User</TableCell>
|
||||
<TableCell align="right">Amount</TableCell>
|
||||
<TableCell>{t('admin.testWallet.date')}</TableCell>
|
||||
<TableCell>{t('admin.testWallet.user')}</TableCell>
|
||||
<TableCell align="right">{t('admin.testWallet.amount')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -212,7 +212,7 @@ export function TestWalletAdminPage() {
|
||||
{!historyQ.data?.items?.length && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} sx={{ opacity: 0.7 }}>
|
||||
No test credits granted yet.
|
||||
{t('admin.testWallet.noHistory')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
|
||||
@ -24,6 +24,7 @@ import {
|
||||
import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
@ -81,6 +82,7 @@ function formatRaw(amount: string | null, decimals: number): string {
|
||||
}
|
||||
|
||||
export function TreasuryAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [coldForms, setColdForms] = useState<Record<number, { address: string; label: string }>>({});
|
||||
const [fundingForm, setFundingForm] = useState({ walletTypeId: 2, amount: '', notes: '' });
|
||||
@ -116,7 +118,7 @@ export function TreasuryAdminPage() {
|
||||
const runSweepsMut = useMutation({
|
||||
mutationFn: () => api.post<{ message?: string }>('/api/v1/admin/treasury/sweeps/run'),
|
||||
onSuccess: (res) => {
|
||||
setPendingMsg(res.data.message ?? 'Sweep request submitted — pending super-admin approval');
|
||||
setPendingMsg(res.data.message ?? t('admin.treasury.sweepPending'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-sweeps'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] });
|
||||
},
|
||||
@ -126,7 +128,7 @@ export function TreasuryAdminPage() {
|
||||
mutationFn: (body: { walletTypeId: number; amount: string; notes?: string }) =>
|
||||
api.post<{ message?: string }>('/api/v1/admin/treasury/funding', body),
|
||||
onSuccess: (res) => {
|
||||
setPendingMsg(res.data.message ?? 'Funding request submitted — pending super-admin approval');
|
||||
setPendingMsg(res.data.message ?? t('admin.treasury.fundingPending'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] });
|
||||
setFundingForm((f) => ({ ...f, amount: '', notes: '' }));
|
||||
},
|
||||
@ -147,10 +149,10 @@ export function TreasuryAdminPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<AccountBalanceWalletRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Treasury"
|
||||
title={t('admin.treasury.title')}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh treasury"
|
||||
label={t('admin.treasury.refresh')}
|
||||
onClick={() => {
|
||||
void overviewQ.refetch();
|
||||
void sweepsQ.refetch();
|
||||
@ -167,7 +169,7 @@ export function TreasuryAdminPage() {
|
||||
|
||||
{overviewQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
Failed to load treasury overview.
|
||||
{t('admin.treasury.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -175,25 +177,23 @@ export function TreasuryAdminPage() {
|
||||
<Stack spacing={2} sx={{ mb: 3 }}>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>
|
||||
<Chip
|
||||
label={overview.sweepEnabled ? 'Sweeps enabled' : 'Sweeps disabled'}
|
||||
label={overview.sweepEnabled ? t('admin.treasury.sweepsEnabled') : t('admin.treasury.sweepsDisabled')}
|
||||
color={overview.sweepEnabled ? 'success' : 'default'}
|
||||
/>
|
||||
<Chip
|
||||
label={overview.withdrawalsEnabled ? 'Withdrawals on' : 'Withdrawals off'}
|
||||
label={overview.withdrawalsEnabled ? t('admin.treasury.withdrawalsOn') : t('admin.treasury.withdrawalsOff')}
|
||||
color={overview.withdrawalsEnabled ? 'warning' : 'default'}
|
||||
/>
|
||||
{overview.recentPendingSweeps > 0 && (
|
||||
<Chip label={`${overview.recentPendingSweeps} pending sweeps`} color="info" />
|
||||
<Chip label={t('admin.treasury.pendingSweeps', { count: overview.recentPendingSweeps })} color="info" />
|
||||
)}
|
||||
{overview.recentFailedSweeps > 0 && (
|
||||
<Chip label={`${overview.recentFailedSweeps} failed sweeps`} color="error" />
|
||||
<Chip label={t('admin.treasury.failedSweeps', { count: overview.recentFailedSweeps })} color="error" />
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
{!overview.sweepEnabled && (
|
||||
<Alert severity="info">
|
||||
Set <code>SWEEP_ENABLED=true</code> in backend .env to auto-move deposits to cold storage.
|
||||
</Alert>
|
||||
<Alert severity="info">{t('admin.treasury.sweepDisabledHint')}</Alert>
|
||||
)}
|
||||
|
||||
{overview.assets.map((asset) => {
|
||||
@ -210,18 +210,22 @@ export function TreasuryAdminPage() {
|
||||
</Typography>
|
||||
<Stack spacing={1} sx={{ mb: 2, fontFamily: 'monospace', fontSize: 13 }}>
|
||||
<Typography>
|
||||
Cold: {asset.coldWallet?.address ?? '—'} · on-chain{' '}
|
||||
{formatRaw(asset.coldOnChainBalance, wt.decimals)}
|
||||
{t('admin.treasury.coldOnChain', {
|
||||
address: asset.coldWallet?.address ?? '—',
|
||||
balance: formatRaw(asset.coldOnChainBalance, wt.decimals),
|
||||
})}
|
||||
</Typography>
|
||||
<Typography>
|
||||
Hot: {asset.hotWallet?.address ?? '—'} · on-chain{' '}
|
||||
{formatRaw(asset.hotOnChainBalance, wt.decimals)}
|
||||
{t('admin.treasury.hotOnChain', {
|
||||
address: asset.hotWallet?.address ?? '—',
|
||||
balance: formatRaw(asset.hotOnChainBalance, wt.decimals),
|
||||
})}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Cold wallet address"
|
||||
label={t('admin.treasury.coldAddress')}
|
||||
fullWidth
|
||||
value={form.address}
|
||||
onChange={(e) =>
|
||||
@ -233,7 +237,7 @@ export function TreasuryAdminPage() {
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Label"
|
||||
label={t('admin.treasury.label')}
|
||||
value={form.label}
|
||||
onChange={(e) =>
|
||||
setColdForms((prev) => ({
|
||||
@ -253,7 +257,7 @@ export function TreasuryAdminPage() {
|
||||
})
|
||||
}
|
||||
>
|
||||
Save cold
|
||||
{t('admin.treasury.saveCold')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
@ -266,15 +270,15 @@ export function TreasuryAdminPage() {
|
||||
<Card sx={{ borderRadius: 3, mb: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>
|
||||
Cold → Hot funding
|
||||
{t('admin.treasury.fundingTitle')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75, mb: 2 }}>
|
||||
Create a request, transfer manually from cold wallet, then confirm with the blockchain transaction ID.
|
||||
{t('admin.treasury.fundingSubtitle')}
|
||||
</Typography>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} sx={{ mb: 2 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Wallet type ID (USDT_TRC20)"
|
||||
label={t('admin.treasury.walletTypeId')}
|
||||
type="number"
|
||||
value={fundingForm.walletTypeId}
|
||||
onChange={(e) =>
|
||||
@ -283,13 +287,13 @@ export function TreasuryAdminPage() {
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Amount (raw units)"
|
||||
label={t('admin.treasury.amountRaw')}
|
||||
value={fundingForm.amount}
|
||||
onChange={(e) => setFundingForm((f) => ({ ...f, amount: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Notes"
|
||||
label={t('admin.treasury.notes')}
|
||||
fullWidth
|
||||
value={fundingForm.notes}
|
||||
onChange={(e) => setFundingForm((f) => ({ ...f, notes: e.target.value }))}
|
||||
@ -305,7 +309,7 @@ export function TreasuryAdminPage() {
|
||||
})
|
||||
}
|
||||
>
|
||||
Request funding for approval
|
||||
{t('admin.treasury.requestFunding')}
|
||||
</Button>
|
||||
</Stack>
|
||||
{overview?.pendingColdToHotFunding?.length ? (
|
||||
@ -313,8 +317,8 @@ export function TreasuryAdminPage() {
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Amount</TableCell>
|
||||
<TableCell>From → To</TableCell>
|
||||
<TableCell>{t('admin.treasury.amount')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.fromTo')}</TableCell>
|
||||
<TableCell />
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
@ -327,7 +331,7 @@ export function TreasuryAdminPage() {
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button size="small" onClick={() => setConfirmFunding({ id: f.id, txId: '' })}>
|
||||
Confirm tx
|
||||
{t('admin.treasury.confirmTx')}
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@ -337,7 +341,7 @@ export function TreasuryAdminPage() {
|
||||
</ScrollableTable>
|
||||
) : (
|
||||
<Typography variant="body2" sx={{ opacity: 0.6 }}>
|
||||
No pending funding requests.
|
||||
{t('admin.treasury.noPendingFunding')}
|
||||
</Typography>
|
||||
)}
|
||||
</CardContent>
|
||||
@ -351,7 +355,7 @@ export function TreasuryAdminPage() {
|
||||
sx={{ alignItems: { sm: 'center' }, mb: 2 }}
|
||||
>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
Deposit sweeps
|
||||
{t('admin.treasury.sweepsTitle')}
|
||||
</Typography>
|
||||
<Button
|
||||
size="small"
|
||||
@ -360,17 +364,17 @@ export function TreasuryAdminPage() {
|
||||
onClick={() => void runSweepsMut.mutateAsync()}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'auto' } }}
|
||||
>
|
||||
Submit sweeps for approval
|
||||
{t('admin.treasury.submitSweeps')}
|
||||
</Button>
|
||||
</Stack>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Amount</TableCell>
|
||||
<TableCell>To cold</TableCell>
|
||||
<TableCell>Tx</TableCell>
|
||||
<TableCell>{t('admin.treasury.status')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.amount')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.toCold')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.tx')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -395,11 +399,11 @@ export function TreasuryAdminPage() {
|
||||
</Card>
|
||||
|
||||
<Dialog open={!!confirmFunding} onClose={() => setConfirmFunding(null)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>Confirm cold → hot transfer</DialogTitle>
|
||||
<DialogTitle>{t('admin.treasury.confirmDialogTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Blockchain transaction ID"
|
||||
label={t('admin.treasury.blockchainTxId')}
|
||||
margin="dense"
|
||||
value={confirmFunding?.txId ?? ''}
|
||||
onChange={(e) =>
|
||||
@ -408,7 +412,7 @@ export function TreasuryAdminPage() {
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setConfirmFunding(null)}>Cancel</Button>
|
||||
<Button onClick={() => setConfirmFunding(null)}>{t('common.cancel')}</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!confirmFunding?.txId || confirmFundingMut.isPending}
|
||||
@ -420,7 +424,7 @@ export function TreasuryAdminPage() {
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirm
|
||||
{t('common.confirm')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,5 +1,6 @@
|
||||
/** Admin user list row returned by GET /api/v1/admin/users */
|
||||
import dayjs from 'dayjs';
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
export type AdminUser = {
|
||||
id: string;
|
||||
@ -132,30 +133,30 @@ export function deriveAccountStatus(
|
||||
}
|
||||
|
||||
/** Human-readable reasons when status is not active (shown in Status tooltip). */
|
||||
export function accountStatusReasons(row: AdminUser): string[] {
|
||||
export function accountStatusReasons(t: TFunction, row: AdminUser): string[] {
|
||||
const reasons: string[] = [];
|
||||
if (!row.is_enabled) return ['Account disabled'];
|
||||
if (!row.is_account_non_locked) reasons.push('Account locked');
|
||||
if (!row.is_account_non_expired) reasons.push('Account expired');
|
||||
if (!row.is_credentials_non_expired) reasons.push('Credentials expired');
|
||||
if (row.withdrawals_suspended) reasons.push('Withdrawals suspended');
|
||||
if (row.under_surveillance) reasons.push('Under surveillance');
|
||||
if (!row.is_enabled) return [t('admin.users.statusReasons.disabled')];
|
||||
if (!row.is_account_non_locked) reasons.push(t('admin.users.statusReasons.locked'));
|
||||
if (!row.is_account_non_expired) reasons.push(t('admin.users.statusReasons.expired'));
|
||||
if (!row.is_credentials_non_expired) reasons.push(t('admin.users.statusReasons.credentialsExpired'));
|
||||
if (row.withdrawals_suspended) reasons.push(t('admin.users.statusReasons.withdrawalsSuspended'));
|
||||
if (row.under_surveillance) reasons.push(t('admin.users.statusReasons.underSurveillance'));
|
||||
return reasons;
|
||||
}
|
||||
|
||||
/** Age bucket from date of birth for demographic reporting. */
|
||||
export function ageCategory(dob: string | null | undefined): string {
|
||||
export function ageCategory(t: TFunction, dob: string | null | undefined): string {
|
||||
if (!dob) return '—';
|
||||
const dateOnly = dob.match(/^(\d{4}-\d{2}-\d{2})/)?.[1] ?? dob;
|
||||
const age = dayjs().diff(dayjs(dateOnly, 'YYYY-MM-DD', true), 'year');
|
||||
if (age < 0 || !Number.isFinite(age)) return '—';
|
||||
if (age < 18) return 'Under 18';
|
||||
if (age < 25) return '18–24';
|
||||
if (age < 35) return '25–34';
|
||||
if (age < 45) return '35–44';
|
||||
if (age < 55) return '45–54';
|
||||
if (age < 65) return '55–64';
|
||||
return '65+';
|
||||
if (age < 18) return t('admin.users.ageBuckets.under18');
|
||||
if (age < 25) return t('admin.users.ageBuckets.18_24');
|
||||
if (age < 35) return t('admin.users.ageBuckets.25_34');
|
||||
if (age < 45) return t('admin.users.ageBuckets.35_44');
|
||||
if (age < 55) return t('admin.users.ageBuckets.45_54');
|
||||
if (age < 65) return t('admin.users.ageBuckets.55_64');
|
||||
return t('admin.users.ageBuckets.65_plus');
|
||||
}
|
||||
|
||||
export const COLUMN_VISIBILITY_STORAGE_KEY = 'admin_users_column_visibility';
|
||||
@ -177,13 +178,13 @@ function parseAgeFilter(value: string): number | undefined {
|
||||
}
|
||||
|
||||
/** Label for active age range filter chip. */
|
||||
export function ageFilterLabel(minAge: string, maxAge: string): string | null {
|
||||
export function ageFilterLabel(t: TFunction, minAge: string, maxAge: string): string | null {
|
||||
const min = parseAgeFilter(minAge);
|
||||
const max = parseAgeFilter(maxAge);
|
||||
if (min === undefined && max === undefined) return null;
|
||||
if (min !== undefined && max !== undefined) return `Age ${min}–${max}`;
|
||||
if (max !== undefined) return `Age ≤ ${max}`;
|
||||
return `Age ≥ ${min}`;
|
||||
if (min !== undefined && max !== undefined) return t('admin.users.ageFilter.range', { min, max });
|
||||
if (max !== undefined) return t('admin.users.ageFilter.max', { max });
|
||||
return t('admin.users.ageFilter.min', { min });
|
||||
}
|
||||
|
||||
export type AdminUserListResponse = {
|
||||
|
||||
@ -20,6 +20,7 @@ import SendRoundedIcon from '@mui/icons-material/SendRounded';
|
||||
import SouthWestRoundedIcon from '@mui/icons-material/SouthWestRounded';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import { BonusWalletCard } from './components/BonusWalletCard';
|
||||
@ -36,6 +37,7 @@ import { rawToHuman, shortSymbol } from './utils/walletFormat';
|
||||
type DialogKind = 'receive' | 'transfer' | 'withdraw' | null;
|
||||
|
||||
export function WalletPage() {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState(0);
|
||||
const [dialog, setDialog] = useState<DialogKind>(null);
|
||||
const [toast, setToast] = useState<string | null>(null);
|
||||
@ -72,7 +74,7 @@ export function WalletPage() {
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([balancesQ.refetch(), txQ.refetch(), healthQ.refetch()]);
|
||||
setToast('Wallet refreshed');
|
||||
setToast(t('common.walletRefreshed'));
|
||||
};
|
||||
|
||||
const loading = balancesQ.isLoading;
|
||||
@ -81,16 +83,12 @@ export function WalletPage() {
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<AccountBalanceWalletRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title="Wallet"
|
||||
subtitle={
|
||||
<>
|
||||
Deposit <b>USDT (TRC20)</b> on TRON to fund your account and play Candle Predict.
|
||||
</>
|
||||
}
|
||||
title={t('wallet.title')}
|
||||
subtitle={<Trans i18nKey="wallet.subtitle" components={{ b: <b /> }} />}
|
||||
mb={2.5}
|
||||
actions={
|
||||
<RefreshIconButton
|
||||
label="Refresh wallet"
|
||||
label={t('wallet.refreshWallet')}
|
||||
onClick={() => void refreshAll()}
|
||||
disabled={loading}
|
||||
/>
|
||||
@ -99,7 +97,7 @@ export function WalletPage() {
|
||||
|
||||
{balancesQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Failed to load balances. Make sure you are logged in and the API is running.
|
||||
{t('wallet.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@ -115,7 +113,7 @@ export function WalletPage() {
|
||||
}}
|
||||
>
|
||||
<Typography variant="overline" sx={{ opacity: 0.8, letterSpacing: 1.2 }}>
|
||||
Main USDT balance
|
||||
{t('wallet.mainBalance')}
|
||||
</Typography>
|
||||
{loading ? (
|
||||
<Skeleton variant="text" width={200} height={48} sx={{ mt: 1 }} />
|
||||
@ -125,11 +123,11 @@ export function WalletPage() {
|
||||
{portfolioSummary.human} {shortSymbol(USDT_WALLET_CODE)}
|
||||
</Typography>
|
||||
{portfolioSummary.hasLocked && (
|
||||
<Chip size="small" variant="outlined" label={`${portfolioSummary.locked} locked`} />
|
||||
<Chip size="small" variant="outlined" label={t('wallet.locked', { amount: portfolioSummary.locked })} />
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<Typography sx={{ opacity: 0.7, mt: 1 }}>No balance yet — receive USDT to get started.</Typography>
|
||||
<Typography sx={{ opacity: 0.7, mt: 1 }}>{t('wallet.noBalance')}</Typography>
|
||||
)}
|
||||
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ mt: 2.5 }}>
|
||||
@ -139,7 +137,7 @@ export function WalletPage() {
|
||||
onClick={() => setDialog('receive')}
|
||||
sx={{ flex: 1 }}
|
||||
>
|
||||
Receive USDT
|
||||
{t('wallet.receiveUsdt')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@ -147,7 +145,7 @@ export function WalletPage() {
|
||||
onClick={() => setDialog('transfer')}
|
||||
sx={{ flex: 1 }}
|
||||
>
|
||||
Send
|
||||
{t('wallet.send')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
@ -156,7 +154,7 @@ export function WalletPage() {
|
||||
onClick={() => setDialog('withdraw')}
|
||||
sx={{ flex: 1 }}
|
||||
>
|
||||
Withdraw
|
||||
{t('wallet.withdraw')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
@ -169,8 +167,8 @@ export function WalletPage() {
|
||||
allowScrollButtonsMobile
|
||||
sx={{ mb: 2, borderBottom: '1px solid rgba(255,255,255,0.08)' }}
|
||||
>
|
||||
<Tab label="Asset" />
|
||||
<Tab label="Activity" />
|
||||
<Tab label={t('wallet.tabAsset')} />
|
||||
<Tab label={t('wallet.tabActivity')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 0 && (
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
import CardGiftcardRoundedIcon from '@mui/icons-material/CardGiftcardRounded';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
|
||||
@ -26,6 +27,7 @@ type BonusWalletCardProps = {
|
||||
};
|
||||
|
||||
export function BonusWalletCard({ balance, onSuccess, onError }: BonusWalletCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [transferring, setTransferring] = useState(false);
|
||||
|
||||
@ -57,10 +59,10 @@ export function BonusWalletCard({ balance, onSuccess, onError }: BonusWalletCard
|
||||
qc.invalidateQueries({ queryKey: ['bonus-balances'] }),
|
||||
qc.invalidateQueries({ queryKey: ['wallet-transactions'] }),
|
||||
]);
|
||||
onSuccess?.('Bonus transferred to main wallet');
|
||||
onSuccess?.(t('wallet.bonusCard.transferSuccess'));
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? 'Transfer failed');
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? t('common.transferFailed'));
|
||||
} finally {
|
||||
setTransferring(false);
|
||||
}
|
||||
@ -93,22 +95,22 @@ export function BonusWalletCard({ balance, onSuccess, onError }: BonusWalletCard
|
||||
<CardGiftcardRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography sx={{ fontWeight: 800 }}>Bonus wallet</Typography>
|
||||
<Typography sx={{ fontWeight: 800 }}>{t('wallet.bonusCard.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
USDT credits for Candle Predict
|
||||
{t('wallet.bonusCard.subtitle')}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
color="secondary"
|
||||
variant="outlined"
|
||||
label={hasBonus ? 'Funds available' : 'Empty'}
|
||||
label={hasBonus ? 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' }}>
|
||||
Bonus balance
|
||||
{t('wallet.bonusCard.balance')}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="h5"
|
||||
@ -118,7 +120,7 @@ export function BonusWalletCard({ balance, onSuccess, onError }: BonusWalletCard
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mt: 1 }}>
|
||||
Use the bonus wallet when placing predictions. Winnings from bonus stakes are credited to your main wallet.
|
||||
{t('wallet.bonusCard.hint')}
|
||||
</Typography>
|
||||
|
||||
{bonusWithdrawable && hasBonus && (
|
||||
@ -130,13 +132,13 @@ export function BonusWalletCard({ balance, onSuccess, onError }: BonusWalletCard
|
||||
disabled={transferring}
|
||||
onClick={transferAllToMain}
|
||||
>
|
||||
{transferring ? 'Transferring…' : 'Move all to main wallet'}
|
||||
{transferring ? t('wallet.bonusCard.transferring') : t('wallet.bonusCard.moveToMain')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{!bonusWithdrawable && (
|
||||
<Alert severity="info" sx={{ mt: 2, borderRadius: 2 }} variant="outlined">
|
||||
Bonus funds can only be used for predictions (transfer to main is disabled by platform policy).
|
||||
{t('wallet.bonusCard.policyHint')}
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import QrCode2RoundedIcon from '@mui/icons-material/QrCode2Rounded';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import { coinColors, coinSymbol, networkLabel } from '../utils/coinDisplay';
|
||||
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
|
||||
@ -24,6 +25,7 @@ type MainAssetCardProps = {
|
||||
};
|
||||
|
||||
export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const [c1, c2] = coinColors(USDT_WALLET_CODE);
|
||||
const hasLocked = BigInt(balance.locked || '0') > 0n;
|
||||
|
||||
@ -47,24 +49,24 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
|
||||
{coinSymbol(USDT_WALLET_CODE)}
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography sx={{ fontWeight: 800 }}>Main wallet</Typography>
|
||||
<Typography sx={{ fontWeight: 800 }}>{t('wallet.mainCard.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
{balance.walletType.name} · {networkLabel(USDT_WALLET_CODE)}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
color="primary"
|
||||
label="Deposits & withdrawals"
|
||||
label={t('wallet.mainCard.badge')}
|
||||
sx={{ mt: 0.75, fontWeight: 700 }}
|
||||
/>
|
||||
</Box>
|
||||
<IconButton size="small" aria-label="Receive USDT" onClick={onReceive}>
|
||||
<IconButton size="small" aria-label={t('wallet.mainCard.receiveAria')} onClick={onReceive}>
|
||||
<QrCode2RoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, textTransform: 'uppercase', mt: 2, display: 'block' }}>
|
||||
Available balance
|
||||
{t('wallet.mainCard.availableBalance')}
|
||||
</Typography>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900 }}>
|
||||
{formatBalance(balance.available, balance.walletType.decimals, USDT_WALLET_CODE)}
|
||||
@ -72,17 +74,17 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
|
||||
|
||||
{hasLocked && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.65, mt: 0.5 }}>
|
||||
Locked:{' '}
|
||||
{t('wallet.mainCard.locked')}{' '}
|
||||
{formatBalance(balance.locked, balance.walletType.decimals, USDT_WALLET_CODE)}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ mt: 2 }}>
|
||||
<Button size="small" variant="contained" onClick={onReceive}>
|
||||
Receive
|
||||
{t('wallet.mainCard.receive')}
|
||||
</Button>
|
||||
<Button size="small" variant="outlined" onClick={onSend}>
|
||||
Send
|
||||
{t('wallet.send')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
|
||||
@ -16,6 +16,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
|
||||
import QRCode from 'react-qr-code';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { useDepositAddress } from '../hooks/useWalletData';
|
||||
import { networkLabel } from '../utils/coinDisplay';
|
||||
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
|
||||
@ -27,6 +28,7 @@ type ReceiveDialogProps = {
|
||||
};
|
||||
|
||||
export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const depositQ = useDepositAddress(USDT_WALLET_CODE, open);
|
||||
|
||||
const copyAddress = async () => {
|
||||
@ -34,24 +36,27 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
|
||||
if (!addr) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(addr);
|
||||
onCopied?.('Address copied to clipboard');
|
||||
onCopied?.(t('common.addressCopied'));
|
||||
} catch {
|
||||
onCopied?.('Copy failed');
|
||||
onCopied?.(t('common.copyFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>Receive USDT</DialogTitle>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.receiveDialog.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2.5} sx={{ pt: 0.5 }}>
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Send <b>USDT</b> on <b>{networkLabel(USDT_WALLET_CODE)}</b> only. This balance is used
|
||||
for Candle Predict stakes.
|
||||
<Trans
|
||||
i18nKey="wallet.receiveDialog.info"
|
||||
values={{ network: networkLabel(USDT_WALLET_CODE) }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
Wrong asset or network may result in permanent loss.
|
||||
{t('wallet.receiveDialog.wrongNetwork')}
|
||||
</Alert>
|
||||
|
||||
{depositQ.isLoading ? (
|
||||
@ -61,7 +66,7 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
|
||||
) : depositQ.isError ? (
|
||||
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||
{(depositQ.error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error ?? 'Failed to load deposit address'}
|
||||
?.error ?? t('wallet.receiveDialog.loadAddressFailed')}
|
||||
</Alert>
|
||||
) : depositQ.data ? (
|
||||
<Stack spacing={2} sx={{ alignItems: 'center' }}>
|
||||
@ -97,23 +102,27 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
|
||||
>
|
||||
{depositQ.data.address}
|
||||
</Typography>
|
||||
<IconButton size="small" onClick={copyAddress} aria-label="Copy address">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={copyAddress}
|
||||
aria-label={t('wallet.receiveDialog.copyAddressAria')}
|
||||
>
|
||||
<ContentCopyRoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, textAlign: 'center' }}>
|
||||
Deposits are credited after the required on-chain confirmations.
|
||||
{t('wallet.receiveDialog.confirmationsHint')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
) : null}
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2 }}>
|
||||
<Button onClick={onClose}>Close</Button>
|
||||
<Button onClick={onClose}>{t('common.close')}</Button>
|
||||
<Button variant="contained" onClick={copyAddress} disabled={!depositQ.data?.address}>
|
||||
Copy address
|
||||
{t('common.copyAddress')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
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 type { BalanceEntry } from '../types';
|
||||
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
|
||||
@ -40,6 +41,7 @@ type TestWalletCardProps = {
|
||||
};
|
||||
|
||||
export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [requesting, setRequesting] = useState(false);
|
||||
|
||||
@ -54,9 +56,7 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
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 creditHuman = status ? rawToHuman(status.creditAmountRaw, status.decimals) : '—';
|
||||
|
||||
const requestCredits = async () => {
|
||||
setRequesting(true);
|
||||
@ -69,7 +69,7 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
onSuccess?.(res.data.message);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? 'Request failed');
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? t('auth.requestFailed'));
|
||||
} finally {
|
||||
setRequesting(false);
|
||||
}
|
||||
@ -102,22 +102,22 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
<ScienceRoundedIcon fontSize="small" />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography sx={{ fontWeight: 800 }}>Test wallet</Typography>
|
||||
<Typography sx={{ fontWeight: 800 }}>{t('wallet.testCard.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
Play-money for practice predictions
|
||||
{t('wallet.testCard.subtitle')}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
color="success"
|
||||
variant="outlined"
|
||||
label={hasTest ? 'Funds available' : 'Empty'}
|
||||
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' }}>
|
||||
Test balance
|
||||
{t('wallet.testCard.balance')}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="h5"
|
||||
@ -127,8 +127,7 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mt: 1 }}>
|
||||
Use test credits to explore predictions with the same rules as real play. Winnings and losses
|
||||
stay in this wallet — they cannot be withdrawn or transferred to your main wallet.
|
||||
{t('wallet.testCard.hint')}
|
||||
</Typography>
|
||||
|
||||
{status?.enabled ? (
|
||||
@ -141,12 +140,15 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
onClick={requestCredits}
|
||||
>
|
||||
{requesting
|
||||
? 'Crediting…'
|
||||
: `Request ${creditHuman} test credits`}
|
||||
? t('wallet.testCard.crediting')
|
||||
: t('wallet.testCard.requestCredits', { amount: creditHuman })}
|
||||
</Button>
|
||||
{status.maxRequests > 0 && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
Requests used: {status.requestsUsed} / {status.maxRequests}
|
||||
{t('wallet.testCard.requestsUsed', {
|
||||
used: status.requestsUsed,
|
||||
max: status.maxRequests,
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
{!status.canRequest && status.reason && (
|
||||
@ -155,7 +157,9 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
{status.cooldownEndsAt && (
|
||||
<>
|
||||
{' '}
|
||||
Available after {new Date(status.cooldownEndsAt).toLocaleString()}.
|
||||
{t('wallet.testCard.availableAfter', {
|
||||
date: new Date(status.cooldownEndsAt).toLocaleString(),
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</Alert>
|
||||
@ -163,7 +167,7 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
|
||||
</Stack>
|
||||
) : (
|
||||
<Alert severity="warning" sx={{ mt: 2, borderRadius: 2 }} variant="outlined">
|
||||
Test wallet requests are currently disabled by the platform.
|
||||
{t('wallet.testCard.disabled')}
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@ -18,9 +18,10 @@ import {
|
||||
} from '@mui/material';
|
||||
import { ScrollableTable } from '../../../shared/components/ScrollableTable';
|
||||
import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { BalanceEntry, WalletTransaction } from '../types';
|
||||
import { coinColors, coinSymbol } from '../utils/coinDisplay';
|
||||
import { isCredit, txLabel } from '../utils/transactionDisplay';
|
||||
import { isCredit, txLabel, txStatusLabel } from '../utils/transactionDisplay';
|
||||
import { rawToHuman, shortSymbol } from '../utils/walletFormat';
|
||||
|
||||
type TransactionListProps = {
|
||||
@ -53,6 +54,7 @@ export function TransactionList({
|
||||
total,
|
||||
onPageChange,
|
||||
}: TransactionListProps) {
|
||||
const { t } = useTranslation();
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
||||
const from = total === 0 ? 0 : page * pageSize + 1;
|
||||
const to = Math.min(total, (page + 1) * pageSize);
|
||||
@ -77,9 +79,9 @@ export function TransactionList({
|
||||
border: '1px solid rgba(255,255,255,0.08)',
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ opacity: 0.7 }}>No transactions yet</Typography>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('wallet.transactions.empty')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.5, mt: 0.5 }}>
|
||||
Deposits, predictions, and withdrawals will appear here.
|
||||
{t('wallet.transactions.emptyHint')}
|
||||
</Typography>
|
||||
</Paper>
|
||||
);
|
||||
@ -98,11 +100,11 @@ export function TransactionList({
|
||||
<Table size="small" sx={{ minWidth: 560 }}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Asset</TableCell>
|
||||
<TableCell>Type</TableCell>
|
||||
<TableCell align="right">Amount</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Date</TableCell>
|
||||
<TableCell>{t('common.asset')}</TableCell>
|
||||
<TableCell>{t('common.type')}</TableCell>
|
||||
<TableCell align="right">{t('common.amount')}</TableCell>
|
||||
<TableCell>{t('common.status')}</TableCell>
|
||||
<TableCell>{t('common.date')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
@ -153,7 +155,7 @@ export function TransactionList({
|
||||
<TableCell>
|
||||
<Chip
|
||||
size="small"
|
||||
label={tx.status}
|
||||
label={txStatusLabel(tx.status)}
|
||||
color={
|
||||
tx.status === 'completed'
|
||||
? 'success'
|
||||
@ -183,7 +185,9 @@ export function TransactionList({
|
||||
sx={{ alignItems: 'center', justifyContent: 'space-between' }}
|
||||
>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{total > 0 ? `${from}–${to} of ${total}` : 'No results'}
|
||||
{total > 0
|
||||
? t('common.pagination', { from, to, total })
|
||||
: t('common.noResults')}
|
||||
</Typography>
|
||||
<Pagination
|
||||
count={pageCount}
|
||||
|
||||
@ -19,6 +19,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import { networkLabel } from '../utils/coinDisplay';
|
||||
@ -44,6 +45,7 @@ export function TransferDialog({
|
||||
onSuccess,
|
||||
onError,
|
||||
}: TransferDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [asset, setAsset] = useState('');
|
||||
const [toEmail, setToEmail] = useState('');
|
||||
@ -79,11 +81,11 @@ export function TransferDialog({
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
onSuccess?.('Transfer completed successfully');
|
||||
onSuccess?.(t('wallet.transferDialog.success'));
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? 'Transfer failed');
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? t('common.transferFailed'));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setConfirmOpen(false);
|
||||
@ -99,15 +101,15 @@ export function TransferDialog({
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open && !confirmOpen} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>Send to user</DialogTitle>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.transferDialog.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ pt: 0.5 }}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Transfer to another Prediqo account instantly. On-chain fees do not apply.
|
||||
{t('wallet.transferDialog.subtitle')}
|
||||
</Typography>
|
||||
|
||||
<TextField
|
||||
label="Recipient email"
|
||||
label={t('wallet.transferDialog.recipientEmail')}
|
||||
type="email"
|
||||
fullWidth
|
||||
value={toEmail}
|
||||
@ -116,10 +118,10 @@ export function TransferDialog({
|
||||
/>
|
||||
|
||||
<FormControl fullWidth>
|
||||
<InputLabel id="transfer-asset-label">Asset</InputLabel>
|
||||
<InputLabel id="transfer-asset-label">{t('common.asset')}</InputLabel>
|
||||
<Select
|
||||
labelId="transfer-asset-label"
|
||||
label="Asset"
|
||||
label={t('common.asset')}
|
||||
value={asset}
|
||||
onChange={(e) => setAsset(e.target.value)}
|
||||
>
|
||||
@ -132,63 +134,69 @@ export function TransferDialog({
|
||||
</FormControl>
|
||||
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Network: <b>{networkLabel(asset)}</b> (auto-selected)
|
||||
<Trans
|
||||
i18nKey="wallet.transferDialog.networkAuto"
|
||||
values={{ network: networkLabel(asset) }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
<TextField
|
||||
label="Amount"
|
||||
label={t('common.amount')}
|
||||
fullWidth
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
inputMode="decimal"
|
||||
helperText={
|
||||
selected
|
||||
? `Available: ${formatBalance(selected.available, selected.walletType.decimals, asset)}`
|
||||
? t('wallet.transferDialog.available', {
|
||||
amount: formatBalance(selected.available, selected.walletType.decimals, asset),
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="2FA code"
|
||||
label={t('wallet.transferDialog.totpCode')}
|
||||
fullWidth
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
inputMode="numeric"
|
||||
placeholder="6-digit code"
|
||||
helperText="Required if 2FA is enabled on your account"
|
||||
placeholder={t('wallet.transferDialog.totpPlaceholder')}
|
||||
helperText={t('wallet.transferDialog.totpRequired')}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2 }}>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canProceed}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Review transfer
|
||||
<Button onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button variant="contained" disabled={!canProceed} onClick={() => setConfirmOpen(true)}>
|
||||
{t('wallet.transferDialog.review')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} maxWidth="xs" fullWidth>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>Confirm transfer</DialogTitle>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.transferDialog.confirmTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={1} sx={{ pt: 0.5 }}>
|
||||
<Typography>
|
||||
Send <b>{amount}</b> <b>{shortSymbol(asset)}</b> to <b>{toEmail}</b>?
|
||||
<Trans
|
||||
i18nKey="wallet.transferDialog.confirmBody"
|
||||
values={{ amount, asset: shortSymbol(asset), email: toEmail }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
This action cannot be undone.
|
||||
{t('wallet.transferDialog.irreversible')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2 }}>
|
||||
<Button onClick={() => setConfirmOpen(false)} disabled={submitting}>
|
||||
Back
|
||||
{t('common.back')}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={submit} disabled={submitting}>
|
||||
{submitting ? 'Sending…' : 'Confirm'}
|
||||
{submitting ? t('common.sending') : t('common.confirm')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
/**
|
||||
* On-chain withdrawal dialog for the wallet page.
|
||||
* Sends crypto to an external address with network warnings and 2FA.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -19,6 +18,7 @@ import {
|
||||
} from '@mui/material';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import { networkLabel } from '../utils/coinDisplay';
|
||||
@ -28,7 +28,6 @@ type WithdrawDialogProps = {
|
||||
open: boolean;
|
||||
balances: BalanceEntry[];
|
||||
withdrawalsEnabled: boolean;
|
||||
/** Network fee in smallest USDT units (from /health). */
|
||||
networkFeeRaw: string;
|
||||
initialAsset?: string | null;
|
||||
onClose: () => void;
|
||||
@ -36,9 +35,6 @@ type WithdrawDialogProps = {
|
||||
onError?: (message: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Modal to withdraw crypto to an external blockchain address.
|
||||
*/
|
||||
export function WithdrawDialog({
|
||||
open,
|
||||
balances,
|
||||
@ -49,6 +45,7 @@ export function WithdrawDialog({
|
||||
onSuccess,
|
||||
onError,
|
||||
}: WithdrawDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [asset, setAsset] = useState('');
|
||||
const [toAddress, setToAddress] = useState('');
|
||||
@ -126,21 +123,24 @@ export function WithdrawDialog({
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
const feeHuman =
|
||||
res.data.fee && res.data.fee !== '0'
|
||||
? ` (fee ${rawToHuman(res.data.fee, selected.walletType.decimals)} USDT)`
|
||||
: '';
|
||||
onSuccess?.(`Withdrawal submitted successfully${feeHuman}`);
|
||||
? rawToHuman(res.data.fee, selected.walletType.decimals)
|
||||
: null;
|
||||
onSuccess?.(
|
||||
feeHuman
|
||||
? t('wallet.withdrawDialog.successWithFee', { fee: feeHuman })
|
||||
: t('wallet.withdrawDialog.success')
|
||||
);
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } }; message?: string };
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? 'Withdrawal failed');
|
||||
onError?.(err?.response?.data?.error ?? err?.message ?? t('common.withdrawalFailed'));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setConfirmOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const insufficientFunds =
|
||||
amountRaw > 0n && feeRaw >= 0n && availableRaw < totalDebitRaw;
|
||||
const insufficientFunds = amountRaw > 0n && feeRaw >= 0n && availableRaw < totalDebitRaw;
|
||||
|
||||
const canProceed =
|
||||
withdrawalsEnabled &&
|
||||
@ -149,36 +149,38 @@ export function WithdrawDialog({
|
||||
amountRaw > 0n &&
|
||||
!insufficientFunds;
|
||||
|
||||
const feePart =
|
||||
feeRaw > 0n && selected
|
||||
? t('wallet.withdrawDialog.networkFeePart', { fee: feeLabel })
|
||||
: '';
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open && !confirmOpen} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>Withdraw</DialogTitle>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.withdrawDialog.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ pt: 0.5 }}>
|
||||
{!withdrawalsEnabled && (
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
Withdrawals are disabled on this server (testnet safety). Contact an administrator
|
||||
to enable <code>ALLOW_WITHDRAWALS=true</code> when ready.
|
||||
<Trans i18nKey="wallet.withdrawDialog.disabled" components={{ code: <code /> }} />
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Alert severity="error" variant="outlined" sx={{ borderRadius: 2 }}>
|
||||
Double-check the destination address and network. Wrong network transfers are
|
||||
irreversible.
|
||||
{t('wallet.withdrawDialog.networkWarning')}
|
||||
</Alert>
|
||||
|
||||
{feeRaw > 0n && (
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
A network fee of <b>{feeLabel}</b> is deducted from your balance in addition to the
|
||||
withdrawal amount (covers TRON gas for the on-chain transfer).
|
||||
<Trans i18nKey="wallet.withdrawDialog.networkFee" values={{ fee: feeLabel }} components={{ b: <b /> }} />
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FormControl fullWidth disabled={!withdrawalsEnabled}>
|
||||
<InputLabel id="withdraw-asset-label">Asset</InputLabel>
|
||||
<InputLabel id="withdraw-asset-label">{t('common.asset')}</InputLabel>
|
||||
<Select
|
||||
labelId="withdraw-asset-label"
|
||||
label="Asset"
|
||||
label={t('common.asset')}
|
||||
value={asset}
|
||||
onChange={(e) => setAsset(e.target.value)}
|
||||
>
|
||||
@ -191,11 +193,15 @@ export function WithdrawDialog({
|
||||
</FormControl>
|
||||
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
Network: <b>{networkLabel(asset)}</b> (cannot be changed)
|
||||
<Trans
|
||||
i18nKey="wallet.withdrawDialog.networkFixed"
|
||||
values={{ network: networkLabel(asset) }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
<TextField
|
||||
label="Destination address"
|
||||
label={t('wallet.withdrawDialog.destinationAddress')}
|
||||
fullWidth
|
||||
value={toAddress}
|
||||
onChange={(e) => setToAddress(e.target.value)}
|
||||
@ -207,7 +213,7 @@ export function WithdrawDialog({
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="Amount to receive"
|
||||
label={t('wallet.withdrawDialog.amountToReceive')}
|
||||
fullWidth
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
@ -217,51 +223,63 @@ export function WithdrawDialog({
|
||||
helperText={
|
||||
selected
|
||||
? insufficientFunds
|
||||
? `Insufficient balance — need ${totalDebitLabel} (amount + network fee)`
|
||||
: `Available: ${formatBalance(selected.available, selected.walletType.decimals, asset)}${
|
||||
feeRaw > 0n ? ` · Network fee: ${feeLabel}` : ''
|
||||
}`
|
||||
? t('wallet.withdrawDialog.insufficient', { total: totalDebitLabel })
|
||||
: t('wallet.withdrawDialog.availableWithFee', {
|
||||
available: formatBalance(
|
||||
selected.available,
|
||||
selected.walletType.decimals,
|
||||
asset
|
||||
),
|
||||
feePart,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="2FA code (optional)"
|
||||
label={t('wallet.withdrawDialog.totpOptional')}
|
||||
fullWidth
|
||||
value={totpCode}
|
||||
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
inputMode="numeric"
|
||||
disabled={!withdrawalsEnabled}
|
||||
placeholder="6-digit code"
|
||||
placeholder={t('wallet.withdrawDialog.totpPlaceholder')}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2 }}>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="warning"
|
||||
disabled={!canProceed}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
Review withdrawal
|
||||
{t('wallet.withdrawDialog.review')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} maxWidth="xs" fullWidth>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>Confirm withdrawal</DialogTitle>
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.withdrawDialog.confirmTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={1.5} sx={{ pt: 0.5 }}>
|
||||
<Typography>
|
||||
You will receive <b>{amount}</b> <b>{shortSymbol(asset)}</b> on{' '}
|
||||
<b>{networkLabel(asset)}</b>.
|
||||
<Trans
|
||||
i18nKey="wallet.withdrawDialog.receiveOnNetwork"
|
||||
values={{
|
||||
amount,
|
||||
asset: shortSymbol(asset),
|
||||
network: networkLabel(asset),
|
||||
}}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Typography>
|
||||
{feeRaw > 0n && (
|
||||
<Typography variant="body2">
|
||||
Network fee: <b>{feeLabel}</b>
|
||||
{t('wallet.withdrawDialog.networkFeeLabel')} <b>{feeLabel}</b>
|
||||
<br />
|
||||
Total debited from your balance: <b>{totalDebitLabel}</b>
|
||||
{t('wallet.withdrawDialog.totalDebited')} <b>{totalDebitLabel}</b>
|
||||
</Typography>
|
||||
)}
|
||||
<Typography
|
||||
@ -270,16 +288,16 @@ export function WithdrawDialog({
|
||||
{toAddress}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
This transaction is irreversible once broadcast.
|
||||
{t('wallet.withdrawDialog.broadcastIrreversible')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 3, pb: 2 }}>
|
||||
<Button onClick={() => setConfirmOpen(false)} disabled={submitting}>
|
||||
Back
|
||||
{t('common.back')}
|
||||
</Button>
|
||||
<Button variant="contained" color="warning" onClick={submit} disabled={submitting}>
|
||||
{submitting ? 'Withdrawing…' : 'Confirm'}
|
||||
{submitting ? t('wallet.withdrawDialog.withdrawing') : t('common.confirm')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Display helpers for wallet transaction history (labels, credit vs debit).
|
||||
*/
|
||||
import i18n from '../../../shared/i18n';
|
||||
import type { WalletTransaction } from '../types';
|
||||
|
||||
/** All transaction types returned by GET /api/v1/transactions. */
|
||||
@ -18,26 +19,34 @@ const CREDIT_TYPES = new Set<WalletTransactionType>([
|
||||
export function txLabel(tx: WalletTransaction): string {
|
||||
switch (tx.type) {
|
||||
case 'deposit':
|
||||
return 'Deposit';
|
||||
return i18n.t('wallet.transactions.types.deposit');
|
||||
case 'withdrawal':
|
||||
return 'Withdrawal';
|
||||
return i18n.t('wallet.transactions.types.withdrawal');
|
||||
case 'transfer':
|
||||
return tx.metadata?.direction === 'in' ? 'Transfer in' : 'Transfer out';
|
||||
return tx.metadata?.direction === 'in'
|
||||
? i18n.t('wallet.transactions.types.transferIn')
|
||||
: i18n.t('wallet.transactions.types.transferOut');
|
||||
case 'game_stake':
|
||||
return 'Prediction stake';
|
||||
return i18n.t('wallet.transactions.types.gameStake');
|
||||
case 'game_payout':
|
||||
return 'Prediction win';
|
||||
return i18n.t('wallet.transactions.types.gamePayout');
|
||||
case 'game_refund':
|
||||
return 'Prediction refund';
|
||||
return i18n.t('wallet.transactions.types.gameRefund');
|
||||
case 'bonus':
|
||||
return 'Bonus credit';
|
||||
return i18n.t('wallet.transactions.types.bonus');
|
||||
case 'admin_adjustment':
|
||||
return 'Balance adjustment';
|
||||
return i18n.t('wallet.transactions.types.adminAdjustment');
|
||||
default:
|
||||
return tx.type;
|
||||
}
|
||||
}
|
||||
|
||||
/** Localized transaction status label when a known key exists. */
|
||||
export function txStatusLabel(status: string): string {
|
||||
const key = `wallet.transactions.status.${status}`;
|
||||
return i18n.exists(key) ? i18n.t(key) : status;
|
||||
}
|
||||
|
||||
/** Whether the amount increases the user's balance (shown with + and credit color). */
|
||||
export function isCredit(tx: WalletTransaction): boolean {
|
||||
if (tx.type === 'transfer') return tx.metadata?.direction === 'in';
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
*/
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './shared/i18n';
|
||||
import { App } from './app/App';
|
||||
import './styles/global.css';
|
||||
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
* Searchable country picker (name or ISO code).
|
||||
*/
|
||||
import { Autocomplete, TextField } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type CountryOption = { code: string; name: string };
|
||||
|
||||
@ -37,8 +38,9 @@ export function CountryAutocomplete({
|
||||
required = false,
|
||||
error = false,
|
||||
helperText,
|
||||
placeholder = 'Search by country name or code…',
|
||||
placeholder,
|
||||
}: CountryAutocompleteProps) {
|
||||
const { t } = useTranslation();
|
||||
const selected = options.find((country) => country.code === value) ?? null;
|
||||
|
||||
return (
|
||||
@ -54,7 +56,9 @@ export function CountryAutocomplete({
|
||||
getOptionLabel={(option) => `${option.name} (${option.code})`}
|
||||
isOptionEqualToValue={(a, b) => a.code === b.code}
|
||||
filterOptions={(opts, state) => filterCountries(opts, state.inputValue)}
|
||||
noOptionsText={loading ? 'Loading countries…' : 'No country found'}
|
||||
noOptionsText={
|
||||
loading ? t('common.countryLoading') : t('common.noCountryFound')
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
@ -62,7 +66,7 @@ export function CountryAutocomplete({
|
||||
required={required}
|
||||
error={error}
|
||||
helperText={helperText}
|
||||
placeholder={placeholder}
|
||||
placeholder={placeholder ?? t('common.countrySearchPlaceholder')}
|
||||
/>
|
||||
)}
|
||||
slotProps={{
|
||||
|
||||
@ -6,7 +6,8 @@ import {
|
||||
Select,
|
||||
type SelectProps,
|
||||
} from '@mui/material';
|
||||
import { USER_GENDER_OPTIONS, type UserGender } from '../constants/userGender';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { USER_GENDER_VALUES, type UserGender } from '../constants/userGender';
|
||||
|
||||
type GenderSelectProps = {
|
||||
value: UserGender | '';
|
||||
@ -19,19 +20,22 @@ type GenderSelectProps = {
|
||||
error?: boolean;
|
||||
};
|
||||
|
||||
/** Dropdown for user gender (Masculin, Féminin, Autre). */
|
||||
/** Dropdown for user gender. */
|
||||
export function GenderSelect({
|
||||
value,
|
||||
onChange,
|
||||
label = 'Sexe',
|
||||
label,
|
||||
required,
|
||||
helperText,
|
||||
fullWidth = true,
|
||||
disabled,
|
||||
error,
|
||||
}: GenderSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
const resolvedLabel = label ?? t('gender.label');
|
||||
|
||||
const selectProps: SelectProps = {
|
||||
label,
|
||||
label: resolvedLabel,
|
||||
value: value || '',
|
||||
onChange: (e) => onChange(e.target.value as UserGender),
|
||||
disabled,
|
||||
@ -40,16 +44,16 @@ export function GenderSelect({
|
||||
|
||||
return (
|
||||
<FormControl fullWidth={fullWidth} required={required} error={error}>
|
||||
<InputLabel id="gender-select-label">{label}</InputLabel>
|
||||
<InputLabel id="gender-select-label">{resolvedLabel}</InputLabel>
|
||||
<Select labelId="gender-select-label" {...selectProps}>
|
||||
{!required && (
|
||||
<MenuItem value="">
|
||||
<em>Sélectionner…</em>
|
||||
<em>{t('gender.select')}</em>
|
||||
</MenuItem>
|
||||
)}
|
||||
{USER_GENDER_OPTIONS.map((opt) => (
|
||||
<MenuItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
{USER_GENDER_VALUES.map((opt) => (
|
||||
<MenuItem key={opt} value={opt}>
|
||||
{t(`gender.${opt}`)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
|
||||
import { Box, IconButton, Stack, Typography } from '@mui/material';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type PageHeaderProps = {
|
||||
icon?: ReactNode;
|
||||
@ -114,9 +115,11 @@ type RefreshIconButtonProps = {
|
||||
label?: string;
|
||||
};
|
||||
|
||||
export function RefreshIconButton({ onClick, disabled, label = 'Refresh' }: RefreshIconButtonProps) {
|
||||
export function RefreshIconButton({ onClick, disabled, label }: RefreshIconButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const resolvedLabel = label ?? t('common.refresh');
|
||||
return (
|
||||
<IconButton aria-label={label} onClick={onClick} disabled={disabled} sx={{ flexShrink: 0 }}>
|
||||
<IconButton aria-label={resolvedLabel} onClick={onClick} disabled={disabled} sx={{ flexShrink: 0 }}>
|
||||
<RefreshRoundedIcon />
|
||||
</IconButton>
|
||||
);
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
import i18n from '../i18n';
|
||||
|
||||
export type UserGender = 'male' | 'female' | 'other';
|
||||
|
||||
export const USER_GENDER_OPTIONS: { value: UserGender; label: string }[] = [
|
||||
{ value: 'male', label: 'Masculin' },
|
||||
{ value: 'female', label: 'Féminin' },
|
||||
{ value: 'other', label: 'Autre' },
|
||||
];
|
||||
export const USER_GENDER_VALUES: UserGender[] = ['male', 'female', 'other'];
|
||||
|
||||
export function genderLabel(value: UserGender | string | null | undefined): string {
|
||||
if (!value) return '—';
|
||||
const match = USER_GENDER_OPTIONS.find((o) => o.value === value);
|
||||
return match?.label ?? value;
|
||||
const key = `gender.${value}`;
|
||||
if (i18n.exists(key)) return i18n.t(key);
|
||||
return value;
|
||||
}
|
||||
|
||||
74
prediqo_web/src/shared/i18n/LanguageSwitcher.tsx
Normal file
74
prediqo_web/src/shared/i18n/LanguageSwitcher.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Compact language toggle for English / French.
|
||||
*/
|
||||
import LanguageRoundedIcon from '@mui/icons-material/LanguageRounded';
|
||||
import { Button, Menu, MenuItem, Tooltip } from '@mui/material';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LOCALE_STORAGE_KEY, normalizeLocale, type AppLocale } from './index';
|
||||
|
||||
const OPTIONS: { code: AppLocale; labelKey: 'common.english' | 'common.french' }[] = [
|
||||
{ code: 'en', labelKey: 'common.english' },
|
||||
{ code: 'fr', labelKey: 'common.french' },
|
||||
];
|
||||
|
||||
const ABBREV: Record<AppLocale, string> = { en: 'EN', fr: 'FR' };
|
||||
|
||||
type LanguageSwitcherProps = {
|
||||
/** Show "EN"/"FR" (default) or full language name. */
|
||||
display?: 'abbrev' | 'full';
|
||||
};
|
||||
|
||||
export function LanguageSwitcher({ display = 'abbrev' }: LanguageSwitcherProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [anchor, setAnchor] = useState<null | HTMLElement>(null);
|
||||
const current = normalizeLocale(i18n.language);
|
||||
const currentOption = OPTIONS.find((o) => o.code === current) ?? OPTIONS[0];
|
||||
const currentLabel =
|
||||
display === 'full' ? t(currentOption.labelKey) : ABBREV[current];
|
||||
|
||||
const select = async (code: AppLocale) => {
|
||||
setAnchor(null);
|
||||
if (code === current) return;
|
||||
try {
|
||||
localStorage.setItem(LOCALE_STORAGE_KEY, code);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
await i18n.changeLanguage(code);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip title={t('common.language')}>
|
||||
<Button
|
||||
size="small"
|
||||
color="inherit"
|
||||
aria-label={`${t('common.language')}: ${t(currentOption.labelKey)}`}
|
||||
onClick={(e) => setAnchor(e.currentTarget)}
|
||||
startIcon={<LanguageRoundedIcon fontSize="small" />}
|
||||
sx={{
|
||||
minWidth: 0,
|
||||
px: 1.25,
|
||||
fontWeight: 800,
|
||||
letterSpacing: display === 'abbrev' ? '0.04em' : undefined,
|
||||
border: '1px solid rgba(255,255,255,0.15)',
|
||||
}}
|
||||
>
|
||||
{currentLabel}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Menu anchorEl={anchor} open={!!anchor} onClose={() => setAnchor(null)}>
|
||||
{OPTIONS.map((opt) => (
|
||||
<MenuItem
|
||||
key={opt.code}
|
||||
selected={opt.code === current}
|
||||
onClick={() => void select(opt.code)}
|
||||
>
|
||||
{display === 'abbrev' ? `${ABBREV[opt.code]} — ${t(opt.labelKey)}` : t(opt.labelKey)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
}
|
||||
44
prediqo_web/src/shared/i18n/index.ts
Normal file
44
prediqo_web/src/shared/i18n/index.ts
Normal file
@ -0,0 +1,44 @@
|
||||
/**
|
||||
* i18n bootstrap — English and French for the Prediqo web app.
|
||||
*/
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
import LanguageDetector from 'i18next-browser-languagedetector';
|
||||
import { en } from './locales/en';
|
||||
import { fr } from './locales/fr';
|
||||
|
||||
export const LOCALE_STORAGE_KEY = 'prediqo.locale';
|
||||
|
||||
export const SUPPORTED_LOCALES = ['en', 'fr'] as const;
|
||||
export type AppLocale = (typeof SUPPORTED_LOCALES)[number];
|
||||
|
||||
export function normalizeLocale(lng: string | undefined): AppLocale {
|
||||
if (!lng) return 'en';
|
||||
return lng.toLowerCase().startsWith('fr') ? 'fr' : 'en';
|
||||
}
|
||||
|
||||
void i18n
|
||||
.use(LanguageDetector)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
resources: {
|
||||
en: { translation: en },
|
||||
fr: { translation: fr },
|
||||
},
|
||||
fallbackLng: 'en',
|
||||
supportedLngs: [...SUPPORTED_LOCALES],
|
||||
interpolation: { escapeValue: false },
|
||||
detection: {
|
||||
order: ['localStorage', 'navigator'],
|
||||
lookupLocalStorage: LOCALE_STORAGE_KEY,
|
||||
caches: ['localStorage'],
|
||||
},
|
||||
});
|
||||
|
||||
i18n.on('languageChanged', (lng) => {
|
||||
document.documentElement.lang = normalizeLocale(lng);
|
||||
});
|
||||
|
||||
document.documentElement.lang = normalizeLocale(i18n.language);
|
||||
|
||||
export default i18n;
|
||||
2046
prediqo_web/src/shared/i18n/locales/en.ts
Normal file
2046
prediqo_web/src/shared/i18n/locales/en.ts
Normal file
File diff suppressed because it is too large
Load Diff
2059
prediqo_web/src/shared/i18n/locales/fr.ts
Normal file
2059
prediqo_web/src/shared/i18n/locales/fr.ts
Normal file
File diff suppressed because it is too large
Load Diff
@ -44,6 +44,8 @@ import { Link as RouterLink, Outlet, useLocation } from 'react-router-dom';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { useAppPresenceHeartbeat } from '../hooks/useAppPresenceHeartbeat';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LanguageSwitcher } from '../i18n/LanguageSwitcher';
|
||||
|
||||
/**
|
||||
* Main shell with sidebar navigation, top app bar, and outlet for protected pages.
|
||||
@ -52,6 +54,7 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
* @returns The responsive admin layout wrapping child routes.
|
||||
*/
|
||||
export function AppShell() {
|
||||
const { t } = useTranslation();
|
||||
const { logout, isAdmin, isStaff, auth, canApproveFundOps } = useAuth();
|
||||
const theme = useTheme();
|
||||
const isMdUp = useMediaQuery(theme.breakpoints.up('md'));
|
||||
@ -103,15 +106,15 @@ export function AppShell() {
|
||||
const navItems = useMemo(
|
||||
() =>
|
||||
[
|
||||
{ label: 'Home', to: '/home', icon: <HomeRoundedIcon /> },
|
||||
{ label: 'Wallet', to: '/wallet', icon: <AccountBalanceWalletRoundedIcon /> },
|
||||
{ label: 'Referrals', to: '/referral', icon: <GroupAddRoundedIcon /> },
|
||||
{ label: 'Profile', to: '/profile', icon: <PersonRoundedIcon /> },
|
||||
{ label: 'FAQ', to: '/help/faq', icon: <HelpOutlineRoundedIcon /> },
|
||||
{ label: t('nav.home'), to: '/home', icon: <HomeRoundedIcon /> },
|
||||
{ label: t('nav.wallet'), to: '/wallet', icon: <AccountBalanceWalletRoundedIcon /> },
|
||||
{ label: t('nav.referrals'), to: '/referral', icon: <GroupAddRoundedIcon /> },
|
||||
{ label: t('nav.profile'), to: '/profile', icon: <PersonRoundedIcon /> },
|
||||
{ label: t('nav.faq'), to: '/help/faq', icon: <HelpOutlineRoundedIcon /> },
|
||||
...(isStaff
|
||||
? [
|
||||
{
|
||||
label: 'Assistance',
|
||||
label: t('nav.support'),
|
||||
to: '/admin/support',
|
||||
icon: (
|
||||
<Badge color="error" badgeContent={unreadSupport} invisible={unreadSupport === 0}>
|
||||
@ -122,16 +125,16 @@ export function AppShell() {
|
||||
]
|
||||
: []),
|
||||
...(canApproveFundOps
|
||||
? [{ label: 'Approvals', to: '/admin/approvals', icon: <GavelRoundedIcon /> }]
|
||||
? [{ label: t('nav.approvals'), to: '/admin/approvals', icon: <GavelRoundedIcon /> }]
|
||||
: []),
|
||||
...(isAdmin
|
||||
? [
|
||||
{ label: 'Overview', to: '/dashboard', icon: <DashboardRoundedIcon /> },
|
||||
{ label: 'Rapports', to: '/admin/reports', icon: <AssessmentRoundedIcon /> },
|
||||
{ label: 'Options', to: '/options', icon: <TuneRoundedIcon /> },
|
||||
{ label: 'Users', to: '/admin/users', icon: <PeopleOutlineRoundedIcon /> },
|
||||
{ label: t('nav.overview'), to: '/dashboard', icon: <DashboardRoundedIcon /> },
|
||||
{ label: t('nav.reports'), to: '/admin/reports', icon: <AssessmentRoundedIcon /> },
|
||||
{ label: t('nav.options'), to: '/options', icon: <TuneRoundedIcon /> },
|
||||
{ label: t('nav.users'), to: '/admin/users', icon: <PeopleOutlineRoundedIcon /> },
|
||||
{
|
||||
label: 'Security',
|
||||
label: t('nav.security'),
|
||||
to: '/admin/security',
|
||||
icon: (
|
||||
<Badge color="error" badgeContent={unreadNotifications} invisible={unreadNotifications === 0}>
|
||||
@ -139,11 +142,11 @@ export function AppShell() {
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{ label: 'Settings', to: '/admin/settings', icon: <SettingsOutlinedIcon /> },
|
||||
{ label: t('nav.settings'), to: '/admin/settings', icon: <SettingsOutlinedIcon /> },
|
||||
]
|
||||
: []),
|
||||
] as const,
|
||||
[isAdmin, isStaff, canApproveFundOps, unreadNotifications, unreadSupport]
|
||||
[t, isAdmin, isStaff, canApproveFundOps, unreadNotifications, unreadSupport]
|
||||
);
|
||||
|
||||
const drawer = (
|
||||
@ -218,7 +221,7 @@ export function AppShell() {
|
||||
{!isMdUp && (
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Open navigation"
|
||||
aria-label={t('common.openNav')}
|
||||
onClick={() => setMobileOpen(true)}
|
||||
sx={{ mr: 0.5 }}
|
||||
>
|
||||
@ -243,16 +246,17 @@ export function AppShell() {
|
||||
useFlexGap
|
||||
sx={{ justifyContent: 'flex-end', minWidth: 0, alignItems: 'center', flexWrap: 'wrap' }}
|
||||
>
|
||||
<LanguageSwitcher />
|
||||
<Chip
|
||||
size="small"
|
||||
label={`Role: ${role}`}
|
||||
label={`${t('common.role')}: ${role}`}
|
||||
color={role === 'admin' ? 'primary' : 'default'}
|
||||
variant="outlined"
|
||||
sx={{ display: { xs: 'none', sm: 'inline-flex' } }}
|
||||
/>
|
||||
<Chip
|
||||
size="small"
|
||||
label={`User: ${userShort}`}
|
||||
label={`${t('common.user')}: ${userShort}`}
|
||||
variant="outlined"
|
||||
sx={{ display: { xs: 'none', md: 'inline-flex' } }}
|
||||
/>
|
||||
@ -264,7 +268,7 @@ export function AppShell() {
|
||||
size="small"
|
||||
sx={{ borderColor: 'rgba(255,255,255,0.2)', px: 1.5 }}
|
||||
>
|
||||
Logout
|
||||
{t('common.logout')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Toolbar>
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Network health banner — shown on the admin Network status page only.
|
||||
* Polls `/health` for testnet and withdrawal configuration.
|
||||
*/
|
||||
import { Alert, AlertTitle, Box, Button, Chip, Stack, Typography } from '@mui/material';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { api } from '../services/api';
|
||||
|
||||
type Health = {
|
||||
@ -14,12 +14,8 @@ type Health = {
|
||||
withdrawalsEnabled: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Displays backend network configuration with loading, error, and safe-testnet states.
|
||||
*
|
||||
* @returns An alert banner summarizing USDT (TRC20) network, withdrawal, and environment settings.
|
||||
*/
|
||||
export function NetworkBanner() {
|
||||
const { t } = useTranslation();
|
||||
const q = useQuery({
|
||||
queryKey: ['health'],
|
||||
queryFn: async () => {
|
||||
@ -31,14 +27,8 @@ export function NetworkBanner() {
|
||||
if (q.isLoading) {
|
||||
return (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Alert
|
||||
severity="info"
|
||||
sx={{
|
||||
borderRadius: 2,
|
||||
'& .MuiAlert-message': { width: '100%' },
|
||||
}}
|
||||
>
|
||||
Chargement de la configuration réseau…
|
||||
<Alert severity="info" sx={{ borderRadius: 2, '& .MuiAlert-message': { width: '100%' } }}>
|
||||
{t('network.loading')}
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
@ -52,11 +42,11 @@ export function NetworkBanner() {
|
||||
sx={{ borderRadius: 2, '& .MuiAlert-message': { width: '100%' } }}
|
||||
action={
|
||||
<Button color="inherit" size="small" onClick={() => q.refetch()}>
|
||||
Réessayer
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
Impossible de charger `/health`.
|
||||
{t('network.loadFailed')}
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
@ -76,23 +66,25 @@ export function NetworkBanner() {
|
||||
}}
|
||||
action={
|
||||
<Button color="inherit" size="small" onClick={() => q.refetch()}>
|
||||
Actualiser
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<AlertTitle>
|
||||
État réseau {safe ? 'OK (testnet)' : 'Vérifier la configuration'}
|
||||
{safe ? t('network.titleOk') : t('network.titleCheck')}
|
||||
</AlertTitle>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<Chip size="small" label="USDT (TRC20)" />
|
||||
<Chip size="small" label={`TRON : ${network}`} />
|
||||
<Chip size="small" label={t('network.tronNetwork', { network })} />
|
||||
<Chip
|
||||
size="small"
|
||||
color={withdrawalsEnabled ? 'error' : 'default'}
|
||||
label={`Retraits : ${withdrawalsEnabled ? 'ACTIVÉS' : 'DÉSACTIVÉS'}`}
|
||||
label={
|
||||
withdrawalsEnabled ? t('network.withdrawalsOn') : t('network.withdrawalsOff')
|
||||
}
|
||||
/>
|
||||
<Typography variant="body2" sx={{ opacity: 0.85 }}>
|
||||
env : <b>{env}</b>
|
||||
<Trans i18nKey="network.envLabel" values={{ env }} components={{ b: <b /> }} />
|
||||
</Typography>
|
||||
</Stack>
|
||||
</Alert>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user