Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

13.4 KB
Raw Blame
import MAdminSchoolHolidayCatalog from './MAdminSchoolHolidayCatalog'
import { useState } from 'react'
import {
  ArrowUp,
  Bell,
  Blocks,
  Briefcase,
  Bug,
  ChevronDown,
  ChevronLeft,
  Compass,
  Database,
  FileText,
  GitBranch,
  HardDrive,
  KeyRound,
  Map,
  Puzzle,
  ScrollText,
  Shield,
  ShieldCheck,
  SlidersHorizontal,
  UserCog,
  UserPlus,
  Users,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import { useCountUp } from '../../../hooks/useCountUp'
import { useAdmin } from '../../../pages/admin/useAdmin'
import MAdminAddonManager from './MAdminAddonManager'
import MAdminMcpTokensPanel from './MAdminMcpTokensPanel'
import MAdminPluginsPanel from './MAdminPluginsPanel'
import MAdminAuditLogPanel from './MAdminAuditLogPanel'
import MAdminBackupPanel from './MAdminBackupPanel'
import MAdminCategoryManager from './MAdminCategoryManager'
import MAdminDefaultUserSettings from './MAdminDefaultUserSettings'
import MAdminDevNotificationsPanel from './MAdminDevNotificationsPanel'
import MAdminGitHubPanel from './MAdminGitHubPanel'
import MAdminPackingTemplateManager from './MAdminPackingTemplateManager'
import MAdminNotificationsSection from './MAdminNotificationsSection'
import MAdminSettingsSection from './MAdminSettingsSection'
import MAdminSheets from './MAdminSheets'
import MAdminStoragePanel from './MAdminStoragePanel'
import MAdminUsersSection from './MAdminUsersSection'
import { MAdminButton } from './MAdminUi'
import { managedAdminTabs } from '../../../managed'
import { useIsSplit } from '../../../hooks/sizeClass'
import MSectionNav, { MSectionList, SECTION_SCREEN, type MSection } from '../../components/MSectionNav'

// Stat card of the 2×2 grid (design §6.3): 34px icon tile, 19px/800 number,
// small tracking label. Count-up animation matches the desktop stat cards.
function MAdminStat({ label, value, icon: Icon }: { label: string; value: number; icon: LucideIcon }) {
  const animated = useCountUp(value, 900)
  return (
    <div className="flex items-center gap-[11px] rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[13px]">
      <span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
        <Icon size={16} strokeWidth={2} />
      </span>
      <div className="min-w-0">
        <div className="text-[1.1875rem] font-extrabold leading-none text-m-ink">{animated}</div>
        <div className="mt-[2px] truncate font-geist text-[0.59375rem] font-bold tracking-[0.06em] text-m-faint" title={label}>{label}</div>
      </div>
    </div>
  )
}

/**
 * Mobile admin screen (design §6): section switcher pill with the grouped
 * dropdown of the desktop sidebar's sections, update banner, stats grid and
 * the active section.
 */
export default function MAdmin() {
  const { t, locale } = useTranslation()
  const admin = useAdmin()
  const {
    demoMode, mcpEnabled, devMode, managed, navigate,
    activeTab, setActiveTab, stats, serverTimezone,
    bagTrackingEnabled, collabFeatures,
    setShowCreateUser,
    updateInfo, setShowUpdateModal,
    saveDemoBaseline, toggleBagTracking, toggleCollabFeature,
  } = admin
  const [sectionsOpen, setSectionsOpen] = useState(false)
  // With room for two panes the sections stand in a list beside the page, as in
  // settings, instead of behind the header's dropdown.
  const split = useIsSplit()

  // The desktop sidebar's sections, groups, order, icons and gating, so a link
  // to a tab and a habit from the laptop land on the same place here.
  const gUsers = t('admin.group.users')
  const gConfig = t('admin.group.config')
  const gMaintenance = t('admin.group.maintenance')
  const groupOf = { users: gUsers, config: gConfig, integration: gConfig, maintenance: gMaintenance }
  const sections: MSection[] = [
    { id: 'users', label: t('admin.tabs.users'), icon: Users, group: gUsers },
    { id: 'defaults', label: t('admin.tabs.defaults'), icon: UserCog, group: gUsers },
    { id: 'security', label: t('admin.tabs.security'), icon: ShieldCheck, group: gConfig },
    { id: 'services', label: t('admin.tabs.services'), icon: Compass, group: gConfig },
    { id: 'addons', label: t('admin.tabs.addons'), icon: Puzzle, group: gConfig },
    { id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal, group: gConfig },
    { id: 'notifications', label: t('admin.tabs.notifications'), icon: Bell, group: gConfig },
    ...(mcpEnabled ? [{ id: 'mcp-tokens', label: t('admin.tabs.mcpTokens'), icon: KeyRound, group: gConfig }] : []),
    // A hosted instance offers no plugins, storage backends, backup schedule or
    // releases: they belong to whoever operates the install.
    ...(managed ? [] : [{ id: 'plugins', label: t('admin.tabs.plugins'), icon: Blocks, group: gConfig }]),
    ...(managed ? [] : [{ id: 'storage', label: t('admin.tabs.storage'), icon: HardDrive, group: gMaintenance }]),
    ...(managed ? [] : [{ id: 'backup', label: t('admin.tabs.backup'), icon: Database, group: gMaintenance }]),
    ...(managed ? [] : [{ id: 'github', label: t('admin.tabs.github'), icon: GitBranch, group: gMaintenance }]),
    { id: 'audit', label: t('admin.tabs.audit'), icon: ScrollText, group: gMaintenance },
    ...(devMode ? [{ id: 'dev-notifications', label: 'Dev: Notifications', icon: Bug, group: gMaintenance }] : []),
    // The install's own tabs (managed/index.tsx), after the built-in ones as on the desktop.
    ...managedAdminTabs.map(tab => ({ id: tab.id, label: tab.label, icon: tab.Icon, group: groupOf[tab.group ?? 'config'] })),
  ]
  const activeSection = sections.find((s) => s.id === activeTab) ?? sections[0]

  return (
    // Flow screen: scrolls with the document (#1809), so no height and no
    // scroll container of its own.
    <div className={SECTION_SCREEN}>
      {split && (
        <MSectionNav
          title={t('admin.title')}
          backLabel={t('common.back')}
          onBack={() => void navigate('/dashboard')}
          sections={sections}
          activeId={activeSection.id}
          onPick={setActiveTab}
          action={
            <button
              type="button"
              onClick={() => setShowCreateUser(true)}
              className="flex h-[34px] w-full items-center justify-center gap-[7px] rounded-full bg-m-act px-3 text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-actfg outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--m-act)] focus-visible:ring-offset-2"
            >
              <UserPlus size={14} strokeWidth={2.2} className="flex-none" />
              <span className="truncate">{t('admin.createUser')}</span>
            </button>
          }
        />
      )}
      <div className="min-w-0">
      {/* Header: back · section switcher · create user */}
      {!split && (
      <div className="mb-3 flex items-center gap-2">
        <button
          type="button"
          aria-label={t('common.back')}
          onClick={() => navigate('/dashboard')}
          className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
        >
          <ChevronLeft size={18} strokeWidth={2.2} className="rtl:-scale-x-100" />
        </button>
        <button
          type="button"
          aria-label={t('admin.title')}
          aria-expanded={sectionsOpen}
          onClick={() => setSectionsOpen((v) => !v)}
          className="flex h-[38px] min-w-0 flex-1 items-center gap-[7px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] px-[14px] text-[0.8125rem] font-bold text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
        >
          <Shield size={14} strokeWidth={2.2} className="flex-none" />
          <span className="min-w-0 flex-1 truncate text-start">{activeSection.label}</span>
          <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
        </button>
        <button
          type="button"
          aria-label={t('admin.createUser')}
          onClick={() => setShowCreateUser(true)}
          className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-m-act text-m-actfg shadow-[0_5px_12px_-8px_rgba(0,0,0,.3)]"
        >
          <UserPlus size={16} strokeWidth={2.2} />
        </button>
      </div>
      )}

      {/* Section dropdown */}
      {sectionsOpen && !split && (
        <div className="-mt-[6px] mb-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px] shadow-[0_16px_40px_-20px_rgba(0,0,0,.4)]">
          <MSectionList
            sections={sections}
            activeId={activeSection.id}
            onPick={(id) => {
              setActiveTab(id)
              setSectionsOpen(false)
            }}
          />
        </div>
      )}

      {/* Update banner (§6.2) — real update check, shown on every section */}
      {updateInfo && (
        <div className="mb-3 flex items-center gap-[10px] rounded-2xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-[14px] py-3">
          <span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-full bg-[color:var(--m-st-pending)] text-white">
            <ArrowUp size={17} strokeWidth={2.4} />
          </span>
          <div className="min-w-0 flex-1">
            <div className="text-[0.78125rem] font-extrabold text-m-ink">{t('admin.update.available')}</div>
            <div className="font-geist text-[0.625rem] text-m-muted">
              {t('mobileAdmin.updateLine', { version: `v${updateInfo.latest}`, current: `v${updateInfo.current}` })}
            </div>
          </div>
          <MAdminButton onClick={() => setShowUpdateModal(true)}>{t('mobileAdmin.updateAction')}</MAdminButton>
        </div>
      )}

      {/* Demo baseline (demo instances only) */}
      {demoMode && (
        <div className="mb-3 flex items-center gap-[10px] rounded-2xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-[14px] py-3">
          <div className="min-w-0 flex-1">
            <div className="text-[0.78125rem] font-extrabold text-m-ink">{t('admin.demoBaseline.title')}</div>
            <div className="font-geist text-[0.625rem] leading-relaxed text-m-muted">
              {t('admin.demoBaseline.hint')}
            </div>
          </div>
          <MAdminButton onClick={saveDemoBaseline}>{t('admin.demoBaseline.button')}</MAdminButton>
        </div>
      )}

      {/* Stats grid (§6.3) */}
      {stats && (
        <div className="mb-3 grid grid-cols-2 gap-[10px] wide:grid-cols-4">
          <MAdminStat label={t('admin.stats.users', { count: stats.totalUsers })} value={stats.totalUsers} icon={Users} />
          <MAdminStat label={t('admin.stats.trips', { count: stats.totalTrips })} value={stats.totalTrips} icon={Briefcase} />
          <MAdminStat label={t('admin.stats.places', { count: stats.totalPlaces })} value={stats.totalPlaces} icon={Map} />
          <MAdminStat label={t('admin.stats.files', { count: stats.totalFiles || 0 })} value={stats.totalFiles || 0} icon={FileText} />
        </div>
      )}

      {/* Active section */}
      {activeTab === 'users' && <MAdminUsersSection admin={admin} t={t} locale={locale} />}
      {activeTab === 'security' && <MAdminSettingsSection admin={admin} t={t} part="security" />}
      {activeTab === 'services' && <MAdminSettingsSection admin={admin} t={t} part="services" />}
      {activeTab === 'notifications' && <MAdminNotificationsSection admin={admin} t={t} />}
      {activeTab === 'defaults' && <MAdminDefaultUserSettings />}
      {activeTab === 'config' && (
        <div className="space-y-4">
          <MAdminPackingTemplateManager />
          <MAdminCategoryManager />
          <MAdminSchoolHolidayCatalog />
        </div>
      )}
      {activeTab === 'addons' && (
        <div className="space-y-4">
          <MAdminAddonManager
            bagTrackingEnabled={bagTrackingEnabled}
            onToggleBagTracking={toggleBagTracking}
            collabFeatures={collabFeatures}
            onToggleCollabFeature={toggleCollabFeature}
            // Live flight status and the booking mail import are rows of the addon groups,
            // and the paddle water data a row under Tours (desktop parity).
            flightLive={{
              on: admin.flightLive,
              locked: admin.flightLiveLocked,
              managed: !!managed,
              onToggle: () =>
                void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
            }}
            mailImport={!managed}
          />
        </div>
      )}
      {activeTab === 'plugins' && <MAdminPluginsPanel />}
      {activeTab === 'storage' && <MAdminStoragePanel />}
      {activeTab === 'mcp-tokens' && <MAdminMcpTokensPanel />}
      {activeTab === 'github' && <MAdminGitHubPanel isPrerelease={updateInfo?.is_prerelease ?? false} />}
      {activeTab === 'backup' && <MAdminBackupPanel />}
      {activeTab === 'audit' && <MAdminAuditLogPanel serverTimezone={serverTimezone} />}
      {activeTab === 'dev-notifications' && <MAdminDevNotificationsPanel />}
      {managedAdminTabs.map(tab =>
        activeTab === tab.id ? <div key={tab.id}>{tab.mobileElement ?? tab.element}</div> : null,
      )}

      </div>

      <MAdminSheets admin={admin} t={t} />
    </div>
  )
}