mams_frontend/src/features/dashboard/DashboardPage.tsx

475 lines
20 KiB
TypeScript

import { useEffect, useMemo, useState, type ReactElement } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Alert, Avatar, Box, Button, Chip, Paper, Skeleton, Stack, Typography, alpha, useTheme } from '@mui/material';
import { useAuth } from '../../auth/AuthContext';
import { isRtl, useLabel, useT, useUi } from '../../i18n';
import { PageHeader } from '../../components/PageHeader';
import { rpc } from '../../api/client';
import type { Option } from '../../api/entity';
import { DASHBOARDS } from '../../layout/nav';
import { buildDashboard, buildInfographic, type Block, type Item } from './model';
import { blockIcon, itemTint } from './icons';
import FullscreenOutlined from '@mui/icons-material/FullscreenOutlined';
import FullscreenExitOutlined from '@mui/icons-material/FullscreenExitOutlined';
import { useFullscreen } from '../../layout/FullscreenContext';
import { useNav } from '../../layout/NavContext';
import PauseOutlined from '@mui/icons-material/PauseOutlined';
import PlayArrowOutlined from '@mui/icons-material/PlayArrowOutlined';
import { FleetInfographic, PersonnelInfographic } from './infographics';
import { FleetDashboard, PersonnelDashboard, StakeholderDashboard, StakeholdersInfographic } from './dashboards';
interface Page {
kind: 'dashboard' | 'infographic';
name: string;
/** offers the industrial-city filter the old page had */
locations?: boolean;
}
const PAGES: Record<string, Page> = {
stakeholders: { kind: 'dashboard', name: 'STAKEHOLDER_DASHBOARD', locations: true },
fleet: { kind: 'dashboard', name: 'FLEET_DASHBOARD', locations: true },
personnel: { kind: 'dashboard', name: 'PERSONNEL_DASHBOARD', locations: true },
'fleet-infographic': { kind: 'infographic', name: 'FLEET_INFOGRAPH' },
'personnel-infographic': { kind: 'infographic', name: 'PERSONNEL_INFOGRAPH' },
'stakeholders-infographic': { kind: 'infographic', name: 'STAKEHOLDERS_INFOGRAPH' },
};
type CustomProps = { data: unknown; lab: (k: string) => string; rtl: boolean; nat: string };
const CUSTOM: Record<string, (p: CustomProps) => ReactElement> = {
stakeholders: StakeholderDashboard,
fleet: FleetDashboard,
personnel: PersonnelDashboard,
'stakeholders-infographic': StakeholdersInfographic,
'fleet-infographic': FleetInfographic,
'personnel-infographic': PersonnelInfographic,
};
/** How long each dashboard stays up in full screen. */
const ROTATE_MS = 5000;
const fmt = (n: number) => n.toLocaleString();
// titles / categories the system has no caption for (it falls back to a readable version of the code)
const OWN: Record<string, { en: string; ar: string }> = {
REGISTERED_STAKEHOLDER: { en: 'Registered stakeholders', ar: 'الجهات المسجلة' },
STAKEHOLDER_STATUS_CODES: { en: 'Stakeholders by status', ar: 'الجهات حسب الحالة' },
STAKEHOLDER_LOCATION: { en: 'Stakeholders by industrial city', ar: 'الجهات حسب المدينة الصناعية' },
PERSONNEL_EDUCATIONAL_LEVEL: { en: 'Education level', ar: 'المستوى التعليمي' },
PERSONNEL_EMPLOYMENT_CATEGORY: { en: 'Employment category', ar: 'فئة التوظيف' },
PERSONNEL_HEADER: { en: 'Workforce overview', ar: 'نظرة عامة على العاملين' },
PERSONNEL_RELATIVES: { en: 'Relatives', ar: 'الأقارب' },
PERSONNEL_STATUS_CODES: { en: 'Personnel by status', ar: 'العاملون حسب الحالة' },
TOP_NATIONALITY: { en: 'Top nationalities', ar: 'أعلى الجنسيات' },
USAGE_TYPE_CARGO: { en: 'Trailers by cargo type', ar: 'المقطورات حسب نوع الحمولة' },
USAGE_TYPE_TANK: { en: 'Tankers by type', ar: 'الصهاريج حسب النوع' },
FLEET_LOCATION: { en: 'Fleet by industrial city', ar: 'المركبات حسب المدينة الصناعية' },
OTHER_TRAILERS_TYPE: { en: 'Other trailer types', ar: 'أنواع المقطورات الأخرى' },
STAKEHOLDER_FLEET: { en: 'Fleet by stakeholders', ar: 'المركبات حسب الجهات' },
TRAILERS_TYPE: { en: 'Trailer types', ar: 'أنواع المقطورات' },
Educational_Level: { en: 'Education level', ar: 'المستوى التعليمي' },
Nationality: { en: 'Nationality', ar: 'الجنسية' },
HEAVY: { en: 'Heavy', ar: 'ثقيل' },
MEDIUM: { en: 'Medium', ar: 'متوسط' },
SMALL: { en: 'Small', ar: 'صغير' },
LARGE: { en: 'Large', ar: 'كبير' },
HEAVYEQUIPMENT: { en: 'Heavy equipment', ar: 'معدات ثقيلة' },
MEDIUMEQUIPMENT: { en: 'Medium equipment', ar: 'معدات متوسطة' },
OMN_NAT: { en: 'Omani', ar: 'عماني' },
OTHERS_NAT: { en: 'Non-Omani', ar: 'غير عماني' },
SUBSCRIPED: { en: 'Subscribed', ar: 'مشترك' },
NOT_SUBSCRIPED: { en: 'Not subscribed', ar: 'غير مشترك' },
OTHER_NAT_DRVR: { en: 'Drivers of other nationalities', ar: 'سائقون من جنسيات أخرى' },
OMN_NAT_DRVR: { en: 'Omani drivers', ar: 'سائقون عمانيون' },
INVESTORS_RUSAIL: { en: 'Rusayl investors', ar: 'مستثمرو الرسيل' },
INVESTORS_ALMAZYUNAH: { en: 'Al Mazyunah investors', ar: 'مستثمرو المزيونة' },
INVESTORS_NIZWA: { en: 'Nizwa investors', ar: 'مستثمرو نزوى' },
INVESTORS_SUHAR: { en: 'Sohar investors', ar: 'مستثمرو صحار' },
DRIVERS: { en: 'Drivers', ar: 'السائقون' },
OTHERS: { en: 'Others', ar: 'أخرى' },
YES: { en: 'Yes', ar: 'نعم' },
NO: { en: 'No', ar: 'لا' },
};
function Tiles({ items }: { items: Item[] }) {
return (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: 'repeat(auto-fill, minmax(170px, 1fr))' }}>
{items.map((i, idx) => {
const { icon: Icon, color } = itemTint(i.code, idx);
return (
<Paper
key={i.label}
variant="outlined"
sx={{
p: 1.75,
display: 'flex',
alignItems: 'center',
gap: 1.5,
borderInlineStart: 3,
borderInlineStartColor: color,
}}
>
<Avatar sx={{ bgcolor: alpha(color, 0.15), color, width: 42, height: 42 }}>
<Icon fontSize="small" />
</Avatar>
<Box sx={{ minWidth: 0 }}>
<Typography
variant="h5"
sx={{
fontWeight: 800,
color,
lineHeight: 1.1
}}>{fmt(i.value)}</Typography>
<Typography
variant="body2"
noWrap
sx={{
color: "text.secondary",
unicodeBidi: 'plaintext',
textAlign: 'start'
}}>{i.label}</Typography>
</Box>
</Paper>
);
})}
</Box>
);
}
/** A CSS conic-gradient donut: no charting library needed for a handful of slices. */
function Pie({ items }: { items: Item[] }) {
const theme = useTheme();
const ui = useUi();
const total = Math.max(1, items.reduce((a, i) => a + i.value, 0));
let acc = 0;
const stops = items
.filter((i) => i.value > 0)
.map((i, idx) => {
const from = (acc / total) * 100;
acc += i.value;
const to = (acc / total) * 100;
return { ...i, color: itemTint(i.code, idx).color, from, to };
});
const gradient = stops.length
? `conic-gradient(${stops.map((s) => `${s.color} ${s.from}% ${s.to}%`).join(', ')})`
: theme.palette.action.hover;
return (
<Stack
direction="row"
spacing={3}
useFlexGap
sx={{
alignItems: "center",
flexWrap: "wrap"
}}>
<Box sx={{ position: 'relative', width: 150, height: 150, flexShrink: 0 }}>
<Box sx={{ width: '100%', height: '100%', borderRadius: '50%', background: gradient }} />
<Box
sx={{
position: 'absolute', inset: 22, borderRadius: '50%', bgcolor: 'background.paper',
display: 'grid', placeItems: 'center', boxShadow: `0 0 0 1px ${theme.palette.divider} inset`,
}}
>
<Box sx={{ textAlign: 'center' }}>
<Typography
variant="h6"
sx={{
fontWeight: 800,
lineHeight: 1.1
}}>{fmt(items.reduce((a, i) => a + i.value, 0))}</Typography>
<Typography variant="caption" sx={{
color: "text.secondary"
}}>{ui('total')}</Typography>
</Box>
</Box>
</Box>
<Stack spacing={0.75} sx={{ flex: 1, minWidth: 160 }}>
{stops.map((s) => (
<Stack key={s.label} direction="row" spacing={1} sx={{
alignItems: "center"
}}>
<Box sx={{ width: 10, height: 10, borderRadius: '50%', bgcolor: s.color, flexShrink: 0 }} />
<Typography variant="body2" sx={{ flex: 1, unicodeBidi: 'plaintext', textAlign: 'start' }} noWrap title={s.label}>{s.label}</Typography>
<Typography variant="body2" sx={{
fontWeight: 700
}}>{fmt(s.value)}</Typography>
<Typography
variant="caption"
sx={{
color: "text.secondary",
width: 40,
textAlign: 'end'
}}>
{Math.round((s.value / total) * 100)}%
</Typography>
</Stack>
))}
</Stack>
</Stack>
);
}
function Bars({ items }: { items: Item[] }) {
const max = Math.max(1, ...items.map((i) => i.value));
return (
<Stack spacing={1}>
{items.map((i) => (
<Box key={i.label}>
<Stack
direction="row"
sx={{
justifyContent: "space-between",
mb: 0.25
}}>
<Typography variant="body2">{i.label}</Typography>
<Typography variant="body2" sx={{
fontWeight: 700
}}>{fmt(i.value)}</Typography>
</Stack>
<Box sx={{ height: 8, borderRadius: 4, bgcolor: 'action.hover', overflow: 'hidden' }}>
<Box sx={{ width: `${(i.value / max) * 100}%`, height: '100%', bgcolor: 'primary.main', borderRadius: 4, minWidth: i.value ? 3 : 0 }} />
</Box>
</Box>
))}
</Stack>
);
}
function Stacked({ items }: { items: Item[] }) {
const theme = useTheme();
const color: Record<string, string> = {
REGISTERED: theme.palette.success.main,
ACTIVE: theme.palette.success.main,
INCOMPLETE: theme.palette.warning.main,
PENDING: theme.palette.info.main,
PENDING_UPDATE: theme.palette.info.light,
RETURNED: theme.palette.secondary.main,
INACTIVE: theme.palette.grey[500],
};
const palette = [theme.palette.primary.main, theme.palette.secondary.main, theme.palette.success.main, theme.palette.warning.main];
const keys = [...new Set(items.flatMap((i) => i.segments?.map((s) => s.key) ?? []))];
const labels = new Map(items.flatMap((i) => i.segments ?? []).map((s) => [s.key, s.label]));
const col = (k: string) => color[k] ?? palette[keys.indexOf(k) % palette.length];
const max = Math.max(1, ...items.map((i) => i.value));
return (
<Stack spacing={1.25}>
<Stack direction="row" spacing={1.5} useFlexGap sx={{
flexWrap: "wrap"
}}>
{keys.map((k) => (
<Stack key={k} direction="row" spacing={0.5} sx={{
alignItems: "center"
}}>
<Box sx={{ width: 10, height: 10, borderRadius: 0.5, bgcolor: col(k) }} />
<Typography variant="caption" sx={{
color: "text.secondary"
}}>{labels.get(k)}</Typography>
</Stack>
))}
</Stack>
{items.map((i) => (
<Box key={i.label}>
<Stack
direction="row"
sx={{
justifyContent: "space-between",
mb: 0.25
}}>
<Typography variant="body2">{i.label}</Typography>
<Typography variant="body2" sx={{
fontWeight: 700
}}>{fmt(i.value)}</Typography>
</Stack>
<Box sx={{ display: 'flex', height: 10, width: `${Math.max(4, (i.value / max) * 100)}%`, borderRadius: 5, overflow: 'hidden', bgcolor: 'action.hover' }}>
{i.segments?.filter((s) => s.value > 0).map((s) => (
<Box key={s.key} title={`${s.label}: ${fmt(s.value)}`} sx={{ width: `${(s.value / Math.max(1, i.value)) * 100}%`, bgcolor: col(s.key) }} />
))}
</Box>
</Box>
))}
</Stack>
);
}
function BlockCard({ block }: { block: Block }) {
const body =
block.kind === 'tiles' ? <Tiles items={block.items} />
: block.kind === 'pie' ? <Pie items={block.items} />
: block.kind === 'stacked' ? <Stacked items={block.items} />
: <Bars items={block.items} />;
if (block.kind === 'tiles' && !block.title) return body;
const tint = blockIcon(block.key);
return (
<Paper variant="outlined" sx={{ p: 2, height: '100%' }}>
<Stack
direction="row"
spacing={1}
sx={{
alignItems: "center",
mb: 1.5
}}>
{tint && (
<Avatar sx={{ bgcolor: alpha(tint.color, 0.15), color: tint.color, width: 28, height: 28 }}>
<tint.icon sx={{ fontSize: 16 }} />
</Avatar>
)}
<Typography
component="h2"
sx={{
fontWeight: 700,
fontSize: 14.5
}}>{block.title}</Typography>
</Stack>
{body}
</Paper>
);
}
export function DashboardPage() {
const { slug = '' } = useParams();
const page = PAGES[slug];
const { user, lang } = useAuth();
const caption = useT();
const humanize = useLabel();
const ui = useUi();
// system caption first, then our own bilingual title, then a readable form of the code
const lab = (k: string) => {
// on the dashboards OWNERS is the separate 254-record group, not the drivers (those are DRIVERS), so it keeps its own name
if (page?.kind === 'dashboard' && k === 'OWNERS') return isRtl(lang) ? 'المالكون' : 'Owners';
const own = OWN[k] ?? OWN[k.toUpperCase()];
return caption(k) !== k ? caption(k) : own ? (isRtl(lang) ? own.ar : own.en) : humanize(k);
};
const fullscreen = useFullscreen();
// leaving the page leaves full screen, so the menu is never left hidden on another page
const leave = fullscreen.exit;
useEffect(() => () => leave(), [leave]);
const [location, setLocation] = useState(0);
const [nat, setNat] = useState('ALL');
const meta = Object.values(DASHBOARDS).find((d) => d.slug === slug);
// users bound to one industrial city only ever see that city (as in the old page)
const lockedTo = Number(user?.use_location_id) === 1 ? Number(user?.location_id) : null;
const loc = lockedTo ?? location;
const locations = useQuery({
queryKey: ['dash-locations'],
queryFn: () => rpc<{ INDUSTRIALESTATESARRAY?: Option[] }>('CONFIG', 'getIndustrialLocs', { related_entity_id: '', related_entity_record_id: '' }),
enabled: !!page?.locations,
staleTime: 10 * 60_000,
});
const data = useQuery({
queryKey: ['dashboard', slug, loc],
queryFn: () =>
page!.kind === 'dashboard'
? rpc<unknown>('CONFIG', 'GetDashBoard', { DASHBOARD_NAME: page!.name, LOCATIONID: loc })
: rpc<unknown>('CONFIG', 'GetInfoGraphic', { INFOGRAPH_NAME: page!.name }),
enabled: !!page,
staleTime: 60_000,
});
const model = useMemo(() => {
if (!page || !data.data) return { blocks: [] as Block[], nats: [] as string[] };
if (page.kind === 'dashboard') return { blocks: buildDashboard(data.data, lab), nats: [] as string[] };
return buildInfographic(data.data, lab, nat);
}, [page, data.data, lab, nat]);
// in full screen the dashboards take turns: every few seconds the next one the user may open comes up
const nav = useNavigate();
const { sections } = useNav();
const slugs = useMemo(() => (sections.find((x) => x.key === 'dashboard')?.items ?? []).map((i) => i.to.replace('/dashboard/', '')), [sections]);
const [paused, setPaused] = useState(false);
const rotating = fullscreen.active && !paused && slugs.length > 1 && !data.isPending;
useEffect(() => {
if (!rotating) return;
const t = setTimeout(() => nav(`/dashboard/${slugs[(Math.max(0, slugs.indexOf(slug)) + 1) % slugs.length]}`), ROTATE_MS);
return () => clearTimeout(t);
}, [rotating, slug, slugs, nav]);
const Custom = CUSTOM[slug];
if (!page) return <Alert severity="info">{ui('noResults')}</Alert>;
const title = meta ? (isRtl(lang) ? meta.ar : meta.en) : slug;
const estates = locations.data?.INDUSTRIALESTATESARRAY ?? [];
return (
<>
{rotating && (
<Box
key={slug}
sx={{ position: 'fixed', top: 0, insetInlineStart: 0, height: 3, bgcolor: 'primary.main', zIndex: 2000, animation: `rotate-progress ${ROTATE_MS}ms linear forwards`, '@keyframes rotate-progress': { from: { width: '0%' }, to: { width: '100%' } } }}
/>
)}
<PageHeader
title={title}
actions={
<>
{fullscreen.active && slugs.length > 1 && (
<Button variant="outlined" startIcon={paused ? <PlayArrowOutlined /> : <PauseOutlined />} onClick={() => setPaused((p) => !p)}>
{paused ? ui('resumeRotation') : ui('pauseRotation')}
</Button>
)}
<Button variant={fullscreen.active ? 'contained' : 'outlined'} startIcon={fullscreen.active ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={fullscreen.active ? fullscreen.exit : fullscreen.enter}>
{fullscreen.active ? ui('exitFullscreen') : ui('fullscreen')}
</Button>
</>
}
/>
{page.locations && estates.length > 0 && (
<Stack
direction="row"
spacing={0.75}
useFlexGap
sx={{
flexWrap: "wrap",
mb: 2
}}>
<Chip label={lab('ALL_LOCATIONS')} color={loc === 0 ? 'primary' : 'default'} variant={loc === 0 ? 'filled' : 'outlined'} disabled={lockedTo !== null} onClick={() => setLocation(0)} />
{estates.map((e) => (
<Chip key={String(e.CODE)} label={lab(e.CAPTION_CODE ?? String(e.CODE))} color={Number(e.CODE) === loc ? 'primary' : 'default'} variant={Number(e.CODE) === loc ? 'filled' : 'outlined'} disabled={lockedTo !== null && Number(e.CODE) !== lockedTo} onClick={() => setLocation(Number(e.CODE))} />
))}
</Stack>
)}
{model.nats.length > 0 && (
<Stack
direction="row"
spacing={0.75}
useFlexGap
sx={{
flexWrap: "wrap",
mb: 2
}}>
{model.nats.map((n) => (
<Chip key={n} label={n === 'ALL' ? ui('all') : lab(n)} color={n === nat ? 'primary' : 'default'} variant={n === nat ? 'filled' : 'outlined'} onClick={() => setNat(n)} />
))}
</Stack>
)}
{data.error && <Alert severity="error">{ui('loadError')}</Alert>}
{data.isPending && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, 1fr)' } }}>
{[0, 1, 2, 3].map((i) => <Skeleton key={i} variant="rounded" height={160} />)}
</Box>
)}
{/* every dashboard and infographic has its own richer layout; the generic blocks below remain as the fallback */}
{!data.isPending && !data.error && Custom && <Custom data={data.data} lab={lab} rtl={isRtl(lang)} nat={nat} />}
{!data.isPending && !Custom && (() => {
// the statistics (KPI tiles) always come first, as their own full-width row; the diagrams
// that follow sit in a multi-column grid so they line up side by side wherever there is room
const stats = model.blocks.filter((b) => b.kind === 'tiles');
const charts = model.blocks.filter((b) => b.kind !== 'tiles');
return (
<Stack spacing={1.5}>
{stats.length > 0 && (
<Stack spacing={1.5}>
{stats.map((b) => <BlockCard key={b.key} block={b} />)}
</Stack>
)}
{charts.length > 0 && (
<Box sx={{ display: 'grid', gap: 1.5, gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', xl: 'repeat(3, 1fr)' }, alignItems: 'stretch' }}>
{charts.map((b) => <BlockCard key={b.key} block={b} />)}
</Box>
)}
</Stack>
);
})()}
</>
);
}