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 = { 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 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 = { 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 ( {items.map((i, idx) => { const { icon: Icon, color } = itemTint(i.code, idx); return ( {fmt(i.value)} {i.label} ); })} ); } /** 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 ( {fmt(items.reduce((a, i) => a + i.value, 0))} {ui('total')} {stops.map((s) => ( {s.label} {fmt(s.value)} {Math.round((s.value / total) * 100)}% ))} ); } function Bars({ items }: { items: Item[] }) { const max = Math.max(1, ...items.map((i) => i.value)); return ( {items.map((i) => ( {i.label} {fmt(i.value)} ))} ); } function Stacked({ items }: { items: Item[] }) { const theme = useTheme(); const color: Record = { 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 ( {keys.map((k) => ( {labels.get(k)} ))} {items.map((i) => ( {i.label} {fmt(i.value)} {i.segments?.filter((s) => s.value > 0).map((s) => ( ))} ))} ); } function BlockCard({ block }: { block: Block }) { const body = block.kind === 'tiles' ? : block.kind === 'pie' ? : block.kind === 'stacked' ? : ; if (block.kind === 'tiles' && !block.title) return body; const tint = blockIcon(block.key); return ( {tint && ( )} {block.title} {body} ); } 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('CONFIG', 'GetDashBoard', { DASHBOARD_NAME: page!.name, LOCATIONID: loc }) : rpc('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 {ui('noResults')}; const title = meta ? (isRtl(lang) ? meta.ar : meta.en) : slug; const estates = locations.data?.INDUSTRIALESTATESARRAY ?? []; return ( <> {rotating && ( )} {fullscreen.active && slugs.length > 1 && ( )} } /> {page.locations && estates.length > 0 && ( setLocation(0)} /> {estates.map((e) => ( setLocation(Number(e.CODE))} /> ))} )} {model.nats.length > 0 && ( {model.nats.map((n) => ( setNat(n)} /> ))} )} {data.error && {ui('loadError')}} {data.isPending && ( {[0, 1, 2, 3].map((i) => )} )} {/* every dashboard and infographic has its own richer layout; the generic blocks below remain as the fallback */} {!data.isPending && !data.error && Custom && } {!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 ( {stats.length > 0 && ( {stats.map((b) => )} )} {charts.length > 0 && ( {charts.map((b) => )} )} ); })()} ); }