WorkBoardPresenter.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. 'use client'
  2. import { useBoardCalendar } from '../hooks/useBoardCalendar'
  3. import { useWorkshopDayRollover } from '../hooks/useWorkshopDayRollover'
  4. import { useState, useEffect, useCallback, useMemo } from 'react'
  5. import { useSearchParams, useRouter, usePathname } from 'next/navigation'
  6. import { DndContext } from '@dnd-kit/core'
  7. import { Button } from '@/components/ui/button'
  8. import { ChevronLeft, ChevronRight, Wifi, WifiOff } from 'lucide-react'
  9. import { useWorkBoardStore, type Technician } from '../store/workboardStore'
  10. import { useWorkBoardWebSocket } from '../hooks/useWorkBoardWebSocket'
  11. import type { WorkBay, WorkBoardJob } from '../Actions/boardActions'
  12. import { getBoardJobs } from '../Actions/boardActions'
  13. import { getTechnicians } from '../Actions/technicianActions'
  14. import { getWorkBays } from '../Actions/workBayActions'
  15. import { PresenterKanbanView } from './PresenterKanbanView'
  16. import { WeekTimeline } from './WeekTimeline'
  17. import { WeekCardGrid } from './WeekCardGrid'
  18. import { type BoardLayout, isBoardLayout } from '../hooks/useBoardPreferences'
  19. import { type ClockFormat } from '../utils/clock'
  20. import { boardNow, toBoardJob } from '../utils/board-time'
  21. import { type LaneGrouping, buildLanes, groupJobsByLane, isLaneGrouping } from '../utils/lanes'
  22. import { useTranslations, useLocale } from 'next-intl'
  23. import { useDateSettings } from '@/components/date-settings-context'
  24. import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
  25. import { cn } from '@/lib/utils'
  26. type Period = 'day' | 'week'
  27. /** Timeline and Overview are the board's own layouts; Status is the kanban,
  28. * which only makes sense for a single day. */
  29. type PresenterLayout = BoardLayout | 'status'
  30. /** Older pinned displays carry ?view=; keep those URLs working. */
  31. const LEGACY_VIEWS: Record<string, { period: Period; layout: PresenterLayout }> = {
  32. timeline: { period: 'day', layout: 'timeline' },
  33. day: { period: 'day', layout: 'cards' },
  34. status: { period: 'day', layout: 'status' },
  35. week: { period: 'week', layout: 'timeline' },
  36. }
  37. function toLocalDateString(d: Date): string {
  38. return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  39. }
  40. function getWeekStart(date: Date, weekStartDay: number): string {
  41. const d = new Date(date)
  42. const diff = (d.getDay() - weekStartDay + 7) % 7
  43. d.setDate(d.getDate() - diff)
  44. return toLocalDateString(d)
  45. }
  46. function getWeekDays(weekStart: string): string[] {
  47. const days: string[] = []
  48. for (let i = 0; i < 7; i++) {
  49. const d = new Date(weekStart + 'T12:00:00')
  50. d.setDate(d.getDate() + i)
  51. days.push(toLocalDateString(d))
  52. }
  53. return days
  54. }
  55. /** The presenter shows the board; it never changes it. */
  56. const noop = () => undefined
  57. function formatWeekRange(weekStart: string, locale?: string): string {
  58. const start = new Date(weekStart + 'T12:00:00')
  59. const end = new Date(start)
  60. end.setDate(end.getDate() + 6)
  61. const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' }
  62. return `${start.toLocaleDateString(locale, opts)} – ${end.toLocaleDateString(locale, { ...opts, year: 'numeric' })}`
  63. }
  64. function formatDayDate(dateStr: string, locale?: string): string {
  65. return new Date(dateStr + 'T12:00:00').toLocaleDateString(locale, {
  66. weekday: 'long',
  67. month: 'long',
  68. day: 'numeric',
  69. })
  70. }
  71. /**
  72. * The wall clock in the header.
  73. *
  74. * Rendered null until the first tick, because the server has no idea what time
  75. * it is where the screen is and a mismatched first paint is a hydration error.
  76. * That left a one-space-wide element that jumped to full width a moment later,
  77. * shoving the header about, so the space is reserved up front: tabular figures
  78. * and a width sized for the longest the format can be.
  79. */
  80. function LiveClock({ format, timeZone }: { format: ClockFormat; timeZone: string }) {
  81. const [time, setTime] = useState<string | null>(null)
  82. useEffect(() => {
  83. function update() {
  84. setTime(
  85. new Date().toLocaleTimeString(undefined, {
  86. hour: '2-digit',
  87. minute: '2-digit',
  88. second: '2-digit',
  89. hour12: format === '12h',
  90. // The board below runs on the workshop's clock, so this does too.
  91. ...(timeZone ? { timeZone } : {}),
  92. })
  93. )
  94. }
  95. update()
  96. const timer = setInterval(update, 1000)
  97. return () => clearInterval(timer)
  98. }, [format, timeZone])
  99. return (
  100. <span
  101. className="inline-block text-right tabular-nums"
  102. // "11:59:59 PM" against "23:59:59": reserve for whichever is in use.
  103. style={{ minWidth: format === '12h' ? '10ch' : '8ch' }}
  104. >
  105. {time ?? '\u00A0'}
  106. </span>
  107. )
  108. }
  109. export function WorkBoardPresenter({
  110. initialTechnicians,
  111. initialWorkBays = [],
  112. initialAssignments,
  113. initialWeekStart,
  114. workDayStart = '07:00',
  115. workDayEnd = '15:00',
  116. weekStartDay = 1,
  117. }: {
  118. initialTechnicians: Technician[]
  119. initialWorkBays?: WorkBay[]
  120. initialAssignments: WorkBoardJob[]
  121. initialWeekStart: string
  122. workDayStart?: string
  123. workDayEnd?: string
  124. weekStartDay?: number
  125. }) {
  126. const store = useWorkBoardStore()
  127. const t = useTranslations('workBoard.presenter')
  128. const tb = useTranslations('workBoard.board')
  129. const tt = useTranslations('workBoard.toolbar')
  130. const { timeFormat, timezone } = useDateSettings()
  131. const locale = useLocale()
  132. const searchParams = useSearchParams()
  133. const router = useRouter()
  134. const pathname = usePathname()
  135. const legacy = LEGACY_VIEWS[searchParams.get('view') ?? '']
  136. const urlPeriod = searchParams.get('period')
  137. const urlLayout = searchParams.get('layout')
  138. const urlDate = searchParams.get('date')
  139. const urlGrouping = searchParams.get('group')
  140. const [period, setPeriodState] = useState<Period>(
  141. urlPeriod === 'day' || urlPeriod === 'week' ? urlPeriod : (legacy?.period ?? 'week')
  142. )
  143. const [layout, setLayoutState] = useState<PresenterLayout>(
  144. urlLayout === 'status' || isBoardLayout(urlLayout)
  145. ? (urlLayout as PresenterLayout)
  146. : (legacy?.layout ?? 'timeline')
  147. )
  148. const [selectedDate, setSelectedDateState] = useState(urlDate || boardNow(timezone).dayKey)
  149. // The presenter keeps its settings in the address bar rather than reading the
  150. // planner's saved preference: a wall display is usually a different machine,
  151. // and one that should stay on whatever it was pinned to.
  152. const [grouping, setGroupingState] = useState<LaneGrouping>(
  153. isLaneGrouping(urlGrouping) ? urlGrouping : 'technician'
  154. )
  155. const updateUrl = useCallback(
  156. (p: Period, l: PresenterLayout, d: string, g: LaneGrouping) => {
  157. const params = new URLSearchParams()
  158. params.set('period', p)
  159. params.set('layout', l)
  160. params.set('date', d)
  161. params.set('group', g)
  162. router.replace(`${pathname}?${params.toString()}`, { scroll: false })
  163. },
  164. [router, pathname]
  165. )
  166. const setSelectedDate = useCallback(
  167. (d: string) => {
  168. setSelectedDateState(d)
  169. updateUrl(period, layout, d, grouping)
  170. },
  171. [period, layout, grouping, updateUrl]
  172. )
  173. const setPeriod = (p: Period) => {
  174. // Status is a single day's kanban; a week has no such thing to show.
  175. const next: PresenterLayout = p === 'week' && layout === 'status' ? 'timeline' : layout
  176. setPeriodState(p)
  177. setLayoutState(next)
  178. updateUrl(p, next, selectedDate, grouping)
  179. }
  180. /** The status board is a day's kanban, so asking for it asks for a day. */
  181. const showStatusBoard = () => {
  182. setPeriodState('day')
  183. setLayoutState('status')
  184. updateUrl('day', 'status', selectedDate, grouping)
  185. }
  186. const setLayout = (l: PresenterLayout) => {
  187. setLayoutState(l)
  188. updateUrl(period, l, selectedDate, grouping)
  189. }
  190. const setGrouping = (g: LaneGrouping) => {
  191. setGroupingState(g)
  192. updateUrl(period, layout, selectedDate, g)
  193. }
  194. useEffect(() => {
  195. store.setTechnicians(initialTechnicians)
  196. store.setWorkBays(initialWorkBays)
  197. store.setJobs(initialAssignments)
  198. store.setWeekStart(initialWeekStart) /* eslint-disable-next-line react-hooks/exhaustive-deps */
  199. }, [])
  200. useWorkBoardWebSocket()
  201. const weekStart = store.weekStart || initialWeekStart
  202. // Day is the same board given one day's worth of columns, exactly as on the
  203. // planner. Switching period used to swap in a different component entirely.
  204. const days = period === 'day' ? [selectedDate] : getWeekDays(weekStart)
  205. const loadWeekData = useCallback(
  206. async (ws: string) => {
  207. store.setWeekStart(ws)
  208. const [assignRes, techRes, bayRes] = await Promise.all([
  209. getBoardJobs(ws),
  210. getTechnicians(),
  211. getWorkBays(),
  212. ])
  213. if (assignRes.success && assignRes.data) store.setJobs(assignRes.data as WorkBoardJob[])
  214. if (techRes.success && techRes.data) store.setTechnicians(techRes.data as Technician[])
  215. if (bayRes.success && bayRes.data) store.setWorkBays(bayRes.data as WorkBay[])
  216. },
  217. [store]
  218. )
  219. const ensureWeekLoaded = useCallback(
  220. (dateStr: string) => {
  221. const m = getWeekStart(new Date(dateStr + 'T12:00:00'), weekStartDay)
  222. if (m !== weekStart) loadWeekData(m)
  223. },
  224. [weekStart, loadWeekData, weekStartDay]
  225. )
  226. const handlePrev = () => {
  227. if (period === 'week') {
  228. const d = new Date(weekStart + 'T12:00:00')
  229. d.setDate(d.getDate() - 7)
  230. loadWeekData(toLocalDateString(d))
  231. } else {
  232. const d = new Date(selectedDate + 'T12:00:00')
  233. d.setDate(d.getDate() - 1)
  234. const nd = toLocalDateString(d)
  235. setSelectedDate(nd)
  236. ensureWeekLoaded(nd)
  237. }
  238. }
  239. const handleNext = () => {
  240. if (period === 'week') {
  241. const d = new Date(weekStart + 'T12:00:00')
  242. d.setDate(d.getDate() + 7)
  243. loadWeekData(toLocalDateString(d))
  244. } else {
  245. const d = new Date(selectedDate + 'T12:00:00')
  246. d.setDate(d.getDate() + 1)
  247. const nd = toLocalDateString(d)
  248. setSelectedDate(nd)
  249. ensureWeekLoaded(nd)
  250. }
  251. }
  252. const handleToday = () => {
  253. const today = boardNow(timezone).dayKey
  254. setSelectedDate(today)
  255. loadWeekData(getWeekStart(new Date(`${today}T12:00:00`), weekStartDay))
  256. }
  257. // A wall display moves on to the next day by itself, at the workshop's midnight.
  258. const showNewDay = useCallback(
  259. (today: string) => {
  260. setSelectedDate(today)
  261. loadWeekData(getWeekStart(new Date(`${today}T12:00:00`), weekStartDay))
  262. },
  263. [loadWeekData, setSelectedDate, weekStartDay]
  264. )
  265. useWorkshopDayRollover(timezone, showNewDay)
  266. const dateLabel =
  267. period === 'week' ? formatWeekRange(weekStart, locale) : formatDayDate(selectedDate, locale)
  268. // Drawn on the workshop's clock; the store keeps real instants.
  269. const boardJobs = useMemo(
  270. () => store.jobs.map((job) => toBoardJob(job, timezone)),
  271. [store.jobs, timezone]
  272. )
  273. const lanes = useMemo(
  274. () =>
  275. buildLanes({
  276. grouping,
  277. technicians: store.technicians,
  278. workBays: store.workBays,
  279. jobs: boardJobs,
  280. labels: {
  281. unlaned: grouping === 'bay' ? tb('lanes.noBay') : tb('lanes.noTechnician'),
  282. all: tb('lanes.everyone'),
  283. },
  284. }),
  285. [grouping, store.technicians, store.workBays, boardJobs, tb]
  286. )
  287. // Closed days and who is away, the same as on the board itself.
  288. const calendarDays = useMemo(() => getWeekDays(weekStart), [weekStart])
  289. const technicianLaneIds = useMemo(
  290. () =>
  291. grouping === 'technician'
  292. ? lanes.filter((lane) => !lane.isPlaceholder).map((lane) => lane.id)
  293. : [],
  294. [lanes, grouping]
  295. )
  296. const boardCalendar = useBoardCalendar({ days: calendarDays, technicianLaneIds })
  297. const owners = useMemo(() => {
  298. const map = new Map<string, { name: string; color: string }>()
  299. for (const tech of store.technicians) map.set(tech.id, { name: tech.name, color: tech.color })
  300. for (const bay of store.workBays) map.set(bay.id, { name: bay.name, color: bay.color })
  301. return map
  302. }, [store.technicians, store.workBays])
  303. const jobsByLane = useMemo(
  304. () =>
  305. groupJobsByLane(
  306. boardJobs,
  307. grouping,
  308. new Set(lanes.filter((lane) => !lane.isPlaceholder).map((lane) => lane.id))
  309. ),
  310. [boardJobs, grouping, lanes]
  311. )
  312. return (
  313. <div className="flex h-screen flex-col bg-background">
  314. <header className="flex shrink-0 items-center justify-between border-b px-4 py-2">
  315. <div className="flex items-center gap-3">
  316. <h1 className="text-lg font-bold">{t('title')}</h1>
  317. <span className="min-w-[240px] text-sm text-muted-foreground">{dateLabel}</span>
  318. </div>
  319. <div className="flex items-center gap-3">
  320. {/* Period, then how to draw it, then what the lanes are: the same
  321. three questions the board asks, in the same order. */}
  322. <div className="flex rounded-md border">
  323. <Button
  324. variant={period === 'day' ? 'default' : 'ghost'}
  325. size="sm"
  326. className="rounded-none rounded-l-md"
  327. onClick={() => setPeriod('day')}
  328. >
  329. {t('day')}
  330. </Button>
  331. <Button
  332. variant={period === 'week' ? 'default' : 'ghost'}
  333. size="sm"
  334. className="rounded-none rounded-r-md border-l"
  335. onClick={() => setPeriod('week')}
  336. >
  337. {t('week')}
  338. </Button>
  339. </div>
  340. <div className="flex rounded-md border">
  341. <Button
  342. variant={layout === 'timeline' ? 'default' : 'ghost'}
  343. size="sm"
  344. className="rounded-none rounded-l-md"
  345. onClick={() => setLayout('timeline')}
  346. >
  347. {tt('layoutTimeline')}
  348. </Button>
  349. <Button
  350. variant={layout === 'cards' ? 'default' : 'ghost'}
  351. size="sm"
  352. className="rounded-none border-x"
  353. onClick={() => setLayout('cards')}
  354. >
  355. {tt('layoutCards')}
  356. </Button>
  357. {/* A kanban of one day's work by status. There is no weekly
  358. equivalent, so choosing it switches to a day rather than
  359. disappearing when a week is selected: a control that moves
  360. around under the pointer is worse than one that acts. */}
  361. <Button
  362. variant={layout === 'status' ? 'default' : 'ghost'}
  363. size="sm"
  364. className="rounded-none rounded-r-md"
  365. onClick={() => showStatusBoard()}
  366. >
  367. {t('status')}
  368. </Button>
  369. </div>
  370. {/* Kept in place rather than removed while the status board is up:
  371. the kanban groups by status, so these have nothing to do, but
  372. hiding them shifts every control beside them. */}
  373. <div
  374. className="flex rounded-md border"
  375. title={layout === 'status' ? t('groupingUnused') : undefined}
  376. >
  377. <Button
  378. variant={grouping === 'technician' ? 'default' : 'ghost'}
  379. size="sm"
  380. className="rounded-none rounded-l-md"
  381. disabled={layout === 'status'}
  382. onClick={() => setGrouping('technician')}
  383. >
  384. {tt('technicians')}
  385. </Button>
  386. <Button
  387. variant={grouping === 'bay' ? 'default' : 'ghost'}
  388. size="sm"
  389. className="rounded-none rounded-r-md border-l"
  390. disabled={layout === 'status'}
  391. onClick={() => setGrouping('bay')}
  392. >
  393. {tt('workBays')}
  394. </Button>
  395. </div>
  396. <div className="flex items-center gap-1">
  397. <Button variant="ghost" size="icon" onClick={handlePrev} aria-label={t('previous')}>
  398. <ChevronLeft className="h-5 w-5" />
  399. </Button>
  400. <Button variant="outline" size="sm" onClick={handleToday}>
  401. {t('today')}
  402. </Button>
  403. <Button variant="ghost" size="icon" onClick={handleNext} aria-label={t('next')}>
  404. <ChevronRight className="h-5 w-5" />
  405. </Button>
  406. </div>
  407. <div className="flex items-center gap-2 text-sm text-muted-foreground">
  408. {/* Icon only, and always the same size. The words "Live updates
  409. disconnected" are four times the width of "Live", so swapping
  410. between them shoved every control in the header sideways. */}
  411. <Tooltip>
  412. <TooltipTrigger asChild>
  413. <span
  414. className={cn(
  415. 'flex h-4 w-4 items-center justify-center',
  416. store.connection === 'open' && 'text-green-600',
  417. store.connection === 'closed' && 'animate-pulse text-red-500',
  418. store.connection === 'connecting' && 'text-muted-foreground'
  419. )}
  420. >
  421. {store.connection === 'closed' ? (
  422. <WifiOff className="h-4 w-4" />
  423. ) : (
  424. <Wifi className="h-4 w-4" />
  425. )}
  426. </span>
  427. </TooltipTrigger>
  428. <TooltipContent side="bottom">
  429. {store.connection === 'open'
  430. ? t('live')
  431. : store.connection === 'closed'
  432. ? t('disconnected')
  433. : t('connecting')}
  434. </TooltipContent>
  435. </Tooltip>
  436. <LiveClock format={timeFormat} timeZone={timezone} />
  437. </div>
  438. </div>
  439. </header>
  440. {layout === 'status' ? (
  441. <PresenterKanbanView
  442. date={selectedDate}
  443. technicians={store.technicians}
  444. assignments={boardJobs}
  445. />
  446. ) : lanes.length === 0 ? (
  447. <div className="flex flex-1 items-center justify-center p-10">
  448. <p className="text-lg text-muted-foreground">
  449. {grouping === 'bay' ? tb('noBays') : t('noTechnicians')}
  450. </p>
  451. </div>
  452. ) : (
  453. <div className="flex min-h-0 flex-1 flex-col p-2">
  454. {/* The board the shop plans on, minus everything you could change:
  455. a wall display is read while walking past it. */}
  456. <DndContext>
  457. {layout === 'cards' ? (
  458. <WeekCardGrid
  459. days={days}
  460. lanes={lanes}
  461. jobsByLane={jobsByLane}
  462. todayStr={boardNow(timezone).dayKey}
  463. timeFormat={timeFormat}
  464. lookup={owners}
  465. readOnly
  466. onOpenJob={noop}
  467. closedByDay={boardCalendar.closedByDay}
  468. awayByLaneDay={boardCalendar.awayByLaneDay}
  469. />
  470. ) : (
  471. <WeekTimeline
  472. days={days}
  473. lanes={lanes}
  474. jobs={boardJobs}
  475. grouping={grouping}
  476. zoom={1}
  477. snapMinutes={15}
  478. workDayStart={workDayStart}
  479. workDayEnd={workDayEnd}
  480. onOpenJob={noop}
  481. onSchedule={noop}
  482. readOnly
  483. closedByDay={boardCalendar.closedByDay}
  484. awayByLaneDay={boardCalendar.awayByLaneDay}
  485. />
  486. )}
  487. </DndContext>
  488. </div>
  489. )}
  490. </div>
  491. )
  492. }