games_app/prediqo_web/src/shared/layout/AppShell.tsx

371 lines
13 KiB
TypeScript

/**
* Authenticated application layout for the Tloto web app.
* Renders responsive navigation, header actions, and nested route content.
*/
import {
AppBar,
Alert,
Box,
Button,
Chip,
Container,
Divider,
IconButton,
Stack,
Toolbar,
} from '@mui/material';
import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
import PeopleOutlineRoundedIcon from '@mui/icons-material/PeopleOutlineRounded';
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
import DashboardRoundedIcon from '@mui/icons-material/DashboardRounded';
import TuneRoundedIcon from '@mui/icons-material/TuneRounded';
import InsightsRoundedIcon from '@mui/icons-material/InsightsRounded';
import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded';
import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
import PersonRoundedIcon from '@mui/icons-material/PersonRounded';
import MenuRoundedIcon from '@mui/icons-material/MenuRounded';
import AssessmentRoundedIcon from '@mui/icons-material/AssessmentRounded';
import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded';
import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded';
import GavelRoundedIcon from '@mui/icons-material/GavelRounded';
import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded';
import { PrediqoLogo } from '../brand/PrediqoLogo';
import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded';
import Badge from '@mui/material/Badge';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import {
Drawer,
List,
ListItemButton,
ListItemIcon,
ListItemText,
useMediaQuery,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { Link as RouterLink, Outlet, useLocation } from 'react-router-dom';
import { prefetchRoute } from '../../app/router/routePrefetch';
import { useAuth } from '../auth/AuthContext';
import { ADMIN_PAGE_PERMISSIONS } from '../auth/permissions';
import { useAppPresenceHeartbeat } from '../hooks/useAppPresenceHeartbeat';
import { useEffect, useMemo, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { LanguageSwitcher } from '../i18n/LanguageSwitcher';
import { useSecuritySocket } from '../../features/security/hooks/useSecuritySocket';
import type { SecurityWsServerMessage } from '../../features/security/ws/protocol';
import { apiErrorMessage, isAdmin2faRequiredError } from '../utils/apiError';
/**
* Main shell with sidebar navigation, top app bar, and outlet for protected pages.
* Shows admin-only nav items when the current user has the admin role.
*
* @returns The responsive admin layout wrapping child routes.
*/
export function AppShell() {
const { t } = useTranslation();
const { logout, isAdmin, hasAdminPanel, isStaff, auth, canApproveFundOps, can } = useAuth();
const theme = useTheme();
const isMdUp = useMediaQuery(theme.breakpoints.up('md'));
const [mobileOpen, setMobileOpen] = useState(false);
const location = useLocation();
const qc = useQueryClient();
const role = auth.roles?.length
? auth.roles.join(', ')
: (auth.role ?? 'unknown');
const userShort = auth.userId ? `${auth.userId.slice(0, 8)}…` : '—';
useAppPresenceHeartbeat();
const onSecurityBadgeEvent = useCallback(
(msg: SecurityWsServerMessage) => {
if (msg.type === 'security.notification.new' || msg.type === 'security.alert.raised') {
void qc.invalidateQueries({ queryKey: ['admin-notifications-unread'] });
}
},
[qc]
);
const { connected: securityWsConnected } = useSecuritySocket({
enabled: hasAdminPanel || isAdmin,
onEvent: onSecurityBadgeEvent,
});
const notificationsQ = useQuery({
queryKey: ['admin-notifications-unread'],
queryFn: async () => {
const res = await api.get<{ unreadCount: number }>('/api/v1/admin/notifications', {
params: { limit: '1' },
});
return res.data.unreadCount;
},
enabled: hasAdminPanel || isAdmin,
refetchInterval: securityWsConnected ? 120_000 : 30_000,
});
const adminAccessProbeQ = useQuery({
queryKey: ['admin-access-probe'],
queryFn: async () => {
await api.get('/api/v1/admin/overview');
return true;
},
enabled: hasAdminPanel || isAdmin,
retry: false,
staleTime: 60_000,
});
const admin2faRequired = isAdmin2faRequiredError(adminAccessProbeQ.error);
const supportUnreadQ = useQuery({
queryKey: ['admin-support-unread'],
queryFn: async () => {
const res = await api.get<{ unreadCount: number }>('/api/v1/admin/support/unread');
return res.data.unreadCount;
},
enabled: isStaff,
refetchInterval: 15_000,
});
// No polling: refresh on mount/focus and whenever a mutation invalidates ['admin-fund-requests'].
const pendingApprovalsQ = useQuery({
queryKey: ['admin-fund-requests', 'pending-count'],
queryFn: async () => {
const res = await api.get<{ total: number }>('/api/v1/admin/fund-requests', {
params: { status: 'pending_approval', limit: 1 },
});
return res.data.total;
},
enabled: canApproveFundOps,
staleTime: 30_000,
});
const unreadNotifications = notificationsQ.data ?? 0;
const unreadSupport = supportUnreadQ.data ?? 0;
const pendingApprovals = pendingApprovalsQ.data ?? 0;
useEffect(() => {
if (!isMdUp) {
setMobileOpen(false);
}
}, [isMdUp]);
useEffect(() => {
setMobileOpen(false);
}, [location.pathname]);
const adminNavItems = useMemo(
() =>
[
{ label: t('nav.overview'), to: '/dashboard', icon: <DashboardRoundedIcon /> },
{ label: t('nav.reports'), to: '/admin/reports', icon: <AssessmentRoundedIcon /> },
{ label: t('nav.options'), to: '/options', icon: <TuneRoundedIcon /> },
{ label: t('nav.marketing'), to: '/admin/marketing', icon: <InsightsRoundedIcon /> },
{ label: t('nav.users'), to: '/admin/users', icon: <PeopleOutlineRoundedIcon /> },
{
label: t('nav.security'),
to: '/admin/security',
icon: (
<Badge color="error" badgeContent={unreadNotifications} invisible={unreadNotifications === 0}>
<SecurityRoundedIcon />
</Badge>
),
},
{ label: t('nav.settings'), to: '/admin/settings', icon: <SettingsOutlinedIcon /> },
].filter((item) => {
const perm = ADMIN_PAGE_PERMISSIONS[item.to];
return !perm || can(perm);
}),
[t, can, unreadNotifications]
);
const navItems = useMemo(
() =>
[
{ label: t('nav.home'), to: '/home', icon: <HomeRoundedIcon /> },
{ label: t('nav.wallet'), to: '/wallet', icon: <AccountBalanceWalletRoundedIcon /> },
{ label: t('nav.referrals'), to: '/referral', icon: <GroupAddRoundedIcon /> },
{ label: t('nav.profile'), to: '/profile', icon: <PersonRoundedIcon /> },
{ label: t('nav.faq'), to: '/help/faq', icon: <HelpOutlineRoundedIcon /> },
...(isStaff
? [
{
label: t('nav.support'),
to: '/admin/support',
icon: (
<Badge color="error" badgeContent={unreadSupport} invisible={unreadSupport === 0}>
<HeadsetMicRoundedIcon />
</Badge>
),
},
]
: []),
...(canApproveFundOps
? [
{
label: t('nav.approvals'),
to: '/admin/approvals',
icon: (
<Badge color="error" badgeContent={pendingApprovals} invisible={pendingApprovals === 0}>
<GavelRoundedIcon />
</Badge>
),
},
{
label: t('nav.approvalPolicies'),
to: '/admin/approval-policies',
icon: <RuleFolderRoundedIcon />,
},
]
: []),
...(hasAdminPanel || isAdmin ? adminNavItems : []),
] as const,
[t, isAdmin, hasAdminPanel, isStaff, canApproveFundOps, unreadSupport, pendingApprovals, adminNavItems]
);
const drawer = (
<Box sx={{ width: 280, px: 1.5, py: 2 }}>
<Box sx={{ px: 1.5, pb: 1.25 }}>
<PrediqoLogo size={32} />
</Box>
<Divider sx={{ opacity: 0.2, mb: 1 }} />
<List>
{navItems.map((it) => {
const selected = location.pathname === it.to || location.pathname.startsWith(it.to + '/');
return (
<ListItemButton
key={it.to}
component={RouterLink}
to={it.to}
selected={selected}
onClick={() => setMobileOpen(false)}
onMouseEnter={() => prefetchRoute(it.to)}
onFocus={() => prefetchRoute(it.to)}
onTouchStart={() => prefetchRoute(it.to)}
sx={{ borderRadius: 2, mb: 0.5 }}
>
<ListItemIcon sx={{ minWidth: 40 }}>{it.icon}</ListItemIcon>
<ListItemText primary={it.label} />
</ListItemButton>
);
})}
</List>
</Box>
);
return (
<Box sx={{ minHeight: '100vh', display: 'flex', minWidth: 0, overflowX: 'hidden' }}>
{/* Sidebar */}
<Box component="nav" sx={{ width: { xs: 0, md: 280 }, flexShrink: { md: 0 }, overflow: 'hidden' }}>
<Drawer
variant={isMdUp ? 'permanent' : 'temporary'}
open={isMdUp ? true : mobileOpen}
onClose={() => setMobileOpen(false)}
ModalProps={{ keepMounted: true }}
sx={{
'& .MuiDrawer-paper': {
width: 280,
boxSizing: 'border-box',
borderRight: '1px solid rgba(255,255,255,0.08)',
backgroundImage: 'none',
backgroundColor: 'rgba(18,23,36,0.92)',
backdropFilter: 'blur(12px)',
},
}}
>
{drawer}
</Drawer>
</Box>
{/* Main */}
<Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflowX: 'hidden' }}>
<AppBar
position="sticky"
color="transparent"
elevation={0}
sx={{
backdropFilter: 'blur(12px)',
borderBottom: '1px solid rgba(255,255,255,0.08)',
}}
>
<Container maxWidth="xl" sx={{ minWidth: 0 }}>
<Toolbar
disableGutters
sx={{
minHeight: 68,
gap: 1.5,
flexWrap: 'wrap',
py: 1,
}}
>
{!isMdUp && (
<IconButton
size="small"
aria-label={t('common.openNav')}
onClick={() => setMobileOpen(true)}
sx={{ mr: 0.5 }}
>
<MenuRoundedIcon fontSize="small" />
</IconButton>
)}
<Box
component={RouterLink}
to="/home"
sx={{ textDecoration: 'none', color: 'inherit', display: 'inline-flex' }}
>
<PrediqoLogo size={28} />
</Box>
<Box sx={{ flex: 1, minWidth: 16 }} />
<Stack
direction="row"
spacing={1}
useFlexGap
sx={{ justifyContent: 'flex-end', minWidth: 0, alignItems: 'center', flexWrap: 'wrap' }}
>
<LanguageSwitcher />
<Chip
size="small"
label={`${t('common.role')}: ${role}`}
color={isAdmin ? 'primary' : 'default'}
variant="outlined"
sx={{ display: { xs: 'none', sm: 'inline-flex' } }}
/>
<Chip
size="small"
label={`${t('common.user')}: ${userShort}`}
variant="outlined"
sx={{ display: { xs: 'none', md: 'inline-flex' } }}
/>
<Button
onClick={logout}
color="inherit"
variant="outlined"
size="small"
sx={{ borderColor: 'rgba(255,255,255,0.2)', px: 1.5 }}
>
{t('common.logout')}
</Button>
</Stack>
</Toolbar>
</Container>
</AppBar>
<Container maxWidth="xl" sx={{ py: { xs: 2, md: 3 }, px: { xs: 2, sm: 3 }, flex: 1, minWidth: 0 }}>
<Box sx={{ minWidth: 0 }}>
{admin2faRequired && (
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
{apiErrorMessage(adminAccessProbeQ.error, t('admin.admin2faRequired'))}{' '}
<Button component={RouterLink} to="/profile" size="small" sx={{ ml: 1 }}>
{t('admin.enable2faInProfile')}
</Button>
</Alert>
)}
<Outlet />
</Box>
</Container>
</Box>
</Box>
);
}