| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523 |
- 'use client'
- import { useBoardCalendar } from '../hooks/useBoardCalendar'
- import { useWorkshopDayRollover } from '../hooks/useWorkshopDayRollover'
- import { useState, useEffect, useCallback, useMemo } from 'react'
- import { useSearchParams, useRouter, usePathname } from 'next/navigation'
- import { DndContext } from '@dnd-kit/core'
- import { Button } from '@/components/ui/button'
- import { ChevronLeft, ChevronRight, Wifi, WifiOff } from 'lucide-react'
- import { useWorkBoardStore, type Technician } from '../store/workboardStore'
- import { useWorkBoardWebSocket } from '../hooks/useWorkBoardWebSocket'
- import type { WorkBay, WorkBoardJob } from '../Actions/boardActions'
- import { getBoardJobs } from '../Actions/boardActions'
- import { getTechnicians } from '../Actions/technicianActions'
- import { getWorkBays } from '../Actions/workBayActions'
- import { PresenterKanbanView } from './PresenterKanbanView'
- import { WeekTimeline } from './WeekTimeline'
- import { WeekCardGrid } from './WeekCardGrid'
- import { type BoardLayout, isBoardLayout } from '../hooks/useBoardPreferences'
- import { type ClockFormat } from '../utils/clock'
- import { boardNow, toBoardJob } from '../utils/board-time'
- import { type LaneGrouping, buildLanes, groupJobsByLane, isLaneGrouping } from '../utils/lanes'
- import { useTranslations, useLocale } from 'next-intl'
- import { useDateSettings } from '@/components/date-settings-context'
- import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
- import { cn } from '@/lib/utils'
- type Period = 'day' | 'week'
- /** Timeline and Overview are the board's own layouts; Status is the kanban,
- * which only makes sense for a single day. */
- type PresenterLayout = BoardLayout | 'status'
- /** Older pinned displays carry ?view=; keep those URLs working. */
- const LEGACY_VIEWS: Record<string, { period: Period; layout: PresenterLayout }> = {
- timeline: { period: 'day', layout: 'timeline' },
- day: { period: 'day', layout: 'cards' },
- status: { period: 'day', layout: 'status' },
- week: { period: 'week', layout: 'timeline' },
- }
- function toLocalDateString(d: Date): string {
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
- }
- function getWeekStart(date: Date, weekStartDay: number): string {
- const d = new Date(date)
- const diff = (d.getDay() - weekStartDay + 7) % 7
- d.setDate(d.getDate() - diff)
- return toLocalDateString(d)
- }
- function getWeekDays(weekStart: string): string[] {
- const days: string[] = []
- for (let i = 0; i < 7; i++) {
- const d = new Date(weekStart + 'T12:00:00')
- d.setDate(d.getDate() + i)
- days.push(toLocalDateString(d))
- }
- return days
- }
- /** The presenter shows the board; it never changes it. */
- const noop = () => undefined
- function formatWeekRange(weekStart: string, locale?: string): string {
- const start = new Date(weekStart + 'T12:00:00')
- const end = new Date(start)
- end.setDate(end.getDate() + 6)
- const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' }
- return `${start.toLocaleDateString(locale, opts)} – ${end.toLocaleDateString(locale, { ...opts, year: 'numeric' })}`
- }
- function formatDayDate(dateStr: string, locale?: string): string {
- return new Date(dateStr + 'T12:00:00').toLocaleDateString(locale, {
- weekday: 'long',
- month: 'long',
- day: 'numeric',
- })
- }
- /**
- * The wall clock in the header.
- *
- * Rendered null until the first tick, because the server has no idea what time
- * it is where the screen is and a mismatched first paint is a hydration error.
- * That left a one-space-wide element that jumped to full width a moment later,
- * shoving the header about, so the space is reserved up front: tabular figures
- * and a width sized for the longest the format can be.
- */
- function LiveClock({ format, timeZone }: { format: ClockFormat; timeZone: string }) {
- const [time, setTime] = useState<string | null>(null)
- useEffect(() => {
- function update() {
- setTime(
- new Date().toLocaleTimeString(undefined, {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- hour12: format === '12h',
- // The board below runs on the workshop's clock, so this does too.
- ...(timeZone ? { timeZone } : {}),
- })
- )
- }
- update()
- const timer = setInterval(update, 1000)
- return () => clearInterval(timer)
- }, [format, timeZone])
- return (
- <span
- className="inline-block text-right tabular-nums"
- // "11:59:59 PM" against "23:59:59": reserve for whichever is in use.
- style={{ minWidth: format === '12h' ? '10ch' : '8ch' }}
- >
- {time ?? '\u00A0'}
- </span>
- )
- }
- export function WorkBoardPresenter({
- initialTechnicians,
- initialWorkBays = [],
- initialAssignments,
- initialWeekStart,
- workDayStart = '07:00',
- workDayEnd = '15:00',
- weekStartDay = 1,
- }: {
- initialTechnicians: Technician[]
- initialWorkBays?: WorkBay[]
- initialAssignments: WorkBoardJob[]
- initialWeekStart: string
- workDayStart?: string
- workDayEnd?: string
- weekStartDay?: number
- }) {
- const store = useWorkBoardStore()
- const t = useTranslations('workBoard.presenter')
- const tb = useTranslations('workBoard.board')
- const tt = useTranslations('workBoard.toolbar')
- const { timeFormat, timezone } = useDateSettings()
- const locale = useLocale()
- const searchParams = useSearchParams()
- const router = useRouter()
- const pathname = usePathname()
- const legacy = LEGACY_VIEWS[searchParams.get('view') ?? '']
- const urlPeriod = searchParams.get('period')
- const urlLayout = searchParams.get('layout')
- const urlDate = searchParams.get('date')
- const urlGrouping = searchParams.get('group')
- const [period, setPeriodState] = useState<Period>(
- urlPeriod === 'day' || urlPeriod === 'week' ? urlPeriod : (legacy?.period ?? 'week')
- )
- const [layout, setLayoutState] = useState<PresenterLayout>(
- urlLayout === 'status' || isBoardLayout(urlLayout)
- ? (urlLayout as PresenterLayout)
- : (legacy?.layout ?? 'timeline')
- )
- const [selectedDate, setSelectedDateState] = useState(urlDate || boardNow(timezone).dayKey)
- // The presenter keeps its settings in the address bar rather than reading the
- // planner's saved preference: a wall display is usually a different machine,
- // and one that should stay on whatever it was pinned to.
- const [grouping, setGroupingState] = useState<LaneGrouping>(
- isLaneGrouping(urlGrouping) ? urlGrouping : 'technician'
- )
- const updateUrl = useCallback(
- (p: Period, l: PresenterLayout, d: string, g: LaneGrouping) => {
- const params = new URLSearchParams()
- params.set('period', p)
- params.set('layout', l)
- params.set('date', d)
- params.set('group', g)
- router.replace(`${pathname}?${params.toString()}`, { scroll: false })
- },
- [router, pathname]
- )
- const setSelectedDate = useCallback(
- (d: string) => {
- setSelectedDateState(d)
- updateUrl(period, layout, d, grouping)
- },
- [period, layout, grouping, updateUrl]
- )
- const setPeriod = (p: Period) => {
- // Status is a single day's kanban; a week has no such thing to show.
- const next: PresenterLayout = p === 'week' && layout === 'status' ? 'timeline' : layout
- setPeriodState(p)
- setLayoutState(next)
- updateUrl(p, next, selectedDate, grouping)
- }
- /** The status board is a day's kanban, so asking for it asks for a day. */
- const showStatusBoard = () => {
- setPeriodState('day')
- setLayoutState('status')
- updateUrl('day', 'status', selectedDate, grouping)
- }
- const setLayout = (l: PresenterLayout) => {
- setLayoutState(l)
- updateUrl(period, l, selectedDate, grouping)
- }
- const setGrouping = (g: LaneGrouping) => {
- setGroupingState(g)
- updateUrl(period, layout, selectedDate, g)
- }
- useEffect(() => {
- store.setTechnicians(initialTechnicians)
- store.setWorkBays(initialWorkBays)
- store.setJobs(initialAssignments)
- store.setWeekStart(initialWeekStart) /* eslint-disable-next-line react-hooks/exhaustive-deps */
- }, [])
- useWorkBoardWebSocket()
- const weekStart = store.weekStart || initialWeekStart
- // Day is the same board given one day's worth of columns, exactly as on the
- // planner. Switching period used to swap in a different component entirely.
- const days = period === 'day' ? [selectedDate] : getWeekDays(weekStart)
- const loadWeekData = useCallback(
- async (ws: string) => {
- store.setWeekStart(ws)
- const [assignRes, techRes, bayRes] = await Promise.all([
- getBoardJobs(ws),
- getTechnicians(),
- getWorkBays(),
- ])
- if (assignRes.success && assignRes.data) store.setJobs(assignRes.data as WorkBoardJob[])
- if (techRes.success && techRes.data) store.setTechnicians(techRes.data as Technician[])
- if (bayRes.success && bayRes.data) store.setWorkBays(bayRes.data as WorkBay[])
- },
- [store]
- )
- const ensureWeekLoaded = useCallback(
- (dateStr: string) => {
- const m = getWeekStart(new Date(dateStr + 'T12:00:00'), weekStartDay)
- if (m !== weekStart) loadWeekData(m)
- },
- [weekStart, loadWeekData, weekStartDay]
- )
- const handlePrev = () => {
- if (period === 'week') {
- const d = new Date(weekStart + 'T12:00:00')
- d.setDate(d.getDate() - 7)
- loadWeekData(toLocalDateString(d))
- } else {
- const d = new Date(selectedDate + 'T12:00:00')
- d.setDate(d.getDate() - 1)
- const nd = toLocalDateString(d)
- setSelectedDate(nd)
- ensureWeekLoaded(nd)
- }
- }
- const handleNext = () => {
- if (period === 'week') {
- const d = new Date(weekStart + 'T12:00:00')
- d.setDate(d.getDate() + 7)
- loadWeekData(toLocalDateString(d))
- } else {
- const d = new Date(selectedDate + 'T12:00:00')
- d.setDate(d.getDate() + 1)
- const nd = toLocalDateString(d)
- setSelectedDate(nd)
- ensureWeekLoaded(nd)
- }
- }
- const handleToday = () => {
- const today = boardNow(timezone).dayKey
- setSelectedDate(today)
- loadWeekData(getWeekStart(new Date(`${today}T12:00:00`), weekStartDay))
- }
- // A wall display moves on to the next day by itself, at the workshop's midnight.
- const showNewDay = useCallback(
- (today: string) => {
- setSelectedDate(today)
- loadWeekData(getWeekStart(new Date(`${today}T12:00:00`), weekStartDay))
- },
- [loadWeekData, setSelectedDate, weekStartDay]
- )
- useWorkshopDayRollover(timezone, showNewDay)
- const dateLabel =
- period === 'week' ? formatWeekRange(weekStart, locale) : formatDayDate(selectedDate, locale)
- // Drawn on the workshop's clock; the store keeps real instants.
- const boardJobs = useMemo(
- () => store.jobs.map((job) => toBoardJob(job, timezone)),
- [store.jobs, timezone]
- )
- const lanes = useMemo(
- () =>
- buildLanes({
- grouping,
- technicians: store.technicians,
- workBays: store.workBays,
- jobs: boardJobs,
- labels: {
- unlaned: grouping === 'bay' ? tb('lanes.noBay') : tb('lanes.noTechnician'),
- all: tb('lanes.everyone'),
- },
- }),
- [grouping, store.technicians, store.workBays, boardJobs, tb]
- )
- // Closed days and who is away, the same as on the board itself.
- const calendarDays = useMemo(() => getWeekDays(weekStart), [weekStart])
- const technicianLaneIds = useMemo(
- () =>
- grouping === 'technician'
- ? lanes.filter((lane) => !lane.isPlaceholder).map((lane) => lane.id)
- : [],
- [lanes, grouping]
- )
- const boardCalendar = useBoardCalendar({ days: calendarDays, technicianLaneIds })
- const owners = useMemo(() => {
- const map = new Map<string, { name: string; color: string }>()
- for (const tech of store.technicians) map.set(tech.id, { name: tech.name, color: tech.color })
- for (const bay of store.workBays) map.set(bay.id, { name: bay.name, color: bay.color })
- return map
- }, [store.technicians, store.workBays])
- const jobsByLane = useMemo(
- () =>
- groupJobsByLane(
- boardJobs,
- grouping,
- new Set(lanes.filter((lane) => !lane.isPlaceholder).map((lane) => lane.id))
- ),
- [boardJobs, grouping, lanes]
- )
- return (
- <div className="flex h-screen flex-col bg-background">
- <header className="flex shrink-0 items-center justify-between border-b px-4 py-2">
- <div className="flex items-center gap-3">
- <h1 className="text-lg font-bold">{t('title')}</h1>
- <span className="min-w-[240px] text-sm text-muted-foreground">{dateLabel}</span>
- </div>
- <div className="flex items-center gap-3">
- {/* Period, then how to draw it, then what the lanes are: the same
- three questions the board asks, in the same order. */}
- <div className="flex rounded-md border">
- <Button
- variant={period === 'day' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-l-md"
- onClick={() => setPeriod('day')}
- >
- {t('day')}
- </Button>
- <Button
- variant={period === 'week' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-r-md border-l"
- onClick={() => setPeriod('week')}
- >
- {t('week')}
- </Button>
- </div>
- <div className="flex rounded-md border">
- <Button
- variant={layout === 'timeline' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-l-md"
- onClick={() => setLayout('timeline')}
- >
- {tt('layoutTimeline')}
- </Button>
- <Button
- variant={layout === 'cards' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none border-x"
- onClick={() => setLayout('cards')}
- >
- {tt('layoutCards')}
- </Button>
- {/* A kanban of one day's work by status. There is no weekly
- equivalent, so choosing it switches to a day rather than
- disappearing when a week is selected: a control that moves
- around under the pointer is worse than one that acts. */}
- <Button
- variant={layout === 'status' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-r-md"
- onClick={() => showStatusBoard()}
- >
- {t('status')}
- </Button>
- </div>
- {/* Kept in place rather than removed while the status board is up:
- the kanban groups by status, so these have nothing to do, but
- hiding them shifts every control beside them. */}
- <div
- className="flex rounded-md border"
- title={layout === 'status' ? t('groupingUnused') : undefined}
- >
- <Button
- variant={grouping === 'technician' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-l-md"
- disabled={layout === 'status'}
- onClick={() => setGrouping('technician')}
- >
- {tt('technicians')}
- </Button>
- <Button
- variant={grouping === 'bay' ? 'default' : 'ghost'}
- size="sm"
- className="rounded-none rounded-r-md border-l"
- disabled={layout === 'status'}
- onClick={() => setGrouping('bay')}
- >
- {tt('workBays')}
- </Button>
- </div>
- <div className="flex items-center gap-1">
- <Button variant="ghost" size="icon" onClick={handlePrev} aria-label={t('previous')}>
- <ChevronLeft className="h-5 w-5" />
- </Button>
- <Button variant="outline" size="sm" onClick={handleToday}>
- {t('today')}
- </Button>
- <Button variant="ghost" size="icon" onClick={handleNext} aria-label={t('next')}>
- <ChevronRight className="h-5 w-5" />
- </Button>
- </div>
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- {/* Icon only, and always the same size. The words "Live updates
- disconnected" are four times the width of "Live", so swapping
- between them shoved every control in the header sideways. */}
- <Tooltip>
- <TooltipTrigger asChild>
- <span
- className={cn(
- 'flex h-4 w-4 items-center justify-center',
- store.connection === 'open' && 'text-green-600',
- store.connection === 'closed' && 'animate-pulse text-red-500',
- store.connection === 'connecting' && 'text-muted-foreground'
- )}
- >
- {store.connection === 'closed' ? (
- <WifiOff className="h-4 w-4" />
- ) : (
- <Wifi className="h-4 w-4" />
- )}
- </span>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- {store.connection === 'open'
- ? t('live')
- : store.connection === 'closed'
- ? t('disconnected')
- : t('connecting')}
- </TooltipContent>
- </Tooltip>
- <LiveClock format={timeFormat} timeZone={timezone} />
- </div>
- </div>
- </header>
- {layout === 'status' ? (
- <PresenterKanbanView
- date={selectedDate}
- technicians={store.technicians}
- assignments={boardJobs}
- />
- ) : lanes.length === 0 ? (
- <div className="flex flex-1 items-center justify-center p-10">
- <p className="text-lg text-muted-foreground">
- {grouping === 'bay' ? tb('noBays') : t('noTechnicians')}
- </p>
- </div>
- ) : (
- <div className="flex min-h-0 flex-1 flex-col p-2">
- {/* The board the shop plans on, minus everything you could change:
- a wall display is read while walking past it. */}
- <DndContext>
- {layout === 'cards' ? (
- <WeekCardGrid
- days={days}
- lanes={lanes}
- jobsByLane={jobsByLane}
- todayStr={boardNow(timezone).dayKey}
- timeFormat={timeFormat}
- lookup={owners}
- readOnly
- onOpenJob={noop}
- closedByDay={boardCalendar.closedByDay}
- awayByLaneDay={boardCalendar.awayByLaneDay}
- />
- ) : (
- <WeekTimeline
- days={days}
- lanes={lanes}
- jobs={boardJobs}
- grouping={grouping}
- zoom={1}
- snapMinutes={15}
- workDayStart={workDayStart}
- workDayEnd={workDayEnd}
- onOpenJob={noop}
- onSchedule={noop}
- readOnly
- closedByDay={boardCalendar.closedByDay}
- awayByLaneDay={boardCalendar.awayByLaneDay}
- />
- )}
- </DndContext>
- </div>
- )}
- </div>
- )
- }
|