From 79d18dae1397881a04b507534591c6c6506fcba8 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 2 Jul 2026 19:32:28 +0200 Subject: [PATCH] After finalise with the internationarization of web part --- prediqo_web/package-lock.json | 87 +- prediqo_web/package.json | 3 + prediqo_web/src/app/App.tsx | 12 +- prediqo_web/src/app/theme/theme.ts | 23 +- .../src/features/approvals/ApprovalsPage.tsx | 67 +- .../src/features/auth/ForgotPasswordPage.tsx | 26 +- prediqo_web/src/features/auth/LoginPage.tsx | 56 +- .../src/features/auth/RegisterPage.tsx | 74 +- .../src/features/auth/ResetPasswordPage.tsx | 26 +- prediqo_web/src/features/auth/SetupPage.tsx | 128 +- .../src/features/auth/VerifyEmailPage.tsx | 25 +- .../candle-predict/CandlePredictPage.tsx | 86 +- .../components/AdminPoolInsights.tsx | 44 +- .../components/AutoPredictionBanner.tsx | 24 +- .../components/AutoPredictionPanel.tsx | 143 +- .../components/BettingPanel.tsx | 47 +- .../components/CandlestickChart.tsx | 4 +- .../components/CustomStakeAmountField.tsx | 20 +- .../components/IntervalSelector.tsx | 6 +- .../components/MultiCandleBettingPanel.tsx | 61 +- .../candle-predict/components/PoolBar.tsx | 24 +- .../components/RecentPredictionsPanel.tsx | 181 +- .../components/StakeWalletBalanceBar.tsx | 18 +- .../components/StakeWalletSelector.tsx | 33 +- .../components/TestModeBanner.tsx | 9 +- .../candle-predict/utils/stakeAmountInput.ts | 31 + .../catalog/CandlePredictConfigPanel.tsx | 122 +- .../catalog/CandlePredictIntervalsPanel.tsx | 183 +- .../catalog/CandlePredictMultiLevelsPanel.tsx | 55 +- .../src/features/catalog/CatalogAdminPage.tsx | 121 +- .../features/countries/CountriesAdminPage.tsx | 45 +- .../src/features/dashboard/DashboardPage.tsx | 45 +- .../dashboard/components/DashboardCharts.tsx | 8 +- .../components/DashboardFiltersBar.tsx | 68 +- .../components/DashboardSections.tsx | 413 ++-- .../components/PersonalizationToolbar.tsx | 29 +- .../dashboard/components/ReportDetailLink.tsx | 6 +- .../components/TreasuryDashboardCards.tsx | 14 +- .../src/features/dashboard/utils/format.ts | 17 - prediqo_web/src/features/faq/FaqAdminPage.tsx | 100 +- prediqo_web/src/features/faq/FaqPage.tsx | 35 +- prediqo_web/src/features/home/HomePage.tsx | 30 +- .../src/features/home/components/GameCard.tsx | 30 +- .../features/network/NetworkStatusPage.tsx | 10 +- .../src/features/options/OptionsPage.tsx | 582 ++--- .../src/features/profile/ProfilePage.tsx | 58 +- .../profile/components/ChangePasswordForm.tsx | 25 +- .../components/EmailVerificationPanel.tsx | 42 +- .../profile/components/ProfileEditForm.tsx | 69 +- .../profile/components/ReferralPanel.tsx | 39 +- .../profile/components/TwoFactorPanel.tsx | 35 +- .../features/referral/ReferralAdminPage.tsx | 174 +- .../referral/ReferralFraudDashboardPage.tsx | 138 +- .../src/features/referral/ReferralPage.tsx | 111 +- .../components/ReferralCommissionsPanel.tsx | 28 +- .../referral/components/ReferralTableView.tsx | 47 +- .../referral/components/ReferralTreeView.tsx | 38 +- .../src/features/reports/ReportDetailPage.tsx | 122 +- .../src/features/reports/ReportsHubPage.tsx | 14 +- .../src/features/reports/reportBulkActions.ts | 27 +- .../features/security/SecurityAdminPage.tsx | 199 +- .../src/features/settings/SettingsPage.tsx | 102 +- .../src/features/support/SupportAdminPage.tsx | 97 +- .../support/components/SupportChatPanel.tsx | 38 +- .../support/components/SupportWidget.tsx | 8 +- .../test-wallet/TestWalletAdminPage.tsx | 42 +- .../features/treasury/TreasuryAdminPage.tsx | 82 +- .../src/features/users/UserManagementPage.tsx | 424 ++-- .../src/features/users/adminUserTypes.ts | 39 +- .../src/features/wallet/WalletPage.tsx | 32 +- .../wallet/components/BonusWalletCard.tsx | 20 +- .../wallet/components/MainAssetCard.tsx | 16 +- .../wallet/components/ReceiveDialog.tsx | 31 +- .../wallet/components/TestWalletCard.tsx | 34 +- .../wallet/components/TransactionList.tsx | 24 +- .../wallet/components/TransferDialog.tsx | 58 +- .../wallet/components/WithdrawDialog.tsx | 96 +- .../wallet/utils/transactionDisplay.ts | 25 +- prediqo_web/src/main.tsx | 1 + .../shared/components/CountryAutocomplete.tsx | 10 +- .../src/shared/components/GenderSelect.tsx | 22 +- .../src/shared/components/PageHeader.tsx | 7 +- .../src/shared/constants/userGender.ts | 13 +- .../src/shared/i18n/LanguageSwitcher.tsx | 74 + prediqo_web/src/shared/i18n/index.ts | 44 + prediqo_web/src/shared/i18n/locales/en.ts | 2046 ++++++++++++++++ prediqo_web/src/shared/i18n/locales/fr.ts | 2059 +++++++++++++++++ prediqo_web/src/shared/layout/AppShell.tsx | 40 +- .../src/shared/network/NetworkBanner.tsx | 34 +- 89 files changed, 7263 insertions(+), 2592 deletions(-) create mode 100644 prediqo_web/src/shared/i18n/LanguageSwitcher.tsx create mode 100644 prediqo_web/src/shared/i18n/index.ts create mode 100644 prediqo_web/src/shared/i18n/locales/en.ts create mode 100644 prediqo_web/src/shared/i18n/locales/fr.ts diff --git a/prediqo_web/package-lock.json b/prediqo_web/package-lock.json index ef9bd15b..ce07fed1 100644 --- a/prediqo_web/package-lock.json +++ b/prediqo_web/package-lock.json @@ -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", diff --git a/prediqo_web/package.json b/prediqo_web/package.json index 19b3fde5..5c1f8278 100644 --- a/prediqo_web/package.json +++ b/prediqo_web/package.json @@ -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", diff --git a/prediqo_web/src/app/App.tsx b/prediqo_web/src/app/App.tsx index 02d0027d..5a443be9 100644 --- a/prediqo_web/src/app/App.tsx +++ b/prediqo_web/src/app/App.tsx @@ -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 ( @@ -35,3 +39,7 @@ export function App() { ); } + +export function App() { + return ; +} diff --git a/prediqo_web/src/app/theme/theme.ts b/prediqo_web/src/app/theme/theme.ts index da8be460..9512e739 100644 --- a/prediqo_web/src/app/theme/theme.ts +++ b/prediqo_web/src/app/theme/theme.ts @@ -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); } diff --git a/prediqo_web/src/features/approvals/ApprovalsPage.tsx b/prediqo_web/src/features/approvals/ApprovalsPage.tsx index d4daf572..9236594d 100644 --- a/prediqo_web/src/features/approvals/ApprovalsPage.tsx +++ b/prediqo_web/src/features/approvals/ApprovalsPage.tsx @@ -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 = { - 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(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 ( - You do not have permission to approve fund operations. - ); + return {t('admin.approvals.noPermission')}; } const items = listQ.data?.items ?? []; @@ -95,10 +102,10 @@ export function ApprovalsPage() { } - title="Approvals" - subtitle="Review and approve sensitive fund operations" + title={t('admin.approvals.title')} + subtitle={t('admin.approvals.subtitle')} actions={ - void listQ.refetch()} /> + void listQ.refetch()} /> } /> @@ -110,7 +117,7 @@ export function ApprovalsPage() { {listQ.isError && ( - Failed to load approval queue. + {t('admin.approvals.loadError')} )} @@ -118,11 +125,11 @@ export function ApprovalsPage() { - Type - Requested by - Created - Status - Actions + {t('admin.approvals.type')} + {t('admin.approvals.requestedBy')} + {t('admin.approvals.created')} + {t('common.status')} + {t('admin.approvals.actions')} @@ -130,14 +137,14 @@ export function ApprovalsPage() { - No pending approvals. + {t('admin.approvals.noPending')} ) : ( items.map((r) => ( - {OP_LABELS[r.operationType] ?? r.operationType} + {opLabel(r.operationType)} {r.requestedBy.slice(0, 8)}… @@ -153,10 +160,10 @@ export function ApprovalsPage() { disabled={approveMut.isPending} onClick={() => void approveMut.mutateAsync(r.id)} > - Approve + {t('admin.approvals.approve')} @@ -168,13 +175,13 @@ export function ApprovalsPage() { setRejectId(null)} maxWidth="sm" fullWidth> - Reject request + {t('admin.approvals.rejectTitle')} - Provide a reason for rejection. + {t('admin.approvals.rejectHint')} - + diff --git a/prediqo_web/src/features/auth/ForgotPasswordPage.tsx b/prediqo_web/src/features/auth/ForgotPasswordPage.tsx index 8be05a80..dbf20880 100644 --- a/prediqo_web/src/features/auth/ForgotPasswordPage.tsx +++ b/prediqo_web/src/features/auth/ForgotPasswordPage.tsx @@ -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(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 ( - + + + + - Reset password - - - Enter your email and we'll send you a secure link to choose a new password. + {t('auth.resetPassword')} + {t('auth.resetPasswordSubtitle')} {error && {error}} @@ -54,7 +58,7 @@ export function ForgotPasswordPage() { {devUrl && ( - Local / console mode — no email is sent. Open this link to reset your password: + {t('auth.consoleResetHint')} {devUrl} @@ -62,7 +66,7 @@ export function ForgotPasswordPage() { )} setEmail(e.target.value)} @@ -70,11 +74,11 @@ export function ForgotPasswordPage() { autoComplete="email" /> - Back to sign in + {t('auth.backToSignIn')} diff --git a/prediqo_web/src/features/auth/LoginPage.tsx b/prediqo_web/src/features/auth/LoginPage.tsx index 18d12c14..edf04807 100644 --- a/prediqo_web/src/features/auth/LoginPage.tsx +++ b/prediqo_web/src/features/auth/LoginPage.tsx @@ -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 ( - + + + + Prediqo - - Prediction games platform — sign in to manage or play. - + {t('auth.brandSubtitle')} - {verifyHint && ( - - We sent a confirmation link to your email. Verify your address before signing in. - - )} + {verifyHint && {t('auth.verifyEmailHint')}} {setupQ.data?.needsSetup && ( - Aucun administrateur n'est configuré.{' '} + {t('auth.noAdminConfigured')}{' '} - Initialiser la plateforme + {t('auth.initializePlatform')} )} @@ -139,8 +139,7 @@ export function LoginPage() { {emailNotVerified && ( - Your account exists but the email is not verified yet. Request a new confirmation - link below (check spam if nothing arrives). + {t('auth.emailNotVerified')} )} {resendSuccess && {resendSuccess}} {devVerifyUrl && ( - Dev link:{' '} + {t('auth.devVerifyLink')}{' '} - Open verification URL + {t('auth.openVerificationUrl')} )} setEmail(e.target.value)} autoComplete="email" fullWidth /> setPassword(e.target.value)} type="password" @@ -177,29 +176,29 @@ export function LoginPage() { fullWidth /> setTotpCode(e.target.value)} slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }} fullWidth /> - Forgot password? + {t('auth.forgotPassword')} - Foire aux questions + {t('auth.faqLink')} - No account yet?{' '} + {t('auth.noAccount')}{' '} - Create one + {t('auth.createOne')} @@ -208,4 +207,3 @@ export function LoginPage() { ); } - diff --git a/prediqo_web/src/features/auth/RegisterPage.tsx b/prediqo_web/src/features/auth/RegisterPage.tsx index 41e0242a..1a76908b 100644 --- a/prediqo_web/src/features/auth/RegisterPage.tsx +++ b/prediqo_web/src/features/auth/RegisterPage.tsx @@ -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 ( - + + + + - Create account - - - Join Prediqo — use a friend's referral link or sign up directly. + {t('auth.createAccount')} + {t('auth.registerSubtitle')} {refFromUrl && ( - You were invited with referral code {refFromUrl}. + }} /> )} @@ -136,14 +137,14 @@ export function RegisterPage() { {success && {success}} setFullName(e.target.value)} fullWidth autoComplete="name" /> setEmail(e.target.value)} @@ -151,14 +152,14 @@ export function RegisterPage() { autoComplete="email" /> setPhone(e.target.value)} fullWidth autoComplete="tel" /> setPassword(e.target.value)} @@ -167,60 +168,51 @@ export function RegisterPage() { /> - + - {countriesQ.isError && ( - - Could not load country list. Ask an admin to sync countries, then refresh. - - )} + {countriesQ.isError && {t('auth.countriesLoadFailed')}} 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()} /> - Already have an account?{' '} + {t('auth.alreadyHaveAccount')}{' '} - Sign in + {t('auth.signIn')} diff --git a/prediqo_web/src/features/auth/ResetPasswordPage.tsx b/prediqo_web/src/features/auth/ResetPasswordPage.tsx index aa83ee36..dfca9eb2 100644 --- a/prediqo_web/src/features/auth/ResetPasswordPage.tsx +++ b/prediqo_web/src/features/auth/ResetPasswordPage.tsx @@ -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(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 ( - + + + + - Choose new password + {t('auth.chooseNewPassword')} {tokenValid === null && ( @@ -85,7 +91,7 @@ export function ResetPasswordPage() { {tokenValid === false && !success && ( - Invalid or expired reset link. Request a new one from the forgot password page. + {t('auth.invalidResetLink')} )} @@ -93,7 +99,7 @@ export function ResetPasswordPage() { {success} )} @@ -102,7 +108,7 @@ export function ResetPasswordPage() { {error && {error}} setPassword(e.target.value)} @@ -110,7 +116,7 @@ export function ResetPasswordPage() { autoComplete="new-password" /> setConfirm(e.target.value)} @@ -118,14 +124,14 @@ export function ResetPasswordPage() { autoComplete="new-password" /> )} - Request a new link + {t('auth.requestNewLink')} diff --git a/prediqo_web/src/features/auth/SetupPage.tsx b/prediqo_web/src/features/auth/SetupPage.tsx index 1a15f3ec..80117687 100644 --- a/prediqo_web/src/features/auth/SetupPage.tsx +++ b/prediqo_web/src/features/auth/SetupPage.tsx @@ -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('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 ( - - Chargement… + const shell = (children: ReactNode) => ( + + + - ); + {children} + + ); + + if (statusQ.isLoading) { + return shell({t('setup.loading')}); } if (statusQ.isError) { - return ( - - - - - Impossible de vérifier l'état d'initialisation - - - L'API n'a pas répondu. Vérifiez que{' '} - VITE_API_BASE_URL correspond à l'URL publique (ex.{' '} - http://prediqo.redirectme.net:9080) puis reconstruisez le frontend. - - - - - + return shell( + + + + {t('setup.statusCheckFailed')} + + + , code: }} + /> + + + + ); } if (!needsSetup) { - return ( - - - - - Configuration terminée - - - Un compte administrateur existe déjà. Connectez-vous pour accéder à la plateforme. - - - - - + return shell( + + + + {t('setup.setupComplete')} + + {t('setup.adminExists')} + + + ); } return ( - + + + + - Initialisation Prediqo + {t('setup.title')} - - Créez le premier compte administrateur pour configurer la plateforme en production. - + {t('setup.subtitle')} {!setupEnabled && ( - Définissez la variable d'environnement{' '} - INITIAL_SETUP_TOKEN sur le serveur (min. 16 caractères aléatoires), puis - redémarrez l'API. + }} /> )} setSetupToken(e.target.value)} - helperText="Secret configuré uniquement sur le serveur — ne le partagez pas." + helperText={t('setup.setupTokenHelper')} sx={{ mb: 2 }} /> setTab(v)} sx={{ mb: 2 }}> - - + + setEmail(e.target.value)} @@ -181,25 +184,24 @@ export function SetupPage() { {tab === 'create' && ( <> setFullName(e.target.value)} /> setPassword(e.target.value)} - helperText="Minimum 8 caractères" + helperText={t('setup.passwordMin')} /> )} {tab === 'promote' && ( - 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')} )} @@ -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')} - Retour à la connexion + {t('setup.backToLogin')} diff --git a/prediqo_web/src/features/auth/VerifyEmailPage.tsx b/prediqo_web/src/features/auth/VerifyEmailPage.tsx index 4cbc5954..e7b20f38 100644 --- a/prediqo_web/src/features/auth/VerifyEmailPage.tsx +++ b/prediqo_web/src/features/auth/VerifyEmailPage.tsx @@ -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(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 ( + + + - Verifying your email… + {t('auth.verifyingEmail')} )} @@ -90,10 +97,10 @@ export function VerifyEmailPage() { {message} )} @@ -105,10 +112,10 @@ export function VerifyEmailPage() { {message} - Request a new link from your profile if this one expired. + {t('auth.requestNewLinkFromProfile')} )} @@ -116,10 +123,10 @@ export function VerifyEmailPage() { {status === 'missing' && ( <> - Missing verification token. Open the full link from your email. + {t('auth.missingVerificationToken')} )} diff --git a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx index 61efeeb3..c667beff 100644 --- a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx +++ b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx @@ -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() { }} > - Single candle + {t('candlePredict.singleCandle')} - Multi-candle + {t('candlePredict.multiCandle')} ) : 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 ( - Failed to load Candle Predict. {detail ? `${detail}. ` : ''} + {t('candlePredict.loadError')} {detail ? `${detail}. ` : ''} {hint} ); @@ -486,7 +509,7 @@ export function CandlePredictPage() { + } @@ -494,19 +517,14 @@ export function CandlePredictPage() { title={ - Candle Predict + {t('candlePredict.title')} } - subtitle={ - <> - Prédisez si la prochaine bougie sera baissière (Short ↓) ou haussière ( - Long ↑), puis attendez le résultat de la manche. - - } + subtitle={ }} />} mb={2.5} - actions={ void refresh()} />} + actions={ void refresh()} />} /> - Round status + + {t('candlePredict.roundStatus.title')} + - This game is temporarily disabled by an administrator. + {t('candlePredict.gameDisabledAdmin')} )} diff --git a/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx b/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx index d9d153b1..b518beb4 100644 --- a/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx +++ b/prediqo_web/src/features/candle-predict/components/AdminPoolInsights.tsx @@ -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 ( - Vue administrateur — mécanismes internes + {t('candlePredict.adminInsights.title')} - + - {neutralityRulesSummary}. {NEUTRAL_ROUND_BEHAVIOR} + {neutralityRulesSummary}. {t('candlePredict.adminInsights.neutralBehavior')} - Non visible pour les joueurs. Les pools et règles de règlement ne doivent pas influencer leurs - prédictions. + {t('candlePredict.adminInsights.footer')} {round && } diff --git a/prediqo_web/src/features/candle-predict/components/AutoPredictionBanner.tsx b/prediqo_web/src/features/candle-predict/components/AutoPredictionBanner.tsx index a3d41617..64a723ba 100644 --- a/prediqo_web/src/features/candle-predict/components/AutoPredictionBanner.tsx +++ b/prediqo_web/src/features/candle-predict/components/AutoPredictionBanner.tsx @@ -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({ }} > - Prédiction auto active · {autoLabel} + + {t('candlePredict.autoBanner.activeOnInterval', { interval: autoLabel })} + {directionLabel} · {settings.stakeDisplay} USDT · {modeLabel} @@ -68,18 +74,20 @@ export function AutoPredictionBanner({ action={ onSwitchToAutoInterval ? ( ) : undefined } > - Auto prediction active on {autoLabel} + {t('candlePredict.autoBanner.activeOtherInterval', { interval: autoLabel })} - 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, + })} diff --git a/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx b/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx index 98c03cde..ff9452a9 100644 --- a/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/AutoPredictionPanel.tsx @@ -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; 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({ > - Target period: + {t('candlePredict.autoPrediction.targetPeriod')} {viewingDifferentPeriod ? ( - You are viewing {interval.label}. Save to move auto to {interval.label}. + {t('candlePredict.autoPrediction.viewingDifferent', { + viewing: interval.label, + target: interval.label, + })} ) : ( - Set from the prediction period you select when saving. One auto config per account. + {t('candlePredict.autoPrediction.targetHint')} )} - Direction - + {t('candlePredict.direction.shortCandle')} + {t('candlePredict.direction.longCandle')} @@ -214,58 +232,62 @@ export function AutoPredictionPanel({ /> - Mode + {t('candlePredict.autoPrediction.mode')} {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')} {mode === 'interval' && ( )} {serverEnabled && ( )} @@ -290,9 +312,9 @@ export function AutoPredictionPanel({ - Auto Prediction + {t('candlePredict.autoPrediction.title')} - Activez pour parier automatiquement à chaque manche. + {t('candlePredict.autoPrediction.enableHint')} @@ -301,12 +323,12 @@ export function AutoPredictionPanel({ control={ void handleToggle(e.target.checked)} /> } - label="Activer la prédiction auto" + label={t('candlePredict.autoPrediction.enable')} /> - {current.lastAutoBetAt && ( + {lastAutoBetLabel && ( - Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()} + {lastAutoBetLabel} )} @@ -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({ > - Prédiction auto active + {t('candlePredict.autoPrediction.titleActive')} void handleToggle(e.target.checked)} /> } - label="Désactiver" + label={t('candlePredict.autoPrediction.disable')} /> @@ -364,12 +385,17 @@ export function AutoPredictionPanel({ sx={{ fontWeight: 700 }} /> - + - {current.lastAutoBetAt && ( + {lastAutoBetLabel && ( - Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()} + {lastAutoBetLabel} )} @@ -390,14 +416,12 @@ export function AutoPredictionPanel({ - Auto Prediction + {t('candlePredict.autoPrediction.title')} {!showCompact && ( - - Place automatiquement une prédiction par manche 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 Enregistrer. + + }} /> )} @@ -407,12 +431,7 @@ export function AutoPredictionPanel({ <> - + - {current.lastAutoBetAt && ( + {lastAutoBetLabel && ( - Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()} + {lastAutoBetLabel} )} @@ -444,23 +463,21 @@ export function AutoPredictionPanel({ control={ void handleToggle(e.target.checked)} /> } - label="Activer la prédiction auto" + label={t('candlePredict.autoPrediction.enable')} /> )} {configuring && !serverEnabled && ( - - Paramétrez votre prédiction ci-dessous, puis cliquez sur{' '} - Enregistrer les paramètres auto pour activer le mode. Aucune mise ne sera - placée avant l'enregistrement. + + }} /> )} {settingsForm} - {!showCompact && current.lastAutoBetAt && ( + {!showCompact && lastAutoBetLabel && ( - Dernière mise auto : {new Date(current.lastAutoBetAt).toLocaleString()} + {lastAutoBetLabel} )} diff --git a/prediqo_web/src/features/candle-predict/components/BettingPanel.tsx b/prediqo_web/src/features/candle-predict/components/BettingPanel.tsx index 74f385e9..c87115da 100644 --- a/prediqo_web/src/features/candle-predict/components/BettingPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/BettingPanel.tsx @@ -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({ - Place your prediction + {t('candlePredict.betting.title')} - Short = bougie baissière · Long = bougie haussière. Choisissez une direction et confirmez votre - mise. + {t('candlePredict.betting.hint')} {round?.status === 'betting' && predictionOpen && ( 0 && ( )} {!config.isActive && ( - Game disabled by admin — predictions are unavailable. + {t('candlePredict.betting.gameDisabled')} )} {hasPrediction && ( - Your prediction is locked for this round. + {t('candlePredict.betting.predictionLocked')} )} {round?.status === 'locked' && !hasPrediction && ( - Candle in progress — place your prediction when the window opens - {untilOpen > 0 ? ` (in ${formatWait(untilOpen)})` : ''}. + {t('candlePredict.betting.candleInProgress', { + suffix: untilOpen > 0 ? ` (${formatWait(untilOpen)})` : '', + })} )} {round?.status === 'waiting' && ( - The next prediction window opens shortly before the new candle. + {t('candlePredict.betting.nextWindowOpens')} )} {error && !hasPrediction && {error}} @@ -141,7 +146,9 @@ export function BettingPanel({ - Stake amount ({config.walletTypeCode.replace('_', ' ')}) + {t('candlePredict.betting.stakeAmount', { + code: config.walletTypeCode.replace('_', ' '), + })} {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 })} /> - Prediction + {t('candlePredict.betting.prediction')} - Short ↓ + {t('candlePredict.betting.short')} ↓ - Long ↑ + {t('candlePredict.betting.long')} ↑ @@ -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, + })} diff --git a/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx b/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx index 8987cf80..1e6ed367 100644 --- a/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx +++ b/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx @@ -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(null); const chartRef = useRef(null); const seriesRef = useRef | null>(null); @@ -255,7 +257,7 @@ export function CandlestickChart({ userSelect: 'none', }} > - Glisser ou molette pour voir l'historique + {t('candlePredict.chart.scrollHint')} ); diff --git a/prediqo_web/src/features/candle-predict/components/CustomStakeAmountField.tsx b/prediqo_web/src/features/candle-predict/components/CustomStakeAmountField.tsx index 5bb056c0..1cc89de7 100644 --- a/prediqo_web/src/features/candle-predict/components/CustomStakeAmountField.tsx +++ b/prediqo_web/src/features/candle-predict/components/CustomStakeAmountField.tsx @@ -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 ( - Prediction period + {t('candlePredict.interval.title')} {intervals.map((interval) => ( @@ -30,7 +32,7 @@ export function IntervalSelector({ intervals, selectedMinutes, onChange }: Props ))} - Votre prédiction cible la manche qui se clôture à la fin de cette période. + {t('candlePredict.interval.hint')} ); diff --git a/prediqo_web/src/features/candle-predict/components/MultiCandleBettingPanel.tsx b/prediqo_web/src/features/candle-predict/components/MultiCandleBettingPanel.tsx index 9b91eed2..706a8d64 100644 --- a/prediqo_web/src/features/candle-predict/components/MultiCandleBettingPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/MultiCandleBettingPanel.tsx @@ -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 ( : } - 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({ > - Multi-candle prediction in progress + {t('candlePredict.multiBetting.inProgress')} - 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, + })} {activeBet.sequenceDirections.map((dir, i) => ( @@ -141,7 +148,7 @@ export function MultiCandleBettingPanel({ {i < step ? ( ) : i === step ? ( - + ) : ( )} @@ -149,8 +156,7 @@ export function MultiCandleBettingPanel({ ))} - One wrong candle ends the sequence immediately. Your stake stays pending until the final - candle is validated. + {t('candlePredict.multiBetting.progressAlert')} @@ -169,38 +175,38 @@ export function MultiCandleBettingPanel({ - Multi-candle prediction + {t('candlePredict.multiBetting.title')} - Predict {level} consecutive candles in exact order. Minimum level 2 — use single mode for - one candle. + {t('candlePredict.multiBetting.hint')} {!enabledLevels.length && ( - No multi-candle levels are currently available. + {t('candlePredict.multiBetting.noLevels')} )} {hasSinglePrediction && ( - - You already have a single-candle prediction for this round (including auto). Multi-candle - is unavailable until the next window. - + {t('candlePredict.multiBetting.singleBlocksMulti')} )} {enabledLevels.length > 0 && ( <> - Level + {t('candlePredict.multiBetting.level')} @@ -208,7 +214,7 @@ export function MultiCandleBettingPanel({ - Your sequence + {t('candlePredict.multiBetting.yourSequence')} {sequence.map((dir, index) => ( @@ -219,7 +225,7 @@ export function MultiCandleBettingPanel({ sx={{ alignItems: { sm: 'center' } }} > - Candle {index + 1} + {t('candlePredict.multiBetting.candleN', { n: index + 1 })} - Short + {t('candlePredict.betting.short')} - Long + {t('candlePredict.betting.long')} @@ -253,7 +259,7 @@ export function MultiCandleBettingPanel({ - Stake amount + {t('candlePredict.betting.stake')} {config.stakeAmounts.map((amount) => ( @@ -284,7 +290,10 @@ export function MultiCandleBettingPanel({ {levelConfig && ( - Gain en cas de succès : mise × {levelConfig.payoutMultiplier} ({interval.label}). + {t('candlePredict.multiBetting.winHint', { + multiplier: levelConfig.payoutMultiplier, + interval: interval.label, + })} )} @@ -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 })} )} diff --git a/prediqo_web/src/features/candle-predict/components/PoolBar.tsx b/prediqo_web/src/features/candle-predict/components/PoolBar.tsx index 3104cbcc..72d0d1a0 100644 --- a/prediqo_web/src/features/candle-predict/components/PoolBar.tsx +++ b/prediqo_web/src/features/candle-predict/components/PoolBar.tsx @@ -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 ( - Stake pools + {t('candlePredict.poolBar.title')} - Short (bearish) + {t('candlePredict.direction.shortBearish')} {hasAmounts ? `${shortPool.toFixed(0)} · ` : ''} @@ -58,7 +60,7 @@ export function PoolBar({ round, poolWinnerRule }: Props) { - Long (bullish) + {t('candlePredict.direction.longBullish')} {hasAmounts ? `${longPool.toFixed(0)} · ` : ''} @@ -78,7 +80,7 @@ export function PoolBar({ round, poolWinnerRule }: Props) { - {poolWinnerRulePoolHint(poolWinnerRule)} + {t('candlePredict.poolBar.hint', { winner })} ); diff --git a/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx b/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx index ba1deb52..be37cfa9 100644 --- a/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx +++ b/prediqo_web/src/features/candle-predict/components/RecentPredictionsPanel.tsx @@ -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 ( - {formatStatus(status)} + {formatStatus(t, status)} ); } -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 ( {prediction.isAuto && ( ) } - 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 ) : ( )} - {isShort ? 'Short' : 'Long'} + {isShort ? t('candlePredict.betting.short') : t('candlePredict.betting.long')} ); } -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 ; + return ; } 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 ( @@ -309,7 +315,7 @@ function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction {i + 1}. - + - {multiProgressDetail(prediction) && ( + {progressDetail && ( - {multiProgressDetail(prediction)} + {progressDetail} )} ); } -function PredictionCell({ prediction }: { prediction: CandlePredictPrediction }) { +function PredictionCell({ prediction, t }: { prediction: CandlePredictPrediction; t: TFunction }) { if (isMultiPrediction(prediction)) { - return ; + return ; } - return ; + return ; } 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 ( @@ -424,10 +432,13 @@ export function RecentPredictionsPanel({ sx={{ alignItems: 'center', justifyContent: 'space-between', mb: 1.5, flexWrap: 'wrap' }} > - Recent predictions + {t('candlePredict.recentPredictions.title')} - {total} total · {PREDICTIONS_PAGE_SIZE} per page + {t('candlePredict.recentPredictions.totalPerPage', { + total, + size: PREDICTIONS_PAGE_SIZE, + })} @@ -437,8 +448,9 @@ export function RecentPredictionsPanel({ <> {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 ( - + } + label={} size="small" variant="outlined" sx={{ @@ -473,7 +485,7 @@ export function RecentPredictionsPanel({ - + @@ -485,8 +497,11 @@ export function RecentPredictionsPanel({ )} - {period.placedAt} · Stake {p.stakeDisplay} · Payout{' '} - {p.payoutDisplay > 0 ? p.payoutDisplay : '—'} + {t('candlePredict.recentPredictions.stakeLine', { + placed: period.placedAt, + stake: p.stakeDisplay, + payout, + })} {progressDetail && !isMultiPrediction(p) && ( @@ -497,7 +512,9 @@ export function RecentPredictionsPanel({ ); })} {!items.length && ( - No predictions yet + + {t('candlePredict.recentPredictions.empty')} + )} @@ -519,23 +536,23 @@ export function RecentPredictionsPanel({
- Mode - Prediction - Period + {t(`${cols}.mode`)} + {t(`${cols}.prediction`)} + {t(`${cols}.period`)} - Stake + {t(`${cols}.stake`)} - Account - Status + {t(`${cols}.account`)} + {t(`${cols}.status`)} - Payout + {t(`${cols}.payout`)} {items.map((p) => { - const period = formatCandlePeriod(p); - const progressDetail = multiProgressDetail(p); + const period = formatCandlePeriod(t, p); + const progressDetail = multiProgressDetail(t, p); return ( - + - + @@ -559,7 +576,7 @@ export function RecentPredictionsPanel({ - + {progressDetail && ( - No predictions yet + {t('candlePredict.recentPredictions.empty')} )} @@ -614,7 +631,7 @@ export function RecentPredictionsPanel({ {predictionsQ.isError && ( - Could not load predictions. Try refreshing the page. + {t('candlePredict.recentPredictions.loadError')} )} diff --git a/prediqo_web/src/features/candle-predict/components/StakeWalletBalanceBar.tsx b/prediqo_web/src/features/candle-predict/components/StakeWalletBalanceBar.tsx index 22b0acb8..254580c3 100644 --- a/prediqo_web/src/features/candle-predict/components/StakeWalletBalanceBar.tsx +++ b/prediqo_web/src/features/candle-predict/components/StakeWalletBalanceBar.tsx @@ -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 ( - Vos portefeuilles de mise + {t('candlePredict.stakeWallet.barTitle')} - + {balancesVisible ? ( @@ -151,7 +157,7 @@ export function StakeWalletBalanceBar({ }} > } accent="#D6B25E" @@ -159,7 +165,7 @@ export function StakeWalletBalanceBar({ hidden={!balancesVisible} /> } accent="#7C5CFF" @@ -167,7 +173,7 @@ export function StakeWalletBalanceBar({ hidden={!balancesVisible} /> } accent="#4CAF50" diff --git a/prediqo_web/src/features/candle-predict/components/StakeWalletSelector.tsx b/prediqo_web/src/features/candle-predict/components/StakeWalletSelector.tsx index 0a188a92..51f7d55a 100644 --- a/prediqo_web/src/features/candle-predict/components/StakeWalletSelector.tsx +++ b/prediqo_web/src/features/candle-predict/components/StakeWalletSelector.tsx @@ -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 ( - Stake wallet + {t('candlePredict.stakeWalletSelector.label')} diff --git a/prediqo_web/src/features/candle-predict/components/TestModeBanner.tsx b/prediqo_web/src/features/candle-predict/components/TestModeBanner.tsx index be1d977e..61d4ea5d 100644 --- a/prediqo_web/src/features/candle-predict/components/TestModeBanner.tsx +++ b/prediqo_web/src/features/candle-predict/components/TestModeBanner.tsx @@ -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 ( - Mode test - - 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. + + {t('candlePredict.testMode.title')} + {t('candlePredict.testMode.hint')} ); diff --git a/prediqo_web/src/features/candle-predict/utils/stakeAmountInput.ts b/prediqo_web/src/features/candle-predict/utils/stakeAmountInput.ts index 31aed44e..dbb6de3b 100644 --- a/prediqo_web/src/features/candle-predict/utils/stakeAmountInput.ts +++ b/prediqo_web/src/features/candle-predict/utils/stakeAmountInput.ts @@ -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 } diff --git a/prediqo_web/src/features/catalog/CandlePredictConfigPanel.tsx b/prediqo_web/src/features/catalog/CandlePredictConfigPanel.tsx index 495d1818..df404746 100644 --- a/prediqo_web/src/features/catalog/CandlePredictConfigPanel.tsx +++ b/prediqo_web/src/features/catalog/CandlePredictConfigPanel.tsx @@ -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(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 Loading game config…; + const poolWinnerDesc = + form.poolWinnerRule === 'majority' + ? t('admin.catalog.candlePredict.config.poolWinnerMajorityDesc') + : t('admin.catalog.candlePredict.config.poolWinnerMinorityDesc'); + + if (configQ.isLoading) { + return {t('admin.catalog.candlePredict.config.loading')}; + } return ( - Global settings + {t('admin.catalog.candlePredict.config.globalTitle')} - 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')} - {message && ( - - {message} + {feedback && ( + + {feedback.text} )} 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')} /> 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')} /> 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')} /> - Neutral round rules + {t('admin.catalog.candlePredict.config.neutralTitle')} - {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')} 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')} /> setForm({ ...form, tieToleranceMinEnabled: e.target.checked })} /> } - label="Enable min tolerance rule" + label={t('admin.catalog.candlePredict.config.enableMinTolerance')} /> 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')} /> setForm({ ...form, tieToleranceMaxEnabled: e.target.checked })} /> } - label="Enable max tolerance rule" + label={t('admin.catalog.candlePredict.config.enableMaxTolerance')} /> - Pool winner rule + + {t('admin.catalog.candlePredict.config.poolWinnerRule')} + - {poolWinnerRuleDescription(form.poolWinnerRule)} Applied immediately to new settlements. + {poolWinnerDesc} {t('admin.catalog.candlePredict.config.poolWinnerApplied')} setForm({ ...form, basePrice: Number(e.target.value) })} fullWidth /> 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')} /> 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')} /> 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' } }} /> - Prediction modes + {t('admin.catalog.candlePredict.config.modesTitle')} - Enable or disable each prediction type independently. Disabled modes are hidden from players. + {t('admin.catalog.candlePredict.config.modesIntro')} setForm({ ...form, predictionSingleEnabled: e.target.checked })} /> } - label="Single-candle predictions" + label={t('admin.catalog.candlePredict.config.singleEnabled')} /> setForm({ ...form, predictionAutoEnabled: e.target.checked })} /> } - label="Auto predictions" + label={t('admin.catalog.candlePredict.config.autoEnabled')} /> setForm({ ...form, predictionMultiEnabled: e.target.checked })} /> } - label="Multi-candle predictions" + label={t('admin.catalog.candlePredict.config.multiEnabled')} /> - - Prediction intervals + {t('admin.catalog.candlePredict.config.intervalsTitle')} diff --git a/prediqo_web/src/features/catalog/CandlePredictIntervalsPanel.tsx b/prediqo_web/src/features/catalog/CandlePredictIntervalsPanel.tsx index f3ce298e..729b9bf8 100644 --- a/prediqo_web/src/features/catalog/CandlePredictIntervalsPanel.tsx +++ b/prediqo_web/src/features/catalog/CandlePredictIntervalsPanel.tsx @@ -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(emptyForm()); - const [message, setMessage] = useState(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 Loading intervals…; + if (intervalsQ.isLoading) { + return {t('admin.catalog.candlePredict.intervals.loading')}; + } const rows = intervalsQ.data ?? []; const windowMaxLabel = formatWindowLimit(form.intervalMinutes); @@ -210,9 +238,7 @@ export function CandlePredictIntervalsPanel() { sx={{ alignItems: { sm: 'center' }, mb: 2 }} > - 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')} - {message && ( - - {message} + {feedback && ( + + {feedback.text} )} @@ -238,17 +261,17 @@ export function CandlePredictIntervalsPanel() {
- Order - Label - Minutes - Window (s) - Min tie % - Max tie % - Pool - Payout - Initial batch - Status - Actions + {t('admin.catalog.candlePredict.intervals.columns.order')} + {t('admin.catalog.candlePredict.intervals.columns.label')} + {t('admin.catalog.candlePredict.intervals.columns.minutes')} + {t('admin.catalog.candlePredict.intervals.columns.window')} + {t('admin.catalog.candlePredict.intervals.columns.minTie')} + {t('admin.catalog.candlePredict.intervals.columns.maxTie')} + {t('admin.catalog.candlePredict.intervals.columns.pool')} + {t('admin.catalog.candlePredict.intervals.columns.payout')} + {t('admin.catalog.candlePredict.intervals.columns.initialBatch')} + {t('admin.catalog.candlePredict.intervals.columns.status')} + {t('admin.catalog.candlePredict.intervals.columns.actions')} @@ -258,7 +281,12 @@ export function CandlePredictIntervalsPanel() { {row.label} {row.isDefault && ( - + )} {row.intervalMinutes} @@ -271,7 +299,11 @@ export function CandlePredictIntervalsPanel() { @@ -288,7 +320,7 @@ export function CandlePredictIntervalsPanel() { {!rows.length && ( - No intervals configured + {t('admin.catalog.candlePredict.intervals.noIntervals')} )} @@ -298,11 +330,15 @@ export function CandlePredictIntervalsPanel() { setDialog({ open: false })} fullWidth maxWidth="sm"> - {dialog.editing ? 'Edit interval' : 'New interval'} + + {dialog.editing + ? t('admin.catalog.candlePredict.intervals.editTitle') + : t('admin.catalog.candlePredict.intervals.newTitle')} + setForm({ ...form, intervalMinutes: Number(e.target.value) })} @@ -310,98 +346,109 @@ export function CandlePredictIntervalsPanel() { disabled={!!dialog.editing} /> setForm({ ...form, label: e.target.value })} fullWidth /> setForm({ ...form, sortOrder: Number(e.target.value) })} fullWidth /> 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, + })} /> setForm({ ...form, tieTolerancePercent: e.target.value })} fullWidth - helperText="Leave empty to inherit global default" + helperText={t('admin.catalog.candlePredict.intervals.minTieOverrideHint')} /> setForm({ ...form, tieToleranceMaxPercent: e.target.value })} fullWidth - helperText="Neutral when largest pool ≥ this % — empty inherits global" + helperText={t('admin.catalog.candlePredict.intervals.maxTieOverrideHint')} /> - Min tolerance rule + + {t('admin.catalog.candlePredict.intervals.minToleranceRule')} + - Max tolerance rule + + {t('admin.catalog.candlePredict.intervals.maxToleranceRule')} + 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')} /> 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')} /> setForm({ ...form, basePrice: e.target.value })} fullWidth /> 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')} /> setForm({ ...form, isActive: e.target.checked })} /> } - label="Active" + label={t('admin.catalog.candlePredict.intervals.active')} /> setForm({ ...form, isDefault: e.target.checked })} /> } - label="Default interval for new players" + label={t('admin.catalog.candlePredict.intervals.defaultForNewPlayers')} /> - + diff --git a/prediqo_web/src/features/catalog/CandlePredictMultiLevelsPanel.tsx b/prediqo_web/src/features/catalog/CandlePredictMultiLevelsPanel.tsx index affb0654..d5cbd81f 100644 --- a/prediqo_web/src/features/catalog/CandlePredictMultiLevelsPanel.tsx +++ b/prediqo_web/src/features/catalog/CandlePredictMultiLevelsPanel.tsx @@ -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([]); - const [message, setMessage] = useState(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() { - Multi-candle levels + {t('admin.catalog.candlePredict.multiLevels.title')} - 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')} - {message && ( - setMessage(null)}> - {message} + {feedback && ( + setFeedback(null)}> + {feedback.text} )} @@ -72,12 +77,24 @@ export function CandlePredictMultiLevelsPanel() {
- Level - Candles - Enabled - Pool multiplier - Payout multiplier - Sort + + {t('admin.catalog.candlePredict.multiLevels.columns.level')} + + + {t('admin.catalog.candlePredict.multiLevels.columns.candles')} + + + {t('admin.catalog.candlePredict.multiLevels.columns.enabled')} + + + {t('admin.catalog.candlePredict.multiLevels.columns.poolMultiplier')} + + + {t('admin.catalog.candlePredict.multiLevels.columns.payoutMultiplier')} + + + {t('admin.catalog.candlePredict.multiLevels.columns.sort')} + @@ -138,7 +155,7 @@ export function CandlePredictMultiLevelsPanel() { onClick={() => void handleSave()} disabled={saveMut.isPending || levelsQ.isLoading} > - Save levels + {t('admin.catalog.candlePredict.multiLevels.saveLevels')} diff --git a/prediqo_web/src/features/catalog/CatalogAdminPage.tsx b/prediqo_web/src/features/catalog/CatalogAdminPage.tsx index 6accf90c..24074008 100644 --- a/prediqo_web/src/features/catalog/CatalogAdminPage.tsx +++ b/prediqo_web/src/features/catalog/CatalogAdminPage.tsx @@ -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('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 ( } + title={t('admin.catalog.title')} + subtitle={t('admin.catalog.subtitle')} + actions={} /> setTab(v)} sx={{ mb: 2 }} variant="scrollable" scrollButtons="auto"> - } iconPosition="start" label="Games" /> - } iconPosition="start" label="Advertisements" /> - } iconPosition="start" label="Candle Predict" /> + } iconPosition="start" label={t('admin.catalog.tabs.games')} /> + } iconPosition="start" label={t('admin.catalog.tabs.ads')} /> + } iconPosition="start" label={t('admin.catalog.tabs.candle')} /> {tab === 'games' && ( @@ -248,10 +250,10 @@ export function CatalogAdminPage() { onClick={openCreateGame} sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }} > - Add game + {t('admin.catalog.addGame')} {gamesQ.isLoading ? ( - Loading games… + {t('admin.catalog.loadingGames')} ) : ( - openEditGame(game)} aria-label="Edit game"> + openEditGame(game)} aria-label={t('admin.catalog.editGame')}> @@ -306,12 +308,12 @@ export function CatalogAdminPage() { variant="outlined" /> ) : ( - + )} {game.implementationKey && !hasWebImplementation(game.implementationKey) && ( - + )} - {game.isFeatured && } + {game.isFeatured && } @@ -330,10 +332,10 @@ export function CatalogAdminPage() { onClick={openCreateAd} sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }} > - Add advertisement + {t('admin.catalog.addAd')} {adsQ.isLoading ? ( - Loading advertisements… + {t('admin.catalog.loadingAds')} ) : ( - + {ad.subtitle && ( @@ -405,19 +407,19 @@ export function CatalogAdminPage() { fullWidth maxWidth="sm" > - {gameDialog.editing ? 'Edit game' : 'New game'} + {gameDialog.editing ? t('admin.catalog.gameDialog.edit') : t('admin.catalog.gameDialog.new')} {error && {error}} 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 })} )} setGameForm({ ...gameForm, title: e.target.value })} fullWidth required /> setGameForm({ ...gameForm, description: e.target.value })} fullWidth @@ -452,27 +454,27 @@ export function CatalogAdminPage() { minRows={2} /> setGameForm({ ...gameForm, category: e.target.value })} fullWidth /> setGameForm({ ...gameForm, thumbnailUrl: e.target.value || null })} fullWidth /> setGameForm({ ...gameForm, accentColor: e.target.value })} fullWidth /> - Implementation + {t('admin.catalog.fields.implementation')} - Links this catalog entry to a backend game module. Required for playable games. + {t('admin.catalog.fields.implementationHint')} {gameForm.implementationKey && !hasWebImplementation(gameForm.implementationKey) && ( - 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')} )} - Status + {t('admin.catalog.fields.status')} 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')} /> - + setAdDialog({ open: false })} fullWidth maxWidth="sm"> - {adDialog.editing ? 'Edit advertisement' : 'New advertisement'} + {adDialog.editing ? t('admin.catalog.adDialog.edit') : t('admin.catalog.adDialog.new')} {error && {error}} - Placement + {t('admin.catalog.fields.placement')} setAdForm({ ...adForm, title: e.target.value })} fullWidth required /> setAdForm({ ...adForm, subtitle: e.target.value })} fullWidth @@ -576,39 +577,39 @@ export function CatalogAdminPage() { minRows={2} /> setAdForm({ ...adForm, ctaLabel: e.target.value })} fullWidth /> setAdForm({ ...adForm, linkUrl: e.target.value })} fullWidth placeholder="/wallet or https://..." /> setAdForm({ ...adForm, imageUrl: e.target.value || null })} fullWidth /> setAdForm({ ...adForm, backgroundGradient: e.target.value || null })} fullWidth placeholder="linear-gradient(135deg, ...)" /> setAdForm({ ...adForm, accentColor: e.target.value })} fullWidth /> 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')} /> - + diff --git a/prediqo_web/src/features/countries/CountriesAdminPage.tsx b/prediqo_web/src/features/countries/CountriesAdminPage.tsx index 812c8910..59a8ef48 100644 --- a/prediqo_web/src/features/countries/CountriesAdminPage.tsx +++ b/prediqo_web/src/features/countries/CountriesAdminPage.tsx @@ -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() { > - Countries + {t('admin.countries.title')} - Catalog synced from ISO 3166 by default, or from{' '} + {t('admin.countries.descriptionBeforeLink')}{' '} REST Countries v5 {' '} - when REST_COUNTRIES_API_KEY is configured on the backend. Disable registration - for specific countries of residence. + {t('admin.countries.descriptionAfterLink')} {syncMut.isSuccess && ( 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'), + })} )} {syncMut.isError && ( syncMut.reset()}> {(syncMut.error as { response?: { data?: { error?: string } } })?.response?.data?.error ?? - 'Country sync failed'} + t('admin.countries.syncFailed')} )} {q.isError && ( - Failed to load countries from the server. + {t('admin.countries.loadError')} )} {q.data?.total === 0 && ( - No countries in database. Click "Sync from API" to load the catalog. + {t('admin.countries.emptyDb')} )} @@ -137,14 +143,17 @@ export function CountriesAdminPage() { setSearch(e.target.value)} sx={{ flex: 1 }} /> - 0 ? 'warning' : 'default'} /> + 0 ? 'warning' : 'default'} + /> - Blocked only + {t('admin.countries.blockedOnly')} setShowBlockedOnly(e.target.checked)} /> @@ -153,9 +162,9 @@ export function CountriesAdminPage() {
- Code - Name - Registration + {t('admin.countries.code')} + {t('admin.countries.name')} + {t('admin.countries.registration')} @@ -177,7 +186,7 @@ export function CountriesAdminPage() { {filtered.length === 0 && !q.isLoading && ( - No countries match your filters + {t('admin.countries.noMatch')} )} diff --git a/prediqo_web/src/features/dashboard/DashboardPage.tsx b/prediqo_web/src/features/dashboard/DashboardPage.tsx index ec62e908..78ed3c0f 100644 --- a/prediqo_web/src/features/dashboard/DashboardPage.tsx +++ b/prediqo_web/src/features/dashboard/DashboardPage.tsx @@ -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(defaultFilters); const [forceRefresh, setForceRefresh] = useState(false); const [hiddenSections, setHiddenSections] = useState( @@ -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 && ( - Sélectionnez les dates « Du » et « Au » pour charger les analytics de l’intervalle personnalisé. + {t('admin.dashboard.customRangePending')} )} {customRangeInvalid && ( - La date « Du » doit être antérieure ou égale à la date « Au ». + {t('admin.dashboard.customRangeInvalid')} )} {q.isError && !customRangePending && ( - Impossible de charger les analytics. Vérifiez que le backend est démarré et que vous êtes administrateur. + {t('admin.dashboard.loadError')} )} {q.data?.meta?.chartsFromMaterializedViews && ( - 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')} )} {q.data?.meta?.cached && ( - 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'), + })} )} {q.data?.meta?.degraded && ( - 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 ? ( {q.data.meta.warnings.map((w) => ( @@ -162,7 +167,7 @@ export function DashboardPage() { {q.isFetching && !q.isLoading && ( - Mise à jour des données… + {t('admin.dashboard.updating')} )} diff --git a/prediqo_web/src/features/dashboard/components/DashboardCharts.tsx b/prediqo_web/src/features/dashboard/components/DashboardCharts.tsx index 78710855..fe18862f 100644 --- a/prediqo_web/src/features/dashboard/components/DashboardCharts.tsx +++ b/prediqo_web/src/features/dashboard/components/DashboardCharts.tsx @@ -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(); 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 ( ); diff --git a/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx b/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx index 1c3ff6f6..b052423a 100644 --- a/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx +++ b/prediqo_web/src/features/dashboard/components/DashboardFiltersBar.tsx @@ -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 ( @@ -77,7 +79,7 @@ export function DashboardFiltersBar({ disabled={loading || disableActions} sx={{ flexShrink: 0 }} > - Exporter + {t('admin.dashboard.exportAction')} } @@ -85,15 +87,15 @@ export function DashboardFiltersBar({ - Période + {t('admin.dashboard.period')} @@ -102,7 +104,7 @@ export function DashboardFiltersBar({ {filters.preset === 'custom' && ( <> - Jeu + {t('admin.dashboard.game')} } + title={t('admin.dashboard.sections.kpi.title')} + subtitle={t('admin.dashboard.sections.kpi.subtitle')} + action={} > - Utilisateurs + {t('admin.dashboard.sections.kpi.groups.users')} = 0 ? 'positive' : 'danger'} /> - + - Dépôts + {t('admin.dashboard.sections.kpi.groups.deposits')} - + - + - Retraits & bonus + {t('admin.dashboard.sections.kpi.groups.withdrawalsBonus')} - + @@ -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 ( } > - + - + - + - + = 0 ? 'positive' : 'danger'} to={REPORT_PATHS.predictionsReal} @@ -290,8 +297,8 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) { = 0 ? 'positive' : 'danger'} to={REPORT_PATHS.predictionsTest} @@ -299,16 +306,16 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) { - + @@ -316,14 +323,20 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) { - Trésorerie on-chain + {t('admin.dashboard.sections.financial.onChainTreasury')} - + @@ -335,7 +348,7 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) { `${formatRawUsdt(v)} USDT`} /> @@ -345,7 +358,7 @@ export function FinancialSection({ data }: { data: AdminDashboardData }) { `${formatRawUsdt(v)} USDT`} /> @@ -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 ( - }> + } + > - + - + - + - + @@ -384,34 +405,24 @@ export function GameSection({ data }: { data: AdminDashboardData }) {
- Segment - - Utilisateurs - - - Prédictions - - - Misé - - - Net P/L - - - Taux réussite - + {t(`${tbl}.segment`)} + {t(`${tbl}.users`)} + {t(`${tbl}.predictions`)} + {t(`${tbl}.stake`)} + {t(`${tbl}.netPnl`)} + {t(`${tbl}.winRate`)} - - - - - - - - - + + + + + + + + +
@@ -420,15 +431,15 @@ export function GameSection({ data }: { data: AdminDashboardData }) { = 0 ? 'positive' : 'danger'} to={reportUrl(REPORT_PATHS.predictionsTest, dateQ)} @@ -437,23 +448,25 @@ export function GameSection({ data }: { data: AdminDashboardData }) { - Répartitions (taille fixe) + {t('admin.dashboard.sections.game.distributionsFixed')} - + - Direction - Prédictions - Misé + {t(`${tbl}.direction`)} + {t(`${tbl}.predictions`)} + {t(`${tbl}.stake`)} {data.charts.shortVsLong.map((r) => ( - {r.direction === 'long' ? 'Long' : 'Short'} + + {r.direction === 'long' ? t('admin.dashboard.sections.game.long') : t('admin.dashboard.sections.game.short')} + {formatCount(r.count)} {formatRawUsdt(r.stakeRaw)} @@ -463,20 +476,20 @@ export function GameSection({ data }: { data: AdminDashboardData }) { - +
- Intervalle - Participants - Misé - P/L maison + {t(`${tbl}.interval`)} + {t(`${tbl}.participants`)} + {t(`${tbl}.stake`)} + {t(`${tbl}.housePnl`)} {data.charts.byInterval.map((r) => ( - {r.intervalMinutes} min + {t('admin.dashboard.minSuffix', { n: r.intervalMinutes })} {formatCount(r.participants)} {formatRawUsdt(r.stakeRaw)} }> + } + > - Sécurité & conformité + {t('admin.dashboard.sections.users.securityCompliance')} {securityItems.map((item) => ( - - + + ))} - Activité + {t('admin.dashboard.sections.users.activity')} 0 ? 3 : 0 }}> {activityItems.map((item) => ( - - + + ))} {recentLogins.length > 0 && ( - +
- Utilisateur - Date + {t(`${tbl}.user`)} + {t(`${tbl}.date`)} @@ -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 ( - }> + }> ({ 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 }) { ({ 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 }) { - +
- Pays - Utilisateurs - Dépôts - Retraits - Net P/L - Actifs + {t(`${tbl}.country`)} + {t(`${tbl}.users`)} + {t(`${tbl}.deposits`)} + {t(`${tbl}.withdrawals`)} + {t(`${tbl}.netPnl`)} + {t(`${tbl}.active`)} @@ -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 ( - + - + - + - +
- Sexe - Utilisateurs - Misé - Net P/L - Dépôts + {t(`${tbl}.gender`)} + {t(`${tbl}.users`)} + {t(`${tbl}.stake`)} + {t(`${tbl}.netPnl`)} + {t(`${tbl}.deposits`)} {data.demographics.byGender.map((g) => ( - {GENDER_DASHBOARD_LABELS[g.gender] ?? g.gender} + {genderLabel(g.gender)} {formatCount(g.users)} {formatRawUsdt(g.stakeRaw)} {formatRawUsdt(g.netPnlRaw)} @@ -698,21 +732,21 @@ export function DemographicsSection({ data }: { data: AdminDashboardData }) { - +
- Tranche - Utilisateurs - Misé - Net P/L - Dépôts + {t(`${tbl}.ageBucket`)} + {t(`${tbl}.users`)} + {t(`${tbl}.stake`)} + {t(`${tbl}.netPnl`)} + {t(`${tbl}.deposits`)} {data.demographics.byAge.map((a) => ( - {AGE_BUCKET_LABELS[a.ageBucket] ?? a.ageBucket} + {ageLabel(a.ageBucket)} {formatCount(a.users)} {formatRawUsdt(a.stakeRaw)} {formatRawUsdt(a.netPnlRaw)} @@ -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 ( - + - + - + - + - + @@ -793,7 +829,7 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) { - + @@ -801,7 +837,7 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) { `${formatRawUsdt(v)} USDT`} @@ -811,13 +847,13 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) { - + - + @@ -825,10 +861,10 @@ export function ChartsSection({ data }: { data: AdminDashboardData }) { @@ -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 ( - }> + } + > - + - + {recentAlerts.length === 0 ? ( - Aucune alerte récente sur la période. + {t('admin.dashboard.noRecentAlerts')} ) : ( - +
- Type - Sévérité - Statut - Date + {t(`${tbl}.type`)} + {t(`${tbl}.severity`)} + {t(`${tbl}.status`)} + {t(`${tbl}.date`)} diff --git a/prediqo_web/src/features/dashboard/components/PersonalizationToolbar.tsx b/prediqo_web/src/features/dashboard/components/PersonalizationToolbar.tsx index 19a6ef14..78dc5e38 100644 --- a/prediqo_web/src/features/dashboard/components/PersonalizationToolbar.tsx +++ b/prediqo_web/src/features/dashboard/components/PersonalizationToolbar.tsx @@ -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({ {savedViews.slice(0, 3).map((v) => ( ))} - Masquer/afficher des sections · vues sauvegardées (local) + {t(`${p}.hint`)} setOpen(false)} fullWidth maxWidth="sm"> - Personnalisation du dashboard + {t(`${p}.dialogTitle`)} - Sections visibles + {t(`${p}.visibleSections`)} {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}`)} /> ))} - Sauvegarder la vue actuelle + {t(`${p}.saveCurrentView`)} setViewName(e.target.value)} /> {savedViews.length > 0 && ( - Vues enregistrées + {t(`${p}.savedViews`)} {savedViews.map((v) => ( - Rapports par e-mail (bientôt) + {t(`${p}.emailReportsSoon`)} setEmailReport(e.target.value)} - helperText="La programmation automatique de rapports sera disponible dans une prochaine version." + helperText={t(`${p}.emailHelper`)} disabled /> - + diff --git a/prediqo_web/src/features/dashboard/components/ReportDetailLink.tsx b/prediqo_web/src/features/dashboard/components/ReportDetailLink.tsx index 6e21fd1e..46891ee6 100644 --- a/prediqo_web/src/features/dashboard/components/ReportDetailLink.tsx +++ b/prediqo_web/src/features/dashboard/components/ReportDetailLink.tsx @@ -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 ( ); } diff --git a/prediqo_web/src/features/dashboard/components/TreasuryDashboardCards.tsx b/prediqo_web/src/features/dashboard/components/TreasuryDashboardCards.tsx index 61bd82df..8fa49294 100644 --- a/prediqo_web/src/features/dashboard/components/TreasuryDashboardCards.tsx +++ b/prediqo_web/src/features/dashboard/components/TreasuryDashboardCards.tsx @@ -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 ( - Impossible de charger la trésorerie on-chain (hot/cold). Consultez la page Treasury pour le détail. + {t('admin.dashboard.treasury.loadError')} ); } @@ -64,7 +66,7 @@ export function TreasuryDashboardCards() { 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 diff --git a/prediqo_web/src/features/dashboard/utils/format.ts b/prediqo_web/src/features/dashboard/utils/format.ts index 94cf5542..f7a4efcc 100644 --- a/prediqo_web/src/features/dashboard/utils/format.ts +++ b/prediqo_web/src/features/dashboard/utils/format.ts @@ -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 = { - 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 = { - male: 'Masculin', - female: 'Féminin', - other: 'Autre', - unknown: 'Non renseigné', -}; diff --git a/prediqo_web/src/features/faq/FaqAdminPage.tsx b/prediqo_web/src/features/faq/FaqAdminPage.tsx index c94643e1..a22efc6d 100644 --- a/prediqo_web/src/features/faq/FaqAdminPage.tsx +++ b/prediqo_web/src/features/faq/FaqAdminPage.tsx @@ -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('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() { - Gestion FAQ + {t('admin.faqAdmin.title')} - - Créez et organisez les questions fréquentes affichées aux utilisateurs. - + {t('admin.faqAdmin.subtitle')} setTab(v)} sx={{ mb: 2 }}> - - + + {tab === 'entries' && ( @@ -231,19 +231,19 @@ export function FaqAdminPage() { setSearch(e.target.value)} sx={{ flex: 1 }} /> - Catégorie + {t('admin.faqAdmin.category')} - Statut + {t('admin.faqAdmin.status')} {(entriesQ.error || saveEntryM.error) && ( - {(saveEntryM.error as Error)?.message ?? 'Erreur de chargement'} + {(saveEntryM.error as Error)?.message ?? t('admin.faqAdmin.loadError')} )} @@ -284,14 +284,20 @@ export function FaqAdminPage() { - + - 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()}` : ''} @@ -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); }} > @@ -311,7 +317,7 @@ export function FaqAdminPage() { ))} {!entriesQ.isLoading && sortedEntries.length === 0 && ( - Aucune FAQ trouvée. + {t('admin.faqAdmin.noEntries')} )} @@ -321,7 +327,7 @@ export function FaqAdminPage() { <> @@ -331,8 +337,8 @@ export function FaqAdminPage() { {cat.name} - 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') : ''} 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() { )} setEntryDialogOpen(false)} maxWidth="md" fullWidth> - {editingEntry ? 'Modifier la FAQ' : 'Nouvelle FAQ'} + {editingEntry ? t('admin.faqAdmin.entryDialogEdit') : t('admin.faqAdmin.entryDialogNew')} - Catégorie + {t('admin.faqAdmin.category')} setEntryForm((f) => ({ ...f, question: e.target.value }))} /> - Réponse + {t('admin.faqAdmin.answer')} setEntryForm((f) => ({ ...f, answerHtml: html }))} /> setEntryForm((f) => ({ ...f, isActive: e.target.checked }))} /> } - label="Active" + label={t('admin.faqAdmin.entryActive')} /> {saveEntryM.error && ( @@ -410,32 +416,32 @@ export function FaqAdminPage() { - + setCatDialogOpen(false)} maxWidth="sm" fullWidth> - {editingCat ? 'Modifier la catégorie' : 'Nouvelle catégorie'} + {editingCat ? t('admin.faqAdmin.categoryDialogEdit') : t('admin.faqAdmin.categoryDialogNew')} setCatForm((f) => ({ ...f, name: e.target.value }))} /> setCatForm((f) => ({ ...f, slug: e.target.value }))} - helperText="Généré automatiquement si vide" + helperText={t('admin.faqAdmin.slugAuto')} /> 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 && {(saveCatM.error as Error).message}} - + diff --git a/prediqo_web/src/features/faq/FaqPage.tsx b/prediqo_web/src/features/faq/FaqPage.tsx index 31ce8e4d..f562221d 100644 --- a/prediqo_web/src/features/faq/FaqPage.tsx +++ b/prediqo_web/src/features/faq/FaqPage.tsx @@ -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 ( - Merci pour votre retour ! + {t('faq.thankYou')} ); } @@ -78,7 +80,7 @@ function HelpfulButtons({ return ( - Cette réponse vous a-t-elle été utile ? + {t('faq.helpfulQuestion')} ); @@ -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(null); const [expandedId, setExpandedId] = useState(false); @@ -172,16 +175,16 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { {!isLoggedIn && ( <> )} {isLoggedIn && ( )} @@ -192,17 +195,15 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { - Foire aux questions + {t('faq.title')} - - Trouvez rapidement des réponses aux questions les plus fréquentes. - + {t('faq.subtitle')} setSearch(e.target.value)} slotProps={{ @@ -219,7 +220,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { setCategorySlug(null)} variant={categorySlug === null ? 'filled' : 'outlined'} @@ -240,7 +241,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { - Questions populaires + {t('faq.popular')} @@ -267,7 +268,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { {(categoriesQ.error || faqsQ.error) && ( - Impossible de charger les FAQ. Réessayez plus tard. + {t('faq.loadError')} )} @@ -276,7 +277,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { ) : entries.length === 0 ? ( - Aucune question ne correspond à votre recherche. + {t('faq.noResults')} ) : ( {entries.map((entry) => ( @@ -292,7 +293,7 @@ export function FaqPage({ showPublicHeader = false }: FaqPageProps) { {entry.question} {entry.categoryName} - {entry.viewCount > 0 ? ` · ${entry.viewCount} consultation(s)` : ''} + {entry.viewCount > 0 ? ` · ${t('faq.views', { count: entry.viewCount })}` : ''} diff --git a/prediqo_web/src/features/home/HomePage.tsx b/prediqo_web/src/features/home/HomePage.tsx index ea5c068b..5c445fa9 100644 --- a/prediqo_web/src/features/home/HomePage.tsx +++ b/prediqo_web/src/features/home/HomePage.tsx @@ -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() { } - 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={ void refreshAll()} disabled={loading} /> @@ -80,7 +82,7 @@ export function HomePage() { {(gamesQ.isError || heroQ.isError) && ( - Some content failed to load. Run database migrations and ensure the API is running. + {t('home.loadError')} )} @@ -105,19 +107,19 @@ export function HomePage() { > } - label="Live games" + label={t('home.liveGames')} value={String(liveCount)} color="#D6B25E" /> } - label="Featured" + label={t('home.featured')} value={String(featuredCount)} color="#7C5CFF" /> } - 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() { - Promotions + {t('home.promotions')} @@ -135,7 +137,7 @@ export function HomePage() { - Promotions + {t('home.promotions')} @@ -158,12 +160,12 @@ export function HomePage() { sx={{ flexWrap: 'wrap', alignItems: 'center' }} > - Categories + {t('home.categories')} {categories.map((cat) => ( - Available games + {t('home.availableGames')} @@ -200,7 +202,7 @@ export function HomePage() { ) : filtered.length === 0 ? ( - No games in this category yet. + {t('home.noGamesInCategory')} ) : ( = { @@ -12,14 +14,22 @@ const categoryIcons: Record = { 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: }; + return { + label: t('home.gameStatus.soon'), + color: 'warning' as const, + icon: , + }; } - return { label: 'Maintenance', color: 'default' as const, icon: }; + return { + label: t('home.gameStatus.maintenance'), + color: 'default' as const, + icon: , + }; } 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) { )} {game.isFeatured && ( - + )} - {playable ? 'Play now' : meta.label} + {playable ? t('home.gameStatus.playNow') : meta.label} diff --git a/prediqo_web/src/features/network/NetworkStatusPage.tsx b/prediqo_web/src/features/network/NetworkStatusPage.tsx index 68f995e5..274db13d 100644 --- a/prediqo_web/src/features/network/NetworkStatusPage.tsx +++ b/prediqo_web/src/features/network/NetworkStatusPage.tsx @@ -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 ( - Réseau & environnement - - - Configuration serveur réservée aux administrateurs : réseau blockchain, retraits et environnement - d'exécution. + {t('admin.network.title')} + {t('admin.network.subtitle')} diff --git a/prediqo_web/src/features/options/OptionsPage.tsx b/prediqo_web/src/features/options/OptionsPage.tsx index 20a559de..b85d7b19 100644 --- a/prediqo_web/src/features/options/OptionsPage.tsx +++ b/prediqo_web/src/features/options/OptionsPage.tsx @@ -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 ( - Options - - - Administrative tools and configuration. + {t('admin.options.title')} + {t('admin.options.subtitle')} - - nav('/admin/users')} sx={{ height: '100%' }}> - - - - - - - - - User Management - - + {OPTION_CARDS.map((card) => { + const Icon = card.icon; + return ( + + nav(card.path)} sx={{ height: '100%' }}> + + + + + + + + + {t(`admin.options.cards.${card.key}.title`)} + + + + + {t(`admin.options.cards.${card.key}.description`)} + + - - Search users, open details, and manage account flags safely. - - - - - - - - - nav('/admin/settings')} sx={{ height: '100%' }}> - - - - - - - - - Settings - - - - - Configure password policy and access/refresh token expiration without code changes. - - - - - - - - - nav('/admin/catalog')} sx={{ height: '100%' }}> - - - - - - - - - Games & Ads - - - - - Publish games and home-page promotions dynamically — no deploy required. - - - - - - - - - nav('/admin/treasury')} sx={{ height: '100%' }}> - - - - - - - - - Treasury - - - - - Cold wallet addresses, deposit sweeps, and hot wallet funding from cold storage. - - - - - - - - - nav('/admin/referral')} sx={{ height: '100%' }}> - - - - - - - - - Referral program - - - - - Multi-level commissions, bonus pool, eligibility rules, and signup analytics. - - - - - - - - - nav('/admin/referral/fraud')} sx={{ height: '100%' }}> - - - - - - - - - Referral fraud dashboard - - - - - Review queue, high-risk referrers, monthly caps, and commission clawbacks. - - - - - - - - - nav('/admin/test-wallet')} sx={{ height: '100%' }}> - - - - - - - - - Test wallet - - - - - Credit amounts, request limits, cooldowns, and grant history for practice play. - - - - - - - - - nav('/admin/security')} sx={{ height: '100%' }}> - - - - - - - - - Security - - - - - Integrity checks, security alerts, in-app notifications, and approved ledger credits. - - - - - - - - - nav('/admin/network')} sx={{ height: '100%' }}> - - - - - - - - - Réseau & environnement - - - - - Testnet, état des retraits USDT (TRC20) et environnement serveur. - - - - - - - - - nav('/admin/faq')} sx={{ height: '100%' }}> - - - - - - - - - Foire aux questions - - - - - Gérer les questions, catégories, médias et statistiques FAQ. - - - - - - - - - nav('/admin/support')} sx={{ height: '100%' }}> - - - - - - - - - Centre d'assistance - - - - - Conversations utilisateurs et visiteurs, réponses en temps réel. - - - - - - - - - nav('/admin/countries')} sx={{ height: '100%' }}> - - - - - - - - - Countries - - - - - Sync country catalog and block registration by country of residence. - - - - - - + + + + ); + })} ); } - diff --git a/prediqo_web/src/features/profile/ProfilePage.tsx b/prediqo_web/src/features/profile/ProfilePage.tsx index 6e81d397..b4260ba8 100644 --- a/prediqo_web/src/features/profile/ProfilePage.tsx +++ b/prediqo_web/src/features/profile/ProfilePage.tsx @@ -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 ( } - title="Profile" - subtitle="View and manage your personal information and account security." + title={t('profile.title')} + subtitle={t('profile.subtitle')} mb={2.5} actions={ void refresh()} disabled={profileQ.isLoading} /> @@ -68,7 +70,7 @@ export function ProfilePage() { {profileQ.isError && ( - Failed to load profile. Make sure you are logged in and the API is running. + {t('profile.loadError')} )} @@ -115,16 +117,16 @@ export function ProfilePage() { useFlexGap sx={{ mt: 1.5, flexWrap: 'wrap', justifyContent: { xs: 'center', sm: 'flex-start' } }} > - + @@ -145,8 +147,8 @@ export function ProfilePage() { allowScrollButtonsMobile sx={{ mb: 2, borderBottom: '1px solid rgba(255,255,255,0.08)' }} > - } iconPosition="start" label="Personal" /> - } iconPosition="start" label="Security" /> + } iconPosition="start" label={t('profile.tabPersonal')} /> + } iconPosition="start" label={t('profile.tabSecurity')} /> {tab === 0 && ( @@ -160,7 +162,7 @@ export function ProfilePage() { setEditing(true)} sx={{ flexShrink: 0 }} > - Edit + {t('common.edit')} ) : undefined } @@ -199,7 +201,7 @@ export function ProfilePage() { - Email verification + {t('profile.emailVerification')} {profileQ.isLoading ? ( @@ -216,7 +218,7 @@ export function ProfilePage() { - Referral program + {t('profile.referralProgram')} @@ -225,7 +227,7 @@ export function ProfilePage() { - Account details + {t('profile.accountDetails')} {profileQ.isLoading ? ( @@ -235,17 +237,23 @@ export function ProfilePage() { ) : profile ? ( }> - - + + - - + + ) : ( - + )} @@ -264,10 +272,10 @@ export function ProfilePage() { - Change password + {t('profile.changePassword')} - Update your password. You will need your current password to confirm. + {t('profile.changePasswordHint')} @@ -276,10 +284,10 @@ export function ProfilePage() { - Two-factor authentication + {t('profile.twoFactorAuth')} - Add an extra layer of security for transfers and sensitive actions. + {t('profile.twoFactorHint')} {profile ? ( 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 ( setConfirmPassword(e.target.value)} /> - Choose a strong password. Server policy (length, complexity) is enforced on save. + {t('profilePassword.strengthHint')} diff --git a/prediqo_web/src/features/profile/components/EmailVerificationPanel.tsx b/prediqo_web/src/features/profile/components/EmailVerificationPanel.tsx index 6bfe23da..8684268d 100644 --- a/prediqo_web/src/features/profile/components/EmailVerificationPanel.tsx +++ b/prediqo_web/src/features/profile/components/EmailVerificationPanel.tsx @@ -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(null); @@ -38,7 +36,11 @@ export function EmailVerificationPanel({ if (emailVerified) { return ( } sx={{ borderRadius: 2 }}> - Your email {email} is verified. + }} + /> ); } @@ -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 ( - Your email {email ?? '—'} is not verified yet. Verify it to secure withdrawals and - account recovery. + }} + /> {error && ( @@ -90,25 +93,26 @@ export function EmailVerificationPanel({ )} - We will send a secure one-time link valid for 24 hours. Changing your email requires - verification again. + {t('profileEmailVerify.hint')} {devLink && ( - Dev mode: SMTP is not used. Open or copy this link to verify locally. + }} /> )} diff --git a/prediqo_web/src/features/profile/components/ProfileEditForm.tsx b/prediqo_web/src/features/profile/components/ProfileEditForm.tsx index 8ecbf71a..07fb7270 100644 --- a/prediqo_web/src/features/profile/components/ProfileEditForm.tsx +++ b/prediqo_web/src/features/profile/components/ProfileEditForm.tsx @@ -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 ( - - - - - - - + + + + + + + - Fields show your current information. Edit only what you want to change, then save. + {t('profileForm.editHint')} setFirstName(e.target.value)} /> setMiddleName(e.target.value)} /> setLastName(e.target.value)} /> setEmail(e.target.value)} /> setPhone(e.target.value)} /> {countriesQ.isError && ( - Could not load country list. Try again later or contact support. + {t('profileForm.countriesLoadFailed')} )} diff --git a/prediqo_web/src/features/profile/components/ReferralPanel.tsx b/prediqo_web/src/features/profile/components/ReferralPanel.tsx index 0e9e53d4..270447d3 100644 --- a/prediqo_web/src/features/profile/components/ReferralPanel.tsx +++ b/prediqo_web/src/features/profile/components/ReferralPanel.tsx @@ -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 Could not load referral information.; + return {t('profileReferral.loadFailed')}; } const info = q.data; if (!info?.referralCode) { - return ( - - Your referral code is not available yet. Contact support if you registered before the - referral program launched. - - ); + return {t('profileReferral.notAvailable')}; } return ( @@ -75,7 +72,7 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) { - Share your link to invite friends and earn commissions on their activity. + {t('profileReferral.shareHint')} - Referral code + {t('profileReferral.referralCode')} void copy(info.referralCode!, 'Referral code')} + aria-label={t('profileReferral.copyCodeAria')} + onClick={() => void copy(info.referralCode!, t('profileReferral.referralCode'))} > @@ -118,7 +115,7 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) { - Referral link + {t('profileReferral.referralLink')} void copy(info.referralLink, 'Referral link')} + aria-label={t('profileReferral.copyLinkAria')} + onClick={() => void copy(info.referralLink, t('profileReferral.referralLink'))} > @@ -141,10 +138,10 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) { variant="outlined" size="small" startIcon={} - 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')} ); diff --git a/prediqo_web/src/features/profile/components/TwoFactorPanel.tsx b/prediqo_web/src/features/profile/components/TwoFactorPanel.tsx index dca2e025..f72b59d9 100644 --- a/prediqo_web/src/features/profile/components/TwoFactorPanel.tsx +++ b/prediqo_web/src/features/profile/components/TwoFactorPanel.tsx @@ -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(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 ( - Two-factor authentication is enabled on your account. A TOTP code is required for - transfers when 2FA is active. + }} /> ); } @@ -81,23 +77,22 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan return ( - 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')} {!setupData ? ( ) : ( - Scan with your authenticator app + {t('profileTwoFactor.scanQr')} - Manual key: {setupData.secret} + {t('profileTwoFactor.manualKey', { secret: setupData.secret })} setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} @@ -127,9 +122,9 @@ export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPan placeholder="000000" /> - + diff --git a/prediqo_web/src/features/referral/ReferralAdminPage.tsx b/prediqo_web/src/features/referral/ReferralAdminPage.tsx index 8487511f..5ef777d4 100644 --- a/prediqo_web/src/features/referral/ReferralAdminPage.tsx +++ b/prediqo_web/src/features/referral/ReferralAdminPage.tsx @@ -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() { - Referral program + {t('admin.referralAdmin.title')} @@ -240,13 +242,13 @@ export function ReferralAdminPage() { )} - {configQ.isError && Failed to load referral configuration.} + {configQ.isError && {t('admin.referralAdmin.loadError')}} {s && ( - Program settings + {t('admin.referralAdmin.programSettings')} setSettingsForm({ ...s, enabled: e.target.checked })} /> } - label="Program enabled" + label={t('admin.referralAdmin.programEnabled')} /> setSettingsForm({ ...s, bonusWithdrawable: e.target.checked })} /> } - label="Bonus withdrawable (transfer bonus → main)" + label={t('admin.referralAdmin.bonusWithdrawable')} /> } - label="Referrer must have verified email" + label={t('admin.referralAdmin.referrerVerified')} /> } - label="Referrer must have deposited" + label={t('admin.referralAdmin.referrerDeposited')} /> } - label="Referred user must have verified email (before payout)" + label={t('admin.referralAdmin.referredVerified')} /> setSettingsForm({ ...s, commissionHoldDays: Number(e.target.value) || 0 }) } - helperText="Delay after first deposit before commission can be paid" + helperText={t('admin.referralAdmin.commissionHoldHelper')} /> setSettingsForm({ ...s, commissionMaxPendingDays: Number(e.target.value) || 1 }) } - helperText="Expire unpaid commissions if eligibility is still not met" + helperText={t('admin.referralAdmin.maxPendingHelper')} /> - Commission modes + {t('admin.referralAdmin.commissionModes')} } - label="Deposit commissions (first deposit of referred users)" + label={t('admin.referralAdmin.depositCommissions')} /> } - label="Withdrawal commissions (prediction gains from main account only)" + label={t('admin.referralAdmin.withdrawalCommissions')} /> - Alertes Slack + {t('admin.referralAdmin.slackAlerts')} } - label="Slack alerts enabled (referral channel: cap blocks, clawbacks, Sybil review)" + label={t('admin.referralAdmin.slackEnabled')} /> - Configure SLACK_REFERRAL_WEBHOOK_URL for #referral-fraud and{' '} - SLACK_SECURITY_WEBHOOK_URL for #security.{' '} - SLACK_WEBHOOK_URL is used as fallback for both. + {t('admin.referralAdmin.slackHint')} - Anti-fraude Sybil (P2) + {t('admin.referralAdmin.sybilSection')} } - label="Sybil detection enabled" + label={t('admin.referralAdmin.sybilEnabled')} /> setSettingsForm({ ...s, sybilReviewThreshold: Number(e.target.value) || 0 }) } - helperText="Score ≥ this → manual review queue" + helperText={t('admin.referralAdmin.sybilReviewHelper')} /> setSettingsForm({ ...s, sybilBlockThreshold: Number(e.target.value) || 1 }) } - helperText="Score ≥ this → auto-block (no commission)" + helperText={t('admin.referralAdmin.sybilBlockHelper')} /> setSettingsForm({ ...s, maxCommissionAmountPerReferrerMonthRaw: e.target.value }) } - helperText="500000000 = 500 USDT (6 decimals). 0 = unlimited." + helperText={t('admin.referralAdmin.maxAmountHelper')} /> setSettingsForm({ ...s, defaultReferrerUserId: e.target.value || null }) } - helperText="Used when no referral code is provided at signup" + helperText={t('admin.referralAdmin.defaultReferrerHelper')} /> setSettingsForm({ ...s, minFirstDepositRaw: e.target.value })} /> setSettingsForm({ ...s, commissionWalletTypeId: Number(e.target.value) }) } - helperText="2 = USDT_TRC20 by default" + helperText={t('admin.referralAdmin.commissionWalletHelper')} /> @@ -478,17 +478,17 @@ export function ReferralAdminPage() { - Commission levels + {t('admin.referralAdmin.levelsTitle')}
- Level - % of first deposit - Max amount / month (raw) - Max count / month - Active + {t('admin.referralAdmin.level')} + {t('admin.referralAdmin.percentDeposit')} + {t('admin.referralAdmin.maxAmountMonthCol')} + {t('admin.referralAdmin.maxCountMonthCol')} + {t('admin.referralAdmin.active')} @@ -497,10 +497,10 @@ export function ReferralAdminPage() { {l.levelNumber} {l.commissionPercent}% - {l.monthlyMaxAmountRaw === '0' ? 'Global' : l.monthlyMaxAmountRaw} - {l.monthlyMaxCount === 0 ? 'Global' : l.monthlyMaxCount} + {l.monthlyMaxAmountRaw === '0' ? t('admin.referralAdmin.global') : l.monthlyMaxAmountRaw} + {l.monthlyMaxCount === 0 ? t('admin.referralAdmin.global') : l.monthlyMaxCount} - + @@ -515,14 +515,14 @@ export function ReferralAdminPage() { }) } > - Edit + {t('admin.referralAdmin.edit')} @@ -533,27 +533,27 @@ export function ReferralAdminPage() { setLevelForm((f) => ({ ...f, levelNumber: e.target.value }))} sx={{ flex: 1 }} /> setLevelForm((f) => ({ ...f, commissionPercent: e.target.value }))} sx={{ flex: 1 }} /> setLevelForm((f) => ({ ...f, monthlyMaxAmountRaw: e.target.value }))} sx={{ flex: 1 }} /> setLevelForm((f) => ({ ...f, monthlyMaxCount: e.target.value }))} @@ -573,7 +573,7 @@ export function ReferralAdminPage() { }); }} > - Add / update level + {t('admin.referralAdmin.addUpdateLevel')} @@ -582,30 +582,30 @@ export function ReferralAdminPage() { - Bonus pool (treasury for referral payouts) + {t('admin.referralAdmin.bonusPoolTitle')} {(config?.pools ?? []).map((p) => ( - Wallet type {p.walletTypeId}: {p.availableBalance} raw units + {t('admin.referralAdmin.walletTypeBalance', { id: p.walletTypeId, balance: p.availableBalance })} ))} setFundForm((f) => ({ ...f, walletTypeId: e.target.value }))} sx={{ flex: 1 }} /> setFundForm((f) => ({ ...f, amountDisplay: e.target.value }))} sx={{ flex: 1 }} /> @@ -614,28 +614,28 @@ export function ReferralAdminPage() { - Manual review queue + {t('admin.referralAdmin.reviewTitle')} {reviewQ.isError && ( - Failed to load review queue. + {t('admin.referralAdmin.reviewLoadError')} )} {(reviewQ.data?.items.length ?? 0) === 0 ? ( - No commissions awaiting review. + {t('admin.referralAdmin.noReview')} ) : (
- Score - Signals - Level - Commission - Beneficiary - Referred + {t('admin.referralAdmin.score')} + {t('admin.referralAdmin.signals')} + {t('admin.referralAdmin.level')} + {t('admin.referralAdmin.commission')} + {t('admin.referralAdmin.beneficiary')} + {t('admin.referralAdmin.referred')} @@ -667,11 +667,11 @@ export function ReferralAdminPage() { onClick={() => approveMut.mutate(item.id)} disabled={approveMut.isPending} > - Approve + {t('admin.referralAdmin.approve')} setRejectReasons((prev) => ({ ...prev, [item.id]: e.target.value })) @@ -688,7 +688,7 @@ export function ReferralAdminPage() { }} disabled={rejectMut.isPending} > - Reject + {t('admin.referralAdmin.reject')} @@ -705,25 +705,31 @@ export function ReferralAdminPage() { - Statistics + {t('admin.referralAdmin.statsTitle')} - - - + + + - Users by country + {t('admin.referralAdmin.byCountry')}
@@ -738,15 +744,15 @@ export function ReferralAdminPage() {
- Top referrers + {t('admin.referralAdmin.topReferrers')} - Code - Direct referrals - Earned (raw) + {t('admin.referralAdmin.code')} + {t('admin.referralAdmin.directReferrals')} + {t('admin.referralAdmin.totalEarned')} diff --git a/prediqo_web/src/features/referral/ReferralFraudDashboardPage.tsx b/prediqo_web/src/features/referral/ReferralFraudDashboardPage.tsx index 200cf41a..9ea0bbd5 100644 --- a/prediqo_web/src/features/referral/ReferralFraudDashboardPage.tsx +++ b/prediqo_web/src/features/referral/ReferralFraudDashboardPage.tsx @@ -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>({}); 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() { - Referral fraud dashboard + {t('admin.referralFraud.title')} - {dashQ.isError && Failed to load fraud dashboard.} + {dashQ.isError && {t('admin.referralFraud.loadError')}} {data && ( <> - - - - + + + + - + - + @@ -224,21 +248,21 @@ export function ReferralFraudDashboardPage() { - Review queue + {t('admin.referralFraud.reviewQueue.title')} {data.reviewQueuePreview.length === 0 ? ( - No commissions awaiting review. + {t('admin.referralFraud.reviewQueue.empty')} ) : (
- Score - Signals - Amount - Beneficiary + {t('admin.referralAdmin.score')} + {t('admin.referralAdmin.signals')} + {t('admin.referralFraud.reviewQueue.amount')} + {t('admin.referralAdmin.beneficiary')} @@ -249,16 +273,20 @@ export function ReferralFraudDashboardPage() { - {item.sybilSignals.join(', ') || '—'} + + {item.sybilSignals.join(', ') || '—'} + {item.commissionAmount} - {item.beneficiaryUserId.slice(0, 8)}… + + {item.beneficiaryUserId.slice(0, 8)}… + @@ -288,17 +316,17 @@ export function ReferralFraudDashboardPage() { - High-risk referrers + {t('admin.referralFraud.highRisk.title')}
- Code - Avg Sybil - Review - Inactive - Month raw + {t('admin.referralAdmin.code')} + {t('admin.referralFraud.highRisk.avgSybil')} + {t('admin.referralFraud.highRisk.review')} + {t('admin.referralFraud.highRisk.inactive')} + {t('admin.referralFraud.highRisk.monthRaw')} @@ -321,12 +349,12 @@ export function ReferralFraudDashboardPage() { - Sybil signals (this month) + {t('admin.referralFraud.sybilSignals.title')} {data.sybilSignalBreakdown.length === 0 ? ( - No signals recorded this month. + {t('admin.referralFraud.sybilSignals.empty')} ) : ( data.sybilSignalBreakdown.map((s) => ( @@ -345,16 +373,16 @@ export function ReferralFraudDashboardPage() { - Clawback (paid commissions) + {t('admin.referralFraud.clawback.title')}
- Score - Amount - Beneficiary - Reason + action + {t('admin.referralAdmin.score')} + {t('admin.referralFraud.reviewQueue.amount')} + {t('admin.referralAdmin.beneficiary')} + {t('admin.referralFraud.clawback.reasonAction')} @@ -369,7 +397,7 @@ export function ReferralFraudDashboardPage() { setClawbackReasons((prev) => ({ ...prev, [p.id]: e.target.value })) @@ -388,7 +416,7 @@ export function ReferralFraudDashboardPage() { }) } > - Clawback + {t('admin.referralFraud.clawback.action')} @@ -405,12 +433,12 @@ export function ReferralFraudDashboardPage() { - Recent clawbacks + {t('admin.referralFraud.recentClawbacks.title')} void downloadClawbacksCsv()} disabled={exporting} > - Export CSV + {exporting + ? t('common.exporting') + : t('admin.referralFraud.recentClawbacks.exportCsv')} {exportError && ( @@ -441,13 +471,17 @@ export function ReferralFraudDashboardPage() { )} {data.recentClawbacks.length === 0 ? ( - None yet. + {t('admin.referralFraud.recentClawbacks.empty')} ) : ( data.recentClawbacks.map((c) => ( - - {c.amount} raw — {c.reason} + + }} + /> {new Date(c.createdAt).toLocaleString()} @@ -462,11 +496,11 @@ export function ReferralFraudDashboardPage() { - Recent blocks (Sybil / cap) + {t('admin.referralFraud.recentBlocks.title')} {data.recentCapBlocks.length === 0 ? ( - None recorded. + {t('admin.referralFraud.recentBlocks.empty')} ) : ( data.recentCapBlocks.map((b, i) => ( diff --git a/prediqo_web/src/features/referral/ReferralPage.tsx b/prediqo_web/src/features/referral/ReferralPage.tsx index 42dea515..c7ee6b96 100644 --- a/prediqo_web/src/features/referral/ReferralPage.tsx +++ b/prediqo_web/src/features/referral/ReferralPage.tsx @@ -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 ( } - title="Referral program" - subtitle="Build your network and earn commissions on your referrals' activity." + title={t('referralPage.title')} + subtitle={t('referralPage.subtitle')} actions={ void refreshAll()} disabled={dashQ.isFetching} /> } /> - {dashQ.isError && Failed to load referral dashboard.} + {dashQ.isError && {t('referralPage.loadError')}} {dashQ.isLoading && ( @@ -118,31 +120,35 @@ export function ReferralPage() { <> {!data.programEnabled && ( - The referral program is temporarily disabled. Your network data is still visible below. + {t('referralPage.programDisabled')} )} - - - + + + - Your invite link + {t('referralPage.invite.title')} {data.referralCode ? ( {data.bonusWithdrawable && ( - + )} - void copy(data.referralCode!, 'Code')}> + void copy(data.referralCode!, t('profileReferral.referralCode'))} + > @@ -184,25 +197,27 @@ export function ReferralPage() { - void copy(data.referralLink, 'Link')}> + void copy(data.referralLink, t('profileReferral.referralLink'))} + > ) : ( - Your referral code is not available yet. + {t('referralPage.invite.codeNotAvailable')} )} @@ -212,7 +227,7 @@ export function ReferralPage() { - Your referrer + {t('referralPage.referrer.title')} {data.referrer ? ( @@ -221,36 +236,40 @@ export function ReferralPage() { {data.referrer.referralCode && ( - Code: {data.referrer.referralCode} + {t('referralPage.invite.codePrefix')}{' '} + {data.referrer.referralCode} )} - Member since {new Date(data.referrer.memberSince).toLocaleDateString()} + {t('referralPage.referrer.memberSince', { + date: new Date(data.referrer.memberSince).toLocaleDateString(i18n.language), + })} ) : ( - You joined without a referral code, or your referrer is not linked. + {t('referralPage.referrer.noReferrer')} )} - Commission levels + {t('referralPage.referrer.commissionLevels')} {data.levels.map((l: { levelNumber: number; commissionPercent: number }) => ( ))} - {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')} @@ -265,16 +284,16 @@ export function ReferralPage() { sx={{ alignItems: { sm: 'center' }, mb: 2 }} > - Your referral network + {t('referralPage.network.title')} 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 })} /> @@ -285,8 +304,8 @@ export function ReferralPage() { scrollButtons="auto" sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }} > - } iconPosition="start" label="Table view" /> - } iconPosition="start" label="Tree view" /> + } iconPosition="start" label={t('referralPage.network.tableView')} /> + } iconPosition="start" label={t('referralPage.network.treeView')} /> {tab === 0 && } @@ -299,7 +318,7 @@ export function ReferralPage() { - Commission history + {t('referralPage.network.commissionHistory')} {commissionsQ.isLoading ? ( diff --git a/prediqo_web/src/features/referral/components/ReferralCommissionsPanel.tsx b/prediqo_web/src/features/referral/components/ReferralCommissionsPanel.tsx index 97fedc4f..4807be7e 100644 --- a/prediqo_web/src/features/referral/components/ReferralCommissionsPanel.tsx +++ b/prediqo_web/src/features/referral/components/ReferralCommissionsPanel.tsx @@ -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 ( - No commission events yet. + {t('referralPage.commissions.empty')} ); } @@ -39,12 +42,12 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp
- Member - Level - Source - Status - Commission - Date + {t('referralPage.commissions.member')} + {t('referralPage.commissions.level')} + {t('referralPage.commissions.source')} + {t('common.status')} + {t('referralPage.commissions.commission')} + {t('referralPage.commissions.date')} @@ -56,7 +59,11 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp @@ -65,7 +72,10 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp {rawToHuman(c.commissionAmountRaw, USDT_DECIMALS)} USDT - {c.commissionPercent}% of {rawToHuman(c.baseAmountRaw, USDT_DECIMALS)} + {t('referralPage.commissions.percentOf', { + percent: c.commissionPercent, + amount: rawToHuman(c.baseAmountRaw, USDT_DECIMALS), + })} diff --git a/prediqo_web/src/features/referral/components/ReferralTableView.tsx b/prediqo_web/src/features/referral/components/ReferralTableView.tsx index 93b4a918..65ce4948 100644 --- a/prediqo_web/src/features/referral/components/ReferralTableView.tsx +++ b/prediqo_web/src/features/referral/components/ReferralTableView.tsx @@ -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 ; - if (status === 'unverified') return ; - return ; -} - 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 ; + } + if (status === 'unverified') { + return ( + + ); + } + return ; + } + if (members.length === 0) { return ( - No referrals in your network yet. Share your invite link to grow your team. + {t('referralPage.table.empty')} ); } @@ -43,15 +52,15 @@ export function ReferralTableView({ members }: ReferralTableViewProps) {
- Member - Country - Level - Registered - Status - Direct refs - Predictions - Commissions - Pending + {t('referralPage.table.member')} + {t('referralPage.table.country')} + {t('referralPage.table.level')} + {t('referralPage.table.registered')} + {t('common.status')} + {t('referralPage.table.directRefs')} + {t('referralPage.table.predictions')} + {t('referralPage.table.commissions')} + {t('referralPage.table.pending')} @@ -70,9 +79,7 @@ export function ReferralTableView({ members }: ReferralTableViewProps) { - - {m.countryName ?? '—'} - + {m.countryName ?? '—'} @@ -89,7 +96,7 @@ export function ReferralTableView({ members }: ReferralTableViewProps) { {BigInt(m.commissionsGeneratedRaw) > BigInt(m.commissionsPaidRaw) && ( - total {formatRaw(m.commissionsGeneratedRaw)} + {t('referralPage.table.total', { amount: formatRaw(m.commissionsGeneratedRaw) })} )} diff --git a/prediqo_web/src/features/referral/components/ReferralTreeView.tsx b/prediqo_web/src/features/referral/components/ReferralTreeView.tsx index 278687d2..798291ad 100644 --- a/prediqo_web/src/features/referral/components/ReferralTreeView.tsx +++ b/prediqo_web/src/features/referral/components/ReferralTreeView.tsx @@ -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 ( {member.displayName} - - + + {member.directReferralsCount > 0 && ( - + )} {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 })}` + : ''} @@ -105,6 +127,8 @@ type ReferralTreeViewProps = { }; export function ReferralTreeView({ members, rootUserId }: ReferralTreeViewProps) { + const { t } = useTranslation(); + const childMap = useMemo(() => { const map = new Map(); for (const m of members) { @@ -123,7 +147,7 @@ export function ReferralTreeView({ members, rootUserId }: ReferralTreeViewProps) if (directChildren.length === 0) { return ( - Your referral tree is empty. Invite members to see the hierarchy here. + {t('referralPage.tree.empty')} ); } diff --git a/prediqo_web/src/features/reports/ReportDetailPage.tsx b/prediqo_web/src/features/reports/ReportDetailPage.tsx index ac813c1c..36e4fe2a 100644 --- a/prediqo_web/src/features/reports/ReportDetailPage.tsx +++ b/prediqo_web/src/features/reports/ReportDetailPage.tsx @@ -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 && ( - + )} @@ -784,7 +791,7 @@ export function ReportDetailPage() { - + @@ -816,25 +823,25 @@ export function ReportDetailPage() { @@ -850,7 +857,7 @@ export function ReportDetailPage() { - Actions de masse + {t('admin.reports.detail.bulkActionsTitle')} @@ -858,19 +865,19 @@ export function ReportDetailPage() { @@ -890,7 +897,7 @@ export function ReportDetailPage() { > - {BULK_ACTION_LABELS[action]} + {bulkActionLabel(t, action)} @@ -898,7 +905,7 @@ export function ReportDetailPage() { @@ -916,15 +923,15 @@ export function ReportDetailPage() { - setSearch(e.target.value)} /> + setSearch(e.target.value)} /> - setFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} /> + setFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} /> - setTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} /> + setTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} /> @@ -932,11 +939,11 @@ export function ReportDetailPage() { - setFavoriteName(e.target.value)} /> + setFavoriteName(e.target.value)} /> @@ -978,7 +985,7 @@ export function ReportDetailPage() { {q.isError && ( - {apiErrorMessage(q.error, 'Impossible de charger ce rapport.')} + {apiErrorMessage(q.error, t('admin.reports.detail.loadError'), t('admin.reports.detail.timeoutError'))} )} @@ -996,17 +1003,29 @@ export function ReportDetailPage() { {q.data.summary.totalAmountRaw != null && ( - Montant total : {formatRawUsdtCell(String(q.data.summary.totalAmountRaw))} USDT + }} + /> )} {q.data.summary.totalCount != null && ( - Nombre d'opérations : {q.data.summary.totalCount.toLocaleString('fr-FR')} + }} + /> )} {q.data.summary.uniqueUsers != null && ( - Utilisateurs distincts : {q.data.summary.uniqueUsers.toLocaleString('fr-FR')} + }} + /> )} @@ -1016,7 +1035,9 @@ export function ReportDetailPage() { - Export serveur en cours… {exportProgress.toLocaleString('fr-FR')} ligne(s) traitées + {t('admin.reports.detail.exportInProgress', { + count: exportProgress.toLocaleString(i18n.language), + })} @@ -1090,13 +1111,14 @@ export function ReportDetailPage() { setPendingAction(null)} maxWidth="xs" fullWidth> - {pendingAction ? BULK_ACTION_LABELS[pendingAction] : ''} + {pendingAction ? bulkActionLabel(t, pendingAction) : ''} - {pendingAction ? BULK_ACTION_CONFIRM[pendingAction] : ''} ({selectedIds.length} ligne(s)) + {pendingAction ? bulkActionConfirm(t, pendingAction) : ''}{' '} + ({t('admin.reports.detail.selectedRows', { count: selectedIds.length })}) @@ -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() { @@ -1144,7 +1166,7 @@ export function ReportDetailPage() { > - Confirmer + {t('admin.reports.detail.confirm')} diff --git a/prediqo_web/src/features/reports/ReportsHubPage.tsx b/prediqo_web/src/features/reports/ReportsHubPage.tsx index 5e1140fc..d03fda8a 100644 --- a/prediqo_web/src/features/reports/ReportsHubPage.tsx +++ b/prediqo_web/src/features/reports/ReportsHubPage.tsx @@ -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 ( - Rapports - - - Données détaillées, tableaux paginés, filtres avancés et exports. Le dashboard affiche uniquement les synthèses. + {t('admin.reports.title')} + {t('admin.reports.subtitle')} setSearch(e.target.value)} sx={{ mb: 3, maxWidth: 560 }} @@ -84,11 +84,11 @@ export function ReportsHubPage() { }} /> - {q.isLoading && Chargement du catalogue…} + {q.isLoading && {t('admin.reports.loading')}} {!q.isLoading && search.trim() && totalVisible === 0 && ( - Aucun rapport ne correspond à « {search.trim()} ». + {t('admin.reports.noResults', { query: search.trim() })} )} diff --git a/prediqo_web/src/features/reports/reportBulkActions.ts b/prediqo_web/src/features/reports/reportBulkActions.ts index 21121037..60454dc9 100644 --- a/prediqo_web/src/features/reports/reportBulkActions.ts +++ b/prediqo_web/src/features/reports/reportBulkActions.ts @@ -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 = { - '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> = { - 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[]; diff --git a/prediqo_web/src/features/security/SecurityAdminPage.tsx b/prediqo_web/src/features/security/SecurityAdminPage.tsx index d9b4fc62..b7851600 100644 --- a/prediqo_web/src/features/security/SecurityAdminPage.tsx +++ b/prediqo_web/src/features/security/SecurityAdminPage.tsx @@ -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 }} > - {total > 0 ? `${from}–${to} of ${total}` : 'No results'} + {total > 0 + ? t('common.pagination', { from, to, total }) + : t('common.noResults')} (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() { } - title="Security" + title={t('admin.security.title')} actions={ { 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')} - {integrityResult && ( - - {integrityResult} + {integrityAlert && ( + + {integrityAlert.message} )} @@ -507,20 +518,20 @@ export function SecurityAdminPage() { allowScrollButtonsMobile sx={{ mb: 2 }} > - + - Notifications + {t('admin.security.tabs.notifications')} {(notificationsQ.data?.unreadCount ?? 0) > 0 && ( )} } /> - - - + + + {tab === 0 && ( @@ -528,27 +539,27 @@ export function SecurityAdminPage() { setAlertFilter('open')} /> setAlertFilter('all')} /> - {alertsQ.isError && Failed to load alerts.} + {alertsQ.isError && {t('admin.security.alerts.loadError')}}
- Severity - Title - Type - User - Status - Created + {t('admin.security.alerts.severity')} + {t('admin.security.alerts.title')} + {t('admin.security.alerts.type')} + {t('admin.security.alerts.user')} + {t('admin.security.alerts.status')} + {t('admin.security.alerts.created')} @@ -578,7 +589,7 @@ export function SecurityAdminPage() { {a.status === 'open' && ( )} @@ -587,7 +598,7 @@ export function SecurityAdminPage() { {alerts.length === 0 && !alertsQ.isLoading && ( - No alerts + {t('admin.security.alerts.empty')} )} @@ -613,7 +624,7 @@ export function SecurityAdminPage() { sx={{ mb: 2, justifyContent: 'space-between', alignItems: { sm: 'center' } }} > - In-app notifications + {t('admin.security.notifications.title')} @@ -641,7 +652,7 @@ export function SecurityAdminPage() { {n.title} {!n.readAt && ( )} @@ -656,7 +667,7 @@ export function SecurityAdminPage() { ))} {notifications.length === 0 && !notificationsQ.isLoading && ( - No notifications + {t('admin.security.notifications.empty')} )} - Approved ledger credits + {t('admin.security.credits.title')}
- Type - User - Amount - Approved by - Date + {t('common.type')} + {t('admin.security.credits.user')} + {t('admin.security.credits.amount')} + {t('admin.security.credits.approvedBy')} + {t('admin.security.credits.date')} @@ -717,7 +728,7 @@ export function SecurityAdminPage() { {credits.length === 0 && !creditsQ.isLoading && ( - No credits yet + {t('admin.security.credits.empty')} )} @@ -738,10 +749,10 @@ export function SecurityAdminPage() { - Direct database changes (audit trail) + {t('admin.security.dbAudit.title')} - Modifications detected outside the application layer (psql, pgAdmin, scripts, etc.). + {t('admin.security.dbAudit.subtitle')} - {tamperEventsQ.isError && Failed to load DB audit events.} + {tamperEventsQ.isError && {t('admin.security.dbAudit.loadError')}}
- Severity - Table - Op - Columns - Source - Processed - When + {t('admin.security.dbAudit.severity')} + {t('admin.security.dbAudit.table')} + {t('admin.security.dbAudit.op')} + {t('admin.security.dbAudit.columns')} + {t('admin.security.dbAudit.source')} + {t('admin.security.dbAudit.processed')} + {t('admin.security.dbAudit.when')} @@ -782,14 +793,14 @@ export function SecurityAdminPage() { {ev.sourceHint} - {ev.processedAt ? 'Yes' : 'Pending'} + {ev.processedAt ? t('admin.security.dbAudit.processedYes') : t('admin.security.dbAudit.processedPending')} {new Date(ev.createdAt).toLocaleString()} ))} {(tamperEventsQ.data?.items ?? []).length === 0 && !tamperEventsQ.isLoading && ( - No direct DB changes recorded + {t('admin.security.dbAudit.empty')} )} @@ -810,10 +821,10 @@ export function SecurityAdminPage() { - Security alert emails + {t('admin.security.alertEmails.title')} - One email per line. Encrypted at rest in the database. + {t('admin.security.alertEmails.subtitle')} setEmailsText(e.target.value)} - placeholder="admin@example.com" + placeholder={t('admin.security.alertEmails.placeholder')} /> {settingsMut.isSuccess && ( - Settings saved + {t('admin.security.alertEmails.saved')} )} @@ -868,10 +879,10 @@ export function SecurityAdminPage() { }); }} > - Resolve alert + {t('admin.security.resolve.title')} setReactivate(e.target.checked)} /> } - label="Reactivate withdrawals and clear security hold for user" + label={t('admin.security.resolve.reactivate')} /> {resolveError && ( @@ -904,10 +915,10 @@ export function SecurityAdminPage() { }} disabled={resolveMut.isPending} > - Cancel + {t('common.cancel')} @@ -921,19 +932,19 @@ export function SecurityAdminPage() { /> setCreditOpen(false)} maxWidth="sm" fullWidth> - Grant ledger credit + {t('admin.security.credits.dialogTitle')} setCreditForm((f) => ({ ...f, userId: e.target.value }))} /> - Wallet + {t('admin.security.credits.wallet')} - Type + {t('common.type')} {creditDestinationLabel} setCreditForm((f) => ({ ...f, amountDisplay: e.target.value }))} /> )} - + diff --git a/prediqo_web/src/features/settings/SettingsPage.tsx b/prediqo_web/src/features/settings/SettingsPage.tsx index 3521c310..dc4bb84c 100644 --- a/prediqo_web/src/features/settings/SettingsPage.tsx +++ b/prediqo_web/src/features/settings/SettingsPage.tsx @@ -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() { - Settings - - - Password policy, security, rate limits, withdrawals, and Candle Predict engine tuning. + {t('admin.settings.title')} + {t('admin.settings.subtitle')} {q.isLoading ? ( - Loading settings… + {t('admin.settings.loading')} ) : q.isError ? ( q.refetch()}> - Retry + {t('admin.settings.retry')} } > - Failed to load settings. + {t('admin.settings.loadError')} ) : !effective ? ( - No settings loaded. + {t('admin.settings.noSettings')} ) : ( @@ -136,16 +136,16 @@ export function SettingsPage() { )} {saved && ( - Settings saved. + {t('admin.settings.saved')} )} }> - Password policy + {t('admin.settings.sections.passwordPolicy.title')} - Enforce complexity rules for all new passwords. + {t('admin.settings.sections.passwordPolicy.subtitle')} @@ -160,7 +160,7 @@ export function SettingsPage() { > 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')} /> set('password_require_lowercase', e.target.checked)} /> } - label="Lowercase" + label={t('admin.settings.sections.passwordPolicy.lowercase')} /> set('password_require_number', e.target.checked)} /> } - label="Number" + label={t('admin.settings.sections.passwordPolicy.number')} /> set('password_require_special', e.target.checked)} /> } - label="Special" + label={t('admin.settings.sections.passwordPolicy.special')} /> @@ -218,9 +218,9 @@ export function SettingsPage() { }> - Email verification + {t('admin.settings.sections.emailVerification.title')} - Require confirmed email before users can sign in. + {t('admin.settings.sections.emailVerification.subtitle')} @@ -234,7 +234,7 @@ export function SettingsPage() { } /> } - label="Block login until email is verified" + label={t('admin.settings.sections.emailVerification.blockLogin')} /> @@ -242,9 +242,9 @@ export function SettingsPage() { }> - Token expiration + {t('admin.settings.sections.tokenExpiration.title')} - Change expiry without redeploying the backend. + {t('admin.settings.sections.tokenExpiration.subtitle')} @@ -258,8 +258,8 @@ export function SettingsPage() { > set('access_token_expiry', e.target.value)} fullWidth @@ -267,8 +267,8 @@ export function SettingsPage() { set('refresh_token_expiry', e.target.value)} fullWidth @@ -281,9 +281,9 @@ export function SettingsPage() { }> - Withdrawals & safety + {t('admin.settings.sections.withdrawals.title')} - Kill-switch and withdrawal limits (applied immediately after save). + {t('admin.settings.sections.withdrawals.subtitle')} @@ -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')} /> @@ -318,7 +318,7 @@ export function SettingsPage() { @@ -329,7 +329,7 @@ export function SettingsPage() { @@ -354,9 +354,9 @@ export function SettingsPage() { }> - Rate limiting + {t('admin.settings.sections.rateLimiting.title')} - API and login throttling. Max limits apply within seconds; window size needs a restart. + {t('admin.settings.sections.rateLimiting.subtitle')} @@ -370,8 +370,8 @@ export function SettingsPage() { > set('rate_limit_window_ms', parseNum(e.target.value))} @@ -380,7 +380,7 @@ export function SettingsPage() { set('rate_limit_max', parseNum(e.target.value))} @@ -389,7 +389,7 @@ export function SettingsPage() { set('login_rate_limit_max', parseNum(e.target.value))} @@ -403,9 +403,9 @@ export function SettingsPage() { }> - Candle Predict engine + {t('admin.settings.sections.candlePredict.title')} - Tick interval and backfill pacing (lower backfill = less DB load at scale). + {t('admin.settings.sections.candlePredict.subtitle')} @@ -419,8 +419,8 @@ export function SettingsPage() { > @@ -431,8 +431,8 @@ export function SettingsPage() { @@ -443,8 +443,8 @@ export function SettingsPage() { @@ -455,8 +455,8 @@ export function SettingsPage() { @@ -475,7 +475,7 @@ export function SettingsPage() { disabled={saving} startIcon={} > - Reset + {t('admin.settings.reset')} diff --git a/prediqo_web/src/features/support/SupportAdminPage.tsx b/prediqo_web/src/features/support/SupportAdminPage.tsx index 80c81238..3e8a5269 100644 --- a/prediqo_web/src/features/support/SupportAdminPage.tsx +++ b/prediqo_web/src/features/support/SupportAdminPage.tsx @@ -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 = { - open: 'Ouverte', - pending: 'En attente', - resolved: 'Résolue', - closed: 'Fermée', -}; +const STATUS_KEYS = ['open', 'pending', 'resolved', 'closed'] as const; const STATUS_COLORS: Record = { open: 'success', @@ -56,9 +52,11 @@ const STATUS_COLORS: Record function AdminMessageList({ messages, staffTyping, + t, }: { messages: SupportMessage[]; staffTyping?: boolean; + t: (key: string) => string; }) { return ( @@ -77,7 +75,7 @@ function AdminMessageList({ > {!isStaff && ( - {msg.senderType === 'visitor' ? 'Visiteur' : 'Utilisateur'} + {msg.senderType === 'visitor' ? t('admin.supportAdmin.visitor') : t('admin.supportAdmin.user')} )} {msg.body && ( @@ -99,7 +97,7 @@ function AdminMessageList({ )} {new Date(msg.createdAt).toLocaleString()} - {msg.readAt ? ' · Lu' : ''} + {msg.readAt ? t('admin.supportAdmin.read') : ''} @@ -107,7 +105,7 @@ function AdminMessageList({ })} {staffTyping && ( - Le visiteur écrit… + {t('admin.supportAdmin.visitorTyping')} )} @@ -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(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() { - Centre d'assistance + {t('admin.supportAdmin.title')} void listQ.refetch()}> @@ -267,7 +266,7 @@ export function SupportAdminPage() { { setSearch(e.target.value); @@ -276,20 +275,20 @@ export function SupportAdminPage() { sx={{ mb: 1.5 }} /> - Statut + {t('admin.supportAdmin.status')} @@ -311,7 +310,7 @@ export function SupportAdminPage() { > - {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) })} {c.unreadStaff > 0 && ( @@ -322,7 +321,11 @@ export function SupportAdminPage() { @@ -330,7 +333,7 @@ export function SupportAdminPage() { ))} {!listQ.data?.items.length && ( - Aucune conversation + {t('admin.supportAdmin.noConversations')} )} @@ -349,21 +352,21 @@ export function SupportAdminPage() { {/* Chat */} {!selectedId ? ( - Sélectionnez une conversation + {t('admin.supportAdmin.selectConversation')} ) : ( <> - Statut + {t('admin.supportAdmin.status')} - + { setDraft(e.target.value); @@ -443,54 +446,54 @@ export function SupportAdminPage() { {/* User context */} - Contexte + {t('admin.supportAdmin.contextTitle')} {conv?.isAnonymous && ( - Conversation anonyme — aucun compte associé. + {t('admin.supportAdmin.anonymousAlert')} )} {user ? ( - Nom : {user.displayName ?? '—'} + {t('admin.supportAdmin.name')} {user.displayName ?? '—'} - ID : {user.id} + {t('admin.supportAdmin.id')} {user.id} - E-mail : {user.email ?? '—'} + {t('admin.supportAdmin.email')} {user.email ?? '—'} - Rôle : {user.role} + {t('admin.supportAdmin.role')} {user.role} - Statut :{' '} + {t('admin.supportAdmin.accountStatus')}{' '} {user.isEnabled ? ( - + ) : ( - + )} - E-mail vérifié : {user.emailVerified ? 'Oui' : 'Non'} + {t('admin.supportAdmin.emailVerified')} {user.emailVerified ? t('common.yes') : t('common.no')} - Inscrit le {new Date(user.createdAt).toLocaleDateString()} + {t('admin.supportAdmin.registeredOn', { date: new Date(user.createdAt).toLocaleDateString() })} ) : ( !conv?.isAnonymous && ( - Chargement… + {t('common.loading')} ) )} {conv && ( - Conversation créée le {new Date(conv.createdAt).toLocaleString()} + {t('admin.supportAdmin.conversationCreated', { date: new Date(conv.createdAt).toLocaleString() })} )} diff --git a/prediqo_web/src/features/support/components/SupportChatPanel.tsx b/prediqo_web/src/features/support/components/SupportChatPanel.tsx index 3c5e02b4..bba84781 100644 --- a/prediqo_web/src/features/support/components/SupportChatPanel.tsx +++ b/prediqo_web/src/features/support/components/SupportChatPanel.tsx @@ -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 ; } -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 ( ) : ( @@ -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')} )} @@ -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([]); @@ -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 && ( - Bonjour ! Comment pouvons-nous vous aider ? + {t('support.chat.greeting')} )} {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} )} - + ); })} {staffTyping && ( - L'équipe est en train d'écrire… + {t('support.chat.typing')} )} @@ -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) => { diff --git a/prediqo_web/src/features/support/components/SupportWidget.tsx b/prediqo_web/src/features/support/components/SupportWidget.tsx index ff2c339e..33269974 100644 --- a/prediqo_web/src/features/support/components/SupportWidget.tsx +++ b/prediqo_web/src/features/support/components/SupportWidget.tsx @@ -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() { - Assistance Prediqo + {t('support.widget.title')} - Réponse en temps réel de notre équipe + {t('support.widget.subtitle')} setOpen(false)} sx={{ color: 'inherit' }}> diff --git a/prediqo_web/src/features/test-wallet/TestWalletAdminPage.tsx b/prediqo_web/src/features/test-wallet/TestWalletAdminPage.tsx index 182cde51..b0b2c5d8 100644 --- a/prediqo_web/src/features/test-wallet/TestWalletAdminPage.tsx +++ b/prediqo_web/src/features/test-wallet/TestWalletAdminPage.tsx @@ -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(null); const [creditDisplay, setCreditDisplay] = useState('1000'); @@ -102,7 +104,7 @@ export function TestWalletAdminPage() { }); if (configQ.isLoading || !form) { - return Loading test wallet settings…; + return {t('admin.testWallet.loading')}; } return ( @@ -111,17 +113,15 @@ export function TestWalletAdminPage() { - Test wallet + {t('admin.testWallet.title')} - - Configure play-money credits so new users can practice predictions before using real funds. - + {t('admin.testWallet.subtitle')} @@ -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')} /> setCreditDisplay(e.target.value)} - helperText="Amount credited automatically when a user requests test funds" + helperText={t('admin.testWallet.creditHelper')} fullWidth /> setForm({ ...form, maxRequestsPerUser: Math.max(0, Number(e.target.value) || 0) }) } - helperText="0 = unlimited" + helperText={t('admin.testWallet.maxRequestsHelper')} fullWidth /> setForm({ ...form, cooldownHours: Math.max(0, Number(e.target.value) || 0) }) } - helperText="0 = no waiting period" + helperText={t('admin.testWallet.cooldownHelper')} fullWidth /> {saveMut.isError && ( {(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data - ?.error ?? 'Save failed'} + ?.error ?? t('admin.testWallet.saveFailed')} )} - {saveMut.isSuccess && Settings saved.} + {saveMut.isSuccess && {t('admin.testWallet.saved')}} - Credit history + {t('admin.testWallet.history')} @@ -192,9 +192,9 @@ export function TestWalletAdminPage() {
- Date - User - Amount + {t('admin.testWallet.date')} + {t('admin.testWallet.user')} + {t('admin.testWallet.amount')} @@ -212,7 +212,7 @@ export function TestWalletAdminPage() { {!historyQ.data?.items?.length && ( - No test credits granted yet. + {t('admin.testWallet.noHistory')} )} diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index a2605267..46d6d0f3 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -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>({}); 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() { } - title="Treasury" + title={t('admin.treasury.title')} actions={ { void overviewQ.refetch(); void sweepsQ.refetch(); @@ -167,7 +169,7 @@ export function TreasuryAdminPage() { {overviewQ.isError && ( - Failed to load treasury overview. + {t('admin.treasury.loadError')} )} @@ -175,25 +177,23 @@ export function TreasuryAdminPage() { {overview.recentPendingSweeps > 0 && ( - + )} {overview.recentFailedSweeps > 0 && ( - + )} {!overview.sweepEnabled && ( - - Set SWEEP_ENABLED=true in backend .env to auto-move deposits to cold storage. - + {t('admin.treasury.sweepDisabledHint')} )} {overview.assets.map((asset) => { @@ -210,18 +210,22 @@ export function TreasuryAdminPage() { - 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), + })} - 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), + })} @@ -233,7 +237,7 @@ export function TreasuryAdminPage() { /> setColdForms((prev) => ({ @@ -253,7 +257,7 @@ export function TreasuryAdminPage() { }) } > - Save cold + {t('admin.treasury.saveCold')} @@ -266,15 +270,15 @@ export function TreasuryAdminPage() { - Cold → Hot funding + {t('admin.treasury.fundingTitle')} - Create a request, transfer manually from cold wallet, then confirm with the blockchain transaction ID. + {t('admin.treasury.fundingSubtitle')} @@ -283,13 +287,13 @@ export function TreasuryAdminPage() { /> setFundingForm((f) => ({ ...f, amount: e.target.value }))} /> setFundingForm((f) => ({ ...f, notes: e.target.value }))} @@ -305,7 +309,7 @@ export function TreasuryAdminPage() { }) } > - Request funding for approval + {t('admin.treasury.requestFunding')} {overview?.pendingColdToHotFunding?.length ? ( @@ -313,8 +317,8 @@ export function TreasuryAdminPage() {
- Amount - From → To + {t('admin.treasury.amount')} + {t('admin.treasury.fromTo')} @@ -327,7 +331,7 @@ export function TreasuryAdminPage() { @@ -337,7 +341,7 @@ export function TreasuryAdminPage() { ) : ( - No pending funding requests. + {t('admin.treasury.noPendingFunding')} )} @@ -351,7 +355,7 @@ export function TreasuryAdminPage() { sx={{ alignItems: { sm: 'center' }, mb: 2 }} > - Deposit sweeps + {t('admin.treasury.sweepsTitle')}
- Status - Amount - To cold - Tx + {t('admin.treasury.status')} + {t('admin.treasury.amount')} + {t('admin.treasury.toCold')} + {t('admin.treasury.tx')} @@ -395,11 +399,11 @@ export function TreasuryAdminPage() { setConfirmFunding(null)} maxWidth="sm" fullWidth> - Confirm cold → hot transfer + {t('admin.treasury.confirmDialogTitle')} @@ -408,7 +412,7 @@ export function TreasuryAdminPage() { /> - + diff --git a/prediqo_web/src/features/users/UserManagementPage.tsx b/prediqo_web/src/features/users/UserManagementPage.tsx index 53bad02d..fa264bc3 100644 --- a/prediqo_web/src/features/users/UserManagementPage.tsx +++ b/prediqo_web/src/features/users/UserManagementPage.tsx @@ -42,6 +42,7 @@ import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded'; import FilterListRoundedIcon from '@mui/icons-material/FilterListRounded'; import { useTheme } from '@mui/material/styles'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { Trans, useTranslation } from 'react-i18next'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import dayjs from 'dayjs'; import { api } from '../../shared/services/api'; @@ -86,18 +87,20 @@ function UsersGridToolbar({ exportLimitLabel, disabled, selectedCount, + t, }: { onOpenDownload: (e: React.MouseEvent) => void; exportLimitLabel: string; disabled: boolean; selectedCount: number; + t: ReturnType['t']; }) { return ( - + {selectedCount > 0 && ( - + )} @@ -169,6 +172,7 @@ function FlagSwitch({ } export function UserManagementPage() { + const { t } = useTranslation(); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('md')); const qc = useQueryClient(); @@ -382,7 +386,7 @@ export function UserManagementPage() { setToast(failed ? `${ok} succeeded, ${failed} failed` : `${ok} user(s) updated`); }, onError: (e: any) => { - setToast(e?.response?.data?.error ?? e?.message ?? 'Batch operation failed'); + setToast(e?.response?.data?.error ?? e?.message ?? t('admin.users.batchFailed')); }, }); @@ -392,12 +396,12 @@ export function UserManagementPage() { return res.data; }, onSuccess: () => { - setToast('Email marked as verified'); + setToast(t('admin.users.emailVerified')); void qc.invalidateQueries({ queryKey: ['admin-users'] }); }, onError: (e: unknown) => { const err = e as { response?: { data?: { error?: string } }; message?: string }; - setToast(err?.response?.data?.error ?? err?.message ?? 'Failed to verify email'); + setToast(err?.response?.data?.error ?? err?.message ?? t('admin.users.emailVerifyFailed')); }, }); @@ -406,12 +410,12 @@ export function UserManagementPage() { api.patch(`/api/v1/admin/users/${body.userId}/roles`, { roles: body.roles }), onSuccess: () => { setRoleDialog(null); - setToast('Roles updated'); + setToast(t('admin.users.rolesUpdated')); void qc.invalidateQueries({ queryKey: ['admin-users'] }); }, onError: (e: unknown) => { const err = e as { response?: { data?: { error?: string } }; message?: string }; - setToast(err?.response?.data?.error ?? err?.message ?? 'Role update failed'); + setToast(err?.response?.data?.error ?? err?.message ?? t('admin.users.roleUpdateFailed')); }, }); @@ -435,10 +439,10 @@ export function UserManagementPage() { const users = q.data?.users ?? []; const total = cachedTotal ?? q.data?.total ?? 0; const totalLabel = q.isLoading - ? 'Loading…' + ? t('common.loading') : totalIsExact - ? `${total} user(s)` - : `~${total.toLocaleString()} user(s) (est.)`; + ? t('admin.users.totalExact', { count: total }) + : t('admin.users.totalEstimate', { count: total.toLocaleString() }); const selectedIds = useMemo(() => { if (rowSelection.type === 'include') { return [...rowSelection.ids].map(String); @@ -449,21 +453,21 @@ export function UserManagementPage() { const copy = async (text: string) => { try { await navigator.clipboard.writeText(text); - setToast('Copied to clipboard'); + setToast(t('admin.users.copied')); } catch { - setToast('Copy failed'); + setToast(t('admin.users.copyFailed')); } }; const onToggle = useCallback((u: AdminUser, field: NonNullable['field'], next: boolean) => { - const fieldLabel = field; + const fieldLabel = t(`admin.users.fields.${field}`); setConfirm({ userId: u.id, label: `${u.email ?? u.id} · ${fieldLabel}`, field, next, }); - }, []); + }, [t]); const applyToggle = async () => { if (!confirm) return; @@ -492,45 +496,45 @@ export function UserManagementPage() { setConfirm(null); void q.refetch(); } catch (e: any) { - setToast(e?.response?.data?.error ?? e?.message ?? 'Update failed'); + setToast(e?.response?.data?.error ?? e?.message ?? t('admin.users.updateFailed')); } }; const columns = useMemo( () => [ - { field: 'id', headerName: 'ID', width: 180, sortable: true }, + { field: 'id', headerName: t('admin.users.columns.id'), width: 180, sortable: true }, { field: 'email', - headerName: 'Email', + headerName: t('admin.users.columns.email'), width: 280, valueGetter: (_v: unknown, row: AdminUser) => row.email ?? '—', }, { field: 'full_name', - headerName: 'Full name', + headerName: t('admin.users.columns.fullName'), width: 200, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => fullName(row), }, { field: 'account_status', - headerName: 'Status', + headerName: t('admin.users.columns.status'), width: 120, sortable: false, renderCell: (p: { row: AdminUser }) => { const status = deriveAccountStatus(p.row); - const reasons = accountStatusReasons(p.row); + const reasons = accountStatusReasons(t, p.row); const tip = status === 'active' - ? 'Account fully active' + ? t('admin.users.accountStatus.fullyActive') : reasons.length ? reasons.join(' · ') - : status; + : t(`admin.users.accountStatus.${status}`); return ( @@ -540,17 +544,17 @@ export function UserManagementPage() { }, { field: 'email_verified', - headerName: 'Email OK', + headerName: t('admin.users.columns.emailOk'), width: 110, sortable: true, renderCell: (p: { row: AdminUser }) => p.row.email_verified ? ( - + ) : ( - + { @@ -565,11 +569,11 @@ export function UserManagementPage() { }, { field: 'role_name', - headerName: 'Role', + headerName: t('admin.users.columns.role'), width: 120, sortable: true, renderCell: (p: { row: AdminUser }) => ( - + countryLabel(row.country_of_residence), }, { field: 'nationality', - headerName: 'Nationality', + headerName: t('admin.users.columns.nationality'), width: 160, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => countryLabel(row.nationality), }, { field: 'date_of_birth', - headerName: 'DOB', + headerName: t('admin.users.columns.dob'), width: 110, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => formatDateOfBirth(row.date_of_birth), }, { field: 'age_category', - headerName: 'Age group', + headerName: t('admin.users.columns.ageGroup'), width: 110, sortable: false, - valueGetter: (_v: unknown, row: AdminUser) => ageCategory(row.date_of_birth), + valueGetter: (_v: unknown, row: AdminUser) => ageCategory(t, row.date_of_birth), }, { field: 'referral_code', - headerName: 'Referral code', + headerName: t('admin.users.columns.referralCode'), width: 130, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => row.referral_code ?? '—', }, { field: 'first_deposit_at', - headerName: 'First deposit', + headerName: t('admin.users.columns.firstDeposit'), width: 150, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => formatDate(row.first_deposit_at), }, { field: 'first_deposit_transaction_id', - headerName: 'First deposit tx', + headerName: t('admin.users.columns.firstDepositTx'), width: 180, sortable: false, valueGetter: (_v: unknown, row: AdminUser) => row.first_deposit_transaction_id ?? '—', }, { field: 'main_balance_raw', - headerName: 'Main USDT', + headerName: t('admin.users.columns.mainUsdt'), width: 120, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatUsdt(row.main_balance_raw), }, { field: 'bonus_balance_raw', - headerName: 'Bonus USDT', + headerName: t('admin.users.columns.bonusUsdt'), width: 120, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatUsdt(row.bonus_balance_raw), }, { field: 'total_bonus_received_raw', - headerName: 'Bonus received', + headerName: t('admin.users.columns.bonusReceived'), width: 130, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatUsdt(row.total_bonus_received_raw), }, { field: 'prediction_count', - headerName: 'Predictions', + headerName: t('admin.users.columns.predictions'), width: 110, sortable: true, type: 'number' as const, }, { field: 'net_pnl_raw', - headerName: 'Net P/L', + headerName: t('admin.users.columns.netPnl'), width: 130, sortable: true, description: 'Cumulative result on Candle Predict: total payouts minus total stakes (USDT).', @@ -686,42 +690,42 @@ export function UserManagementPage() { }, { field: 'total_stake_raw', - headerName: 'Total stake', + headerName: t('admin.users.columns.totalStake'), width: 110, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatUsdt(row.total_stake_raw), }, { field: 'total_payout_raw', - headerName: 'Total payout', + headerName: t('admin.users.columns.totalPayout'), width: 110, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatUsdt(row.total_payout_raw), }, { field: 'created_at', - headerName: 'Created', + headerName: t('admin.users.columns.created'), width: 150, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatDate(row.created_at), }, { field: 'last_login_at', - headerName: 'Last login', + headerName: t('admin.users.columns.lastLogin'), width: 150, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatDate(row.last_login_at), }, { field: 'last_activity_at', - headerName: 'Last activity', + headerName: t('admin.users.columns.lastActivity'), width: 150, sortable: true, valueGetter: (_v: unknown, row: AdminUser) => formatDate(row.last_activity_at), }, { field: 'is_enabled', - headerName: 'Enabled', + headerName: t('admin.users.columns.enabled'), width: 100, sortable: true, align: 'center' as const, @@ -729,14 +733,14 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'isEnabled', v)} /> ), }, { field: 'withdrawals_suspended', - headerName: 'Wd. suspended', + headerName: t('admin.users.columns.wdSuspended'), width: 120, sortable: false, align: 'center' as const, @@ -744,14 +748,14 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'withdrawalsSuspended', v)} /> ), }, { field: 'under_surveillance', - headerName: 'Surveillance', + headerName: t('admin.users.columns.surveillance'), width: 110, sortable: false, align: 'center' as const, @@ -759,23 +763,23 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'underSurveillance', v)} /> ), }, { field: 'totp_enabled', - headerName: '2FA', + headerName: t('admin.users.columns.twoFa'), width: 80, sortable: false, renderCell: (p: { row: AdminUser }) => ( - + ), }, { field: 'is_account_non_expired', - headerName: 'Non expired', + headerName: t('admin.users.columns.nonExpired'), width: 120, sortable: false, align: 'center' as const, @@ -783,14 +787,14 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'isAccountNonExpired', v)} /> ), }, { field: 'is_account_non_locked', - headerName: 'Non locked', + headerName: t('admin.users.columns.nonLocked'), width: 120, sortable: false, align: 'center' as const, @@ -798,14 +802,14 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'isAccountNonLocked', v)} /> ), }, { field: 'is_credentials_non_expired', - headerName: 'Creds valid', + headerName: t('admin.users.columns.credsValid'), width: 120, sortable: false, align: 'center' as const, @@ -813,26 +817,26 @@ export function UserManagementPage() { renderCell: (p: { row: AdminUser }) => ( onToggle(p.row, 'isCredentialsNonExpired', v)} /> ), }, { field: 'actions', - headerName: 'Copy', + headerName: t('admin.users.columns.copy'), width: 90, sortable: false, renderCell: (p: { row: AdminUser }) => ( - - copy(p.row.id)} aria-label="Copy user id"> + + copy(p.row.id)} aria-label={t('admin.users.tooltips.copyUserId')}> {p.row.email && ( - - copy(p.row.email!)} aria-label="Copy email"> + + copy(p.row.email!)} aria-label={t('admin.users.tooltips.copyEmail')}> @@ -841,83 +845,83 @@ export function UserManagementPage() { ), }, ], - [copy, onToggle, countryLabel, verifyEmailMut, openRoleDialog] + [copy, onToggle, countryLabel, verifyEmailMut, openRoleDialog, t] ); const exportColumnDefs = useMemo( () => [ - { field: 'id', header: 'ID', get: (u: AdminUser) => u.id }, - { field: 'email', header: 'Email', get: (u: AdminUser) => u.email ?? '' }, - { field: 'full_name', header: 'Full name', get: (u: AdminUser) => fullName(u) }, - { field: 'account_status', header: 'Account status', get: (u: AdminUser) => deriveAccountStatus(u) }, - { field: 'role_name', header: 'Role', get: (u: AdminUser) => u.role_name }, + { field: 'id', header: t('admin.users.columns.id'), get: (u: AdminUser) => u.id }, + { field: 'email', header: t('admin.users.columns.email'), get: (u: AdminUser) => u.email ?? '' }, + { field: 'full_name', header: t('admin.users.columns.fullName'), get: (u: AdminUser) => fullName(u) }, + { field: 'account_status', header: t('admin.users.columns.status'), get: (u: AdminUser) => deriveAccountStatus(u) }, + { field: 'role_name', header: t('admin.users.columns.role'), get: (u: AdminUser) => u.role_name }, { field: 'country_of_residence', - header: 'Country', + header: t('admin.users.columns.country'), get: (u: AdminUser) => countryLabel(u.country_of_residence), }, { field: 'nationality', - header: 'Nationality', + header: t('admin.users.columns.nationality'), get: (u: AdminUser) => countryLabel(u.nationality), }, - { field: 'date_of_birth', header: 'DOB', get: (u: AdminUser) => formatDateOfBirth(u.date_of_birth) }, - { field: 'age_category', header: 'Age group', get: (u: AdminUser) => ageCategory(u.date_of_birth) }, - { field: 'referral_code', header: 'Referral code', get: (u: AdminUser) => u.referral_code ?? '' }, + { field: 'date_of_birth', header: t('admin.users.columns.dob'), get: (u: AdminUser) => formatDateOfBirth(u.date_of_birth) }, + { field: 'age_category', header: t('admin.users.columns.ageGroup'), get: (u: AdminUser) => ageCategory(t, u.date_of_birth) }, + { field: 'referral_code', header: t('admin.users.columns.referralCode'), get: (u: AdminUser) => u.referral_code ?? '' }, { field: 'first_deposit_at', - header: 'First deposit', + header: t('admin.users.columns.firstDeposit'), get: (u: AdminUser) => formatDate(u.first_deposit_at), }, { field: 'first_deposit_transaction_id', - header: 'First deposit tx ID', + header: t('admin.users.columns.firstDepositTx'), get: (u: AdminUser) => u.first_deposit_transaction_id ?? '', }, - { field: 'email_verified', header: 'Email verified', get: (u: AdminUser) => (u.email_verified ? 'yes' : 'no') }, - { field: 'main_balance_raw', header: 'Main USDT', get: (u: AdminUser) => formatUsdt(u.main_balance_raw) }, - { field: 'bonus_balance_raw', header: 'Bonus USDT', get: (u: AdminUser) => formatUsdt(u.bonus_balance_raw) }, + { field: 'email_verified', header: t('admin.users.filterLabels.emailVerified'), get: (u: AdminUser) => (u.email_verified ? 'yes' : 'no') }, + { field: 'main_balance_raw', header: t('admin.users.columns.mainUsdt'), get: (u: AdminUser) => formatUsdt(u.main_balance_raw) }, + { field: 'bonus_balance_raw', header: t('admin.users.columns.bonusUsdt'), get: (u: AdminUser) => formatUsdt(u.bonus_balance_raw) }, { field: 'total_bonus_received_raw', - header: 'Bonus received', + header: t('admin.users.columns.bonusReceived'), get: (u: AdminUser) => formatUsdt(u.total_bonus_received_raw), }, - { field: 'prediction_count', header: 'Predictions', get: (u: AdminUser) => String(u.prediction_count) }, - { field: 'net_pnl_raw', header: 'Net P/L USDT', get: (u: AdminUser) => formatSignedUsdt(u.net_pnl_raw) }, - { field: 'total_stake_raw', header: 'Total stake', get: (u: AdminUser) => formatUsdt(u.total_stake_raw) }, - { field: 'total_payout_raw', header: 'Total payout', get: (u: AdminUser) => formatUsdt(u.total_payout_raw) }, - { field: 'created_at', header: 'Created', get: (u: AdminUser) => formatDate(u.created_at) }, - { field: 'last_login_at', header: 'Last login', get: (u: AdminUser) => formatDate(u.last_login_at) }, - { field: 'last_activity_at', header: 'Last activity', get: (u: AdminUser) => formatDate(u.last_activity_at) }, - { field: 'is_enabled', header: 'Enabled', get: (u: AdminUser) => (u.is_enabled ? 'true' : 'false') }, + { field: 'prediction_count', header: t('admin.users.columns.predictions'), get: (u: AdminUser) => String(u.prediction_count) }, + { field: 'net_pnl_raw', header: t('admin.users.columns.netPnl'), get: (u: AdminUser) => formatSignedUsdt(u.net_pnl_raw) }, + { field: 'total_stake_raw', header: t('admin.users.columns.totalStake'), get: (u: AdminUser) => formatUsdt(u.total_stake_raw) }, + { field: 'total_payout_raw', header: t('admin.users.columns.totalPayout'), get: (u: AdminUser) => formatUsdt(u.total_payout_raw) }, + { field: 'created_at', header: t('admin.users.columns.created'), get: (u: AdminUser) => formatDate(u.created_at) }, + { field: 'last_login_at', header: t('admin.users.columns.lastLogin'), get: (u: AdminUser) => formatDate(u.last_login_at) }, + { field: 'last_activity_at', header: t('admin.users.columns.lastActivity'), get: (u: AdminUser) => formatDate(u.last_activity_at) }, + { field: 'is_enabled', header: t('admin.users.columns.enabled'), get: (u: AdminUser) => (u.is_enabled ? 'true' : 'false') }, { field: 'withdrawals_suspended', - header: 'Withdrawals suspended', + header: t('admin.users.fields.withdrawalsSuspended'), get: (u: AdminUser) => (u.withdrawals_suspended ? 'true' : 'false'), }, { field: 'under_surveillance', - header: 'Under surveillance', + header: t('admin.users.fields.underSurveillance'), get: (u: AdminUser) => (u.under_surveillance ? 'true' : 'false'), }, - { field: 'totp_enabled', header: '2FA', get: (u: AdminUser) => (u.totp_enabled ? 'yes' : 'no') }, + { field: 'totp_enabled', header: t('admin.users.columns.twoFa'), get: (u: AdminUser) => (u.totp_enabled ? 'yes' : 'no') }, { field: 'is_account_non_expired', - header: 'Account non expired', + header: t('admin.users.fields.isAccountNonExpired'), get: (u: AdminUser) => (u.is_account_non_expired ? 'true' : 'false'), }, { field: 'is_account_non_locked', - header: 'Account non locked', + header: t('admin.users.fields.isAccountNonLocked'), get: (u: AdminUser) => (u.is_account_non_locked ? 'true' : 'false'), }, { field: 'is_credentials_non_expired', - header: 'Credentials valid', + header: t('admin.users.fields.isCredentialsNonExpired'), get: (u: AdminUser) => (u.is_credentials_non_expired ? 'true' : 'false'), }, ], - [countryLabel] + [countryLabel, t] ); useEffect(() => { @@ -961,9 +965,9 @@ export function UserManagementPage() { const exportLimitLabel = useMemo(() => { const n = exportLimitInput.trim() ? parseInt(exportLimitInput.trim(), 10) : 0; - if (Number.isFinite(n) && n > 0) return `Export limit: ${n}`; - return 'Export limit: 100k (server)'; - }, [exportLimitInput]); + if (Number.isFinite(n) && n > 0) return t('admin.users.exportLimit', { count: n }); + return t('admin.users.exportLimitDefault'); + }, [exportLimitInput, t]); const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms)); @@ -976,7 +980,7 @@ export function UserManagementPage() { setExportProgress(0); if (selectedOnly && selectedIds.length === 0) { - setToast('No users selected'); + setToast(t('admin.users.noUsersSelected')); return; } @@ -1017,7 +1021,7 @@ export function UserManagementPage() { } if (job.status === 'failed') { - throw new Error(job.error ?? 'Export failed'); + throw new Error(job.error ?? t('admin.users.exportFailed')); } const download = await api.get(`/api/v1/admin/users/export/${job.id}/download`, { @@ -1033,7 +1037,7 @@ export function UserManagementPage() { setToast(`Exported ${job.rowCount} row(s)`); } catch (e: unknown) { const err = e as { response?: { data?: { error?: string } }; message?: string }; - setToast(err?.response?.data?.error ?? err?.message ?? 'Export failed'); + setToast(err?.response?.data?.error ?? err?.message ?? t('admin.users.exportFailed')); } finally { setExporting(false); setExportProgress(null); @@ -1069,7 +1073,7 @@ export function UserManagementPage() { } else if (batchDialog === 'bonus') { const amountRaw = humanToRaw(batchBonusForm.amountDisplay, USDT_DECIMALS); if (amountRaw === '0') { - setToast('Enter a valid bonus amount'); + setToast(t('admin.users.invalidBonusAmount')); return; } batchMut.mutate({ @@ -1084,22 +1088,22 @@ export function UserManagementPage() { const batchLabel = batchDialog === 'enable' - ? 'Enable accounts' + ? t('admin.users.batch.enableAccounts') : batchDialog === 'disable' - ? 'Disable accounts' + ? t('admin.users.batch.disableAccounts') : batchDialog === 'suspend' - ? 'Suspend withdrawals' + ? t('admin.users.batch.suspendAccounts') : batchDialog === 'reactivate' - ? 'Reactivate withdrawals' - : 'Grant bonus'; + ? t('admin.users.batch.reactivateAccounts') + : t('admin.users.batch.grantBonusTitle'); return ( void q.refetch()} />} + title={t('admin.users.title')} + subtitle={t('admin.users.subtitle')} + actions={ void q.refetch()} />} /> @@ -1114,21 +1118,21 @@ export function UserManagementPage() { }} > - {selectedIds.length} selected + {t('admin.users.selected', { count: selectedIds.length })} @@ -1152,8 +1156,8 @@ export function UserManagementPage() { setFilters((f) => ({ ...f, search: e.target.value }))} /> @@ -1163,7 +1167,7 @@ export function UserManagementPage() { onClick={() => setFiltersOpen((v) => !v)} sx={{ whiteSpace: 'nowrap', minWidth: 120 }} > - Filters + {t('admin.users.filters')} @@ -1180,27 +1184,27 @@ export function UserManagementPage() { - Role + {t('admin.users.filterLabels.role')} - Account status + {t('admin.users.filterLabels.accountStatus')} - Email verified + {t('admin.users.filterLabels.emailVerified')} - Received bonus + {t('admin.users.filterLabels.receivedBonus')} { setPage(0); @@ -1267,26 +1271,26 @@ export function UserManagementPage() { }} options={countryOptions} loading={countriesQ.isLoading} - placeholder="All countries — search by name or code…" + placeholder={t('admin.users.filterLabels.countryPlaceholder')} /> { setPage(0); setFilters((f) => ({ ...f, inactiveSinceDays: e.target.value })); }} - placeholder="e.g. 30" + placeholder={t('admin.users.filterLabels.inactivePlaceholder')} /> { setPage(0); @@ -1297,7 +1301,7 @@ export function UserManagementPage() { { setPage(0); @@ -1308,7 +1312,7 @@ export function UserManagementPage() { { setPage(0); @@ -1319,7 +1323,7 @@ export function UserManagementPage() { { setPage(0); @@ -1330,37 +1334,37 @@ export function UserManagementPage() { { setPage(0); setFilters((f) => ({ ...f, minAge: e.target.value })); }} - placeholder="e.g. 10" - helperText="Completed years (inclusive)" + placeholder={t('admin.users.filterLabels.minAgePlaceholder')} + helperText={t('admin.users.filterLabels.minAgeHelper')} slotProps={{ input: { inputProps: { min: 0, max: 150 } } }} /> { setPage(0); setFilters((f) => ({ ...f, maxAge: e.target.value })); }} - placeholder="e.g. 15 for under 16" - helperText="Use 15 to target users under 16" + placeholder={t('admin.users.filterLabels.maxAgePlaceholder')} + helperText={t('admin.users.filterLabels.maxAgeHelper')} slotProps={{ input: { inputProps: { min: 0, max: 150 } } }} /> { @@ -1373,7 +1377,7 @@ export function UserManagementPage() { { @@ -1388,17 +1392,17 @@ export function UserManagementPage() { - {ageFilterLabel(filters.minAge, filters.maxAge) && ( + {ageFilterLabel(t, filters.minAge, filters.maxAge) && ( )} @@ -1408,10 +1412,10 @@ export function UserManagementPage() { {q.isError ? ( - q.refetch()}>Retry}> + q.refetch()}>{t('common.retry')}}> {(q.error as { response?: { data?: { error?: string } }; message?: string })?.response?.data?.error ?? (q.error as Error)?.message ?? - 'Failed to load users.'} + t('admin.users.loadError')} ) : isMobile ? ( @@ -1439,8 +1443,11 @@ export function UserManagementPage() { /> - Main: {formatUsdt(u.main_balance_raw)} · Bonus: {formatUsdt(u.bonus_balance_raw)} ·{' '} - {u.prediction_count} predictions + {t('admin.users.mobile.mainBonusPredictions', { + main: formatUsdt(u.main_balance_raw), + bonus: formatUsdt(u.bonus_balance_raw), + count: u.prediction_count, + })} - onToggle(u, 'isEnabled', v)} /> + onToggle(u, 'isEnabled', v)} /> onToggle(u, 'withdrawalsSuspended', v)} /> @@ -1498,6 +1505,7 @@ export function UserManagementPage() { exportLimitLabel={exportLimitLabel} disabled={q.isLoading || (total === 0 && selectedIds.length === 0) || exporting} selectedCount={selectedIds.length} + t={t} /> ), }} @@ -1521,14 +1529,14 @@ export function UserManagementPage() { setDownloadAnchorEl(null); try { apiRef.current?.exportDataAsCsv?.(); - setToast('CSV exported'); + setToast(t('admin.users.csvExported')); } catch { - setToast('CSV export failed'); + setToast(t('admin.users.csvExportFailed')); } }} disabled={q.isLoading || total === 0} > - Export CSV (current page) + {t('admin.users.export.csvCurrentPage')} { @@ -1538,7 +1546,7 @@ export function UserManagementPage() { }} disabled={q.isLoading || total === 0 || exporting} > - Export XLSX (all filtered)… + {t('admin.users.export.xlsxAllFiltered')} {selectedIds.length > 0 && ( - Export XLSX (selected) + {t('admin.users.export.xlsxSelected')} )} !exporting && setExportDialogOpen(false)} maxWidth="xs" fullWidth> - Export XLSX (server) + {t('admin.users.export.dialogTitle')} setExportVisibleOnly(v)} /> - Export visible columns only + {t('admin.users.export.visibleOnly')} - Use the Columns button in the toolbar to choose which fields appear and export. + setExportLimitInput(e.target.value)} - placeholder="Default 100,000 on server" + placeholder={t('admin.users.export.maxRowsPlaceholder')} /> - Matching users: {totalLabel.replace('Loading…', '…')} + {t('admin.users.export.matchingUsers', { label: totalLabel.replace(t('common.loading'), '…') })} {exporting && exportProgress !== null && ( - Server export in progress… {exportProgress.toLocaleString()} row(s) + {t('admin.users.export.inProgress', { count: exportProgress.toLocaleString() })} )} - + @@ -1606,14 +1614,14 @@ export function UserManagementPage() { {batchLabel} - Apply to {selectedIds.length} selected user(s)? + {batchDialog === 'bonus' && ( - Type + {t('common.type')} setBatchBonusForm((f) => ({ ...f, amountDisplay: e.target.value }))} /> - + setRoleDialog(null)} maxWidth="xs" fullWidth> - Manage user roles + {t('admin.users.roleDialog.title')} {roleDialog?.email ?? roleDialog?.userId} @@ -1673,14 +1681,14 @@ export function UserManagementPage() { }} /> } - label={role === 'super_admin' ? 'Super administrator' : role.charAt(0).toUpperCase() + role.slice(1)} + label={t(`admin.users.roles.${role}` as 'admin.users.roles.user')} /> ))} setConfirm(null)} maxWidth="xs" fullWidth> - Confirm change + {t('admin.users.confirmDialog.title')} - Set {confirm?.field} to {confirm?.next ? 'true' : 'false'}? + {confirm?.label} - - + + diff --git a/prediqo_web/src/features/users/adminUserTypes.ts b/prediqo_web/src/features/users/adminUserTypes.ts index 18942418..97ab9b4f 100644 --- a/prediqo_web/src/features/users/adminUserTypes.ts +++ b/prediqo_web/src/features/users/adminUserTypes.ts @@ -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 = { diff --git a/prediqo_web/src/features/wallet/WalletPage.tsx b/prediqo_web/src/features/wallet/WalletPage.tsx index 4e488847..993ae89a 100644 --- a/prediqo_web/src/features/wallet/WalletPage.tsx +++ b/prediqo_web/src/features/wallet/WalletPage.tsx @@ -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(null); const [toast, setToast] = useState(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() { } - title="Wallet" - subtitle={ - <> - Deposit USDT (TRC20) on TRON to fund your account and play Candle Predict. - - } + title={t('wallet.title')} + subtitle={ }} />} mb={2.5} actions={ void refreshAll()} disabled={loading} /> @@ -99,7 +97,7 @@ export function WalletPage() { {balancesQ.isError && ( - Failed to load balances. Make sure you are logged in and the API is running. + {t('wallet.loadError')} )} @@ -115,7 +113,7 @@ export function WalletPage() { }} > - Main USDT balance + {t('wallet.mainBalance')} {loading ? ( @@ -125,11 +123,11 @@ export function WalletPage() { {portfolioSummary.human} {shortSymbol(USDT_WALLET_CODE)} {portfolioSummary.hasLocked && ( - + )} ) : ( - No balance yet — receive USDT to get started. + {t('wallet.noBalance')} )} @@ -139,7 +137,7 @@ export function WalletPage() { onClick={() => setDialog('receive')} sx={{ flex: 1 }} > - Receive USDT + {t('wallet.receiveUsdt')} @@ -169,8 +167,8 @@ export function WalletPage() { allowScrollButtonsMobile sx={{ mb: 2, borderBottom: '1px solid rgba(255,255,255,0.08)' }} > - - + + {tab === 0 && ( diff --git a/prediqo_web/src/features/wallet/components/BonusWalletCard.tsx b/prediqo_web/src/features/wallet/components/BonusWalletCard.tsx index cd1b99a1..17af0230 100644 --- a/prediqo_web/src/features/wallet/components/BonusWalletCard.tsx +++ b/prediqo_web/src/features/wallet/components/BonusWalletCard.tsx @@ -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 - Bonus wallet + {t('wallet.bonusCard.title')} - USDT credits for Candle Predict + {t('wallet.bonusCard.subtitle')} - Bonus balance + {t('wallet.bonusCard.balance')} - Use the bonus wallet when placing predictions. Winnings from bonus stakes are credited to your main wallet. + {t('wallet.bonusCard.hint')} {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')} )} {!bonusWithdrawable && ( - Bonus funds can only be used for predictions (transfer to main is disabled by platform policy). + {t('wallet.bonusCard.policyHint')} )} diff --git a/prediqo_web/src/features/wallet/components/MainAssetCard.tsx b/prediqo_web/src/features/wallet/components/MainAssetCard.tsx index aa555430..ba99bed4 100644 --- a/prediqo_web/src/features/wallet/components/MainAssetCard.tsx +++ b/prediqo_web/src/features/wallet/components/MainAssetCard.tsx @@ -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)} - Main wallet + {t('wallet.mainCard.title')} {balance.walletType.name} · {networkLabel(USDT_WALLET_CODE)} - + - Available balance + {t('wallet.mainCard.availableBalance')} {formatBalance(balance.available, balance.walletType.decimals, USDT_WALLET_CODE)} @@ -72,17 +74,17 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps {hasLocked && ( - Locked:{' '} + {t('wallet.mainCard.locked')}{' '} {formatBalance(balance.locked, balance.walletType.decimals, USDT_WALLET_CODE)} )} diff --git a/prediqo_web/src/features/wallet/components/ReceiveDialog.tsx b/prediqo_web/src/features/wallet/components/ReceiveDialog.tsx index 4a9a308e..f92d92f4 100644 --- a/prediqo_web/src/features/wallet/components/ReceiveDialog.tsx +++ b/prediqo_web/src/features/wallet/components/ReceiveDialog.tsx @@ -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 ( - Receive USDT + {t('wallet.receiveDialog.title')} - Send USDT on {networkLabel(USDT_WALLET_CODE)} only. This balance is used - for Candle Predict stakes. + }} + /> - Wrong asset or network may result in permanent loss. + {t('wallet.receiveDialog.wrongNetwork')} {depositQ.isLoading ? ( @@ -61,7 +66,7 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) { ) : depositQ.isError ? ( {(depositQ.error as { response?: { data?: { error?: string } } })?.response?.data - ?.error ?? 'Failed to load deposit address'} + ?.error ?? t('wallet.receiveDialog.loadAddressFailed')} ) : depositQ.data ? ( @@ -97,23 +102,27 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) { > {depositQ.data.address} - + - Deposits are credited after the required on-chain confirmations. + {t('wallet.receiveDialog.confirmationsHint')} ) : null} - + diff --git a/prediqo_web/src/features/wallet/components/TestWalletCard.tsx b/prediqo_web/src/features/wallet/components/TestWalletCard.tsx index 07716c78..b1c4eca7 100644 --- a/prediqo_web/src/features/wallet/components/TestWalletCard.tsx +++ b/prediqo_web/src/features/wallet/components/TestWalletCard.tsx @@ -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 - Test wallet + {t('wallet.testCard.title')} - Play-money for practice predictions + {t('wallet.testCard.subtitle')} - Test balance + {t('wallet.testCard.balance')} - 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')} {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 })} {status.maxRequests > 0 && ( - Requests used: {status.requestsUsed} / {status.maxRequests} + {t('wallet.testCard.requestsUsed', { + used: status.requestsUsed, + max: status.maxRequests, + })} )} {!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(), + })} )} @@ -163,7 +167,7 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr ) : ( - Test wallet requests are currently disabled by the platform. + {t('wallet.testCard.disabled')} )} diff --git a/prediqo_web/src/features/wallet/components/TransactionList.tsx b/prediqo_web/src/features/wallet/components/TransactionList.tsx index f1b95f96..2ba19b1e 100644 --- a/prediqo_web/src/features/wallet/components/TransactionList.tsx +++ b/prediqo_web/src/features/wallet/components/TransactionList.tsx @@ -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)', }} > - No transactions yet + {t('wallet.transactions.empty')} - Deposits, predictions, and withdrawals will appear here. + {t('wallet.transactions.emptyHint')} ); @@ -98,11 +100,11 @@ export function TransactionList({
- Asset - Type - Amount - Status - Date + {t('common.asset')} + {t('common.type')} + {t('common.amount')} + {t('common.status')} + {t('common.date')} @@ -153,7 +155,7 @@ export function TransactionList({ - {total > 0 ? `${from}–${to} of ${total}` : 'No results'} + {total > 0 + ? t('common.pagination', { from, to, total }) + : t('common.noResults')} - Send to user + {t('wallet.transferDialog.title')} - Transfer to another Prediqo account instantly. On-chain fees do not apply. + {t('wallet.transferDialog.subtitle')} - Asset + {t('common.asset')} setAsset(e.target.value)} > @@ -191,11 +193,15 @@ export function WithdrawDialog({ - Network: {networkLabel(asset)} (cannot be changed) + }} + /> setToAddress(e.target.value)} @@ -207,7 +213,7 @@ export function WithdrawDialog({ /> 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 } /> setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))} inputMode="numeric" disabled={!withdrawalsEnabled} - placeholder="6-digit code" + placeholder={t('wallet.withdrawDialog.totpPlaceholder')} /> - + setConfirmOpen(false)} maxWidth="xs" fullWidth> - Confirm withdrawal + {t('wallet.withdrawDialog.confirmTitle')} - You will receive {amount} {shortSymbol(asset)} on{' '} - {networkLabel(asset)}. + }} + /> {feeRaw > 0n && ( - Network fee: {feeLabel} + {t('wallet.withdrawDialog.networkFeeLabel')} {feeLabel}
- Total debited from your balance: {totalDebitLabel} + {t('wallet.withdrawDialog.totalDebited')} {totalDebitLabel}
)} - This transaction is irreversible once broadcast. + {t('wallet.withdrawDialog.broadcastIrreversible')}
diff --git a/prediqo_web/src/features/wallet/utils/transactionDisplay.ts b/prediqo_web/src/features/wallet/utils/transactionDisplay.ts index bf6f6a20..641f1bfd 100644 --- a/prediqo_web/src/features/wallet/utils/transactionDisplay.ts +++ b/prediqo_web/src/features/wallet/utils/transactionDisplay.ts @@ -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([ 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'; diff --git a/prediqo_web/src/main.tsx b/prediqo_web/src/main.tsx index 96451ad3..430f5b16 100644 --- a/prediqo_web/src/main.tsx +++ b/prediqo_web/src/main.tsx @@ -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'; diff --git a/prediqo_web/src/shared/components/CountryAutocomplete.tsx b/prediqo_web/src/shared/components/CountryAutocomplete.tsx index 37059045..81c425b8 100644 --- a/prediqo_web/src/shared/components/CountryAutocomplete.tsx +++ b/prediqo_web/src/shared/components/CountryAutocomplete.tsx @@ -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) => ( )} slotProps={{ diff --git a/prediqo_web/src/shared/components/GenderSelect.tsx b/prediqo_web/src/shared/components/GenderSelect.tsx index b8c9e823..c143f724 100644 --- a/prediqo_web/src/shared/components/GenderSelect.tsx +++ b/prediqo_web/src/shared/components/GenderSelect.tsx @@ -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 ( - {label} + {resolvedLabel} diff --git a/prediqo_web/src/shared/components/PageHeader.tsx b/prediqo_web/src/shared/components/PageHeader.tsx index 64da0413..38a19984 100644 --- a/prediqo_web/src/shared/components/PageHeader.tsx +++ b/prediqo_web/src/shared/components/PageHeader.tsx @@ -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 ( - + ); diff --git a/prediqo_web/src/shared/constants/userGender.ts b/prediqo_web/src/shared/constants/userGender.ts index 82f747a2..e21bd01a 100644 --- a/prediqo_web/src/shared/constants/userGender.ts +++ b/prediqo_web/src/shared/constants/userGender.ts @@ -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; } diff --git a/prediqo_web/src/shared/i18n/LanguageSwitcher.tsx b/prediqo_web/src/shared/i18n/LanguageSwitcher.tsx new file mode 100644 index 00000000..6327eb3f --- /dev/null +++ b/prediqo_web/src/shared/i18n/LanguageSwitcher.tsx @@ -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 = { 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); + 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 ( + <> + + + + setAnchor(null)}> + {OPTIONS.map((opt) => ( + void select(opt.code)} + > + {display === 'abbrev' ? `${ABBREV[opt.code]} — ${t(opt.labelKey)}` : t(opt.labelKey)} + + ))} + + + ); +} diff --git a/prediqo_web/src/shared/i18n/index.ts b/prediqo_web/src/shared/i18n/index.ts new file mode 100644 index 00000000..be9985e5 --- /dev/null +++ b/prediqo_web/src/shared/i18n/index.ts @@ -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; diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts new file mode 100644 index 00000000..eccf4321 --- /dev/null +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -0,0 +1,2046 @@ +export const en = { + common: { + loading: 'Loading…', + refresh: 'Refresh', + role: 'Role', + user: 'User', + logout: 'Logout', + yes: 'Yes', + no: 'No', + openNav: 'Open navigation', + language: 'Language', + english: 'English', + french: 'French', + retry: 'Retry', + back: 'Back', + edit: 'Edit', + email: 'Email', + password: 'Password', + sending: 'Sending…', + save: 'Save', + cancel: 'Cancel', + all: 'All', + on: 'On', + off: 'Off', + exporting: 'Exporting…', + saving: 'Saving…', + close: 'Close', + copyAddress: 'Copy address', + copyFailed: 'Copy failed', + addressCopied: 'Address copied to clipboard', + asset: 'Asset', + confirm: 'Confirm', + countryLoading: 'Loading countries…', + noCountryFound: 'No country found', + countrySearchPlaceholder: 'Search by country name or code…', + review: 'Review', + nothingToCopy: 'Nothing to copy', + copied: '{{label}} copied', + transferFailed: 'Transfer failed', + withdrawalFailed: 'Withdrawal failed', + fundsAvailable: 'Funds available', + empty: 'Empty', + date: 'Date', + type: 'Type', + amount: 'Amount', + status: 'Status', + noResults: 'No results', + pagination: '{{from}}–{{to}} of {{total}}', + catalogRefreshed: 'Catalog refreshed', + walletRefreshed: 'Wallet refreshed', + profileRefreshed: 'Profile refreshed', + gameRefreshed: 'Game refreshed', + }, + nav: { + home: 'Home', + wallet: 'Wallet', + referrals: 'Referrals', + profile: 'Profile', + faq: 'FAQ', + support: 'Support', + approvals: 'Approvals', + overview: 'Overview', + reports: 'Reports', + options: 'Options', + users: 'Users', + security: 'Security', + settings: 'Settings', + }, + auth: { + brandSubtitle: 'Prediction games platform — sign in to manage or play.', + signIn: 'Sign in', + signingIn: 'Signing in…', + signUp: 'Sign up', + createAccount: 'Create account', + forgotPassword: 'Forgot password?', + noAccount: 'No account yet?', + createOne: 'Create one', + alreadyHaveAccount: 'Already have an account?', + backToSignIn: 'Back to sign in', + totpOptional: '2FA code (optional)', + verifyEmailHint: + 'We sent a confirmation link to your email. Verify your address before signing in.', + noAdminConfigured: 'No administrator is configured.', + initializePlatform: 'Initialize the platform', + emailNotVerified: + 'Your account exists but the email is not verified yet. Request a new confirmation link below (check spam if nothing arrives).', + resendVerification: 'Resend verification email', + devVerifyLink: 'Dev link:', + openVerificationUrl: 'Open verification URL', + enterEmailFirst: 'Enter your email address first.', + emailPasswordRequired: 'Email and password are required.', + loginFailed: 'Login failed', + resendFailed: 'Failed to resend verification email', + registerSubtitle: "Join Prediqo — use a friend's referral link or sign up directly.", + invitedWithCode: 'You were invited with referral code {{code}}.', + fullName: 'Full name', + fullNameRequired: 'Full name *', + emailRequired: 'Email *', + phoneOptional: 'Phone (optional)', + passwordRequired: 'Password *', + countryOfResidence: 'Country of residence', + countryHelper: 'Type a country name or ISO code (e.g. France or FR)', + nationalityOptional: 'Nationality (optional)', + nationalityPlaceholder: 'Search nationality…', + referralCodeOptional: 'Referral code (optional)', + referralValid: 'Valid referral code', + referralUnknown: + 'Unknown code — you can still register (default referrer will apply)', + referralEmpty: 'Leave empty to use the platform default referrer', + creatingAccount: 'Creating account…', + registerFieldsRequired: + 'Full name, email, password, country of residence, and gender are required.', + countryIsoInvalid: 'Country must be a 2-letter ISO code (e.g. FR).', + registerSuccess: + 'Account created. Check your email and click the verification link before signing in.', + registerFailed: 'Registration failed', + countriesLoadFailed: + 'Could not load country list. Ask an admin to sync countries, then refresh.', + resetPassword: 'Reset password', + resetPasswordSubtitle: + "Enter your email and we'll send you a secure link to choose a new password.", + emailRequiredShort: 'Email is required.', + sendResetLink: 'Send reset link', + requestFailed: 'Request failed', + consoleResetHint: + 'Local / console mode — no email is sent. Open this link to reset your password:', + chooseNewPassword: 'Choose new password', + invalidResetLink: + 'Invalid or expired reset link. Request a new one from the forgot password page.', + newPassword: 'New password', + confirmPassword: 'Confirm password', + passwordsMustMatch: 'Passwords must match.', + updating: 'Updating…', + updatePassword: 'Update password', + requestNewLink: 'Request a new link', + resetFailed: 'Reset failed', + verifyingEmail: 'Verifying your email…', + goToProfile: 'Go to profile', + backToProfile: 'Back to profile', + verificationFailed: 'Verification failed', + requestNewLinkFromProfile: 'Request a new link from your profile if this one expired.', + missingVerificationToken: 'Missing verification token. Open the full link from your email.', + faqLink: 'FAQ', + }, + setup: { + loading: 'Loading…', + statusCheckFailed: 'Unable to check setup status', + apiUnreachable: + 'The API did not respond. Check that VITE_API_BASE_URL matches the public URL (e.g. http://prediqo.redirectme.net:9080) then rebuild the frontend.', + setupComplete: 'Setup complete', + adminExists: 'An administrator account already exists. Sign in to access the platform.', + goToLogin: 'Go to sign in', + title: 'Prediqo setup', + subtitle: 'Create the first administrator account to configure the platform in production.', + tokenEnvWarning: + 'Set the INITIAL_SETUP_TOKEN environment variable on the server (min. 16 random characters), then restart the API.', + setupTokenLabel: 'Setup token (INITIAL_SETUP_TOKEN)', + setupTokenHelper: 'Secret configured only on the server — do not share it.', + tabCreate: 'Create admin', + tabPromote: 'Promote existing account', + fullName: 'Full name', + passwordMin: 'Minimum 8 characters', + promoteHint: + 'The user must already have registered via the Register page. Their email will be marked as verified and their role will be set to administrator.', + inProgress: 'In progress…', + createAdmin: 'Create administrator', + promoteAdmin: 'Promote to admin', + setupFailed: 'Setup failed', + promotionFailed: 'Promotion failed', + backToLogin: 'Back to sign in', + }, + gender: { + label: 'Gender', + select: 'Select…', + helper: 'Male, Female, or Other', + male: 'Male', + female: 'Female', + other: 'Other', + }, + home: { + title: 'Play & Predict', + subtitle: + 'Explore live prediction games, grab limited-time promos, and compete for rewards.', + refreshCatalog: 'Refresh catalog', + loadError: + 'Some content failed to load. Run database migrations and ensure the API is running.', + liveGames: 'Live games', + featured: 'Featured', + total: 'Total', + promotions: 'Promotions', + categories: 'Categories', + allGames: 'All games', + availableGames: 'Available games', + noGamesInCategory: 'No games in this category yet.', + gameStatus: { + live: 'Live', + soon: 'Soon', + maintenance: 'Maintenance', + featured: 'Featured', + playNow: 'Play now', + }, + }, + wallet: { + title: 'Wallet', + subtitle: + 'Deposit USDT (TRC20) on TRON to fund your account and play Candle Predict.', + refreshWallet: 'Refresh wallet', + loadError: 'Failed to load balances. Make sure you are logged in and the API is running.', + mainBalance: 'Main USDT balance', + locked: '{{amount}} locked', + noBalance: 'No balance yet — receive USDT to get started.', + receiveUsdt: 'Receive USDT', + send: 'Send', + withdraw: 'Withdraw', + tabAsset: 'Asset', + tabActivity: 'Activity', + receiveDialog: { + title: 'Receive USDT', + info: 'Send USDT on {{network}} only. This balance is used for Candle Predict stakes.', + wrongNetwork: 'Wrong asset or network may result in permanent loss.', + loadAddressFailed: 'Failed to load deposit address', + copyAddressAria: 'Copy address', + confirmationsHint: 'Deposits are credited after the required on-chain confirmations.', + }, + transferDialog: { + title: 'Send to user', + subtitle: 'Transfer to another Prediqo account instantly. On-chain fees do not apply.', + recipientEmail: 'Recipient email', + networkAuto: 'Network: {{network}} (auto-selected)', + available: 'Available: {{amount}}', + totpCode: '2FA code', + totpPlaceholder: '6-digit code', + totpRequired: 'Required if 2FA is enabled on your account', + review: 'Review transfer', + confirmTitle: 'Confirm transfer', + confirmBody: 'Send {{amount}} {{asset}} to {{email}}?', + irreversible: 'This action cannot be undone.', + success: 'Transfer completed successfully', + }, + withdrawDialog: { + title: 'Withdraw', + disabled: 'Withdrawals are disabled on this server (testnet safety). Contact an administrator to enable ALLOW_WITHDRAWALS=true when ready.', + networkWarning: 'Double-check the destination address and network. Wrong network transfers are irreversible.', + networkFee: 'A network fee of {{fee}} is deducted from your balance in addition to the withdrawal amount (covers TRON gas for the on-chain transfer).', + networkFixed: 'Network: {{network}} (cannot be changed)', + destinationAddress: 'Destination address', + amountToReceive: 'Amount to receive', + totpOptional: '2FA code (optional)', + totpPlaceholder: '6-digit code', + insufficient: 'Insufficient balance — need {{total}} (amount + network fee)', + availableWithFee: 'Available: {{available}}{{feePart}}', + networkFeePart: ' · Network fee: {{fee}}', + review: 'Review withdrawal', + confirmTitle: 'Confirm withdrawal', + receiveOnNetwork: 'You will receive {{amount}} {{asset}} on {{network}}.', + networkFeeLabel: 'Network fee:', + totalDebited: 'Total debited from your balance:', + broadcastIrreversible: 'This transaction is irreversible once broadcast.', + withdrawing: 'Withdrawing…', + success: 'Withdrawal submitted successfully', + successWithFee: 'Withdrawal submitted successfully (fee {{fee}} USDT)', + }, + mainCard: { + title: 'Main wallet', + badge: 'Deposits & withdrawals', + availableBalance: 'Available balance', + locked: 'Locked:', + receive: 'Receive', + receiveAria: 'Receive USDT', + }, + bonusCard: { + title: 'Bonus wallet', + subtitle: 'USDT credits for Candle Predict', + balance: 'Bonus balance', + hint: 'Use the bonus wallet when placing predictions. Winnings from bonus stakes are credited to your main wallet.', + transferring: 'Transferring…', + moveToMain: 'Move all to main wallet', + transferSuccess: 'Bonus transferred to main wallet', + policyHint: 'Bonus funds can only be used for predictions (transfer to main is disabled by platform policy).', + }, + testCard: { + title: 'Test wallet', + subtitle: 'Play-money for practice predictions', + balance: 'Test balance', + hint: '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.', + crediting: 'Crediting…', + requestCredits: 'Request {{amount}} test credits', + requestsUsed: 'Requests used: {{used}} / {{max}}', + availableAfter: 'Available after {{date}}.', + disabled: 'Test wallet requests are currently disabled by the platform.', + }, + transactions: { + empty: 'No transactions yet', + emptyHint: 'Deposits, predictions, and withdrawals will appear here.', + types: { + deposit: 'Deposit', + withdrawal: 'Withdrawal', + transferIn: 'Transfer in', + transferOut: 'Transfer out', + gameStake: 'Prediction stake', + gamePayout: 'Prediction win', + gameRefund: 'Prediction refund', + bonus: 'Bonus credit', + adminAdjustment: 'Balance adjustment', + }, + status: { + completed: 'Completed', + pending: 'Pending', + failed: 'Failed', + processing: 'Processing', + }, + }, + }, + profileForm: { + editHint: 'Fields show your current information. Edit only what you want to change, then save.', + firstName: 'First name', + middleName: 'Middle name', + lastName: 'Last name', + dateOfBirth: 'Date of birth', + phoneOptional: 'Phone (optional)', + countryHelper: 'Search by country name or ISO code (e.g. France or FR)', + nationalityPlaceholder: 'Search nationality…', + countriesLoadFailed: 'Could not load country list. Try again later or contact support.', + saveProfile: 'Save profile', + saving: 'Saving…', + updated: 'Profile updated successfully', + updateFailed: 'Update failed', + emailEmpty: 'Email cannot be empty', + countryRequired: 'Country of residence is required', + genderRequired: 'Gender is required', + }, + profilePassword: { + current: 'Current password', + new: 'New password', + confirm: 'Confirm new password', + strengthHint: 'Choose a strong password. Server policy (length, complexity) is enforced on save.', + enterCurrent: 'Enter your current password', + enterNew: 'Enter a new password', + mismatch: 'New password and confirmation do not match', + updated: 'Password updated successfully', + failed: 'Password change failed', + }, + profileTwoFactor: { + enabled: 'Two-factor authentication is enabled on your account. A TOTP code is required for transfers when 2FA is active.', + setupHint: 'Protect your account with Google Authenticator or any TOTP app. Scan the QR code, then enter a verification code to enable 2FA.', + setupButton: 'Set up 2FA', + scanQr: 'Scan with your authenticator app', + qrAlt: '2FA QR code', + manualKey: 'Manual key: {{secret}}', + verificationCode: '6-digit verification code', + enabling: 'Enabling…', + enable: 'Enable 2FA', + enterCode: 'Enter the 6-digit code from your authenticator app', + enabledSuccess: 'Two-factor authentication enabled', + setupFailed: '2FA setup failed', + invalidCode: 'Invalid code. Scan the QR again and enter the current 6-digit code.', + }, + profileEmailVerify: { + verified: 'Your email {{email}} is verified.', + notVerified: 'Your email {{email}} is not verified yet. Verify it to secure withdrawals and account recovery.', + hint: 'We will send a secure one-time link valid for 24 hours. Changing your email requires verification again.', + sendEmail: 'Send verification email', + sendFailed: 'Failed to send email', + devMode: 'Dev mode: SMTP is not used. Open or copy this link to verify locally.', + copyDevLink: 'Copy dev link', + devLinkCopied: 'Dev verify link copied', + }, + profileReferral: { + loadFailed: 'Could not load referral information.', + notAvailable: 'Your referral code is not available yet. Contact support if you registered before the referral program launched.', + shareHint: 'Share your link to invite friends and earn commissions on their activity.', + fullNetwork: 'Full network', + directReferrals_one: '{{count}} direct referral', + directReferrals_other: '{{count}} direct referrals', + referralCode: 'Referral code', + referralLink: 'Referral link', + copyCodeAria: 'Copy referral code', + copyLinkAria: 'Copy referral link', + copyInvite: 'Copy invite link', + }, + profile: { + title: 'Profile', + subtitle: 'View and manage your personal information and account security.', + refreshProfile: 'Refresh profile', + loadError: 'Failed to load profile. Make sure you are logged in and the API is running.', + emailVerified: 'Email verified', + emailNotVerified: 'Email not verified', + twoFaEnabled: '2FA enabled', + twoFaOff: '2FA off', + tabPersonal: 'Personal', + tabSecurity: 'Security', + personalInfo: 'Personal information', + emailVerification: 'Email verification', + referralProgram: 'Referral program', + accountDetails: 'Account details', + userId: 'User ID', + memberSince: 'Member since', + changePassword: 'Change password', + changePasswordHint: + 'Update your password. You will need your current password to confirm.', + twoFactorAuth: 'Two-factor authentication', + twoFactorHint: + 'Protect your account with an authenticator app. Required for sensitive operations when enabled.', + enabled: 'Enabled', + disabled: 'Disabled', + }, + candlePredict: { + title: 'Candle Predict', + subtitle: + 'Predict whether the next candle will be bearish (Short ↓) or bullish (Long ↑), then wait for the round result.', + refreshGame: 'Refresh game', + backToHome: 'Back to home', + loadError: 'Failed to load Candle Predict.', + rateLimitHint: 'Too many API requests — wait a minute or restart the backend.', + apiHint: 'Run database migrations and ensure the API is running.', + singleCandle: 'Single candle', + multiCandle: 'Multi-candle', + predictionPlaced: 'Prediction placed for {{interval}} round', + multiPredictionPlaced: 'Multi-candle level {{level}} prediction placed', + placePredictionFailed: 'Failed to place prediction', + multiPlaceFailed: 'Failed to place multi-candle prediction', + autoEnabledPlaced: 'Auto prediction enabled — placed for {{interval}} round', + autoUpdated: 'Auto prediction updated', + autoSaveFailed: 'Failed to save auto settings', + status: { + loading: 'Loading…', + betting: + '{{interval}} · predictions open · target {{target}} · {{countdown}} left', + locked: + '{{interval}} · candle live · {{live}} · predictions in {{untilOpen}}', + waiting: '{{interval}} · next window in {{countdown}}', + neutral: '{{interval}} · neutral round · stake refunded', + shortWin: '{{interval}} · settled · Short won', + longWin: '{{interval}} · settled · Long won', + settled: '{{interval}} · settled', + }, + betting: { + title: 'Place your prediction', + hint: 'Short = bearish candle · Long = bullish candle. Choose a direction and confirm your stake.', + targetRound: 'Target round {{time}} · closes in {{wait}}', + predictionsOpenIn: 'Predictions open in {{wait}}', + gameDisabled: 'Game disabled by admin — predictions are unavailable.', + predictionLocked: 'Your prediction is locked for this round.', + chooseDirection: 'Choose direction', + short: 'Short', + long: 'Long', + stake: 'Stake', + confirm: 'Confirm prediction', + confirming: 'Confirming…', + windowClosed: 'Prediction window is closed for this round.', + minMaxStake: 'Stake must be between {{min}} and {{max}}.', + candleInProgress: + 'Candle in progress — place your prediction when the window opens{{suffix}}.', + nextWindowOpens: 'The next prediction window opens shortly before the new candle.', + stakeAmount: 'Stake amount ({{code}})', + stakeHelper: + 'Quick picks above, or enter any amount from {{min}} to {{max}} USDT (e.g. 0.25)', + prediction: 'Prediction', + confirmCompact: 'Confirm · {{stake}} · ×{{multiplier}}', + confirmFull: 'Confirm prediction · {{stake}} · Payout ×{{multiplier}}', + }, + interval: { + title: 'Prediction period', + hint: 'Your prediction targets the round that closes at the end of this period.', + }, + testMode: { + title: 'Test mode', + hint: '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.', + }, + stakeWallet: { + barTitle: 'Your stake wallets', + main: 'Main', + bonus: 'Bonus', + test: 'Test', + mainWallet: 'Main wallet', + bonusWallet: 'Bonus wallet', + testWallet: 'Test wallet', + showBalances: 'Show balances', + hideBalances: 'Hide balances', + }, + adminInsights: { + title: 'Admin view — internal mechanics', + footer: + 'Not visible to players. Pool totals and settlement rules must not influence their predictions.', + poolWinnerMinority: 'Minority wins', + poolWinnerMajority: 'Majority wins', + neutralMin: 'neutral if pool gap ≤ {{percent}}%', + neutralMax: 'neutral if largest pool ≥ {{percent}}%', + neutralNone: 'No automatic neutral rounds from pool balance', + neutralBehavior: 'Neutral rounds refund all stakes — no winners and no losers.', + }, + roundStatus: { + title: 'Round status', + }, + gameDisabledAdmin: 'This game is temporarily disabled by an administrator.', + direction: { + shortCandle: 'Short candle', + longCandle: 'Long candle', + shortBearish: 'Short (bearish)', + longBullish: 'Long (bullish)', + }, + stakeWalletSelector: { + label: 'Stake wallet', + mainWallet: 'Main wallet · {{balance}}', + bonusWallet: 'Bonus wallet · {{balance}}', + testWallet: 'Test wallet · {{balance}}', + }, + stakeField: { + customAmount: 'Custom amount', + required: 'Enter an amount', + invalidFormat: 'Invalid format: no leading zeros (use 0.5, not 00.5)', + zero: 'Amount must be greater than zero', + invalid: 'Enter a valid amount (e.g. 0.01, 1.5, 10)', + range: 'Amount must be between {{min}} and {{max}}', + }, + multiBetting: { + title: 'Multi-candle prediction', + hint: 'Predict consecutive candles in exact order. Minimum level 2 — use single mode for one candle.', + inProgress: 'Multi-candle prediction in progress', + progress: + 'Level {{level}} · stake {{stake}} · validating candle {{current}} of {{total}}', + current: 'current', + progressAlert: + 'One wrong candle ends the sequence immediately. Your stake stays pending until the final candle is validated.', + noLevels: 'No multi-candle levels are currently available.', + singleBlocksMulti: + 'You already have a single-candle prediction for this round (including auto). Multi-candle is unavailable until the next window.', + level: 'Level', + levelOption: 'Level {{level}} — {{count}} candles · win ×{{multiplier}}', + yourSequence: 'Your sequence', + candleN: 'Candle {{n}}', + winHint: 'Win on success: stake × {{multiplier}} ({{interval}}).', + placing: 'Placing…', + placeLevel: 'Place level {{level}} prediction', + }, + autoPrediction: { + title: 'Auto Prediction', + titleActive: 'Auto prediction active', + enableHint: 'Enable to bet automatically each round.', + enable: 'Enable auto prediction', + disable: 'Disable', + targetPeriod: 'Target period:', + viewingDifferent: + 'You are viewing {{viewing}}. Save to move auto to {{target}}.', + targetHint: + 'Set from the prediction period you select when saving. One auto config per account.', + direction: 'Direction', + stakeAmount: 'Stake amount', + stakeHelper: 'Quick picks: {{picks}} · custom from {{min}} to {{max}} USDT', + mode: 'Mode', + modeEachRound: 'Each new round', + modeInterval: 'Minimum delay', + modeIntervalHelper: + 'At most one bet per round. Waits at least the delay since the last successful auto bet before betting on the next round (or on save).', + modeEachRoundHelper: + 'Places a bet as soon as the prediction window opens for each new round.', + intervalSeconds: 'Minimum delay between auto bets (seconds)', + intervalSecondsHelper: + 'Minimum time since the last successful auto bet. Does not allow multiple bets on the same round — only spaces consecutive bets (e.g. after a recent save).', + save: 'Save auto settings', + cancel: 'Cancel', + edit: 'Edit', + editSettings: 'Edit settings', + intro: + 'Automatically places one prediction per round on the target period with the settings below. The stake is taken from the selected wallet. Nothing is sent until you click Save.', + configureAlert: + 'Configure your prediction below, then click Save auto settings to enable the mode. No bet will be placed before saving.', + lastAutoBet: 'Last auto bet: {{date}}', + modeShortEachRound: 'Each round', + modeShortInterval: 'Min. delay', + }, + autoBanner: { + activeOnInterval: 'Auto prediction active · {{interval}}', + activeOtherInterval: 'Auto prediction active on {{interval}}', + viewingMismatch: + 'You are viewing {{viewing}}. Auto predictions only run on {{auto}} — switch period or re-save auto settings here to move auto to {{viewing}}.', + viewInterval: 'View {{interval}}', + modeInterval: 'min. {{seconds}}s delay between auto bets · 1/round', + modeEachRound: 'each new round', + }, + recentPredictions: { + title: 'Recent predictions', + totalPerPage: '{{total}} total · {{size}} per page', + empty: 'No predictions yet', + loadError: 'Could not load predictions. Try refreshing the page.', + columns: { + mode: 'Mode', + prediction: 'Prediction', + period: 'Period', + stake: 'Stake', + account: 'Account', + status: 'Status', + payout: 'Payout', + }, + modeSingle: 'Single', + modeAuto: 'Auto', + modeMulti: 'Multi · L{{level}}', + status: { + pending: 'Pending', + in_progress: 'In progress', + won: 'Won', + lost: 'Lost', + refunded: 'Refunded', + }, + placed: 'Placed {{time}}', + stakeLine: '{{placed}} · Stake {{stake}} · Payout {{payout}}', + multiPeriod: '{{count}} consecutive candles · {{minutes}}m each', + multiPeriodShort: 'Multi · {{count}} × {{minutes}}m', + multiFailed: 'Failed on candle {{current}} of {{total}}', + multiWon: 'All {{total}} candles validated', + multiValidating: 'Validating candle {{current}} of {{total}}', + multiRefunded: 'Sequence refunded ({{total}} candles)', + }, + poolBar: { + title: 'Stake pools', + shortBearish: 'Short (bearish)', + longBullish: 'Long (bullish)', + hint: + 'Pools include all predictions maturing at this round time (every interval). {{winner}} when the gap exceeds the tie tolerance. Equal pools → neutral round (refund).', + winnerMinority: 'Minority pool wins', + winnerMajority: 'Majority pool wins', + }, + chart: { + scrollHint: 'Drag or scroll to view history', + }, + }, + referralPage: { + title: 'Referral program', + subtitle: "Build your network and earn commissions on your referrals' activity.", + refresh: 'Refresh referral data', + loadError: 'Failed to load referral dashboard.', + programDisabled: + 'The referral program is temporarily disabled. Your network data is still visible below.', + refreshed: 'Referral data refreshed', + stats: { + networkSize: 'Network size', + direct: '{{count}} direct', + totalEarned: 'Total earned', + allStatuses: 'USDT (all statuses)', + paidOut: 'Paid out', + pendingReview: 'Pending / review', + }, + invite: { + title: 'Your invite link', + bonusWithdrawable: 'Bonus withdrawable', + codeNotAvailable: 'Your referral code is not available yet.', + codePrefix: 'Code:', + }, + referrer: { + title: 'Your referrer', + memberSince: 'Member since {{date}}', + noReferrer: 'You joined without a referral code, or your referrer is not linked.', + commissionLevels: 'Commission levels', + levelChip: 'Level {{level}}: {{percent}}%', + depositHint: 'Deposit commissions apply on eligible first deposits. ', + withdrawalHint: + 'Withdrawal commissions apply only on prediction gains withdrawn from the main account (not deposited principal).', + }, + network: { + title: 'Your referral network', + maxDepth: 'Max depth', + showingLevels: 'Showing {{count}} levels', + tableView: 'Table view', + treeView: 'Tree view', + commissionHistory: 'Commission history', + }, + modes: { + both: 'Deposits + withdrawal gains', + deposit: 'First deposits', + withdrawal: 'Withdrawal gains (prediction profits)', + paused: 'Commissions paused', + }, + table: { + empty: 'No referrals in your network yet. Share your invite link to grow your team.', + member: 'Member', + country: 'Country', + level: 'Level', + registered: 'Registered', + directRefs: 'Direct refs', + predictions: 'Predictions', + commissions: 'Commissions', + pending: 'Pending', + total: 'total {{amount}}', + status: { + active: 'Active', + unverified: 'Unverified', + registered: 'Registered', + }, + }, + tree: { + empty: 'Your referral tree is empty. Invite members to see the hierarchy here.', + level: 'Level {{level}}', + direct: '{{count}} direct', + paid: 'Paid: {{amount}} USDT', + pending: 'Pending: {{amount}} USDT', + code: 'Code: {{code}}', + }, + commissions: { + empty: 'No commission events yet.', + member: 'Member', + level: 'Level', + source: 'Source', + status: 'Status', + commission: 'Commission', + date: 'Date', + deposit: 'Deposit', + withdrawal: 'Withdrawal gains', + percentOf: '{{percent}}% of {{amount}}', + }, + }, + faq: { + title: 'Frequently asked questions', + subtitle: 'Find quick answers to the most common questions.', + searchPlaceholder: 'Search for a question…', + allCategories: 'All', + popular: 'Popular questions', + loadError: 'Could not load FAQ. Please try again later.', + noResults: 'No questions match your search.', + helpfulQuestion: 'Was this answer helpful?', + yes: 'Yes ({{count}})', + no: 'No ({{count}})', + thankYou: 'Thanks for your feedback!', + views: '{{count}} view(s)', + publicHeader: { + login: 'Sign in', + register: 'Sign up', + home: 'Home', + }, + }, + support: { + widget: { + ariaLabel: 'Support', + title: 'Prediqo Support', + subtitle: 'Real-time response from our team', + }, + chat: { + greeting: 'Hello! How can we help you?', + typing: 'The team is typing…', + placeholder: 'Type your message…', + today: 'Today', + yesterday: 'Yesterday', + newMessage: 'New message', + file: 'File', + attachment: 'attachment', + }, + }, + admin: { + badge: { + admin: 'Admin', + dynamic: 'Dynamic', + catalog: 'Catalog', + coldHot: 'Cold / Hot', + levelsBonus: 'Levels / Bonus', + sybilReview: 'Sybil / Review / Clawback', + playMoney: 'Play money', + alertsLedger: 'Alerts / Ledger', + staff: 'Staff', + registration: 'Registration', + }, + options: { + title: 'Options', + subtitle: 'Administrative tools and configuration.', + cards: { + users: { + title: 'User Management', + description: 'Search users, open details, and manage account flags safely.', + }, + settings: { + title: 'Settings', + description: 'Configure password policy and access/refresh token expiration without code changes.', + }, + catalog: { + title: 'Games & Ads', + description: 'Publish games and home-page promotions dynamically — no deploy required.', + }, + treasury: { + title: 'Treasury', + description: 'Cold wallet addresses, deposit sweeps, and hot wallet funding from cold storage.', + }, + referral: { + title: 'Referral program', + description: 'Multi-level commissions, bonus pool, eligibility rules, and signup analytics.', + }, + referralFraud: { + title: 'Referral fraud dashboard', + description: 'Review queue, high-risk referrers, monthly caps, and commission clawbacks.', + }, + testWallet: { + title: 'Test wallet', + description: 'Credit amounts, request limits, cooldowns, and grant history for practice play.', + }, + security: { + title: 'Security', + description: 'Integrity checks, security alerts, in-app notifications, and approved ledger credits.', + }, + network: { + title: 'Network & environment', + description: 'Testnet, USDT (TRC20) withdrawal status, and server environment.', + }, + faq: { + title: 'FAQ', + description: 'Manage questions, categories, media, and FAQ statistics.', + }, + support: { + title: 'Support center', + description: 'User and visitor conversations with real-time responses.', + }, + countries: { + title: 'Countries', + description: 'Sync country catalog and block registration by country of residence.', + }, + }, + }, + approvals: { + title: 'Approvals', + subtitle: 'Review and approve sensitive fund operations', + refresh: 'Refresh approvals', + noPermission: 'You do not have permission to approve fund operations.', + approved: 'Request approved and executed.', + rejected: 'Request rejected.', + loadError: 'Failed to load approval queue.', + noPending: 'No pending approvals.', + type: 'Type', + requestedBy: 'Requested by', + created: 'Created', + status: 'Status', + actions: 'Actions', + approve: 'Approve', + reject: 'Reject', + rejectTitle: 'Reject request', + rejectHint: 'Provide a reason for rejection.', + reason: 'Reason', + opTypes: { + 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', + }, + }, + users: { + title: 'Users', + subtitle: 'Advanced user table — filter, sort, select multiple users, and run batch actions.', + refresh: 'Refresh users', + loadError: 'Failed to load users.', + columnsHint: 'Columns → show/hide & export', + download: 'Download', + exportSelected: 'Export ({{count}})', + selected: '{{count}} selected', + exportLimit: 'Export limit: {{count}}', + exportLimitDefault: 'Export limit: 100k (server)', + totalExact: '{{count}} user(s)', + totalEstimate: '~{{count}} user(s) (est.)', + copied: 'Copied to clipboard', + copyFailed: 'Copy failed', + batchFailed: 'Batch operation failed', + emailVerified: 'Email marked as verified', + emailVerifyFailed: 'Failed to verify email', + rolesUpdated: 'Roles updated', + roleUpdateFailed: 'Role update failed', + updateFailed: 'Update failed', + noUsersSelected: 'No users selected', + exportFailed: 'Export failed', + invalidBonusAmount: 'Enter a valid bonus amount', + csvExported: 'CSV exported', + csvExportFailed: 'CSV export failed', + filters: 'Filters', + clear: 'Clear', + filtersActive: 'Filters active: {{count}}', + searchLabel: 'Search by ID, email, or referral code', + searchPlaceholder: 'e.g. user@example.com or REF123', + accountStatus: { + active: 'Active', + disabled: 'Disabled', + suspended: 'Suspended', + fullyActive: 'Account fully active', + }, + statusReasons: { + disabled: 'Account disabled', + locked: 'Account locked', + expired: 'Account expired', + credentialsExpired: 'Credentials expired', + withdrawalsSuspended: 'Withdrawals suspended', + underSurveillance: 'Under surveillance', + }, + ageBuckets: { + under18: 'Under 18', + '18_24': '18–24', + '25_34': '25–34', + '35_44': '35–44', + '45_54': '45–54', + '55_64': '55–64', + '65_plus': '65+', + }, + ageFilter: { + range: 'Age {{min}}–{{max}}', + max: 'Age ≤ {{max}}', + min: 'Age ≥ {{min}}', + }, + filterLabels: { + role: 'Role', + accountStatus: 'Account status', + emailVerified: 'Email verified', + receivedBonus: 'Received bonus', + country: 'Country', + countryPlaceholder: 'All countries — search by name or code…', + inactiveSince: 'Inactive since (days)', + inactivePlaceholder: 'e.g. 30', + minMainBalance: 'Min main balance (USDT)', + maxMainBalance: 'Max main balance (USDT)', + minBonusReceived: 'Min bonus received (USDT)', + maxBonusReceived: 'Max bonus received (USDT)', + minAge: 'Min age (years)', + maxAge: 'Max age (years)', + minAgeHelper: 'Completed years (inclusive)', + maxAgeHelper: 'Use 15 to target users under 16', + minAgePlaceholder: 'e.g. 10', + maxAgePlaceholder: 'e.g. 15 for under 16', + createdFrom: 'Created from', + createdTo: 'Created to', + verified: 'Verified', + notVerified: 'Not verified', + receivedBonusYes: 'Received bonus', + receivedBonusNo: 'No bonus received', + }, + roles: { + user: 'User', + moderator: 'Moderator', + admin: 'Admin', + super_admin: 'Super administrator', + }, + columns: { + id: 'ID', + email: 'Email', + fullName: 'Full name', + status: 'Status', + emailOk: 'Email OK', + role: 'Role', + country: 'Country', + nationality: 'Nationality', + dob: 'DOB', + ageGroup: 'Age group', + referralCode: 'Referral code', + firstDeposit: 'First deposit', + firstDepositTx: 'First deposit tx', + mainUsdt: 'Main USDT', + bonusUsdt: 'Bonus USDT', + bonusReceived: 'Bonus received', + predictions: 'Predictions', + netPnl: 'Net P/L', + totalStake: 'Total stake', + totalPayout: 'Total payout', + created: 'Created', + lastLogin: 'Last login', + lastActivity: 'Last activity', + enabled: 'Enabled', + wdSuspended: 'Wd. suspended', + surveillance: 'Surveillance', + twoFa: '2FA', + nonExpired: 'Non expired', + nonLocked: 'Non locked', + credsValid: 'Creds valid', + copy: 'Copy', + }, + tooltips: { + verifyEmail: 'Click to mark email as verified (admin)', + changeRole: 'Click to change role', + copyUserId: 'Copy user ID', + copyEmail: 'Copy email address', + }, + fields: { + isEnabled: 'Enabled', + withdrawalsSuspended: 'Withdrawals suspended', + underSurveillance: 'Under surveillance', + isAccountNonExpired: 'Account non expired', + isAccountNonLocked: 'Account non locked', + isCredentialsNonExpired: 'Credentials valid', + reactivateWithdrawals: 'Reactivate withdrawals', + }, + mobile: { + mainBonusPredictions: 'Main: {{main}} · Bonus: {{bonus}} · {{count}} predictions', + showFlags: 'Show flags', + hideFlags: 'Hide flags', + }, + batch: { + enable: 'Enable', + disable: 'Disable', + suspend: 'Suspend withdrawals', + reactivate: 'Reactivate', + grantBonus: 'Grant bonus', + exportSelected: 'Export selected', + clearSelection: 'Clear selection', + enableAccounts: 'Enable accounts', + disableAccounts: 'Disable accounts', + suspendAccounts: 'Suspend withdrawals', + reactivateAccounts: 'Reactivate withdrawals', + grantBonusTitle: 'Grant bonus', + applyTo: 'Apply to {{count}} selected user(s)?', + bonusType: 'Bonus (bonus wallet)', + adminAdjustment: 'Admin adjustment (main)', + amountUsdt: 'Amount (USDT)', + reason: 'Reason', + }, + export: { + csvCurrentPage: 'Export CSV (current page)', + xlsxAllFiltered: 'Export XLSX (all filtered)…', + xlsxSelected: 'Export XLSX (selected)', + dialogTitle: 'Export XLSX (server)', + visibleOnly: 'Export visible columns only', + visibleOnlyHint: + 'Use the Columns button in the toolbar to choose which fields appear and export.', + maxRows: 'Max rows', + maxRowsPlaceholder: 'Default 100,000 on server', + matchingUsers: 'Matching users: {{label}}', + inProgress: 'Server export in progress… {{count}} row(s)', + export: 'Export', + }, + roleDialog: { + title: 'Manage user roles', + }, + confirmDialog: { + title: 'Confirm change', + body: 'Set {{field}} to {{value}}?', + true: 'true', + false: 'false', + }, + }, + catalog: { + title: 'Catalog', + subtitle: 'Manage games and dynamic home-page promotions.', + refresh: 'Refresh catalog', + tabs: { games: 'Games', ads: 'Advertisements', candle: 'Candle Predict' }, + addGame: 'Add game', + addAd: 'Add advertisement', + loadingGames: 'Loading games…', + loadingAds: 'Loading advertisements…', + editGame: 'Edit game', + deactivate: 'Deactivate', + noImplementation: 'No implementation', + noWebUi: 'No web UI', + featured: 'Featured', + active: 'Active', + inactive: 'Inactive', + order: 'Order {{order}}', + saveGameFailed: 'Failed to save game', + saveAdFailed: 'Failed to save advertisement', + gameDialog: { edit: 'Edit game', new: 'New game' }, + adDialog: { edit: 'Edit advertisement', new: 'New advertisement' }, + fields: { + slug: 'Slug', + slugRecommended: 'Recommended slug for this implementation: {{slug}}', + useDefaultSlug: 'Use default slug ({{slug}})', + title: 'Title', + description: 'Description', + category: 'Category', + thumbnailUrl: 'Thumbnail URL', + accentColor: 'Accent color', + implementation: 'Implementation', + implementationNone: 'None (catalog only)', + implementationHint: 'Links this catalog entry to a backend game module. Required for playable games.', + implementationNoWeb: + 'This implementation has no web UI module yet. Players on web will see a "not supported" message until you register it in the frontend.', + status: 'Status', + statusActive: 'Active', + statusComingSoon: 'Coming soon', + statusMaintenance: 'Maintenance', + sortOrder: 'Sort order', + featured: 'Featured', + placement: 'Placement', + subtitle: 'Subtitle', + ctaLabel: 'CTA label', + linkUrl: 'Link URL', + imageUrl: 'Image URL', + backgroundGradient: 'Background gradient (CSS)', + placementHomeHero: 'Home hero (carousel)', + placementHomeStrip: 'Home strip', + placementHomeSidebar: 'Home sidebar', + }, + candlePredict: { + config: { + loading: 'Loading game config…', + globalTitle: 'Global settings', + globalIntro: + 'Synthetic candles are generated from player stake pools — no real market data. Interval-specific overrides are managed below; empty fields inherit these defaults.', + stakeAmounts: 'Stake amounts (comma-separated)', + stakeAmountsHint: 'Quick-pick buttons for players — each value must be within min/max below', + minStake: 'Minimum stake (custom input)', + minStakeHint: 'Lowest amount allowed in free-form stake field (e.g. 0.01 for cents)', + maxStake: 'Maximum stake', + predictionWindow: 'Default prediction window (seconds)', + predictionWindowHint: 'Default seconds before each candle close to place predictions', + neutralTitle: 'Neutral round rules', + neutralBehavior: + 'Neutral rounds refund all stakes — no winners and no losers. Use the rules below to declare a round neutral when pools are too balanced or too one-sided.', + minTolerance: 'Min tolerance — close pools (%)', + minToleranceHint: 'Neutral when |Long% − Short%| ≤ this value (e.g. 49/51 at 2%)', + enableMinTolerance: 'Enable min tolerance rule', + maxTolerance: 'Max tolerance — extreme imbalance (%)', + maxToleranceHint: 'Neutral when largest pool ≥ this value (e.g. 95/5 at 95%)', + enableMaxTolerance: 'Enable max tolerance rule', + poolWinnerRule: 'Pool winner rule', + poolWinnerMinority: 'Minority pool wins (smaller total stake)', + poolWinnerMajority: 'Majority pool wins (larger total stake)', + poolWinnerMinorityDesc: 'The minority stake pool wins when pools differ enough.', + poolWinnerMajorityDesc: 'The majority stake pool wins when pools differ enough.', + poolWinnerApplied: 'Applied immediately to new settlements.', + basePrice: 'Default base chart price', + poolMultiplier: 'Default pool multiplier', + poolMultiplierHint: 'Stake weight in Long/Short pools (single, auto, multi final candle)', + payoutMultiplier: 'Default payout multiplier', + payoutMultiplierHint: 'Win payout for correct predictions — independent from pool weight', + walletTypeCode: 'Wallet type code', + gameActive: 'Game active', + modesTitle: 'Prediction modes', + modesIntro: 'Enable or disable each prediction type independently. Disabled modes are hidden from players.', + singleEnabled: 'Single-candle predictions', + autoEnabled: 'Auto predictions', + multiEnabled: 'Multi-candle predictions', + saveGlobal: 'Save global config', + intervalsTitle: 'Prediction intervals', + configSaved: 'Configuration saved', + saveFailed: 'Save failed', + }, + intervals: { + loading: 'Loading intervals…', + intro: + '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.', + addInterval: 'Add interval', + columns: { + order: 'Order', + label: 'Label', + minutes: 'Minutes', + window: 'Window (s)', + minTie: 'Min tie %', + maxTie: 'Max tie %', + pool: 'Pool', + payout: 'Payout', + initialBatch: 'Initial batch', + status: 'Status', + actions: 'Actions', + }, + default: 'Default', + active: 'Active', + disabled: 'Disabled', + noIntervals: 'No intervals configured', + editTitle: 'Edit interval', + newTitle: 'New interval', + intervalMinutes: 'Interval (minutes)', + displayLabel: 'Display label', + sortOrder: 'Sort order', + windowOverride: 'Prediction window override (seconds, optional)', + windowOverrideHint: 'Max {{max}} for {{minutes}} min — leave empty for global default', + minTieOverride: 'Min tie tolerance override (%)', + minTieOverrideHint: 'Leave empty to inherit global default', + maxTieOverride: 'Max tie tolerance override (%)', + maxTieOverrideHint: 'Neutral when largest pool ≥ this % — empty inherits global', + minToleranceRule: 'Min tolerance rule', + maxToleranceRule: 'Max tolerance rule', + inheritGlobal: 'Inherit global', + enabled: 'Enabled', + poolMultiplierOverride: 'Pool multiplier override', + poolMultiplierOverrideHint: 'Weight in Long/Short pools — leave empty to inherit global default', + payoutMultiplierOverride: 'Payout multiplier override', + payoutMultiplierOverrideHint: 'Win payout for correct predictions — leave empty to inherit global default', + basePriceOverride: 'Base price override', + chartBatchSize: 'Initial chart batch size', + chartBatchSizeHint: + 'Candles loaded on open (20–200). Scroll left on the chart to load older history in batches.', + defaultForNewPlayers: 'Default interval for new players', + intervalUpdated: 'Interval updated', + intervalCreated: 'Interval created', + intervalDeleted: 'Interval deleted', + windowMinError: 'Prediction window must be at least 5 seconds', + windowMaxError: + 'Prediction window cannot exceed {{max}} for a {{minutes}}-minute interval', + deleteFailed: 'Delete failed', + }, + multiLevels: { + title: 'Multi-candle levels', + intro: + '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.', + columns: { + level: 'Level', + candles: 'Candles', + enabled: 'Enabled', + poolMultiplier: 'Pool multiplier', + payoutMultiplier: 'Payout multiplier', + sort: 'Sort', + }, + saved: 'Multi-candle levels saved.', + saveFailed: 'Save failed', + saveLevels: 'Save levels', + }, + }, + }, + treasury: { + title: 'Treasury', + refresh: 'Refresh treasury', + loadError: 'Failed to load treasury overview.', + sweepsEnabled: 'Sweeps enabled', + sweepsDisabled: 'Sweeps disabled', + withdrawalsOn: 'Withdrawals on', + withdrawalsOff: 'Withdrawals off', + pendingSweeps: '{{count}} pending sweeps', + failedSweeps: '{{count}} failed sweeps', + sweepDisabledHint: + 'Set SWEEP_ENABLED=true in backend .env to auto-move deposits to cold storage.', + coldOnChain: 'Cold: {{address}} · on-chain {{balance}}', + hotOnChain: 'Hot: {{address}} · on-chain {{balance}}', + coldAddress: 'Cold wallet address', + label: 'Label', + saveCold: 'Save cold', + fundingTitle: 'Cold → Hot funding', + fundingSubtitle: + 'Create a request, transfer manually from cold wallet, then confirm with the blockchain transaction ID.', + walletTypeId: 'Wallet type ID (USDT_TRC20)', + amountRaw: 'Amount (raw units)', + notes: 'Notes', + requestFunding: 'Request funding for approval', + amount: 'Amount', + fromTo: 'From → To', + confirmTx: 'Confirm tx', + noPendingFunding: 'No pending funding requests.', + sweepsTitle: 'Deposit sweeps', + submitSweeps: 'Submit sweeps for approval', + status: 'Status', + toCold: 'To cold', + tx: 'Tx', + confirmDialogTitle: 'Confirm cold → hot transfer', + blockchainTxId: 'Blockchain transaction ID', + sweepPending: 'Sweep request submitted — pending super-admin approval', + fundingPending: 'Funding request submitted — pending super-admin approval', + }, + security: { + title: 'Security', + refresh: 'Refresh security data', + actions: { + runIntegrity: 'Run integrity check', + processTamper: 'Process DB tamper events', + dismissFalse: 'Dismiss false alerts', + }, + integrity: { + passed: 'Integrity check passed — no issues found.', + issuesFound: + 'Found {{count}} issue(s). Affected users were placed under security hold.', + tamperNone: 'DB tamper check — no pending unauthorized changes.', + tamperProcessed: + 'Processed {{count}} unauthorized DB change(s) and raised alerts.', + }, + tabs: { + alerts: 'Alerts ({{count}})', + notifications: 'Notifications', + ledgerCredits: 'Ledger credits', + dbAudit: 'DB audit ({{count}})', + alertEmails: 'Alert emails', + }, + alerts: { + open: 'Open', + all: 'All', + loadError: 'Failed to load alerts.', + severity: 'Severity', + title: 'Title', + type: 'Type', + user: 'User', + status: 'Status', + created: 'Created', + resolve: 'Resolve', + empty: 'No alerts', + }, + notifications: { + title: 'In-app notifications', + markAllRead: 'Mark all read', + markRead: 'Mark read', + empty: 'No notifications', + }, + credits: { + title: 'Approved ledger credits', + grant: 'Grant credit', + user: 'User', + amount: 'Amount', + approvedBy: 'Approved by', + date: 'Date', + empty: 'No credits yet', + bonusWallet: 'Bonus (bonus wallet)', + mainWallet: 'Admin adjustment (main wallet)', + bonusHint: 'Credits the user bonus wallet (account_kind = bonus).', + mainHint: + 'Credits the user main wallet (account_kind = main) — used for gameplay and withdrawals.', + dialogTitle: 'Grant ledger credit', + userId: 'User ID (UUID)', + wallet: 'Wallet', + amountDisplay: 'Amount (display units)', + reason: 'Reason (required, audited)', + invalidAmount: 'Enter a valid amount greater than zero', + failed: 'Credit failed', + pendingApproval: 'Credit request submitted — pending super-admin approval.', + approve: 'Approve credit', + successDefault: 'Credit granted.', + }, + dbAudit: { + title: 'Direct database changes (audit trail)', + subtitle: + 'Modifications detected outside the application layer (psql, pgAdmin, scripts, etc.).', + exportCsv: 'Export CSV', + loadError: 'Failed to load DB audit events.', + severity: 'Severity', + table: 'Table', + op: 'Op', + columns: 'Columns', + source: 'Source', + processed: 'Processed', + when: 'When', + processedYes: 'Yes', + processedPending: 'Pending', + empty: 'No direct DB changes recorded', + }, + alertEmails: { + title: 'Security alert emails', + subtitle: 'One email per line. Encrypted at rest in the database.', + placeholder: 'admin@example.com', + save: 'Save emails', + saved: 'Settings saved', + }, + resolve: { + title: 'Resolve alert', + note: 'Resolution note', + reactivate: 'Reactivate withdrawals and clear security hold for user', + resolving: 'Resolving…', + resolve: 'Resolve', + failed: 'Failed to resolve alert', + success: 'Alert resolved.', + successReactivate: 'Alert resolved and user security hold cleared.', + }, + }, + settings: { + title: 'Settings', + subtitle: + 'Password policy, security, rate limits, withdrawals, and Candle Predict engine tuning.', + loading: 'Loading settings…', + loadError: 'Failed to load settings.', + noSettings: 'No settings loaded.', + saveFailed: 'Failed to save settings', + retry: 'Retry', + save: 'Save settings', + saving: 'Saving…', + saved: 'Settings saved', + reset: 'Reset to server values', + sections: { + passwordPolicy: { + title: 'Password policy', + subtitle: 'Enforce complexity rules for all new passwords.', + minLength: 'Minimum length', + uppercase: 'Uppercase', + lowercase: 'Lowercase', + number: 'Number', + special: 'Special', + }, + emailVerification: { + title: 'Email verification', + subtitle: 'Require confirmed email before users can sign in.', + blockLogin: 'Block login until email is verified', + }, + tokenExpiration: { + title: 'Token expiration', + subtitle: 'Change expiry without redeploying the backend.', + accessToken: 'Access token expiry', + refreshToken: 'Refresh token expiry', + examplesShort: 'Examples: 15m, 1h', + examplesLong: 'Examples: 7d, 30d', + }, + withdrawals: { + title: 'Withdrawals & safety', + subtitle: 'Kill-switch and withdrawal limits (applied immediately after save).', + allowOnChain: 'Allow on-chain withdrawals', + dailyLimit: 'Daily withdrawal limit (USD)', + largeThreshold: 'Large withdrawal threshold (USD)', + networkFee: 'Withdrawal network fee (USDT)', + networkFeeHelper: + "Deducted from the user's USDT balance per withdrawal (covers on-chain TRON gas).", + }, + rateLimiting: { + title: 'Rate limiting', + subtitle: + 'API and login throttling. Max limits apply within seconds; window size needs a restart.', + apiWindow: 'API window (ms)', + restartHint: 'Restart server to apply', + apiMax: 'API max requests / window', + loginMax: 'Login max attempts / 15 min', + }, + candlePredict: { + title: 'Candle Predict engine', + subtitle: 'Tick interval and backfill pacing (lower backfill = less DB load at scale).', + engineTick: 'Engine tick (ms)', + engineTickHelper: 'How often rounds are settled', + backfillInterval: 'Backfill interval (ms)', + backfillIntervalHelper: 'Min delay between backfill runs', + backfillMax: 'Backfill max per tick', + backfillMaxHelper: 'Candles filled per interval per run', + backfillSeed: 'Backfill seed max', + backfillSeedHelper: 'Historical candles on first run', + }, + }, + }, + reports: { + title: 'Reports', + subtitle: + 'Detailed data, paginated tables, advanced filters and exports. The dashboard shows summaries only.', + searchPlaceholder: 'Search for a report (title, description, category…)', + loading: 'Loading catalog…', + noResults: 'No report matches « {{query}} ».', + detail: { + back: 'Back', + filters: 'Filters', + search: 'Search', + from: 'From', + to: 'To', + apply: 'Apply', + favoriteNamePlaceholder: 'Favorite filter name', + saveFilter: 'Save filter', + exportExcelFilters: 'Excel (filters)', + exportCsvFilters: 'CSV (filters)', + exportPdfServer: 'PDF (server)', + bulkActionsTitle: 'Bulk actions', + exportSelectionExcel: 'Export selection (Excel)', + csv: 'CSV', + pdf: 'PDF', + deselectAll: 'Deselect all', + selected: '{{count}} selected', + selectedRows: '{{count}} row(s)', + loadError: 'Could not load this report.', + timeoutError: + 'Request timed out (high data volume). Narrow the period or refine filters.', + bulkFailed: 'Bulk action failed.', + actionFailed: 'Action failed.', + exportFailed: 'Export failed.', + exportDone: 'Export complete ({{count}} rows)', + exportInProgress: 'Server export in progress… {{count}} row(s) processed', + summaryTotal: 'Total amount: {{amount}} USDT', + summaryCount: 'Operation count: {{count}}', + summaryUsers: 'Unique users: {{count}}', + reasonOptional: 'Reason (optional)', + confirm: 'Confirm', + bulkResult: '{{succeeded}} succeeded{{suffix}}', + bulkFailedSuffix: ' · {{failed}} failed', + bulkActions: { + 'export-selection': 'Export selection', + suspend: 'Suspend', + reactivate: 'Reactivate', + enable: 'Enable', + disable: 'Disable', + 'surveillance-on': 'Place under investigation', + 'surveillance-off': 'Remove from investigation', + 'suspend-users': 'Suspend users', + }, + bulkConfirm: { + suspend: 'Suspend selected accounts (withdrawals blocked + under investigation)?', + reactivate: 'Reactivate selected accounts?', + enable: 'Enable selected accounts?', + disable: 'Disable selected accounts?', + 'surveillance-on': 'Place selected accounts under investigation?', + 'surveillance-off': 'Remove selected accounts from investigation?', + 'suspend-users': 'Suspend users linked to selected rows?', + }, + }, + }, + countries: { + title: 'Countries', + sync: 'Sync from API', + description: + 'Catalog synced from ISO 3166 by default, or from REST Countries v5 when REST_COUNTRIES_API_KEY is configured on the backend. Disable registration for specific countries of residence.', + descriptionBeforeLink: + 'Catalog synced from ISO 3166 by default, or from', + descriptionAfterLink: + 'when REST_COUNTRIES_API_KEY is configured on the backend. Disable registration for specific countries of residence.', + syncSuccess: + 'Synced {{synced}} countries{{source}}. Total in database: {{total}}.', + syncSourceRest: ' from REST Countries', + syncSourceIso: ' from ISO 3166', + syncFailed: 'Country sync failed', + loadError: 'Failed to load countries from the server.', + emptyDb: 'No countries in database. Click "Sync from API" to load the catalog.', + search: 'Search country', + blockedCount: '{{count}} blocked', + blockedOnly: 'Blocked only', + code: 'Code', + name: 'Name', + registration: 'Registration', + noMatch: 'No countries match your filters', + }, + testWallet: { + title: 'Test wallet', + enabled: 'Enabled', + disabled: 'Disabled', + subtitle: + 'Configure play-money credits so new users can practice predictions before using real funds.', + loading: 'Loading test wallet settings…', + allowRequests: 'Allow users to request test credits', + creditAmount: 'Credit amount per request (USDT)', + creditHelper: 'Amount credited automatically when a user requests test funds', + maxRequests: 'Max requests per user', + maxRequestsHelper: '0 = unlimited', + cooldown: 'Cooldown between requests (hours)', + cooldownHelper: '0 = no waiting period', + saveFailed: 'Save failed', + saved: 'Settings saved.', + save: 'Save settings', + saving: 'Saving…', + history: 'Credit history', + date: 'Date', + user: 'User', + amount: 'Amount', + noHistory: 'No test credits granted yet.', + }, + network: { + title: 'Network & environment', + subtitle: + 'Admin-only server configuration: blockchain network, withdrawals and runtime environment.', + }, + referralAdmin: { + title: 'Referral program', + fraudDashboard: 'Fraud dashboard', + loadError: 'Failed to load referral configuration.', + fundPending: 'Bonus pool funding submitted — pending super-admin approval', + programSettings: 'Program settings', + programEnabled: 'Program enabled', + bonusWithdrawable: 'Bonus withdrawable (transfer bonus → main)', + referrerVerified: 'Referrer must have verified email', + referrerDeposited: 'Referrer must have deposited', + referredVerified: 'Referred user must have verified email (before payout)', + commissionHold: 'Commission hold (days)', + commissionHoldHelper: 'Delay after first deposit before commission can be paid', + minPredictions: 'Min real-money predictions (referred user)', + maxPendingDays: 'Max pending days', + maxPendingHelper: 'Expire unpaid commissions if eligibility is still not met', + commissionModes: 'Commission modes', + depositCommissions: 'Deposit commissions (first deposit of referred users)', + withdrawalCommissions: 'Withdrawal commissions (prediction gains from main account only)', + slackAlerts: 'Slack alerts', + slackEnabled: 'Slack alerts enabled (referral channel: cap blocks, clawbacks, Sybil review)', + slackHint: + 'Configure SLACK_REFERRAL_WEBHOOK_URL for #referral-fraud and SLACK_SECURITY_WEBHOOK_URL for #security. SLACK_WEBHOOK_URL is used as fallback for both.', + sybilSection: 'Sybil anti-fraud (P2)', + sybilEnabled: 'Sybil detection enabled', + sybilReview: 'Sybil review threshold (score)', + sybilReviewHelper: 'Score ≥ this → manual review queue', + sybilBlock: 'Sybil block threshold (score)', + sybilBlockHelper: 'Score ≥ this → auto-block (no commission)', + maxAmountMonth: 'Max commission amount / referrer / month (raw)', + maxAmountHelper: '500000000 = 500 USDT (6 decimals). 0 = unlimited.', + maxCountMonth: 'Max commissions / referrer / month (count)', + unlimitedHelper: '0 = unlimited', + maxReferralsDay: 'Max referrals per referrer / 24h', + defaultReferrer: 'Default referrer user ID (admin UUID)', + defaultReferrerHelper: 'Used when no referral code is provided at signup', + minFirstDeposit: 'Min first deposit (raw units)', + commissionWalletType: 'Commission wallet type ID', + commissionWalletHelper: '2 = USDT_TRC20 by default', + saveSettings: 'Save settings', + levelsTitle: 'Commission levels', + level: 'Level', + percentDeposit: '% of first deposit', + maxAmountMonthCol: 'Max amount / month (raw)', + maxCountMonthCol: 'Max count / month', + active: 'Active', + global: 'Global', + edit: 'Edit', + delete: 'Delete', + levelNumber: 'Level #', + commissionPercent: 'Commission %', + maxAmountField: 'Max amount / month (raw, 0=global)', + maxCountField: 'Max count / month (0=global)', + addUpdateLevel: 'Add / update level', + bonusPoolTitle: 'Bonus pool (treasury for referral payouts)', + walletTypeBalance: 'Wallet type {{id}}: {{balance}} raw units', + walletTypeId: 'Wallet type ID', + amountDisplay: 'Amount (display)', + fundPool: 'Fund pool', + reviewTitle: 'Manual review queue', + reviewLoadError: 'Failed to load review queue.', + noReview: 'No commissions awaiting review.', + score: 'Score', + signals: 'Signals', + beneficiary: 'Beneficiary', + referred: 'Referred', + approve: 'Approve', + reject: 'Reject', + rejectReason: 'Rejection reason', + statsTitle: 'Statistics', + referredUsers: 'Referred users: {{count}}', + commissionsPaid: 'Commissions paid: {{raw}} raw', + payoutEvents: 'Payout events: {{count}}', + pending: 'Pending: {{count}} ({{raw}} raw)', + review: 'Review: {{count}} ({{raw}} raw)', + byCountry: 'Signups by country of residence', + byNationality: 'Signups by nationality', + topReferrers: 'Top referrers', + directReferrals: 'Direct referrals', + totalEarned: 'Total earned', + code: 'Code', + commission: 'Commission', + }, + referralFraud: { + title: 'Referral fraud dashboard', + programSettings: 'Program settings', + loadError: 'Failed to load fraud dashboard.', + rawAmount: '{{amount}} raw', + stats: { + reviewQueue: 'Review queue', + pending: 'Pending', + paidThisMonth: 'Paid this month', + clawedBackMonth: 'Clawed back (month)', + sybilBlockedMonth: 'Sybil blocked (month)', + capBlockedMonth: 'Cap blocked (month)', + monthlyCaps: 'Monthly caps (per referrer)', + commissionsCount: '{{count}} commissions', + maxRawMonth: 'max {{amount}} raw / month', + }, + reviewQueue: { + title: 'Review queue', + empty: 'No commissions awaiting review.', + amount: 'Amount', + rejectReason: 'Rejected from fraud dashboard', + }, + highRisk: { + title: 'High-risk referrers', + avgSybil: 'Avg Sybil', + review: 'Review', + inactive: 'Inactive', + monthRaw: 'Month raw', + }, + sybilSignals: { + title: 'Sybil signals (this month)', + empty: 'No signals recorded this month.', + }, + clawback: { + title: 'Clawback (paid commissions)', + reasonAction: 'Reason + action', + reasonPlaceholder: 'Clawback reason', + action: 'Clawback', + }, + recentClawbacks: { + title: 'Recent clawbacks', + from: 'From', + to: 'To', + exportCsv: 'Export CSV', + exportFailed: 'Export failed', + empty: 'None yet.', + line: '{{amount}} raw — {{reason}}', + }, + recentBlocks: { + title: 'Recent blocks (Sybil / cap)', + empty: 'None recorded.', + }, + }, + faqAdmin: { + title: 'FAQ management', + subtitle: 'Create and organize frequently asked questions shown to users.', + refresh: 'Refresh', + tabEntries: 'Questions', + tabCategories: 'Categories', + searchPlaceholder: 'Search…', + category: 'Category', + allCategories: 'All', + status: 'Status', + allStatuses: 'All', + activeEntries: 'Active', + inactiveEntries: 'Inactive', + newEntry: 'New FAQ', + newCategory: 'New category', + loadError: 'Failed to load', + noEntries: 'No FAQ entries found.', + deleteEntryConfirm: 'Delete this FAQ entry?', + deleteCategoryConfirm: 'Delete this category? Associated entries must be moved first.', + entryActive: 'Active', + entryInactive: 'Inactive', + order: 'Order: {{order}}', + views: 'Views: {{views}} · Helpful: {{yes}} / {{no}}', + updatedBy: ' · Updated by {{name}}', + slug: 'Slug: {{slug}} · Order: {{order}}', + categoryInactive: ' · Inactive', + entryDialogEdit: 'Edit FAQ entry', + entryDialogNew: 'New FAQ entry', + question: 'Question', + answer: 'Answer', + sortOrder: 'Display order', + categoryDialogEdit: 'Edit category', + categoryDialogNew: 'New category', + name: 'Name', + slugOptional: 'Slug (optional)', + slugAuto: 'Auto-generated if empty', + orderField: 'Order', + categoryRequired: 'Category and question are required', + nameRequired: 'Name is required', + }, + supportAdmin: { + title: 'Support center', + read: ' · Read', + visitorTyping: 'Visitor is typing…', + newMessageTitle: 'New support message', + newMessageBody: 'Message received', + searchPlaceholder: 'Search…', + status: 'Status', + allStatuses: 'All', + anonymousVisitor: 'Anonymous visitor', + userPrefix: 'User {{id}}…', + noConversations: 'No conversations', + selectConversation: 'Select a conversation', + assignSelf: 'Assign to me', + markResolved: 'Resolved', + replyPlaceholder: 'Reply…', + contextTitle: 'Context', + anonymousAlert: 'Anonymous conversation — no linked account.', + name: 'Name:', + id: 'ID:', + email: 'Email:', + role: 'Role:', + accountStatus: 'Status:', + accountActive: 'Active', + accountDisabled: 'Disabled', + emailVerified: 'Email verified:', + registeredOn: 'Registered on {{date}}', + conversationCreated: 'Conversation created on {{date}}', + statuses: { + open: 'Open', + pending: 'Pending', + resolved: 'Resolved', + closed: 'Closed', + }, + visitor: 'Visitor', + user: 'User', + }, + dashboard: { + title: 'Admin Dashboard', + subtitle: 'Platform analytics — {{period}}', + selectedPeriod: 'selected period', + refresh: 'Refresh dashboard', + exportAction: 'Export', + period: 'Period', + from: 'From', + to: 'To', + game: 'Game', + presets: { + today: 'Today', + yesterday: 'Yesterday', + this_week: 'This week', + this_month: 'Current month', + last_30_days: 'Last 30 days', + last_90_days: 'Last 90 days', + this_year: 'This year', + custom: 'Custom range', + }, + games: { + all: 'All games', + candlePredict: 'Candle Predict', + }, + reportDetail: 'View detailed report', + allReports: 'All reports', + securityCenter: 'Security center', + enabled: 'ENABLED', + disabled: 'DISABLED', + unusual: 'Unusual', + normal: 'Normal', + noRecentAlerts: 'No recent alerts for the period.', + recentAlertsMax: 'Recent alerts (max {{count}})', + updating: 'Updating data…', + customRangePending: 'Select the From and To dates to load analytics for the custom range.', + customRangeInvalid: 'The From date must be on or before the To date.', + loadError: 'Could not load analytics. Check that the backend is running and you are an administrator.', + materializedViews: + 'KPIs, financial charts, bets, geography and demographics are fed by PostgreSQL materialized views (refreshed periodically, no external service).', + cached: 'Data served from cache ({{time}}). Use Refresh to force a full recalculation.', + cachedRecent: 'recent', + degraded: + 'Some sections could not be computed in time (high data volume). Displayed indicators may be partial.', + usersCount: '{{count}} users', + played: 'Played: {{amount}} USDT', + minSuffix: '{{n}} min', + hourSuffix: '{{h}}h', + sectionLabels: { + kpis: 'Key indicators', + financial: 'Financial analysis', + games: 'Game analysis', + users: 'User analysis', + geography: 'Geographic analysis', + demographics: 'Demographics', + charts: 'Advanced charts', + alerts: 'Alerts & monitoring', + }, + personalize: { + button: 'Customize', + hint: 'Hide/show sections · saved views (local)', + dialogTitle: 'Dashboard customization', + visibleSections: 'Visible sections', + saveCurrentView: 'Save current view', + viewNamePlaceholder: 'View name', + save: 'Save', + savedViews: 'Saved views', + emailReportsSoon: 'Email reports (coming soon)', + emailHelper: 'Automatic report scheduling will be available in a future version.', + emailPlaceholder: 'admin@example.com', + close: 'Close', + }, + export: { + sheetName: 'Dashboard', + categories: { + users: 'Users', + deposits: 'Deposits', + withdrawals: 'Withdrawals', + games: 'Games', + financial: 'Financial', + alerts: 'Alerts', + }, + indicators: { + totalUsers: 'Total registered', + newUsers: 'New users', + depositTotalRaw: 'Total amount (raw)', + depositTotalUsdt: 'Total amount USDT', + withdrawalTotalRaw: 'Total amount (raw)', + predictions: 'Predictions', + platformNetPnl: 'Platform net P/L (real)', + testNetPnl: 'Test net P/L', + openAlerts: 'Open', + }, + }, + tables: { + segment: 'Segment', + users: 'Users', + predictions: 'Predictions', + stake: 'Staked', + netPnl: 'Net P/L', + winRate: 'Win rate', + direction: 'Direction', + interval: 'Interval', + participants: 'Participants', + housePnl: 'House P/L', + user: 'User', + date: 'Date', + country: 'Country', + deposits: 'Deposits', + withdrawals: 'Withdrawals', + active: 'Active', + type: 'Type', + severity: 'Severity', + status: 'Status', + gender: 'Gender', + ageBucket: 'Age range', + }, + walletKind: { + main: 'Main', + bonus: 'Bonus', + test: 'Test', + }, + gender: { + male: 'Male', + female: 'Female', + other: 'Other', + unknown: 'Not specified', + }, + ageBucket: { + 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+', + }, + treasury: { + loadError: 'Could not load on-chain treasury (hot/cold). See the Treasury page for details.', + hotWallet: 'Hot wallet (on-chain)', + coldWallet: 'Cold wallet (on-chain)', + sweepsInProgress: 'Deposit sweeps in progress', + operations_one: '{{count}} operation · pending / gas / broadcast', + operations_other: '{{count}} operations · pending / gas / broadcast', + noActiveSweep: 'No active sweep', + }, + charts: { + financialFlow: 'Financial flow — deposits vs withdrawals', + deposits: 'Deposits', + withdrawals: 'Withdrawals', + }, + sections: { + kpi: { + title: 'Key indicators', + subtitle: 'Summary view — click a card for the detailed report', + groups: { + users: 'Users', + deposits: 'Deposits', + withdrawalsBonus: 'Withdrawals & bonuses', + }, + cards: { + totalUsers: 'Total registered', + totalUsersSub: 'All accounts', + newUsers: 'New (period)', + newUsersSub: 'Signups in period', + activeUsers: 'Active (period)', + inactiveUsers: 'Inactive', + signupGrowth: 'Signup growth', + onlineGame: 'In game', + onlineGameSub: 'WebSocket Candle Predict', + onlineApp: 'Connected (app)', + onlineAppSub: 'Active session, no prediction required', + admins: 'Administrators', + depositTotal: 'Total amount', + depositCount: 'Deposit count', + depositUsers: 'Depositing users', + depositAvg: 'Average deposit', + withdrawalTotal: 'Withdrawals (total)', + withdrawalCount: 'Withdrawals (count)', + bonusesGranted: 'Bonuses granted', + adminAdjustments: 'Admin adjustments', + platformWithdrawals: 'Platform withdrawals', + }, + }, + financial: { + title: 'Financial analysis', + subtitle: 'Current balances and trends over the period', + onChainTreasury: 'On-chain treasury', + balanceDistribution: 'Balance distribution', + netPnlTrend: 'Net P/L trend (real)', + bonusTrend: 'Bonus trend', + cards: { + mainWallets: 'Main wallets', + bonusWallets: 'Bonus wallets', + testWallets: 'Test wallets', + cumulativeBalance: 'Cumulative balance', + platformNetPnl: 'Platform net P/L', + platformNetPnlSub: 'Real wallets (excl. test)', + testNetPnl: 'Test net P/L', + testNetPnlSub: 'Test wallet only', + depositWithdrawalRatio: 'Deposits / Withdrawals ratio', + bonusCost: 'Bonus cost', + adjustmentCost: 'Adjustment cost', + }, + }, + game: { + title: 'Game analysis', + subtitle: 'Summary by segment (fixed view)', + distributionsFixed: 'Distributions (fixed size)', + cards: { + participants: 'Participants', + predictions: 'Predictions', + avgPerPlayer: 'Avg. / player', + totalStaked: 'Total staked', + testWalletUsers: 'Test wallet — users', + testPnl: 'Test P/L', + }, + segments: { + manual: 'Normal predictions', + auto: 'Auto Prediction', + multiCandle: 'Multi-candle', + realManual: 'Real + manual', + realAuto: 'Real + auto', + realMulti: 'Real + multi-candle', + testManual: 'Test + manual', + testAuto: 'Test + auto', + testMulti: 'Test + multi-candle', + }, + shortVsLong: 'Short vs Long', + byInterval: 'By game interval', + long: 'Long', + short: 'Short', + }, + users: { + title: 'Users & security', + subtitle: 'Counters and recent activity', + securityCompliance: 'Security & compliance', + activity: 'Activity', + recentLogins: 'Recent logins (top 5)', + security: { + emailVerified: 'Verified emails', + emailUnverified: 'Unverified emails', + totpEnabled: '2FA enabled', + totpDisabled: 'Without 2FA', + suspended: 'Suspended', + disabled: 'Disabled', + expired: 'Expired accounts', + credentialsExpired: 'Expired credentials', + underSurveillance: 'Under investigation', + withdrawalsBlocked: 'Withdrawals blocked', + }, + activityLabels: { + activeToday: 'Active today', + activeThisWeek: 'Active this week', + activeThisMonth: 'Active this month', + inactivePeriod: 'Inactive (period)', + }, + }, + geography: { + title: 'Geography', + subtitle: 'Top 8 countries — fixed view', + usersTop8: 'Users (top 8)', + depositsTop8: 'Deposits (top 8)', + summaryTop8: 'Top 8 countries summary', + }, + demographics: { + title: 'Demographics', + subtitle: 'Fixed-size distributions', + byGender: 'By gender', + byAge: 'By age range', + genderDetail: 'Detail by gender', + ageDetail: 'Detail by age range', + }, + charts: { + title: 'Trends & distributions', + subtitle: 'Charts for the period (fixed-size views)', + signups: 'Signups', + logins: 'Logins', + verifiedEmails: 'Verified emails', + totpEnabled: '2FA enabled', + manualAutoMulti: 'Manual vs Auto vs Multi-candle', + manual: 'Manual', + auto: 'Auto', + multiCandle: 'Multi-candle', + shortVsLong: 'Short vs Long', + stakeByInterval: 'Stakes by interval', + loginHours: 'Login hours (24h)', + betHours: 'Betting hours (24h)', + newVsReturning: 'New vs returning', + newUsers: 'New', + returningUsers: 'Returning', + }, + alerts: { + title: 'Alerts', + subtitle: 'Real-time monitoring', + openAlerts: 'Open alerts', + loginAlerts: 'Login alerts', + depositSpike: 'Deposit spike', + withdrawalSpike: 'Withdrawal spike', + }, + }, + }, + }, + network: { + loading: 'Loading network configuration…', + loadFailed: 'Could not load `/health`.', + titleOk: 'Network status OK (testnet)', + titleCheck: 'Check network configuration', + withdrawalsOn: 'Withdrawals: ENABLED', + withdrawalsOff: 'Withdrawals: DISABLED', + tronNetwork: 'TRON: {{network}}', + envLabel: 'env: {{env}}', + }, +} ; + +export type TranslationDict = typeof en; diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts new file mode 100644 index 00000000..f4f94df7 --- /dev/null +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -0,0 +1,2059 @@ +export const fr = { + common: { + loading: 'Chargement…', + refresh: 'Actualiser', + role: 'Rôle', + user: 'Utilisateur', + logout: 'Déconnexion', + yes: 'Oui', + no: 'Non', + openNav: 'Ouvrir la navigation', + language: 'Langue', + english: 'Anglais', + french: 'Français', + retry: 'Réessayer', + back: 'Retour', + edit: 'Modifier', + email: 'E-mail', + password: 'Mot de passe', + sending: 'Envoi…', + save: 'Enregistrer', + cancel: 'Annuler', + all: 'Tous', + on: 'Activé', + off: 'Désactivé', + exporting: 'Export…', + saving: 'Enregistrement…', + close: 'Fermer', + copyAddress: 'Copier l’adresse', + copyFailed: 'Échec de la copie', + addressCopied: 'Adresse copiée dans le presse-papiers', + asset: 'Actif', + confirm: 'Confirmer', + countryLoading: 'Chargement des pays…', + noCountryFound: 'Aucun pays trouvé', + countrySearchPlaceholder: 'Rechercher par nom ou code pays…', + review: 'Vérifier', + nothingToCopy: 'Rien à copier', + copied: '{{label}} copié', + transferFailed: 'Échec du transfert', + withdrawalFailed: 'Échec du retrait', + fundsAvailable: 'Fonds disponibles', + empty: 'Vide', + date: 'Date', + type: 'Type', + amount: 'Montant', + status: 'Statut', + noResults: 'Aucun résultat', + pagination: '{{from}}–{{to}} sur {{total}}', + catalogRefreshed: 'Catalogue actualisé', + walletRefreshed: 'Portefeuille actualisé', + profileRefreshed: 'Profil actualisé', + gameRefreshed: 'Jeu actualisé', + }, + nav: { + home: 'Accueil', + wallet: 'Portefeuille', + referrals: 'Parrainage', + profile: 'Profil', + faq: 'FAQ', + support: 'Assistance', + approvals: 'Approbations', + overview: 'Vue d’ensemble', + reports: 'Rapports', + options: 'Options', + users: 'Utilisateurs', + security: 'Sécurité', + settings: 'Paramètres', + }, + auth: { + brandSubtitle: + 'Plateforme de jeux de prédiction — connectez-vous pour gérer ou jouer.', + signIn: 'Connexion', + signingIn: 'Connexion…', + signUp: 'Inscription', + createAccount: 'Créer un compte', + forgotPassword: 'Mot de passe oublié ?', + noAccount: 'Pas encore de compte ?', + createOne: 'Créer un compte', + alreadyHaveAccount: 'Vous avez déjà un compte ?', + backToSignIn: 'Retour à la connexion', + totpOptional: 'Code 2FA (optionnel)', + verifyEmailHint: + 'Nous avons envoyé un lien de confirmation à votre e-mail. Vérifiez votre adresse avant de vous connecter.', + noAdminConfigured: 'Aucun administrateur n’est configuré.', + initializePlatform: 'Initialiser la plateforme', + emailNotVerified: + 'Votre compte existe mais l’e-mail n’est pas encore vérifié. Demandez un nouveau lien de confirmation ci-dessous (vérifiez les spams si rien n’arrive).', + resendVerification: 'Renvoyer l’e-mail de vérification', + devVerifyLink: 'Lien de dev :', + openVerificationUrl: 'Ouvrir l’URL de vérification', + enterEmailFirst: 'Saisissez d’abord votre adresse e-mail.', + emailPasswordRequired: 'L’e-mail et le mot de passe sont obligatoires.', + loginFailed: 'Échec de la connexion', + resendFailed: 'Échec de l’envoi de l’e-mail de vérification', + registerSubtitle: + 'Rejoignez Prediqo — utilisez le lien de parrainage d’un ami ou inscrivez-vous directement.', + invitedWithCode: 'Vous avez été invité avec le code de parrainage {{code}}.', + fullName: 'Nom complet', + fullNameRequired: 'Nom complet *', + emailRequired: 'E-mail *', + phoneOptional: 'Téléphone (optionnel)', + passwordRequired: 'Mot de passe *', + countryOfResidence: 'Pays de résidence', + countryHelper: 'Saisissez un pays ou un code ISO (ex. France ou FR)', + nationalityOptional: 'Nationalité (optionnel)', + nationalityPlaceholder: 'Rechercher une nationalité…', + referralCodeOptional: 'Code de parrainage (optionnel)', + referralValid: 'Code de parrainage valide', + referralUnknown: + 'Code inconnu — vous pouvez quand même vous inscrire (parrain par défaut appliqué)', + referralEmpty: 'Laissez vide pour utiliser le parrain par défaut de la plateforme', + creatingAccount: 'Création du compte…', + registerFieldsRequired: + 'Le nom complet, l’e-mail, le mot de passe, le pays de résidence et le sexe sont obligatoires.', + countryIsoInvalid: 'Le pays doit être un code ISO à 2 lettres (ex. FR).', + registerSuccess: + 'Compte créé. Consultez votre e-mail et cliquez sur le lien de vérification avant de vous connecter.', + registerFailed: 'Échec de l’inscription', + countriesLoadFailed: + 'Impossible de charger la liste des pays. Demandez à un admin de synchroniser les pays, puis actualisez.', + resetPassword: 'Réinitialiser le mot de passe', + resetPasswordSubtitle: + 'Saisissez votre e-mail et nous vous enverrons un lien sécurisé pour choisir un nouveau mot de passe.', + emailRequiredShort: 'L’e-mail est obligatoire.', + sendResetLink: 'Envoyer le lien', + requestFailed: 'Échec de la demande', + consoleResetHint: + 'Mode local / console — aucun e-mail n’est envoyé. Ouvrez ce lien pour réinitialiser votre mot de passe :', + chooseNewPassword: 'Choisir un nouveau mot de passe', + invalidResetLink: + 'Lien de réinitialisation invalide ou expiré. Demandez-en un nouveau depuis la page mot de passe oublié.', + newPassword: 'Nouveau mot de passe', + confirmPassword: 'Confirmer le mot de passe', + passwordsMustMatch: 'Les mots de passe doivent correspondre.', + updating: 'Mise à jour…', + updatePassword: 'Mettre à jour le mot de passe', + requestNewLink: 'Demander un nouveau lien', + resetFailed: 'Échec de la réinitialisation', + verifyingEmail: 'Vérification de votre e-mail…', + goToProfile: 'Aller au profil', + backToProfile: 'Retour au profil', + verificationFailed: 'Échec de la vérification', + requestNewLinkFromProfile: + 'Demandez un nouveau lien depuis votre profil si celui-ci a expiré.', + missingVerificationToken: + 'Jeton de vérification manquant. Ouvrez le lien complet reçu par e-mail.', + faqLink: 'Foire aux questions', + }, + setup: { + loading: 'Chargement…', + statusCheckFailed: 'Impossible de vérifier l’état d’initialisation', + apiUnreachable: + 'L’API n’a pas répondu. Vérifiez que VITE_API_BASE_URL correspond à l’URL publique (ex. http://prediqo.redirectme.net:9080) puis reconstruisez le frontend.', + setupComplete: 'Configuration terminée', + adminExists: + 'Un compte administrateur existe déjà. Connectez-vous pour accéder à la plateforme.', + goToLogin: 'Aller à la connexion', + title: 'Initialisation Prediqo', + subtitle: + 'Créez le premier compte administrateur pour configurer la plateforme en production.', + tokenEnvWarning: + 'Définissez la variable d’environnement INITIAL_SETUP_TOKEN sur le serveur (min. 16 caractères aléatoires), puis redémarrez l’API.', + setupTokenLabel: 'Jeton d’initialisation (INITIAL_SETUP_TOKEN)', + setupTokenHelper: 'Secret configuré uniquement sur le serveur — ne le partagez pas.', + tabCreate: 'Créer un admin', + tabPromote: 'Promouvoir un compte existant', + fullName: 'Nom complet', + passwordMin: 'Minimum 8 caractères', + promoteHint: + 'L’utilisateur doit déjà s’être inscrit via la page Register. Son e-mail sera marqué comme vérifié et son rôle passera à administrateur.', + inProgress: 'En cours…', + createAdmin: 'Créer l’administrateur', + promoteAdmin: 'Promouvoir en admin', + setupFailed: 'Échec de l’initialisation', + promotionFailed: 'Échec de la promotion', + backToLogin: 'Retour à la connexion', + }, + gender: { + label: 'Sexe', + select: 'Sélectionner…', + helper: 'Masculin, Féminin ou Autre', + male: 'Masculin', + female: 'Féminin', + other: 'Autre', + }, + home: { + title: 'Jouer & Prédire', + subtitle: + 'Explorez les jeux de prédiction en direct, profitez des promos limitées et gagnez des récompenses.', + refreshCatalog: 'Actualiser le catalogue', + loadError: + 'Une partie du contenu n’a pas pu être chargée. Exécutez les migrations et vérifiez que l’API est active.', + liveGames: 'Jeux en direct', + featured: 'À la une', + total: 'Total', + promotions: 'Promotions', + categories: 'Catégories', + allGames: 'Tous les jeux', + availableGames: 'Jeux disponibles', + noGamesInCategory: 'Aucun jeu dans cette catégorie pour le moment.', + gameStatus: { + live: 'En direct', + soon: 'Bientôt', + maintenance: 'Maintenance', + featured: 'À la une', + playNow: 'Jouer', + }, + }, + wallet: { + title: 'Portefeuille', + subtitle: + 'Déposez des USDT (TRC20) sur TRON pour alimenter votre compte et jouer à Candle Predict.', + refreshWallet: 'Actualiser le portefeuille', + loadError: + 'Impossible de charger les soldes. Vérifiez que vous êtes connecté et que l’API est active.', + mainBalance: 'Solde USDT principal', + locked: '{{amount}} bloqué', + noBalance: 'Aucun solde — recevez des USDT pour commencer.', + receiveUsdt: 'Recevoir USDT', + send: 'Envoyer', + withdraw: 'Retirer', + tabAsset: 'Actif', + tabActivity: 'Activité', + receiveDialog: { + title: 'Recevoir USDT', + info: 'Envoyez des USDT sur {{network}} uniquement. Ce solde sert aux mises Candle Predict.', + wrongNetwork: 'Un mauvais actif ou réseau peut entraîner une perte définitive.', + loadAddressFailed: 'Impossible de charger l’adresse de dépôt', + copyAddressAria: 'Copier l’adresse', + confirmationsHint: 'Les dépôts sont crédités après les confirmations blockchain requises.', + }, + transferDialog: { + title: 'Envoyer à un utilisateur', + subtitle: 'Transférez vers un autre compte Prediqo instantanément. Pas de frais on-chain.', + recipientEmail: 'E-mail du destinataire', + networkAuto: 'Réseau : {{network}} (sélection automatique)', + available: 'Disponible : {{amount}}', + totpCode: 'Code 2FA', + totpPlaceholder: 'Code à 6 chiffres', + totpRequired: 'Requis si la 2FA est activée sur votre compte', + review: 'Vérifier le transfert', + confirmTitle: 'Confirmer le transfert', + confirmBody: 'Envoyer {{amount}} {{asset}} à {{email}} ?', + irreversible: 'Cette action est irréversible.', + success: 'Transfert effectué avec succès', + }, + withdrawDialog: { + title: 'Retirer', + disabled: 'Les retraits sont désactivés sur ce serveur (sécurité testnet). Contactez un administrateur pour activer ALLOW_WITHDRAWALS=true lorsque vous êtes prêt.', + networkWarning: 'Vérifiez l’adresse et le réseau de destination. Les transferts sur le mauvais réseau sont irréversibles.', + networkFee: 'Des frais réseau de {{fee}} sont déduits de votre solde en plus du montant du retrait (couvre le gas TRON).', + networkFixed: 'Réseau : {{network}} (non modifiable)', + destinationAddress: 'Adresse de destination', + amountToReceive: 'Montant à recevoir', + totpOptional: 'Code 2FA (optionnel)', + totpPlaceholder: 'Code à 6 chiffres', + insufficient: 'Solde insuffisant — besoin de {{total}} (montant + frais réseau)', + availableWithFee: 'Disponible : {{available}}{{feePart}}', + networkFeePart: ' · Frais réseau : {{fee}}', + review: 'Vérifier le retrait', + confirmTitle: 'Confirmer le retrait', + receiveOnNetwork: 'Vous recevrez {{amount}} {{asset}} sur {{network}}.', + networkFeeLabel: 'Frais réseau :', + totalDebited: 'Total débité de votre solde :', + broadcastIrreversible: 'Cette transaction est irréversible une fois diffusée.', + withdrawing: 'Retrait…', + success: 'Retrait soumis avec succès', + successWithFee: 'Retrait soumis avec succès (frais {{fee}} USDT)', + }, + mainCard: { + title: 'Portefeuille principal', + badge: 'Dépôts et retraits', + availableBalance: 'Solde disponible', + locked: 'Bloqué :', + receive: 'Recevoir', + receiveAria: 'Recevoir USDT', + }, + bonusCard: { + title: 'Portefeuille bonus', + subtitle: 'Crédits USDT pour Candle Predict', + balance: 'Solde bonus', + hint: 'Utilisez le portefeuille bonus pour placer des prédictions. Les gains des mises bonus sont crédités sur votre portefeuille principal.', + transferring: 'Transfert…', + moveToMain: 'Tout transférer vers le principal', + transferSuccess: 'Bonus transféré vers le portefeuille principal', + policyHint: 'Les fonds bonus ne peuvent servir qu’aux prédictions (transfert vers le principal désactivé par la plateforme).', + }, + testCard: { + title: 'Portefeuille test', + subtitle: 'Argent fictif pour s’entraîner', + balance: 'Solde test', + hint: 'Utilisez les crédits test pour explorer les prédictions avec les mêmes règles. Gains et pertes restent dans ce portefeuille — non retirables ni transférables vers le principal.', + crediting: 'Crédit…', + requestCredits: 'Demander {{amount}} crédits test', + requestsUsed: 'Demandes utilisées : {{used}} / {{max}}', + availableAfter: 'Disponible après {{date}}.', + disabled: 'Les demandes de portefeuille test sont actuellement désactivées par la plateforme.', + }, + transactions: { + empty: 'Aucune transaction pour le moment', + emptyHint: 'Dépôts, prédictions et retraits apparaîtront ici.', + types: { + deposit: 'Dépôt', + withdrawal: 'Retrait', + transferIn: 'Transfert entrant', + transferOut: 'Transfert sortant', + gameStake: 'Mise de prédiction', + gamePayout: 'Gain de prédiction', + gameRefund: 'Remboursement de prédiction', + bonus: 'Crédit bonus', + adminAdjustment: 'Ajustement de solde', + }, + status: { + completed: 'Terminé', + pending: 'En attente', + failed: 'Échoué', + processing: 'En cours', + }, + }, + }, + profileForm: { + editHint: 'Les champs affichent vos informations actuelles. Modifiez uniquement ce que vous souhaitez changer, puis enregistrez.', + firstName: 'Prénom', + middleName: 'Deuxième prénom', + lastName: 'Nom', + dateOfBirth: 'Date de naissance', + phoneOptional: 'Téléphone (optionnel)', + countryHelper: 'Recherchez par nom de pays ou code ISO (ex. France ou FR)', + nationalityPlaceholder: 'Rechercher une nationalité…', + countriesLoadFailed: 'Impossible de charger la liste des pays. Réessayez plus tard ou contactez l’assistance.', + saveProfile: 'Enregistrer le profil', + saving: 'Enregistrement…', + updated: 'Profil mis à jour avec succès', + updateFailed: 'Échec de la mise à jour', + emailEmpty: 'L’e-mail ne peut pas être vide', + countryRequired: 'Le pays de résidence est obligatoire', + genderRequired: 'Le sexe est obligatoire', + }, + profilePassword: { + current: 'Mot de passe actuel', + new: 'Nouveau mot de passe', + confirm: 'Confirmer le nouveau mot de passe', + strengthHint: 'Choisissez un mot de passe fort. La politique serveur (longueur, complexité) est appliquée à l’enregistrement.', + enterCurrent: 'Saisissez votre mot de passe actuel', + enterNew: 'Saisissez un nouveau mot de passe', + mismatch: 'Le nouveau mot de passe et la confirmation ne correspondent pas', + updated: 'Mot de passe mis à jour avec succès', + failed: 'Échec du changement de mot de passe', + }, + profileTwoFactor: { + enabled: 'L’authentification à deux facteurs est activée sur votre compte. Un code TOTP est requis pour les transferts lorsque la 2FA est active.', + setupHint: 'Protégez votre compte avec Google Authenticator ou toute application TOTP. Scannez le QR code, puis saisissez un code de vérification pour activer la 2FA.', + setupButton: 'Configurer la 2FA', + scanQr: 'Scannez avec votre application d’authentification', + qrAlt: 'QR code 2FA', + manualKey: 'Clé manuelle : {{secret}}', + verificationCode: 'Code de vérification à 6 chiffres', + enabling: 'Activation…', + enable: 'Activer la 2FA', + enterCode: 'Saisissez le code à 6 chiffres de votre application d’authentification', + enabledSuccess: 'Authentification à deux facteurs activée', + setupFailed: 'Échec de la configuration 2FA', + invalidCode: 'Code invalide. Scannez à nouveau le QR et saisissez le code à 6 chiffres actuel.', + }, + profileEmailVerify: { + verified: 'Votre e-mail {{email}} est vérifié.', + notVerified: 'Votre e-mail {{email}} n’est pas encore vérifié. Vérifiez-le pour sécuriser les retraits et la récupération de compte.', + hint: 'Nous enverrons un lien sécurisé à usage unique valable 24 h. Changer d’e-mail nécessite une nouvelle vérification.', + sendEmail: 'Envoyer l’e-mail de vérification', + sendFailed: 'Échec de l’envoi de l’e-mail', + devMode: 'Mode dev : SMTP non utilisé. Ouvrez ou copiez ce lien pour vérifier en local.', + copyDevLink: 'Copier le lien dev', + devLinkCopied: 'Lien de vérification dev copié', + }, + profileReferral: { + loadFailed: 'Impossible de charger les informations de parrainage.', + notAvailable: 'Votre code de parrainage n’est pas encore disponible. Contactez l’assistance si vous vous êtes inscrit avant le lancement du programme.', + shareHint: 'Partagez votre lien pour inviter des amis et gagner des commissions sur leur activité.', + fullNetwork: 'Réseau complet', + directReferrals_one: '{{count}} filleul direct', + directReferrals_other: '{{count}} filleuls directs', + referralCode: 'Code de parrainage', + referralLink: 'Lien de parrainage', + copyCodeAria: 'Copier le code de parrainage', + copyLinkAria: 'Copier le lien de parrainage', + copyInvite: 'Copier le lien d’invitation', + }, + profile: { + title: 'Profil', + subtitle: + 'Consultez et gérez vos informations personnelles et la sécurité de votre compte.', + refreshProfile: 'Actualiser le profil', + loadError: + 'Impossible de charger le profil. Vérifiez que vous êtes connecté et que l’API est active.', + emailVerified: 'E-mail vérifié', + emailNotVerified: 'E-mail non vérifié', + twoFaEnabled: '2FA activée', + twoFaOff: '2FA désactivée', + tabPersonal: 'Personnel', + tabSecurity: 'Sécurité', + personalInfo: 'Informations personnelles', + emailVerification: 'Vérification e-mail', + referralProgram: 'Programme de parrainage', + accountDetails: 'Détails du compte', + userId: 'ID utilisateur', + memberSince: 'Membre depuis', + changePassword: 'Changer le mot de passe', + changePasswordHint: + 'Mettez à jour votre mot de passe. Votre mot de passe actuel sera demandé pour confirmer.', + twoFactorAuth: 'Authentification à deux facteurs', + twoFactorHint: + 'Protégez votre compte avec une application d’authentification. Requis pour les opérations sensibles lorsqu’elle est activée.', + enabled: 'Activée', + disabled: 'Désactivée', + }, + candlePredict: { + title: 'Candle Predict', + subtitle: + 'Prédisez si la prochaine bougie sera baissière (Short ↓) ou haussière (Long ↑), puis attendez le résultat de la manche.', + refreshGame: 'Actualiser le jeu', + backToHome: 'Retour à l’accueil', + loadError: 'Impossible de charger Candle Predict.', + rateLimitHint: + 'Trop de requêtes API — attendez une minute ou redémarrez le backend.', + apiHint: 'Exécutez les migrations et vérifiez que l’API est active.', + singleCandle: 'Bougie unique', + multiCandle: 'Multi-bougies', + predictionPlaced: 'Prédiction placée pour la manche {{interval}}', + multiPredictionPlaced: 'Prédiction multi-bougies niveau {{level}} placée', + placePredictionFailed: 'Échec du placement de la prédiction', + multiPlaceFailed: 'Échec du placement de la prédiction multi-bougies', + autoEnabledPlaced: + 'Prédiction auto activée — placée pour la manche {{interval}}', + autoUpdated: 'Prédiction auto mise à jour', + autoSaveFailed: 'Échec de l’enregistrement des paramètres auto', + status: { + loading: 'Chargement…', + betting: + '{{interval}} · paris ouverts · cible {{target}} · {{countdown}} restant', + locked: + '{{interval}} · bougie en cours · {{live}} · paris dans {{untilOpen}}', + waiting: '{{interval}} · prochaine fenêtre dans {{countdown}}', + neutral: '{{interval}} · manche nulle · mise remboursée', + shortWin: '{{interval}} · terminé · Short gagnant', + longWin: '{{interval}} · terminé · Long gagnant', + settled: '{{interval}} · terminé', + }, + betting: { + title: 'Placer votre prédiction', + hint: 'Short = bougie baissière · Long = bougie haussière. Choisissez une direction et confirmez votre mise.', + targetRound: 'Manche cible {{time}} · ferme dans {{wait}}', + predictionsOpenIn: 'Paris ouverts dans {{wait}}', + gameDisabled: 'Jeu désactivé par l’admin — les paris sont indisponibles.', + predictionLocked: 'Votre prédiction est verrouillée pour cette manche.', + chooseDirection: 'Choisir la direction', + short: 'Short', + long: 'Long', + stake: 'Mise', + confirm: 'Confirmer la prédiction', + confirming: 'Confirmation…', + windowClosed: 'La fenêtre de pari est fermée pour cette manche.', + minMaxStake: 'La mise doit être entre {{min}} et {{max}}.', + candleInProgress: + 'Bougie en cours — placez votre prédiction à l’ouverture de la fenêtre{{suffix}}.', + nextWindowOpens: + 'La prochaine fenêtre de pari s’ouvre peu avant la nouvelle bougie.', + stakeAmount: 'Montant de la mise ({{code}})', + stakeHelper: + 'Choix rapides ci-dessus, ou saisissez un montant de {{min}} à {{max}} USDT (ex. 0,25)', + prediction: 'Prédiction', + confirmCompact: 'Confirmer · {{stake}} · ×{{multiplier}}', + confirmFull: 'Confirmer la prédiction · {{stake}} · Gain ×{{multiplier}}', + }, + interval: { + title: 'Période de prédiction', + hint: 'Votre prédiction cible la manche qui se clôture à la fin de cette période.', + }, + testMode: { + title: 'Mode test', + hint: 'Vous jouez uniquement avec des crédits test. Gains et pertes restent dans le portefeuille test — non retirables ni transférables vers le principal.', + }, + stakeWallet: { + barTitle: 'Vos portefeuilles de mise', + main: 'Principal', + bonus: 'Bonus', + test: 'Test', + mainWallet: 'Wallet principal', + bonusWallet: 'Wallet bonus', + testWallet: 'Wallet de test', + showBalances: 'Afficher les soldes', + hideBalances: 'Masquer les soldes', + }, + adminInsights: { + title: 'Vue administrateur — mécanismes internes', + footer: + 'Non visible pour les joueurs. Les pools et règles de règlement ne doivent pas influencer leurs prédictions.', + poolWinnerMinority: 'Minorité gagne', + poolWinnerMajority: 'Majorité gagne', + neutralMin: 'neutre si écart de pool ≤ {{percent}} %', + neutralMax: 'neutre si plus grand pool ≥ {{percent}} %', + neutralNone: 'Aucune manche neutre automatique selon l’équilibre des pools', + neutralBehavior: 'Les manches neutres remboursent toutes les mises — ni gagnants ni perdants.', + }, + roundStatus: { + title: 'Statut de la manche', + }, + gameDisabledAdmin: 'Ce jeu est temporairement désactivé par un administrateur.', + direction: { + shortCandle: 'Bougie Short', + longCandle: 'Bougie Long', + shortBearish: 'Short (baissier)', + longBullish: 'Long (haussier)', + }, + stakeWalletSelector: { + label: 'Portefeuille de mise', + mainWallet: 'Wallet principal · {{balance}}', + bonusWallet: 'Wallet bonus · {{balance}}', + testWallet: 'Wallet de test · {{balance}}', + }, + stakeField: { + customAmount: 'Montant personnalisé', + required: 'Saisissez un montant', + invalidFormat: 'Format invalide : pas de zéros en tête (utilisez 0,5, pas 00,5)', + zero: 'Le montant doit être supérieur à zéro', + invalid: 'Saisissez un montant valide (ex. 0,01, 1,5, 10)', + range: 'Le montant doit être entre {{min}} et {{max}}', + }, + multiBetting: { + title: 'Prédiction multi-bougies', + hint: 'Prédisez des bougies consécutives dans l’ordre exact. Niveau minimum 2 — utilisez le mode simple pour une bougie.', + inProgress: 'Prédiction multi-bougies en cours', + progress: + 'Niveau {{level}} · mise {{stake}} · validation bougie {{current}} sur {{total}}', + current: 'en cours', + progressAlert: + 'Une bougie incorrecte termine la séquence immédiatement. Votre mise reste en attente jusqu’à validation de la dernière bougie.', + noLevels: 'Aucun niveau multi-bougies disponible pour l’instant.', + singleBlocksMulti: + 'Vous avez déjà une prédiction simple pour cette manche (y compris auto). Le multi-bougies sera disponible à la prochaine fenêtre.', + level: 'Niveau', + levelOption: 'Niveau {{level}} — {{count}} bougies · gain ×{{multiplier}}', + yourSequence: 'Votre séquence', + candleN: 'Bougie {{n}}', + winHint: 'Gain en cas de succès : mise × {{multiplier}} ({{interval}}).', + placing: 'Envoi…', + placeLevel: 'Placer la prédiction niveau {{level}}', + }, + autoPrediction: { + title: 'Prédiction auto', + titleActive: 'Prédiction auto active', + enableHint: 'Activez pour parier automatiquement à chaque manche.', + enable: 'Activer la prédiction auto', + disable: 'Désactiver', + targetPeriod: 'Période cible :', + viewingDifferent: + 'Vous consultez {{viewing}}. Enregistrez pour déplacer l’auto vers {{target}}.', + targetHint: + 'Défini selon la période de prédiction sélectionnée à l’enregistrement. Une config auto par compte.', + direction: 'Direction', + stakeAmount: 'Montant de mise', + stakeHelper: 'Raccourcis : {{picks}} · personnalisé de {{min}} à {{max}} USDT', + mode: 'Mode', + modeEachRound: 'Chaque nouvelle manche', + modeInterval: 'Délai minimum', + modeIntervalHelper: + '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 à l’enregistrement).', + modeEachRoundHelper: + 'Place une mise dès l’ouverture de la fenêtre de prédiction de chaque nouvelle manche.', + intervalSeconds: 'Délai minimum entre mises auto (secondes)', + intervalSecondsHelper: + 'Temps minimal depuis la dernière mise auto réussie. N’autorise pas plusieurs mises sur la même manche — espacement entre mises consécutives uniquement (ex. après un enregistrement récent).', + save: 'Enregistrer les paramètres auto', + cancel: 'Annuler', + edit: 'Modifier', + editSettings: 'Modifier les paramètres', + intro: + 'Place automatiquement une prédiction par manche 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 Enregistrer.', + configureAlert: + 'Paramétrez votre prédiction ci-dessous, puis cliquez sur Enregistrer les paramètres auto pour activer le mode. Aucune mise ne sera placée avant l’enregistrement.', + lastAutoBet: 'Dernière mise auto : {{date}}', + modeShortEachRound: 'Chaque manche', + modeShortInterval: 'Délai min.', + }, + autoBanner: { + activeOnInterval: 'Prédiction auto active · {{interval}}', + activeOtherInterval: 'Prédiction auto active sur {{interval}}', + viewingMismatch: + 'Vous consultez {{viewing}}. Les prédictions auto ne s’exécutent que sur {{auto}} — changez de période ou réenregistrez ici pour déplacer l’auto vers {{viewing}}.', + viewInterval: 'Voir {{interval}}', + modeInterval: 'délai min. {{seconds}}s entre mises auto · 1/manche', + modeEachRound: 'chaque nouvelle manche', + }, + recentPredictions: { + title: 'Prédictions récentes', + totalPerPage: '{{total}} au total · {{size}} par page', + empty: 'Aucune prédiction pour l’instant', + loadError: 'Impossible de charger les prédictions. Actualisez la page.', + columns: { + mode: 'Mode', + prediction: 'Prédiction', + period: 'Période', + stake: 'Mise', + account: 'Compte', + status: 'Statut', + payout: 'Gain', + }, + modeSingle: 'Simple', + modeAuto: 'Auto', + modeMulti: 'Multi · N{{level}}', + status: { + pending: 'En attente', + in_progress: 'En cours', + won: 'Gagné', + lost: 'Perdu', + refunded: 'Remboursé', + }, + placed: 'Placé {{time}}', + stakeLine: '{{placed}} · Mise {{stake}} · Gain {{payout}}', + multiPeriod: '{{count}} bougies consécutives · {{minutes}} min chacune', + multiPeriodShort: 'Multi · {{count}} × {{minutes}} min', + multiFailed: 'Échec à la bougie {{current}} sur {{total}}', + multiWon: 'Les {{total}} bougies validées', + multiValidating: 'Validation bougie {{current}} sur {{total}}', + multiRefunded: 'Séquence remboursée ({{total}} bougies)', + }, + poolBar: { + title: 'Pools de mise', + shortBearish: 'Short (baissier)', + longBullish: 'Long (haussier)', + hint: + 'Les pools incluent toutes les prédictions arrivant à échéance à cette manche (chaque intervalle). {{winner}} lorsque l’écart dépasse la tolérance d’égalité. Pools égaux → manche neutre (remboursement).', + winnerMinority: 'Le pool minoritaire gagne', + winnerMajority: 'Le pool majoritaire gagne', + }, + chart: { + scrollHint: 'Glisser ou molette pour voir l’historique', + }, + }, + referralPage: { + title: 'Programme de parrainage', + subtitle: 'Développez votre réseau et gagnez des commissions sur l’activité de vos filleuls.', + refresh: 'Actualiser les données de parrainage', + loadError: 'Impossible de charger le tableau de bord parrainage.', + programDisabled: + 'Le programme de parrainage est temporairement désactivé. Vos données réseau restent visibles ci-dessous.', + refreshed: 'Données de parrainage actualisées', + stats: { + networkSize: 'Taille du réseau', + direct: '{{count}} direct(s)', + totalEarned: 'Total gagné', + allStatuses: 'USDT (tous statuts)', + paidOut: 'Versé', + pendingReview: 'En attente / revue', + }, + invite: { + title: 'Votre lien d’invitation', + bonusWithdrawable: 'Bonus retirable', + codeNotAvailable: 'Votre code de parrainage n’est pas encore disponible.', + codePrefix: 'Code :', + }, + referrer: { + title: 'Votre parrain', + memberSince: 'Membre depuis le {{date}}', + noReferrer: 'Vous vous êtes inscrit sans code de parrainage, ou votre parrain n’est pas lié.', + commissionLevels: 'Niveaux de commission', + levelChip: 'Niveau {{level}} : {{percent}} %', + depositHint: 'Les commissions sur dépôt s’appliquent aux premiers dépôts éligibles. ', + withdrawalHint: + 'Les commissions sur retrait s’appliquent uniquement aux gains de prédiction retirés du compte principal (pas au capital déposé).', + }, + network: { + title: 'Votre réseau de parrainage', + maxDepth: 'Profondeur max', + showingLevels: '{{count}} niveaux affichés', + tableView: 'Vue tableau', + treeView: 'Vue arbre', + commissionHistory: 'Historique des commissions', + }, + modes: { + both: 'Dépôts + gains de retrait', + deposit: 'Premiers dépôts', + withdrawal: 'Gains de retrait (profits de prédiction)', + paused: 'Commissions suspendues', + }, + table: { + empty: 'Aucun filleul dans votre réseau. Partagez votre lien d’invitation pour développer votre équipe.', + member: 'Membre', + country: 'Pays', + level: 'Niveau', + registered: 'Inscrit le', + directRefs: 'Filleuls directs', + predictions: 'Prédictions', + commissions: 'Commissions', + pending: 'En attente', + total: 'total {{amount}}', + status: { + active: 'Actif', + unverified: 'Non vérifié', + registered: 'Inscrit', + }, + }, + tree: { + empty: 'Votre arbre de parrainage est vide. Invitez des membres pour voir la hiérarchie ici.', + level: 'Niveau {{level}}', + direct: '{{count}} direct(s)', + paid: 'Versé : {{amount}} USDT', + pending: 'En attente : {{amount}} USDT', + code: 'Code : {{code}}', + }, + commissions: { + empty: 'Aucune commission pour le moment.', + member: 'Membre', + level: 'Niveau', + source: 'Source', + status: 'Statut', + commission: 'Commission', + date: 'Date', + deposit: 'Dépôt', + withdrawal: 'Gains de retrait', + percentOf: '{{percent}} % de {{amount}}', + }, + }, + faq: { + title: 'Foire aux questions', + subtitle: 'Trouvez rapidement des réponses aux questions les plus fréquentes.', + searchPlaceholder: 'Rechercher une question…', + allCategories: 'Toutes', + popular: 'Questions populaires', + loadError: 'Impossible de charger les FAQ. Réessayez plus tard.', + noResults: 'Aucune question ne correspond à votre recherche.', + helpfulQuestion: 'Cette réponse vous a-t-elle été utile ?', + yes: 'Oui ({{count}})', + no: 'Non ({{count}})', + thankYou: 'Merci pour votre retour !', + views: '{{count}} consultation(s)', + publicHeader: { + login: 'Connexion', + register: 'Inscription', + home: 'Accueil', + }, + }, + support: { + widget: { + ariaLabel: 'Assistance', + title: 'Assistance Prediqo', + subtitle: 'Réponse en temps réel de notre équipe', + }, + chat: { + greeting: 'Bonjour ! Comment pouvons-nous vous aider ?', + typing: 'L’équipe est en train d’écrire…', + placeholder: 'Écrivez votre message…', + today: 'Aujourd’hui', + yesterday: 'Hier', + newMessage: 'Nouveau message', + file: 'Fichier', + attachment: 'pièce jointe', + }, + }, + admin: { + badge: { + admin: 'Admin', + dynamic: 'Dynamique', + catalog: 'Catalogue', + coldHot: 'Froid / Chaud', + levelsBonus: 'Niveaux / Bonus', + sybilReview: 'Sybil / Revue / Récupération', + playMoney: 'Argent fictif', + alertsLedger: 'Alertes / Grand livre', + staff: 'Équipe', + registration: 'Inscription', + }, + options: { + title: 'Options', + subtitle: 'Outils administratifs et configuration.', + cards: { + users: { + title: 'Gestion des utilisateurs', + description: 'Rechercher des utilisateurs, ouvrir les détails et gérer les indicateurs de compte en toute sécurité.', + }, + settings: { + title: 'Paramètres', + description: 'Configurer la politique de mot de passe et l’expiration des jetons sans modifier le code.', + }, + catalog: { + title: 'Jeux & publicités', + description: 'Publier jeux et promotions d’accueil dynamiquement — sans redéploiement.', + }, + treasury: { + title: 'Trésorerie', + description: 'Adresses cold wallet, sweeps de dépôts et alimentation du hot wallet depuis le cold storage.', + }, + referral: { + title: 'Programme de parrainage', + description: 'Commissions multi-niveaux, pool bonus, règles d’éligibilité et statistiques d’inscription.', + }, + referralFraud: { + title: 'Tableau de bord fraude parrainage', + description: 'File de revue, parrains à risque, plafonds mensuels et récupérations de commissions.', + }, + testWallet: { + title: 'Wallet de test', + description: 'Montants de crédit, limites de demande, délais et historique pour le jeu d’essai.', + }, + security: { + title: 'Sécurité', + description: 'Contrôles d’intégrité, alertes sécurité, notifications in-app et crédits grand livre approuvés.', + }, + network: { + title: 'Réseau & environnement', + description: 'Testnet, état des retraits USDT (TRC20) et environnement serveur.', + }, + faq: { + title: 'Foire aux questions', + description: 'Gérer les questions, catégories, médias et statistiques FAQ.', + }, + support: { + title: 'Centre d’assistance', + description: 'Conversations utilisateurs et visiteurs, réponses en temps réel.', + }, + countries: { + title: 'Pays', + description: 'Synchroniser le catalogue pays et bloquer l’inscription par pays de résidence.', + }, + }, + }, + approvals: { + title: 'Approbations', + subtitle: 'Examiner et approuver les opérations de fonds sensibles', + refresh: 'Actualiser les approbations', + noPermission: 'Vous n’avez pas la permission d’approuver les opérations de fonds.', + approved: 'Demande approuvée et exécutée.', + rejected: 'Demande rejetée.', + loadError: 'Impossible de charger la file d’approbation.', + noPending: 'Aucune approbation en attente.', + type: 'Type', + requestedBy: 'Demandé par', + created: 'Créé le', + status: 'Statut', + actions: 'Actions', + approve: 'Approuver', + reject: 'Rejeter', + rejectTitle: 'Rejeter la demande', + rejectHint: 'Indiquez un motif de rejet.', + reason: 'Motif', + opTypes: { + ledger_credit: 'Crédit grand livre', + treasury_cold_to_hot: 'Alimentation Froid → Chaud', + bonus_pool_fund: 'Alimentation pool bonus', + sweep_manual: 'Sweeps manuels', + sweep_batch: 'Lot de sweeps auto', + }, + }, + users: { + title: 'Utilisateurs', + subtitle: 'Table avancée — filtrer, trier, sélectionner plusieurs utilisateurs et actions groupées.', + refresh: 'Actualiser les utilisateurs', + loadError: 'Impossible de charger les utilisateurs.', + columnsHint: 'Colonnes → afficher/masquer & exporter', + download: 'Télécharger', + exportSelected: 'Exporter ({{count}})', + selected: '{{count}} sélectionné(s)', + exportLimit: 'Limite export : {{count}}', + exportLimitDefault: 'Limite export : 100k (serveur)', + totalExact: '{{count}} utilisateur(s)', + totalEstimate: '~{{count}} utilisateur(s) (estim.)', + copied: 'Copié dans le presse-papiers', + copyFailed: 'Échec de la copie', + batchFailed: 'Opération groupée échouée', + emailVerified: 'E-mail marqué comme vérifié', + emailVerifyFailed: 'Échec de la vérification e-mail', + rolesUpdated: 'Rôles mis à jour', + roleUpdateFailed: 'Échec de la mise à jour des rôles', + updateFailed: 'Mise à jour échouée', + noUsersSelected: 'Aucun utilisateur sélectionné', + exportFailed: 'Export échoué', + invalidBonusAmount: 'Saisissez un montant de bonus valide', + csvExported: 'CSV exporté', + csvExportFailed: 'Échec export CSV', + filters: 'Filtres', + clear: 'Effacer', + filtersActive: 'Filtres actifs : {{count}}', + searchLabel: 'Rechercher par ID, e-mail ou code parrain', + searchPlaceholder: 'ex. user@example.com ou REF123', + accountStatus: { + active: 'Actif', + disabled: 'Désactivé', + suspended: 'Suspendu', + fullyActive: 'Compte entièrement actif', + }, + statusReasons: { + disabled: 'Compte désactivé', + locked: 'Compte verrouillé', + expired: 'Compte expiré', + credentialsExpired: 'Identifiants expirés', + withdrawalsSuspended: 'Retraits suspendus', + underSurveillance: 'Sous surveillance', + }, + ageBuckets: { + under18: 'Moins de 18 ans', + '18_24': '18–24', + '25_34': '25–34', + '35_44': '35–44', + '45_54': '45–54', + '55_64': '55–64', + '65_plus': '65+', + }, + ageFilter: { + range: 'Âge {{min}}–{{max}}', + max: 'Âge ≤ {{max}}', + min: 'Âge ≥ {{min}}', + }, + filterLabels: { + role: 'Rôle', + accountStatus: 'Statut du compte', + emailVerified: 'E-mail vérifié', + receivedBonus: 'Bonus reçu', + country: 'Pays', + countryPlaceholder: 'Tous les pays — rechercher par nom ou code…', + inactiveSince: 'Inactif depuis (jours)', + inactivePlaceholder: 'ex. 30', + minMainBalance: 'Solde principal min (USDT)', + maxMainBalance: 'Solde principal max (USDT)', + minBonusReceived: 'Bonus reçu min (USDT)', + maxBonusReceived: 'Bonus reçu max (USDT)', + minAge: 'Âge min (années)', + maxAge: 'Âge max (années)', + minAgeHelper: 'Années complètes (inclus)', + maxAgeHelper: 'Utilisez 15 pour cibler les moins de 16 ans', + minAgePlaceholder: 'ex. 10', + maxAgePlaceholder: 'ex. 15 pour moins de 16 ans', + createdFrom: 'Créé à partir du', + createdTo: 'Créé jusqu’au', + verified: 'Vérifié', + notVerified: 'Non vérifié', + receivedBonusYes: 'Bonus reçu', + receivedBonusNo: 'Pas de bonus reçu', + }, + roles: { + user: 'Utilisateur', + moderator: 'Modérateur', + admin: 'Administrateur', + super_admin: 'Super administrateur', + }, + columns: { + id: 'ID', + email: 'E-mail', + fullName: 'Nom complet', + status: 'Statut', + emailOk: 'E-mail OK', + role: 'Rôle', + country: 'Pays', + nationality: 'Nationalité', + dob: 'Naissance', + ageGroup: 'Tranche d’âge', + referralCode: 'Code parrain', + firstDeposit: 'Premier dépôt', + firstDepositTx: 'Tx premier dépôt', + mainUsdt: 'USDT principal', + bonusUsdt: 'USDT bonus', + bonusReceived: 'Bonus reçu', + predictions: 'Prédictions', + netPnl: 'P/L net', + totalStake: 'Mise totale', + totalPayout: 'Gains totaux', + created: 'Créé le', + lastLogin: 'Dernière connexion', + lastActivity: 'Dernière activité', + enabled: 'Activé', + wdSuspended: 'Retraits susp.', + surveillance: 'Surveillance', + twoFa: '2FA', + nonExpired: 'Non expiré', + nonLocked: 'Non verrouillé', + credsValid: 'Ident. valides', + copy: 'Copier', + }, + tooltips: { + verifyEmail: 'Cliquer pour marquer l’e-mail comme vérifié (admin)', + changeRole: 'Cliquer pour changer le rôle', + copyUserId: 'Copier l’ID utilisateur', + copyEmail: 'Copier l’adresse e-mail', + }, + fields: { + isEnabled: 'Activé', + withdrawalsSuspended: 'Retraits suspendus', + underSurveillance: 'Sous surveillance', + isAccountNonExpired: 'Compte non expiré', + isAccountNonLocked: 'Compte non verrouillé', + isCredentialsNonExpired: 'Identifiants valides', + reactivateWithdrawals: 'Réactiver les retraits', + }, + mobile: { + mainBonusPredictions: 'Principal : {{main}} · Bonus : {{bonus}} · {{count}} prédictions', + showFlags: 'Afficher les indicateurs', + hideFlags: 'Masquer les indicateurs', + }, + batch: { + enable: 'Activer', + disable: 'Désactiver', + suspend: 'Suspendre les retraits', + reactivate: 'Réactiver', + grantBonus: 'Attribuer un bonus', + exportSelected: 'Exporter la sélection', + clearSelection: 'Effacer la sélection', + enableAccounts: 'Activer les comptes', + disableAccounts: 'Désactiver les comptes', + suspendAccounts: 'Suspendre les retraits', + reactivateAccounts: 'Réactiver les retraits', + grantBonusTitle: 'Attribuer un bonus', + applyTo: 'Appliquer à {{count}} utilisateur(s) sélectionné(s) ?', + bonusType: 'Bonus (wallet bonus)', + adminAdjustment: 'Ajustement admin (principal)', + amountUsdt: 'Montant (USDT)', + reason: 'Motif', + }, + export: { + csvCurrentPage: 'Exporter CSV (page courante)', + xlsxAllFiltered: 'Exporter XLSX (tous filtrés)…', + xlsxSelected: 'Exporter XLSX (sélection)', + dialogTitle: 'Exporter XLSX (serveur)', + visibleOnly: 'Exporter uniquement les colonnes visibles', + visibleOnlyHint: + 'Utilisez le bouton Colonnes de la barre d’outils pour choisir les champs à afficher et exporter.', + maxRows: 'Lignes max', + maxRowsPlaceholder: '100 000 par défaut sur le serveur', + matchingUsers: 'Utilisateurs correspondants : {{label}}', + inProgress: 'Export serveur en cours… {{count}} ligne(s)', + export: 'Exporter', + }, + roleDialog: { + title: 'Gérer les rôles utilisateur', + }, + confirmDialog: { + title: 'Confirmer la modification', + body: 'Définir {{field}} sur {{value}} ?', + true: 'vrai', + false: 'faux', + }, + }, + catalog: { + title: 'Catalogue', + subtitle: 'Gérer les jeux et les promotions dynamiques de la page d’accueil.', + refresh: 'Actualiser le catalogue', + tabs: { games: 'Jeux', ads: 'Publicités', candle: 'Candle Predict' }, + addGame: 'Ajouter un jeu', + addAd: 'Ajouter une publicité', + loadingGames: 'Chargement des jeux…', + loadingAds: 'Chargement des publicités…', + editGame: 'Modifier le jeu', + deactivate: 'Désactiver', + noImplementation: 'Aucune implémentation', + noWebUi: 'Pas d’UI web', + featured: 'À la une', + active: 'Actif', + inactive: 'Inactif', + order: 'Ordre {{order}}', + saveGameFailed: 'Échec de l’enregistrement du jeu', + saveAdFailed: 'Échec de l’enregistrement de la publicité', + gameDialog: { edit: 'Modifier le jeu', new: 'Nouveau jeu' }, + adDialog: { edit: 'Modifier la publicité', new: 'Nouvelle publicité' }, + fields: { + slug: 'Slug', + slugRecommended: 'Slug recommandé pour cette implémentation : {{slug}}', + useDefaultSlug: 'Utiliser le slug par défaut ({{slug}})', + title: 'Titre', + description: 'Description', + category: 'Catégorie', + thumbnailUrl: 'URL miniature', + accentColor: 'Couleur d’accent', + implementation: 'Implémentation', + implementationNone: 'Aucune (catalogue uniquement)', + implementationHint: 'Lie cette entrée catalogue à un module jeu backend. Requis pour les jeux jouables.', + implementationNoWeb: + 'Cette implémentation n’a pas encore de module UI web. Les joueurs web verront un message « non supporté » jusqu’à enregistrement frontend.', + status: 'Statut', + statusActive: 'Actif', + statusComingSoon: 'Bientôt disponible', + statusMaintenance: 'Maintenance', + sortOrder: 'Ordre d’affichage', + featured: 'À la une', + placement: 'Emplacement', + subtitle: 'Sous-titre', + ctaLabel: 'Libellé CTA', + linkUrl: 'URL du lien', + imageUrl: 'URL image', + backgroundGradient: 'Dégradé de fond (CSS)', + placementHomeHero: 'Bannière accueil (carrousel)', + placementHomeStrip: 'Bandeau accueil', + placementHomeSidebar: 'Barre latérale accueil', + }, + candlePredict: { + config: { + loading: 'Chargement de la configuration du jeu…', + globalTitle: 'Paramètres globaux', + globalIntro: + 'Les bougies synthétiques sont générées à partir des mises des joueurs — pas de données de marché réelles. Les dérogations par intervalle se gèrent ci-dessous ; les champs vides héritent de ces valeurs par défaut.', + stakeAmounts: 'Montants de mise (séparés par des virgules)', + stakeAmountsHint: 'Boutons rapides pour les joueurs — chaque valeur doit être entre min et max ci-dessous', + minStake: 'Mise minimale (saisie libre)', + minStakeHint: 'Montant le plus bas autorisé dans le champ libre (ex. 0,01 pour les centimes)', + maxStake: 'Mise maximale', + predictionWindow: 'Fenêtre de prédiction par défaut (secondes)', + predictionWindowHint: 'Secondes par défaut avant la clôture de chaque bougie pour placer une prédiction', + neutralTitle: 'Règles de manche neutre', + neutralBehavior: + 'Les manches neutres remboursent toutes les mises — ni gagnants ni perdants. Utilisez les règles ci-dessous pour déclarer une manche neutre lorsque les pools sont trop équilibrés ou trop déséquilibrés.', + minTolerance: 'Tolérance min — pools proches (%)', + minToleranceHint: 'Neutre si |Long% − Short%| ≤ cette valeur (ex. 49/51 à 2 %)', + enableMinTolerance: 'Activer la règle de tolérance min', + maxTolerance: 'Tolérance max — déséquilibre extrême (%)', + maxToleranceHint: 'Neutre si le plus grand pool ≥ cette valeur (ex. 95/5 à 95 %)', + enableMaxTolerance: 'Activer la règle de tolérance max', + poolWinnerRule: 'Règle du pool gagnant', + poolWinnerMinority: 'Le pool minoritaire gagne (mise totale la plus faible)', + poolWinnerMajority: 'Le pool majoritaire gagne (mise totale la plus élevée)', + poolWinnerMinorityDesc: 'Le pool minoritaire gagne lorsque les pools diffèrent suffisamment.', + poolWinnerMajorityDesc: 'Le pool majoritaire gagne lorsque les pools diffèrent suffisamment.', + poolWinnerApplied: 'Appliqué immédiatement aux nouveaux règlements.', + basePrice: 'Prix de base du graphique par défaut', + poolMultiplier: 'Multiplicateur de pool par défaut', + poolMultiplierHint: 'Poids des mises dans les pools Long/Short (simple, auto, dernière bougie multi)', + payoutMultiplier: 'Multiplicateur de gain par défaut', + payoutMultiplierHint: 'Gain pour les prédictions correctes — indépendant du poids du pool', + walletTypeCode: 'Code type de portefeuille', + gameActive: 'Jeu actif', + modesTitle: 'Modes de prédiction', + modesIntro: 'Activer ou désactiver chaque type de prédiction indépendamment. Les modes désactivés sont masqués aux joueurs.', + singleEnabled: 'Prédictions sur une bougie', + autoEnabled: 'Prédictions automatiques', + multiEnabled: 'Prédictions multi-bougies', + saveGlobal: 'Enregistrer la config globale', + intervalsTitle: 'Intervalles de prédiction', + configSaved: 'Configuration enregistrée', + saveFailed: 'Échec de l’enregistrement', + }, + intervals: { + loading: 'Chargement des intervalles…', + intro: + 'Chaque intervalle a ses propres manches et graphique. Les joueurs choisissent une période ; les prédictions sont reportées à la manche correspondante à la clôture de la bougie. Laissez les champs de dérogation vides pour hériter des valeurs globales.', + addInterval: 'Ajouter un intervalle', + columns: { + order: 'Ordre', + label: 'Libellé', + minutes: 'Minutes', + window: 'Fenêtre (s)', + minTie: 'Égalité min %', + maxTie: 'Égalité max %', + pool: 'Pool', + payout: 'Gain', + initialBatch: 'Lot initial', + status: 'Statut', + actions: 'Actions', + }, + default: 'Par défaut', + active: 'Actif', + disabled: 'Désactivé', + noIntervals: 'Aucun intervalle configuré', + editTitle: 'Modifier l’intervalle', + newTitle: 'Nouvel intervalle', + intervalMinutes: 'Intervalle (minutes)', + displayLabel: 'Libellé affiché', + sortOrder: 'Ordre d’affichage', + windowOverride: 'Dérogation fenêtre de prédiction (secondes, optionnel)', + windowOverrideHint: 'Max {{max}} pour {{minutes}} min — laisser vide pour la valeur globale', + minTieOverride: 'Dérogation tolérance égalité min (%)', + minTieOverrideHint: 'Laisser vide pour hériter de la valeur globale', + maxTieOverride: 'Dérogation tolérance égalité max (%)', + maxTieOverrideHint: 'Neutre si le plus grand pool ≥ ce % — vide hérite du global', + minToleranceRule: 'Règle tolérance min', + maxToleranceRule: 'Règle tolérance max', + inheritGlobal: 'Hériter du global', + enabled: 'Activé', + poolMultiplierOverride: 'Dérogation multiplicateur de pool', + poolMultiplierOverrideHint: 'Poids dans les pools Long/Short — laisser vide pour hériter du global', + payoutMultiplierOverride: 'Dérogation multiplicateur de gain', + payoutMultiplierOverrideHint: 'Gain pour prédictions correctes — laisser vide pour hériter du global', + basePriceOverride: 'Dérogation prix de base', + chartBatchSize: 'Taille du lot initial du graphique', + chartBatchSizeHint: + 'Bougies chargées à l’ouverture (20–200). Faites défiler le graphique vers la gauche pour charger l’historique par lots.', + defaultForNewPlayers: 'Intervalle par défaut pour les nouveaux joueurs', + intervalUpdated: 'Intervalle mis à jour', + intervalCreated: 'Intervalle créé', + intervalDeleted: 'Intervalle supprimé', + windowMinError: 'La fenêtre de prédiction doit être d’au moins 5 secondes', + windowMaxError: 'La fenêtre de prédiction ne peut pas dépasser {{max}} pour un intervalle de {{minutes}} minutes', + deleteFailed: 'Échec de la suppression', + }, + multiLevels: { + title: 'Niveaux multi-bougies', + intro: + 'Configurez les niveaux à partir de 2. Le multiplicateur de pool pondère les mises dans les pools Long/Short à la dernière bougie ; le multiplicateur de gain s’applique uniquement au gain du joueur lorsque toute la séquence est correcte.', + columns: { + level: 'Niveau', + candles: 'Bougies', + enabled: 'Activé', + poolMultiplier: 'Multiplicateur pool', + payoutMultiplier: 'Multiplicateur gain', + sort: 'Ordre', + }, + saved: 'Niveaux multi-bougies enregistrés.', + saveFailed: 'Échec de l’enregistrement', + saveLevels: 'Enregistrer les niveaux', + }, + }, + }, + treasury: { + title: 'Trésorerie', + refresh: 'Actualiser la trésorerie', + loadError: 'Impossible de charger la vue d’ensemble trésorerie.', + sweepsEnabled: 'Sweeps activés', + sweepsDisabled: 'Sweeps désactivés', + withdrawalsOn: 'Retraits activés', + withdrawalsOff: 'Retraits désactivés', + pendingSweeps: '{{count}} sweep(s) en attente', + failedSweeps: '{{count}} sweep(s) échoué(s)', + sweepDisabledHint: + 'Définissez SWEEP_ENABLED=true dans le .env backend pour déplacer automatiquement les dépôts vers le cold storage.', + coldOnChain: 'Cold : {{address}} · on-chain {{balance}}', + hotOnChain: 'Hot : {{address}} · on-chain {{balance}}', + coldAddress: 'Adresse cold wallet', + label: 'Libellé', + saveCold: 'Enregistrer cold', + fundingTitle: 'Alimentation Cold → Hot', + fundingSubtitle: + 'Créez une demande, transférez manuellement depuis le cold wallet, puis confirmez avec l’ID de transaction blockchain.', + walletTypeId: 'ID type wallet (USDT_TRC20)', + amountRaw: 'Montant (unités brutes)', + notes: 'Notes', + requestFunding: 'Demander un financement (approbation)', + amount: 'Montant', + fromTo: 'De → Vers', + confirmTx: 'Confirmer tx', + noPendingFunding: 'Aucune demande de financement en attente.', + sweepsTitle: 'Sweeps de dépôts', + submitSweeps: 'Soumettre les sweeps pour approbation', + status: 'Statut', + toCold: 'Vers cold', + tx: 'Tx', + confirmDialogTitle: 'Confirmer le transfert cold → hot', + blockchainTxId: 'ID transaction blockchain', + sweepPending: 'Demande de sweep soumise — en attente d’approbation super-admin', + fundingPending: 'Demande de financement soumise — en attente d’approbation super-admin', + }, + security: { + title: 'Sécurité', + refresh: 'Actualiser les données sécurité', + actions: { + runIntegrity: 'Lancer le contrôle d’intégrité', + processTamper: 'Traiter les événements DB', + dismissFalse: 'Rejeter les fausses alertes', + }, + integrity: { + passed: 'Contrôle d’intégrité réussi — aucun problème détecté.', + issuesFound: + '{{count}} problème(s) détecté(s). Les utilisateurs concernés ont été placés sous surveillance sécurité.', + tamperNone: 'Contrôle DB — aucune modification non autorisée en attente.', + tamperProcessed: + '{{count}} modification(s) DB non autorisée(s) traitée(s) et alertes créées.', + }, + tabs: { + alerts: 'Alertes ({{count}})', + notifications: 'Notifications', + ledgerCredits: 'Crédits grand livre', + dbAudit: 'Audit DB ({{count}})', + alertEmails: 'E-mails d’alerte', + }, + alerts: { + open: 'Ouvertes', + all: 'Toutes', + loadError: 'Impossible de charger les alertes.', + severity: 'Gravité', + title: 'Titre', + type: 'Type', + user: 'Utilisateur', + status: 'Statut', + created: 'Créé le', + resolve: 'Résoudre', + empty: 'Aucune alerte', + }, + notifications: { + title: 'Notifications in-app', + markAllRead: 'Tout marquer comme lu', + markRead: 'Marquer lu', + empty: 'Aucune notification', + }, + credits: { + title: 'Crédits grand livre approuvés', + grant: 'Accorder un crédit', + user: 'Utilisateur', + amount: 'Montant', + approvedBy: 'Approuvé par', + date: 'Date', + empty: 'Aucun crédit pour l’instant', + bonusWallet: 'Bonus (wallet bonus)', + mainWallet: 'Ajustement admin (wallet principal)', + bonusHint: 'Crédite le wallet bonus de l’utilisateur (account_kind = bonus).', + mainHint: + 'Crédite le wallet principal (account_kind = main) — utilisé pour le jeu et les retraits.', + dialogTitle: 'Accorder un crédit grand livre', + userId: 'ID utilisateur (UUID)', + wallet: 'Wallet', + amountDisplay: 'Montant (unités affichées)', + reason: 'Motif (obligatoire, audité)', + invalidAmount: 'Saisissez un montant supérieur à zéro', + failed: 'Échec du crédit', + pendingApproval: 'Demande de crédit soumise — en attente d’approbation super-admin.', + approve: 'Approuver le crédit', + successDefault: 'Crédit accordé.', + }, + dbAudit: { + title: 'Modifications directes de la base (piste d’audit)', + subtitle: + 'Modifications détectées en dehors de la couche applicative (psql, pgAdmin, scripts, etc.).', + exportCsv: 'Exporter CSV', + loadError: 'Impossible de charger les événements d’audit DB.', + severity: 'Gravité', + table: 'Table', + op: 'Op', + columns: 'Colonnes', + source: 'Source', + processed: 'Traité', + when: 'Quand', + processedYes: 'Oui', + processedPending: 'En attente', + empty: 'Aucune modification DB directe enregistrée', + }, + alertEmails: { + title: 'E-mails d’alerte sécurité', + subtitle: 'Un e-mail par ligne. Chiffré au repos dans la base de données.', + placeholder: 'admin@example.com', + save: 'Enregistrer les e-mails', + saved: 'Paramètres enregistrés', + }, + resolve: { + title: 'Résoudre l’alerte', + note: 'Note de résolution', + reactivate: 'Réactiver les retraits et lever la suspension sécurité pour l’utilisateur', + resolving: 'Résolution…', + resolve: 'Résoudre', + failed: 'Échec de la résolution de l’alerte', + success: 'Alerte résolue.', + successReactivate: 'Alerte résolue et suspension sécurité levée pour l’utilisateur.', + }, + }, + settings: { + title: 'Paramètres', + subtitle: + 'Politique de mot de passe, sécurité, limites de débit, retraits et réglage moteur Candle Predict.', + loading: 'Chargement des paramètres…', + loadError: 'Impossible de charger les paramètres.', + noSettings: 'Aucun paramètre chargé.', + saveFailed: 'Échec de l’enregistrement des paramètres', + retry: 'Réessayer', + save: 'Enregistrer les paramètres', + saving: 'Enregistrement…', + saved: 'Paramètres enregistrés', + reset: 'Réinitialiser aux valeurs serveur', + sections: { + passwordPolicy: { + title: 'Politique de mot de passe', + subtitle: 'Imposer des règles de complexité pour tous les nouveaux mots de passe.', + minLength: 'Longueur minimale', + uppercase: 'Majuscule', + lowercase: 'Minuscule', + number: 'Chiffre', + special: 'Caractère spécial', + }, + emailVerification: { + title: 'Vérification e-mail', + subtitle: 'Exiger un e-mail confirmé avant que les utilisateurs puissent se connecter.', + blockLogin: 'Bloquer la connexion tant que l’e-mail n’est pas vérifié', + }, + tokenExpiration: { + title: 'Expiration des jetons', + subtitle: 'Modifier l’expiration sans redéployer le backend.', + accessToken: 'Expiration jeton d’accès', + refreshToken: 'Expiration jeton de rafraîchissement', + examplesShort: 'Exemples : 15m, 1h', + examplesLong: 'Exemples : 7d, 30d', + }, + withdrawals: { + title: 'Retraits & sécurité', + subtitle: 'Interrupteur d’urgence et limites de retrait (appliqués immédiatement après enregistrement).', + allowOnChain: 'Autoriser les retraits on-chain', + dailyLimit: 'Limite de retrait quotidienne (USD)', + largeThreshold: 'Seuil de gros retrait (USD)', + networkFee: 'Frais réseau de retrait (USDT)', + networkFeeHelper: + 'Déduit du solde USDT de l’utilisateur par retrait (couvre le gas TRON on-chain).', + }, + rateLimiting: { + title: 'Limitation de débit', + subtitle: + 'Limitation API et connexion. Les max s’appliquent en secondes ; la fenêtre nécessite un redémarrage.', + apiWindow: 'Fenêtre API (ms)', + restartHint: 'Redémarrer le serveur pour appliquer', + apiMax: 'Requêtes API max / fenêtre', + loginMax: 'Tentatives de connexion max / 15 min', + }, + candlePredict: { + title: 'Moteur Candle Predict', + subtitle: 'Intervalle de tick et rythme de backfill (backfill plus bas = moins de charge DB à l’échelle).', + engineTick: 'Tick moteur (ms)', + engineTickHelper: 'Fréquence de règlement des rounds', + backfillInterval: 'Intervalle backfill (ms)', + backfillIntervalHelper: 'Délai minimum entre les exécutions de backfill', + backfillMax: 'Backfill max par tick', + backfillMaxHelper: 'Bougies remplies par intervalle et par exécution', + backfillSeed: 'Backfill seed max', + backfillSeedHelper: 'Bougies historiques au premier lancement', + }, + }, + }, + reports: { + title: 'Rapports', + subtitle: + 'Données détaillées, tableaux paginés, filtres avancés et exports. Le dashboard affiche uniquement les synthèses.', + searchPlaceholder: 'Rechercher un rapport (titre, description, catégorie…)', + loading: 'Chargement du catalogue…', + noResults: 'Aucun rapport ne correspond à « {{query}} ».', + detail: { + back: 'Retour', + filters: 'Filtres', + search: 'Recherche', + from: 'Du', + to: 'Au', + apply: 'Appliquer', + favoriteNamePlaceholder: 'Nom du filtre favori', + saveFilter: 'Sauver filtre', + exportExcelFilters: 'Excel (filtres)', + exportCsvFilters: 'CSV (filtres)', + exportPdfServer: 'PDF (serveur)', + bulkActionsTitle: 'Actions de masse', + exportSelectionExcel: 'Exporter sélection (Excel)', + csv: 'CSV', + pdf: 'PDF', + deselectAll: 'Tout désélectionner', + selected: '{{count}} sélectionné(s)', + selectedRows: '{{count}} ligne(s)', + loadError: 'Impossible de charger ce rapport.', + timeoutError: + 'La requête a pris trop de temps (volume de données élevé). Réduisez la période ou affinez les filtres.', + bulkFailed: 'Action de masse échouée.', + actionFailed: 'Action échouée.', + exportFailed: 'Export échoué.', + exportDone: 'Export terminé ({{count}} lignes)', + exportInProgress: 'Export serveur en cours… {{count}} ligne(s) traitées', + summaryTotal: 'Montant total : {{amount}} USDT', + summaryCount: "Nombre d'opérations : {{count}}", + summaryUsers: 'Utilisateurs distincts : {{count}}', + reasonOptional: 'Motif (optionnel)', + confirm: 'Confirmer', + bulkResult: '{{succeeded}} réussi(s){{suffix}}', + bulkFailedSuffix: ' · {{failed}} échec(s)', + bulkActions: { + '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', + }, + bulkConfirm: { + 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 ?', + }, + }, + }, + countries: { + title: 'Pays', + sync: 'Synchroniser depuis l’API', + description: + 'Catalogue synchronisé depuis ISO 3166 par défaut, ou depuis REST Countries v5 lorsque REST_COUNTRIES_API_KEY est configuré sur le backend. Désactivez l’inscription pour certains pays de résidence.', + descriptionBeforeLink: + 'Catalogue synchronisé depuis ISO 3166 par défaut, ou depuis', + descriptionAfterLink: + 'lorsque REST_COUNTRIES_API_KEY est configuré sur le backend. Désactivez l’inscription pour certains pays de résidence.', + syncSuccess: + '{{synced}} pays synchronisé(s){{source}}. Total en base : {{total}}.', + syncSourceRest: ' depuis REST Countries', + syncSourceIso: ' depuis ISO 3166', + syncFailed: 'Échec de la synchronisation des pays', + loadError: 'Impossible de charger les pays depuis le serveur.', + emptyDb: 'Aucun pays en base. Cliquez sur « Synchroniser depuis l’API » pour charger le catalogue.', + search: 'Rechercher un pays', + blockedCount: '{{count}} bloqué(s)', + blockedOnly: 'Bloqués uniquement', + code: 'Code', + name: 'Nom', + registration: 'Inscription', + noMatch: 'Aucun pays ne correspond à vos filtres', + }, + testWallet: { + title: 'Wallet de test', + enabled: 'Activé', + disabled: 'Désactivé', + subtitle: + 'Configurez les crédits fictifs pour que les nouveaux utilisateurs s’entraînent avant d’utiliser des fonds réels.', + loading: 'Chargement des paramètres wallet de test…', + allowRequests: 'Autoriser les demandes de crédits de test', + creditAmount: 'Montant crédité par demande (USDT)', + creditHelper: 'Montant crédité automatiquement lors d’une demande de fonds de test', + maxRequests: 'Demandes max par utilisateur', + maxRequestsHelper: '0 = illimité', + cooldown: 'Délai entre demandes (heures)', + cooldownHelper: '0 = pas d’attente', + saveFailed: 'Échec de l’enregistrement', + saved: 'Paramètres enregistrés.', + save: 'Enregistrer les paramètres', + saving: 'Enregistrement…', + history: 'Historique des crédits', + date: 'Date', + user: 'Utilisateur', + amount: 'Montant', + noHistory: 'Aucun crédit de test accordé pour l’instant.', + }, + network: { + title: 'Réseau & environnement', + subtitle: + 'Configuration serveur réservée aux administrateurs : réseau blockchain, retraits et environnement d’exécution.', + }, + referralAdmin: { + title: 'Programme de parrainage', + fraudDashboard: 'Tableau de bord fraude', + loadError: 'Impossible de charger la configuration parrainage.', + fundPending: 'Alimentation du pool bonus soumise — en attente d’approbation super-admin', + programSettings: 'Paramètres du programme', + programEnabled: 'Programme activé', + bonusWithdrawable: 'Bonus retirable (transfert bonus → principal)', + referrerVerified: 'Le parrain doit avoir un e-mail vérifié', + referrerDeposited: 'Le parrain doit avoir déposé', + referredVerified: 'Le filleul doit avoir un e-mail vérifié (avant paiement)', + commissionHold: 'Délai de rétention commission (jours)', + commissionHoldHelper: 'Délai après le premier dépôt avant paiement de la commission', + minPredictions: 'Prédictions argent réel min (filleul)', + maxPendingDays: 'Jours max en attente', + maxPendingHelper: 'Expirer les commissions impayées si l’éligibilité n’est toujours pas atteinte', + commissionModes: 'Modes de commission', + depositCommissions: 'Commissions sur dépôt (premier dépôt des filleuls)', + withdrawalCommissions: 'Commissions sur retrait (gains prédictions compte principal uniquement)', + slackAlerts: 'Alertes Slack', + slackEnabled: 'Alertes Slack activées (canal parrainage : plafonds, clawbacks, revue Sybil)', + slackHint: + 'Configurez SLACK_REFERRAL_WEBHOOK_URL pour #referral-fraud et SLACK_SECURITY_WEBHOOK_URL pour #security. SLACK_WEBHOOK_URL sert de repli pour les deux.', + sybilSection: 'Anti-fraude Sybil (P2)', + sybilEnabled: 'Détection Sybil activée', + sybilReview: 'Seuil revue Sybil (score)', + sybilReviewHelper: 'Score ≥ seuil → file de revue manuelle', + sybilBlock: 'Seuil blocage Sybil (score)', + sybilBlockHelper: 'Score ≥ seuil → blocage auto (pas de commission)', + maxAmountMonth: 'Montant commission max / parrain / mois (brut)', + maxAmountHelper: '500000000 = 500 USDT (6 décimales). 0 = illimité.', + maxCountMonth: 'Commissions max / parrain / mois (nombre)', + unlimitedHelper: '0 = illimité', + maxReferralsDay: 'Parrainages max / parrain / 24h', + defaultReferrer: 'ID parrain par défaut (UUID admin)', + defaultReferrerHelper: 'Utilisé quand aucun code parrain n’est fourni à l’inscription', + minFirstDeposit: 'Premier dépôt min (unités brutes)', + commissionWalletType: 'ID type wallet commission', + commissionWalletHelper: '2 = USDT_TRC20 par défaut', + saveSettings: 'Enregistrer les paramètres', + levelsTitle: 'Niveaux de commission', + level: 'Niveau', + percentDeposit: '% du premier dépôt', + maxAmountMonthCol: 'Montant max / mois (brut)', + maxCountMonthCol: 'Nombre max / mois', + active: 'Actif', + global: 'Global', + edit: 'Modifier', + delete: 'Supprimer', + levelNumber: 'Niveau #', + commissionPercent: 'Commission %', + maxAmountField: 'Montant max / mois (brut, 0=global)', + maxCountField: 'Nombre max / mois (0=global)', + addUpdateLevel: 'Ajouter / mettre à jour le niveau', + bonusPoolTitle: 'Pool bonus (trésorerie pour paiements parrainage)', + walletTypeBalance: 'Type wallet {{id}} : {{balance}} unités brutes', + walletTypeId: 'ID type wallet', + amountDisplay: 'Montant (affiché)', + fundPool: 'Alimenter le pool', + reviewTitle: 'File de revue manuelle', + reviewLoadError: 'Impossible de charger la file de revue.', + noReview: 'Aucune commission en attente de revue.', + score: 'Score', + signals: 'Signaux', + beneficiary: 'Bénéficiaire', + referred: 'Filleul', + approve: 'Approuver', + reject: 'Rejeter', + rejectReason: 'Motif de rejet', + statsTitle: 'Statistiques', + referredUsers: 'Utilisateurs parrainés : {{count}}', + commissionsPaid: 'Commissions payées : {{raw}} brut', + payoutEvents: 'Événements de paiement : {{count}}', + pending: 'En attente : {{count}} ({{raw}} brut)', + review: 'Revue : {{count}} ({{raw}} brut)', + byCountry: 'Inscriptions par pays de résidence', + byNationality: 'Inscriptions par nationalité', + topReferrers: 'Meilleurs parrains', + directReferrals: 'Parrainages directs', + totalEarned: 'Total gagné', + code: 'Code', + commission: 'Commission', + }, + referralFraud: { + title: 'Tableau de bord fraude parrainage', + programSettings: 'Paramètres du programme', + loadError: 'Impossible de charger le tableau de bord fraude.', + rawAmount: '{{amount}} brut', + stats: { + reviewQueue: 'File de revue', + pending: 'En attente', + paidThisMonth: 'Payé ce mois', + clawedBackMonth: 'Récupéré (mois)', + sybilBlockedMonth: 'Bloqué Sybil (mois)', + capBlockedMonth: 'Bloqué plafond (mois)', + monthlyCaps: 'Plafonds mensuels (par parrain)', + commissionsCount: '{{count}} commissions', + maxRawMonth: 'max {{amount}} brut / mois', + }, + reviewQueue: { + title: 'File de revue', + empty: 'Aucune commission en attente de revue.', + amount: 'Montant', + rejectReason: 'Rejeté depuis le tableau de bord fraude', + }, + highRisk: { + title: 'Parrains à haut risque', + avgSybil: 'Sybil moy.', + review: 'Revue', + inactive: 'Inactifs', + monthRaw: 'Mois brut', + }, + sybilSignals: { + title: 'Signaux Sybil (ce mois)', + empty: 'Aucun signal enregistré ce mois.', + }, + clawback: { + title: 'Récupération (commissions payées)', + reasonAction: 'Motif + action', + reasonPlaceholder: 'Motif de récupération', + action: 'Récupérer', + }, + recentClawbacks: { + title: 'Récupérations récentes', + from: 'Du', + to: 'Au', + exportCsv: 'Exporter CSV', + exportFailed: 'Export échoué', + empty: 'Aucune pour l’instant.', + line: '{{amount}} brut — {{reason}}', + }, + recentBlocks: { + title: 'Blocages récents (Sybil / plafond)', + empty: 'Aucun enregistré.', + }, + }, + faqAdmin: { + title: 'Gestion FAQ', + subtitle: 'Créez et organisez les questions fréquentes affichées aux utilisateurs.', + refresh: 'Actualiser', + tabEntries: 'Questions', + tabCategories: 'Catégories', + searchPlaceholder: 'Rechercher…', + category: 'Catégorie', + allCategories: 'Toutes', + status: 'Statut', + allStatuses: 'Tous', + activeEntries: 'Actives', + inactiveEntries: 'Inactives', + newEntry: 'Nouvelle FAQ', + newCategory: 'Nouvelle catégorie', + loadError: 'Erreur de chargement', + noEntries: 'Aucune FAQ trouvée.', + deleteEntryConfirm: 'Supprimer cette FAQ ?', + deleteCategoryConfirm: 'Supprimer cette catégorie ? Les FAQ associées doivent être déplacées.', + entryActive: 'Active', + entryInactive: 'Inactive', + order: 'Ordre : {{order}}', + views: 'Vues : {{views}} · Utile : {{yes}} / {{no}}', + updatedBy: ' · Modifié par {{name}}', + slug: 'Slug : {{slug}} · Ordre : {{order}}', + categoryInactive: ' · Inactive', + entryDialogEdit: 'Modifier la FAQ', + entryDialogNew: 'Nouvelle FAQ', + question: 'Question', + answer: 'Réponse', + sortOrder: 'Ordre d’affichage', + categoryDialogEdit: 'Modifier la catégorie', + categoryDialogNew: 'Nouvelle catégorie', + name: 'Nom', + slugOptional: 'Slug (optionnel)', + slugAuto: 'Généré automatiquement si vide', + orderField: 'Ordre', + categoryRequired: 'Catégorie et question requises', + nameRequired: 'Nom requis', + }, + supportAdmin: { + title: 'Centre d’assistance', + read: ' · Lu', + visitorTyping: 'Le visiteur écrit…', + newMessageTitle: 'Nouveau message support', + newMessageBody: 'Message reçu', + searchPlaceholder: 'Rechercher…', + status: 'Statut', + allStatuses: 'Tous', + anonymousVisitor: 'Visiteur anonyme', + userPrefix: 'Utilisateur {{id}}…', + noConversations: 'Aucune conversation', + selectConversation: 'Sélectionnez une conversation', + assignSelf: 'M’assigner', + markResolved: 'Résolu', + replyPlaceholder: 'Répondre…', + contextTitle: 'Contexte', + anonymousAlert: 'Conversation anonyme — aucun compte associé.', + name: 'Nom :', + id: 'ID :', + email: 'E-mail :', + role: 'Rôle :', + accountStatus: 'Statut :', + accountActive: 'Actif', + accountDisabled: 'Désactivé', + emailVerified: 'E-mail vérifié :', + registeredOn: 'Inscrit le {{date}}', + conversationCreated: 'Conversation créée le {{date}}', + statuses: { + open: 'Ouverte', + pending: 'En attente', + resolved: 'Résolue', + closed: 'Fermée', + }, + visitor: 'Visiteur', + user: 'Utilisateur', + }, + dashboard: { + title: 'Dashboard administrateur', + subtitle: 'Vue analytique de la plateforme — {{period}}', + selectedPeriod: 'période sélectionnée', + refresh: 'Actualiser le dashboard', + exportAction: 'Exporter', + period: 'Période', + from: 'Du', + to: 'Au', + game: 'Jeu', + presets: { + today: 'Aujourd’hui', + yesterday: 'Hier', + this_week: 'Cette semaine', + this_month: 'Mois en cours', + last_30_days: '30 derniers jours', + last_90_days: '90 derniers jours', + this_year: 'Cette année', + custom: 'Intervalle personnalisé', + }, + games: { + all: 'Tous les jeux', + candlePredict: 'Candle Predict', + }, + reportDetail: 'Voir le rapport détaillé', + allReports: 'Tous les rapports', + securityCenter: 'Centre sécurité', + enabled: 'ACTIVÉS', + disabled: 'DÉSACTIVÉS', + unusual: 'Inhabituelle', + normal: 'Normale', + noRecentAlerts: 'Aucune alerte récente sur la période.', + recentAlertsMax: 'Alertes récentes (max {{count}})', + updating: 'Mise à jour des données…', + customRangePending: + 'Sélectionnez les dates « Du » et « Au » pour charger les analytics de l’intervalle personnalisé.', + customRangeInvalid: 'La date « Du » doit être antérieure ou égale à la date « Au ».', + loadError: + 'Impossible de charger les analytics. Vérifiez que le backend est démarré et que vous êtes administrateur.', + materializedViews: + '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).', + cached: + 'Données servies depuis le cache ({{time}}). Utilisez « Actualiser » pour forcer un recalcul complet.', + cachedRecent: 'récentes', + degraded: + 'Certaines sections n’ont pas pu être calculées à temps (volume de données élevé). Les indicateurs affichés peuvent être partiels.', + usersCount: '{{count}} utilisateurs', + played: 'Joué : {{amount}} USDT', + minSuffix: '{{n}} min', + hourSuffix: '{{h}}h', + sectionLabels: { + kpis: 'Indicateurs clés', + financial: 'Analyse financière', + games: 'Analyse des jeux', + users: 'Analyse utilisateurs', + geography: 'Analyse géographique', + demographics: 'Démographie', + charts: 'Graphiques avancés', + alerts: 'Alertes & surveillance', + }, + personalize: { + button: 'Personnaliser', + hint: 'Masquer/afficher des sections · vues sauvegardées (local)', + dialogTitle: 'Personnalisation du dashboard', + visibleSections: 'Sections visibles', + saveCurrentView: 'Sauvegarder la vue actuelle', + viewNamePlaceholder: 'Nom de la vue', + save: 'Sauver', + savedViews: 'Vues enregistrées', + emailReportsSoon: 'Rapports par e-mail (bientôt)', + emailHelper: 'La programmation automatique de rapports sera disponible dans une prochaine version.', + emailPlaceholder: 'admin@example.com', + close: 'Fermer', + }, + export: { + sheetName: 'Dashboard', + categories: { + users: 'Utilisateurs', + deposits: 'Dépôts', + withdrawals: 'Retraits', + games: 'Jeux', + financial: 'Financier', + alerts: 'Alertes', + }, + indicators: { + totalUsers: 'Total inscrits', + newUsers: 'Nouveaux', + depositTotalRaw: 'Montant total (raw)', + depositTotalUsdt: 'Montant total USDT', + withdrawalTotalRaw: 'Montant total (raw)', + predictions: 'Prédictions', + platformNetPnl: 'Net P/L plateforme (réel)', + testNetPnl: 'Net P/L test', + openAlerts: 'Ouvertes', + }, + }, + tables: { + segment: 'Segment', + users: 'Utilisateurs', + predictions: 'Prédictions', + stake: 'Misé', + netPnl: 'Net P/L', + winRate: 'Taux réussite', + direction: 'Direction', + interval: 'Intervalle', + participants: 'Participants', + housePnl: 'P/L maison', + user: 'Utilisateur', + date: 'Date', + country: 'Pays', + deposits: 'Dépôts', + withdrawals: 'Retraits', + active: 'Actifs', + type: 'Type', + severity: 'Sévérité', + status: 'Statut', + gender: 'Sexe', + ageBucket: 'Tranche', + }, + walletKind: { + main: 'Principal', + bonus: 'Bonus', + test: 'Test', + }, + gender: { + male: 'Masculin', + female: 'Féminin', + other: 'Autre', + unknown: 'Non renseigné', + }, + ageBucket: { + unknown: 'Inconnu', + under_18: 'Moins de 18 ans', + '18_24': '18–24', + '25_34': '25–34', + '35_44': '35–44', + '45_54': '45–54', + '55_plus': '55+', + }, + treasury: { + loadError: + 'Impossible de charger la trésorerie on-chain (hot/cold). Consultez la page Treasury pour le détail.', + hotWallet: 'Hot wallet (on-chain)', + coldWallet: 'Cold wallet (on-chain)', + sweepsInProgress: 'Deposit sweeps en cours', + operations_one: '{{count}} opération · pending / gas / broadcast', + operations_other: '{{count}} opérations · pending / gas / broadcast', + noActiveSweep: 'Aucun sweep actif', + }, + charts: { + financialFlow: 'Flux financiers — dépôts vs retraits', + deposits: 'Dépôts', + withdrawals: 'Retraits', + }, + sections: { + kpi: { + title: 'Indicateurs clés', + subtitle: 'Vue synthétique — cliquez sur une carte pour le rapport détaillé', + groups: { + users: 'Utilisateurs', + deposits: 'Dépôts', + withdrawalsBonus: 'Retraits & bonus', + }, + cards: { + totalUsers: 'Total inscrits', + totalUsersSub: 'Tous les comptes', + newUsers: 'Nouveaux (période)', + newUsersSub: 'Inscriptions sur la période', + activeUsers: 'Actifs (période)', + inactiveUsers: 'Inactifs', + signupGrowth: 'Croissance inscriptions', + onlineGame: 'Sur le jeu', + onlineGameSub: 'WebSocket Candle Predict', + onlineApp: 'Connectés (app)', + onlineAppSub: 'Session active, sans prédiction requise', + admins: 'Administrateurs', + depositTotal: 'Montant total', + depositCount: 'Nombre de dépôts', + depositUsers: 'Utilisateurs déposants', + depositAvg: 'Dépôt moyen', + withdrawalTotal: 'Retraits (total)', + withdrawalCount: 'Retraits (nombre)', + bonusesGranted: 'Bonus accordés', + adminAdjustments: 'Ajustements admin', + platformWithdrawals: 'Retraits plateforme', + }, + }, + financial: { + title: 'Analyse financière', + subtitle: 'Soldes actuels et tendances sur la période', + onChainTreasury: 'Trésorerie on-chain', + balanceDistribution: 'Répartition des soldes', + netPnlTrend: 'Évolution du Net P/L (réel)', + bonusTrend: 'Évolution des bonus', + cards: { + mainWallets: 'Wallets principaux', + bonusWallets: 'Wallets bonus', + testWallets: 'Wallets test', + cumulativeBalance: 'Solde cumulé', + platformNetPnl: 'Net P/L plateforme', + platformNetPnlSub: 'Wallets réels (hors test)', + testNetPnl: 'Net P/L test', + testNetPnlSub: 'Wallet de test uniquement', + depositWithdrawalRatio: 'Ratio Dépôts / Retraits', + bonusCost: 'Coût bonus', + adjustmentCost: 'Coût ajustements', + }, + }, + game: { + title: 'Analyse des jeux', + subtitle: 'Synthèse par segment (vue fixe)', + distributionsFixed: 'Répartitions (taille fixe)', + cards: { + participants: 'Participants', + predictions: 'Prédictions', + avgPerPlayer: 'Moy. / joueur', + totalStaked: 'Total misé', + testWalletUsers: 'Wallet test — utilisateurs', + testPnl: 'P/L test', + }, + segments: { + manual: 'Prédictions normales', + auto: 'Auto Prediction', + multiCandle: 'Multi-candles', + realManual: 'Réel + manuel', + realAuto: 'Réel + auto', + realMulti: 'Réel + multi-candles', + testManual: 'Test + manuel', + testAuto: 'Test + auto', + testMulti: 'Test + multi-candles', + }, + shortVsLong: 'Short vs Long', + byInterval: 'Par intervalle de jeu', + long: 'Long', + short: 'Short', + }, + users: { + title: 'Utilisateurs & sécurité', + subtitle: 'Compteurs et activité récente', + securityCompliance: 'Sécurité & conformité', + activity: 'Activité', + recentLogins: 'Dernières connexions (top 5)', + security: { + emailVerified: 'E-mails vérifiés', + emailUnverified: 'E-mails non vérifiés', + totpEnabled: '2FA activé', + totpDisabled: 'Sans 2FA', + suspended: 'Suspendus', + disabled: 'Désactivés', + expired: 'Comptes expirés', + credentialsExpired: 'Credentials expirés', + underSurveillance: 'Sous enquête', + withdrawalsBlocked: 'Retraits bloqués', + }, + activityLabels: { + activeToday: 'Actifs aujourd’hui', + activeThisWeek: 'Actifs cette semaine', + activeThisMonth: 'Actifs ce mois', + inactivePeriod: 'Inactifs (période)', + }, + }, + geography: { + title: 'Géographie', + subtitle: 'Top 8 pays — vue fixe', + usersTop8: 'Utilisateurs (top 8)', + depositsTop8: 'Dépôts (top 8)', + summaryTop8: 'Synthèse top 8 pays', + }, + demographics: { + title: 'Démographie', + subtitle: 'Répartitions à taille fixe', + byGender: 'Par sexe', + byAge: 'Par tranche d’âge', + genderDetail: 'Détail par sexe', + ageDetail: 'Détail par tranche d’âge', + }, + charts: { + title: 'Tendances & répartitions', + subtitle: 'Graphiques sur la période (vues à taille fixe)', + signups: 'Inscriptions', + logins: 'Connexions', + verifiedEmails: 'E-mails vérifiés', + totpEnabled: '2FA activé', + manualAutoMulti: 'Manuel vs Auto vs Multi-candles', + manual: 'Manuel', + auto: 'Auto', + multiCandle: 'Multi-candles', + shortVsLong: 'Short vs Long', + stakeByInterval: 'Mises par intervalle', + loginHours: 'Heures de connexion (24h)', + betHours: 'Heures de jeu (24h)', + newVsReturning: 'Nouveaux vs récurrents', + newUsers: 'Nouveaux', + returningUsers: 'Récurrents', + }, + alerts: { + title: 'Alertes', + subtitle: 'Surveillance en temps réel', + openAlerts: 'Alertes ouvertes', + loginAlerts: 'Alertes connexion', + depositSpike: 'Hausse dépôts', + withdrawalSpike: 'Hausse retraits', + }, + }, + }, + }, + network: { + loading: 'Chargement de la configuration réseau…', + loadFailed: 'Impossible de charger `/health`.', + titleOk: 'État réseau OK (testnet)', + titleCheck: 'Vérifier la configuration réseau', + withdrawalsOn: 'Retraits : ACTIVÉS', + withdrawalsOff: 'Retraits : DÉSACTIVÉS', + tronNetwork: 'TRON : {{network}}', + envLabel: 'env : {{env}}', + }, +}; diff --git a/prediqo_web/src/shared/layout/AppShell.tsx b/prediqo_web/src/shared/layout/AppShell.tsx index b85a7c51..9e7f4b64 100644 --- a/prediqo_web/src/shared/layout/AppShell.tsx +++ b/prediqo_web/src/shared/layout/AppShell.tsx @@ -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: }, - { label: 'Wallet', to: '/wallet', icon: }, - { label: 'Referrals', to: '/referral', icon: }, - { label: 'Profile', to: '/profile', icon: }, - { label: 'FAQ', to: '/help/faq', icon: }, + { label: t('nav.home'), to: '/home', icon: }, + { label: t('nav.wallet'), to: '/wallet', icon: }, + { label: t('nav.referrals'), to: '/referral', icon: }, + { label: t('nav.profile'), to: '/profile', icon: }, + { label: t('nav.faq'), to: '/help/faq', icon: }, ...(isStaff ? [ { - label: 'Assistance', + label: t('nav.support'), to: '/admin/support', icon: ( @@ -122,16 +125,16 @@ export function AppShell() { ] : []), ...(canApproveFundOps - ? [{ label: 'Approvals', to: '/admin/approvals', icon: }] + ? [{ label: t('nav.approvals'), to: '/admin/approvals', icon: }] : []), ...(isAdmin ? [ - { label: 'Overview', to: '/dashboard', icon: }, - { label: 'Rapports', to: '/admin/reports', icon: }, - { label: 'Options', to: '/options', icon: }, - { label: 'Users', to: '/admin/users', icon: }, + { label: t('nav.overview'), to: '/dashboard', icon: }, + { label: t('nav.reports'), to: '/admin/reports', icon: }, + { label: t('nav.options'), to: '/options', icon: }, + { label: t('nav.users'), to: '/admin/users', icon: }, { - label: 'Security', + label: t('nav.security'), to: '/admin/security', icon: ( @@ -139,11 +142,11 @@ export function AppShell() { ), }, - { label: 'Settings', to: '/admin/settings', icon: }, + { label: t('nav.settings'), to: '/admin/settings', icon: }, ] : []), ] as const, - [isAdmin, isStaff, canApproveFundOps, unreadNotifications, unreadSupport] + [t, isAdmin, isStaff, canApproveFundOps, unreadNotifications, unreadSupport] ); const drawer = ( @@ -218,7 +221,7 @@ export function AppShell() { {!isMdUp && ( setMobileOpen(true)} sx={{ mr: 0.5 }} > @@ -243,16 +246,17 @@ export function AppShell() { useFlexGap sx={{ justifyContent: 'flex-end', minWidth: 0, alignItems: 'center', flexWrap: 'wrap' }} > + @@ -264,7 +268,7 @@ export function AppShell() { size="small" sx={{ borderColor: 'rgba(255,255,255,0.2)', px: 1.5 }} > - Logout + {t('common.logout')} diff --git a/prediqo_web/src/shared/network/NetworkBanner.tsx b/prediqo_web/src/shared/network/NetworkBanner.tsx index cab4e4df..78c16ae0 100644 --- a/prediqo_web/src/shared/network/NetworkBanner.tsx +++ b/prediqo_web/src/shared/network/NetworkBanner.tsx @@ -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 ( - - Chargement de la configuration réseau… + + {t('network.loading')} ); @@ -52,11 +42,11 @@ export function NetworkBanner() { sx={{ borderRadius: 2, '& .MuiAlert-message': { width: '100%' } }} action={ } > - Impossible de charger `/health`. + {t('network.loadFailed')} ); @@ -76,23 +66,25 @@ export function NetworkBanner() { }} action={ } > - État réseau {safe ? 'OK (testnet)' : 'Vérifier la configuration'} + {safe ? t('network.titleOk') : t('network.titleCheck')} - + - env : {env} + }} />