Просмотр исходного кода

Count a multi-day job as one working day on the work board and show how far over a day is (#609)

* Count a multi-day job as one working day on the work board and say how far over a day is

* Keep the day's load out of the lane button's name on the timeline
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
982cc0f81a

+ 6 - 1
messages/de/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Alle Arbeiten",
       "thisWeek": "Diese Woche"
     },
-    "dropNeedsLane": "Gruppieren Sie das Board nach Mechaniker oder Arbeitsplatz, bevor Sie einen Auftrag darauf ziehen."
+    "dropNeedsLane": "Gruppieren Sie das Board nach Mechaniker oder Arbeitsplatz, bevor Sie einen Auftrag darauf ziehen.",
+    "load": {
+      "over": "{amount} zu viel",
+      "spoken": "Verplant: {booked} von {capacity}",
+      "spokenOver": "Verplant: {booked} von {capacity}, überbucht um {amount}"
+    }
   },
   "unassigned": {
     "title": "Nicht zugewiesene Aufträge ({count})",

+ 6 - 1
messages/en/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "All work",
       "thisWeek": "This week"
     },
-    "dropNeedsLane": "Group the board by technician or work bay before dropping a job onto it."
+    "dropNeedsLane": "Group the board by technician or work bay before dropping a job onto it.",
+    "load": {
+      "over": "{amount} over",
+      "spoken": "{booked} booked of {capacity}",
+      "spokenOver": "{booked} booked of {capacity}, {amount} over"
+    }
   },
   "unassigned": {
     "title": "Unassigned Jobs ({count})",

+ 6 - 1
messages/es/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Todo el trabajo",
       "thisWeek": "Esta semana"
     },
-    "dropNeedsLane": "Agrupa el tablero por técnico o puesto de trabajo antes de soltar un trabajo en él."
+    "dropNeedsLane": "Agrupa el tablero por técnico o puesto de trabajo antes de soltar un trabajo en él.",
+    "load": {
+      "over": "{amount} de más",
+      "spoken": "Programado: {booked} de {capacity}",
+      "spokenOver": "Programado: {booked} de {capacity}, excedido en {amount}"
+    }
   },
   "unassigned": {
     "title": "Trabajos Sin Asignar ({count})",

+ 6 - 1
messages/fr/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Tout le travail",
       "thisWeek": "Cette semaine"
     },
-    "dropNeedsLane": "Groupez le tableau par technicien ou par poste avant d'y déposer une tâche."
+    "dropNeedsLane": "Groupez le tableau par technicien ou par poste avant d'y déposer une tâche.",
+    "load": {
+      "over": "{amount} de trop",
+      "spoken": "Planifié : {booked} sur {capacity}",
+      "spokenOver": "Planifié : {booked} sur {capacity}, dépassement de {amount}"
+    }
   },
   "unassigned": {
     "title": "Travaux Non Assignés ({count})",

+ 6 - 1
messages/it/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Tutto il lavoro",
       "thisWeek": "Questa settimana"
     },
-    "dropNeedsLane": "Raggruppa la lavagna per tecnico o postazione prima di trascinarci un lavoro."
+    "dropNeedsLane": "Raggruppa la lavagna per tecnico o postazione prima di trascinarci un lavoro.",
+    "load": {
+      "over": "{amount} in più",
+      "spoken": "Pianificato: {booked} su {capacity}",
+      "spokenOver": "Pianificato: {booked} su {capacity}, eccedenza di {amount}"
+    }
   },
   "unassigned": {
     "title": "Lavori Non Assegnati ({count})",

+ 6 - 1
messages/lt/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Visi darbai",
       "thisWeek": "Ši savaitė"
     },
-    "dropNeedsLane": "Prieš vilkdami darbą, sugrupuokite lentą pagal meistrą arba darbo vietą."
+    "dropNeedsLane": "Prieš vilkdami darbą, sugrupuokite lentą pagal meistrą arba darbo vietą.",
+    "load": {
+      "over": "{amount} per daug",
+      "spoken": "Suplanuota {booked} iš {capacity}",
+      "spokenOver": "Suplanuota {booked} iš {capacity}, viršyta {amount}"
+    }
   },
   "unassigned": {
     "title": "Nepriskirti darbai ({count})",

+ 6 - 1
messages/nb/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Alt arbeid",
       "thisWeek": "Denne uken"
     },
-    "dropNeedsLane": "Grupper tavlen etter mekaniker eller arbeidsplass før du slipper en jobb på den."
+    "dropNeedsLane": "Grupper tavlen etter mekaniker eller arbeidsplass før du slipper en jobb på den.",
+    "load": {
+      "over": "{amount} for mye",
+      "spoken": "Booket: {booked} av {capacity}",
+      "spokenOver": "Booket: {booked} av {capacity}, overbooket med {amount}"
+    }
   },
   "unassigned": {
     "title": "Utildelte jobber ({count})",

+ 6 - 1
messages/nl/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Al het werk",
       "thisWeek": "Deze week"
     },
-    "dropNeedsLane": "Groepeer het bord op monteur of werkplek voordat je een klus erop sleept."
+    "dropNeedsLane": "Groepeer het bord op monteur of werkplek voordat je een klus erop sleept.",
+    "load": {
+      "over": "{amount} te veel",
+      "spoken": "Ingepland: {booked} van {capacity}",
+      "spokenOver": "Ingepland: {booked} van {capacity}, {amount} te veel"
+    }
   },
   "unassigned": {
     "title": "Niet-toegewezen taken ({count})",

+ 6 - 1
messages/pl/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Cała praca",
       "thisWeek": "Ten tydzień"
     },
-    "dropNeedsLane": "Pogrupuj tablicę według mechanika lub stanowiska, zanim przeciągniesz na nią zlecenie."
+    "dropNeedsLane": "Pogrupuj tablicę według mechanika lub stanowiska, zanim przeciągniesz na nią zlecenie.",
+    "load": {
+      "over": "{amount} za dużo",
+      "spoken": "Zaplanowano {booked} z {capacity}",
+      "spokenOver": "Zaplanowano {booked} z {capacity}, przekroczono o {amount}"
+    }
   },
   "unassigned": {
     "title": "Nieprzyzdzielone Zadania ({count})",

+ 6 - 1
messages/pt-BR/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Todo o trabalho",
       "thisWeek": "Esta semana"
     },
-    "dropNeedsLane": "Agrupe o quadro por técnico ou baia antes de soltar um serviço nele."
+    "dropNeedsLane": "Agrupe o quadro por técnico ou baia antes de soltar um serviço nele.",
+    "load": {
+      "over": "{amount} a mais",
+      "spoken": "Agendado: {booked} de {capacity}",
+      "spokenOver": "Agendado: {booked} de {capacity}, excedido em {amount}"
+    }
   },
   "unassigned": {
     "title": "Trabalhos Não Atribuídos ({count})",

+ 6 - 1
messages/pt-PT/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Todo o trabalho",
       "thisWeek": "Esta semana"
     },
-    "dropNeedsLane": "Agrupe o quadro por técnico ou por posto de trabalho antes de largar um trabalho nele."
+    "dropNeedsLane": "Agrupe o quadro por técnico ou por posto de trabalho antes de largar um trabalho nele.",
+    "load": {
+      "over": "{amount} a mais",
+      "spoken": "Marcado: {booked} de {capacity}",
+      "spokenOver": "Marcado: {booked} de {capacity}, excedido em {amount}"
+    }
   },
   "unassigned": {
     "title": "Trabalhos Não Atribuídos ({count})",

+ 6 - 1
messages/ru/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Вся работа",
       "thisWeek": "Эта неделя"
     },
-    "dropNeedsLane": "Сгруппируйте доску по механику или посту, прежде чем переносить на неё работу."
+    "dropNeedsLane": "Сгруппируйте доску по механику или посту, прежде чем переносить на неё работу.",
+    "load": {
+      "over": "перегруз {amount}",
+      "spoken": "Запланировано {booked} из {capacity}",
+      "spokenOver": "Запланировано {booked} из {capacity}, превышение на {amount}"
+    }
   },
   "unassigned": {
     "title": "Неназначенные работы ({count})",

+ 6 - 1
messages/tr/workBoard.json

@@ -58,7 +58,12 @@
       "everyone": "Tüm işler",
       "thisWeek": "Bu hafta"
     },
-    "dropNeedsLane": "Bir işi panoya bırakmadan önce panoyu teknisyene veya çalışma alanına göre gruplayın."
+    "dropNeedsLane": "Bir işi panoya bırakmadan önce panoyu teknisyene veya çalışma alanına göre gruplayın.",
+    "load": {
+      "over": "{amount} fazla",
+      "spoken": "Planlanan: {booked} / {capacity}",
+      "spokenOver": "Planlanan: {booked} / {capacity}, {amount} aşım"
+    }
   },
   "unassigned": {
     "title": "Atanmamış İşler ({count})",

+ 317 - 0
src/__tests__/features/workboard/day-booked-hours.test.tsx

@@ -0,0 +1,317 @@
+/**
+ * The hours under a technician's day, as a planner reads them.
+ *
+ * A wall screen showed "1117h / 8h" on a Monday: a restoration booked across
+ * seven weeks was counted whole on every day it touched. The figure is how
+ * much of that one day the work takes, so a job that runs for weeks takes a
+ * working day of it and no more, and the card grid and the timeline say the
+ * same number for the same day.
+ *
+ * Every case runs in two zones far from UTC and on opposite sides of it: the
+ * board reads its days with a `Date`'s local getters.
+ */
+
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { DndContext } from '@dnd-kit/core'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import type { WorkBoardJob } from '@/features/workboard/Actions/boardActions'
+import { WeekCardGrid } from '@/features/workboard/Components/WeekCardGrid'
+import { WeekTimeline } from '@/features/workboard/Components/WeekTimeline'
+import {
+  type AwayByLaneDay,
+  type ClosedByDay,
+  awayKey,
+} from '@/features/workboard/hooks/useBoardCalendar'
+import { buildLanes, groupJobsByLane } from '@/features/workboard/utils/lanes'
+import type { Technician } from '@/features/workboard/store/workboardStore'
+import { awayDay, closedDay } from '@/features/workshop-calendar/Lib/boardDays'
+import { type WorkshopCalendar, defaultWeek } from '@/features/workshop-calendar/Lib/calendar'
+
+vi.mock('@/components/date-settings-context', () => ({
+  useDateSettings: () => ({
+    dateFormat: 'yyyy-MM-dd',
+    timeFormat: '24h',
+    timezone: '',
+    weekStartDay: 1,
+  }),
+}))
+
+// Monday to Wednesday of one week.
+const MON = '2026-11-09'
+const TUE = '2026-11-10'
+const WED = '2026-11-11'
+
+const technician = (id: string, name: string, sortOrder: number): Technician => ({
+  id,
+  name,
+  color: '#3b82f6',
+  isActive: true,
+  sortOrder,
+  dailyCapacity: 480,
+  userId: null,
+  organizationId: 'org-a',
+})
+
+const technicians = [technician('ada', 'Ada', 0), technician('sam', 'Sam', 1)]
+
+/** Times without a zone, as the board draws them: the workshop's wall clock. */
+function job(id: string, title: string, start: string, end: string, helperIds: string[] = []) {
+  return {
+    id,
+    type: 'serviceRecord',
+    technicianId: 'ada',
+    helperIds,
+    workBayId: null,
+    customerName: null,
+    sortOrder: 0,
+    title,
+    status: 'in-progress',
+    startDateTime: start,
+    endDateTime: end,
+    promisedAt: null,
+    vehicle: null,
+  } satisfies WorkBoardJob
+}
+
+/** Seven weeks in the shop, like the Dauphine on the wall screen. */
+const restoration = job(
+  'restoration',
+  'Dauphine restoration',
+  '2026-10-19T08:00:00',
+  '2026-12-04T17:00:00'
+)
+const engineRebuild = job('engine', 'Engine rebuild', '2026-11-02T08:00:00', '2026-11-20T16:00:00')
+const respray = job('respray', 'Respray', '2026-11-05T09:00:00', '2026-11-13T15:00:00')
+
+/** Open 08:00 to 16:00 on weekdays: an eight hour day, the same as Ada's capacity. */
+function calendar(extra: Partial<WorkshopCalendar> = {}): WorkshopCalendar {
+  return {
+    timeZone: 'UTC',
+    week: defaultWeek('08:00', '16:00'),
+    closures: [],
+    absences: [],
+    ...extra,
+  }
+}
+
+function boardCalendar(cal: WorkshopCalendar, days: string[]) {
+  const closedByDay: ClosedByDay = {}
+  const awayByLaneDay: AwayByLaneDay = {}
+  for (const day of days) {
+    closedByDay[day] = { ...closedDay(cal, day), label: null }
+    for (const tech of technicians) {
+      const away = awayDay(cal, tech.id, day)
+      if (away)
+        awayByLaneDay[awayKey(tech.id, day)] = {
+          spans: away.spans,
+          allDay: away.allDay,
+          label: 'Holiday',
+        }
+    }
+  }
+  return { closedByDay, awayByLaneDay }
+}
+
+function lanesFor(jobs: WorkBoardJob[]) {
+  return buildLanes({
+    grouping: 'technician',
+    technicians,
+    workBays: [],
+    jobs,
+    labels: { unlaned: 'No technician', all: 'Everyone' },
+  })
+}
+
+function renderCards(jobs: WorkBoardJob[], days: string[], cal: WorkshopCalendar | null) {
+  const board = cal ? boardCalendar(cal, days) : {}
+  render(
+    <TooltipProvider>
+      <DndContext>
+        <WeekCardGrid
+          days={days}
+          lanes={lanesFor(jobs)}
+          jobsByLane={groupJobsByLane(jobs, 'technician')}
+          todayStr={MON}
+          timeFormat="24h"
+          onOpenJob={vi.fn()}
+          {...board}
+        />
+      </DndContext>
+    </TooltipProvider>
+  )
+}
+
+/** The timeline's figure for Ada's day is in the hover on her lane header. */
+async function timelineBooked(jobs: WorkBoardJob[], day: string, cal: WorkshopCalendar | null) {
+  cleanup()
+  const board = cal ? boardCalendar(cal, [day]) : {}
+  render(
+    <TooltipProvider>
+      <DndContext>
+        <WeekTimeline
+          days={[day]}
+          lanes={lanesFor(jobs)}
+          jobs={jobs}
+          grouping="technician"
+          zoom={1}
+          snapMinutes={15}
+          workDayStart="08:00"
+          workDayEnd="16:00"
+          onOpenJob={vi.fn()}
+          onSchedule={vi.fn()}
+          onLaneClick={vi.fn()}
+          {...board}
+        />
+      </DndContext>
+    </TooltipProvider>
+  )
+  fireEvent.focus(screen.getByRole('button', { name: /^Ada/ }))
+  const tip = await screen.findByRole('tooltip')
+  return tip.textContent?.match(/Booked(.+?)(Capacity|Jobs)/)?.[1] ?? null
+}
+
+/** The figures under the days, in the order the grid draws them. */
+function figures() {
+  return screen.queryAllByText(/ \/ 8h$/).map((el) => el.textContent)
+}
+
+// The timeline measures itself; jsdom has nothing to measure with.
+const noop = () => undefined
+vi.stubGlobal(
+  'ResizeObserver',
+  class {
+    observe = noop
+    unobserve = noop
+    disconnect = noop
+  }
+)
+
+const originalTz = process.env.TZ
+
+describe.each(['Pacific/Auckland', 'America/Los_Angeles'])('booked hours on a day (%s)', (zone) => {
+  beforeAll(() => {
+    process.env.TZ = zone
+  })
+  afterAll(() => {
+    process.env.TZ = originalTz
+  })
+
+  it('counts a job that runs for weeks as one working day on each day', () => {
+    renderCards([restoration], [MON, TUE, WED], calendar())
+
+    expect(figures()).toEqual(['8h / 8h', '8h / 8h', '8h / 8h'])
+  })
+
+  it('says the same figure in the timeline', async () => {
+    expect(await timelineBooked([restoration], MON, calendar())).toBe('8h')
+  })
+
+  it('still reads sanely before the opening hours have loaded', async () => {
+    renderCards([restoration], [MON], null)
+
+    // No hours to go by, so the technician's own day is the most it can take.
+    expect(figures()).toEqual(['8h / 8h'])
+    expect(await timelineBooked([restoration], MON, null)).toBe('8h')
+  })
+
+  it('counts a same-day job in full, the part after closing included', async () => {
+    const lateJob = job('late', 'Clutch', `${MON}T13:00:00`, `${MON}T19:00:00`)
+    renderCards([lateJob], [MON], calendar())
+
+    // Closing is 16:00, and the three hours after it are still work.
+    expect(figures()).toEqual(['6h / 8h'])
+    expect(await timelineBooked([lateJob], MON, calendar())).toBe('6h')
+  })
+
+  it('adds nothing from a long job on a day the workshop is closed', async () => {
+    const closed = calendar({
+      closures: [{ name: 'Armistice Day', source: 'holiday', startDate: WED, endDate: WED }],
+    })
+    renderCards([restoration], [TUE, WED], closed)
+
+    // The job is still drawn on the closed day; it just fills none of it.
+    expect(screen.getAllByText('Dauphine restoration')).toHaveLength(2)
+    expect(figures()).toEqual(['8h / 8h'])
+    expect(await timelineBooked([restoration], WED, closed)).toBe('0min')
+  })
+
+  it('adds nothing from a long job on a day the technician is away', () => {
+    const away = calendar({
+      absences: [
+        { id: 'a1', technicianId: 'ada', startDate: TUE, endDate: TUE, reason: 'holiday' },
+      ],
+    })
+    renderCards([restoration], [MON, TUE], away)
+
+    expect(figures()).toEqual(['8h / 8h'])
+  })
+
+  it('still counts a job booked for the closed day itself', () => {
+    const closed = calendar({
+      closures: [{ name: 'Armistice Day', source: 'holiday', startDate: WED, endDate: WED }],
+    })
+    const favour = job('favour', 'Bulb change', `${WED}T10:00:00`, `${WED}T11:00:00`)
+    renderCards([restoration, favour], [WED], closed)
+
+    expect(figures()).toEqual(['1h / 8h'])
+  })
+
+  it('adds three long jobs on one day up to three working days', async () => {
+    const jobs = [restoration, engineRebuild, respray]
+    renderCards(jobs, [MON], calendar())
+
+    expect(figures()).toEqual(['24h / 8h'])
+    expect(await timelineBooked(jobs, MON, calendar())).toBe('24h')
+  })
+
+  it('says how far over a day is, so nobody has to subtract', () => {
+    renderCards([restoration, engineRebuild, respray], [MON], calendar())
+
+    expect(screen.getByText('· 16h over')).toBeInTheDocument()
+    // And as one statement for somebody who hears the board.
+    expect(screen.getByText('24h booked of 8h, 16h over')).toBeInTheDocument()
+  })
+
+  it('says a part of an hour over the way the board writes any duration', () => {
+    const long = job('long', 'Timing belt', `${MON}T08:00:00`, `${MON}T16:30:00`)
+    renderCards([long], [MON], calendar())
+
+    expect(figures()).toEqual(['8h 30min / 8h'])
+    expect(screen.getByText('· 30min over')).toBeInTheDocument()
+  })
+
+  it('says nothing about being over on a day that is full or has room', () => {
+    const short = job('short', 'Oil change', `${TUE}T09:00:00`, `${TUE}T10:00:00`)
+    renderCards([restoration, { ...short, technicianId: 'sam' }], [MON, TUE], calendar())
+
+    expect(figures()).toEqual(['8h / 8h', '8h / 8h', '1h / 8h'])
+    expect(screen.queryByText(/over$/)).toBeNull()
+    expect(screen.getByText('1h booked of 8h')).toBeInTheDocument()
+  })
+
+  it('says the same in the timeline, for the eye and for the ear', async () => {
+    const jobs = [restoration, engineRebuild, respray]
+    expect(await timelineBooked(jobs, MON, calendar())).toBe('24h')
+    expect(screen.getByRole('tooltip')).toHaveTextContent('Over by16h')
+    // The lane's button keeps the lane's name; the load is what describes it.
+    expect(screen.getByRole('button', { name: 'Ada' })).toHaveAccessibleDescription(
+      '24h booked of 8h, 16h over'
+    )
+  })
+
+  it('counts the first and last day of a long job from when it starts and to when it ends', () => {
+    const overnight = job('gearbox', 'Gearbox', `${MON}T14:00:00`, `${WED}T10:00:00`)
+    renderCards([overnight], [MON, TUE, WED], calendar())
+
+    // 14:00 to closing, a whole day, opening to 10:00.
+    expect(figures()).toEqual(['2h / 8h', '8h / 8h', '2h / 8h'])
+  })
+
+  it('fills the day of a helper on a long job as it fills the technician’s', () => {
+    const shared = { ...restoration, helperIds: ['sam'] }
+    renderCards([shared], [MON], calendar())
+
+    expect(figures()).toEqual(['8h / 8h', '8h / 8h'])
+  })
+})

+ 41 - 0
src/__tests__/features/workboard/week-layout.test.ts

@@ -255,6 +255,47 @@ describe('bookedMinutesOnDay', () => {
     expect(total).toBe(120)
   })
 
+  // Closed before 08:00 and after 16:00.
+  const OPEN_8_TO_16 = [
+    { startMins: 0, endMins: 480 },
+    { startMins: 960, endMins: 1440 },
+  ]
+
+  it('counts a job passing through the day for its opening hours, not 24 hours', () => {
+    const passing = job('a', '2026-01-01T08:00:00', '2026-12-31T16:00:00')
+    expect(bookedMinutesOnDay([passing], DAY, { closedSpans: OPEN_8_TO_16 })).toBe(480)
+  })
+
+  it('never lets one such job take more than the lane’s capacity', () => {
+    const passing = job('a', '2026-01-01T08:00:00', '2026-12-31T16:00:00')
+    expect(
+      bookedMinutesOnDay([passing], DAY, { closedSpans: OPEN_8_TO_16, capacityMinutes: 360 })
+    ).toBe(360)
+    // With no opening hours to go by, the capacity is all there is.
+    expect(bookedMinutesOnDay([passing], DAY, { capacityMinutes: 480 })).toBe(480)
+  })
+
+  it('takes the technician’s time away out of a passing job', () => {
+    const passing = job('a', '2026-01-01T08:00:00', '2026-12-31T16:00:00')
+    expect(
+      bookedMinutesOnDay([passing], DAY, {
+        closedSpans: OPEN_8_TO_16,
+        awaySpans: [{ startMins: 720, endMins: 1440 }],
+      })
+    ).toBe(240)
+  })
+
+  it('leaves a same-day job whole whatever the hours say', () => {
+    const late = job('a', `${DAY}T15:00:00`, `${DAY}T19:00:00`)
+    expect(
+      bookedMinutesOnDay([late], DAY, {
+        closedSpans: [{ startMins: 0, endMins: 1440 }],
+        awaySpans: [{ startMins: 0, endMins: 1440 }],
+        capacityMinutes: 60,
+      })
+    ).toBe(240)
+  })
+
   it('counts work booked outside the visible hours', () => {
     const total = bookedMinutesOnDay([job('a', `${DAY}T19:00:00`, `${DAY}T21:00:00`)], DAY)
     expect(total).toBe(120)

+ 95 - 0
src/features/workboard/Components/DayLoad.tsx

@@ -0,0 +1,95 @@
+'use client'
+
+import { useTranslations } from 'next-intl'
+import { cn } from '@/lib/utils'
+import { type DayLoad, dayLoad } from '../utils/layout'
+import { formatDuration } from './DurationSlider'
+
+/** Red past full, amber from three quarters, green below: the one scale every bar uses. */
+function barColour(load: DayLoad): string {
+  return load.overMinutes > 0 ? 'bg-red-500' : load.pct >= 75 ? 'bg-amber-500' : 'bg-emerald-500'
+}
+
+/**
+ * How full a day is, as a bar. It stops at full width however far over the
+ * day is: the amount over is said in words beside it, not drawn.
+ */
+export function DayLoadBar({ load, className }: { load: DayLoad; className?: string }) {
+  return (
+    <span className={cn('block w-full overflow-hidden rounded-full bg-muted', className)}>
+      <span
+        className={cn('block h-full rounded-full', barColour(load))}
+        style={{ width: `${Math.min(load.pct, 100)}%` }}
+      />
+    </span>
+  )
+}
+
+/**
+ * The day's load as one statement for a screen reader: booked, capacity and,
+ * past capacity, how much over. What is drawn beside it is hidden from one,
+ * so the figure is heard once and whole.
+ *
+ * Inside a control, pass an `id` and point the control's `aria-describedby`
+ * at it: the statement is then the control's description and stays out of
+ * its name, so a lane's button is still called by the lane's name alone.
+ */
+export function DayLoadSpoken({ load, id }: { load: DayLoad; id?: string }) {
+  const t = useTranslations('workBoard.board.load')
+  if (load.capacityMinutes <= 0) return null
+  const booked = formatDuration(load.bookedMinutes)
+  const capacity = formatDuration(load.capacityMinutes)
+  return (
+    <span className="sr-only" id={id} aria-hidden={id ? true : undefined}>
+      {load.overMinutes > 0
+        ? t('spokenOver', { booked, capacity, amount: formatDuration(load.overMinutes) })
+        : t('spoken', { booked, capacity })}
+    </span>
+  )
+}
+
+/**
+ * The line under a day: "6h / 8h", and past capacity "11h / 8h · 3h over".
+ *
+ * Red text is the 700 shade on a light theme and the 400 on a dark one, as
+ * src/lib/status-colors.ts has it: the 500 the line used to carry is under
+ * 4.5:1 on a light card at this size.
+ *
+ * The two halves each stay on one line and the pair wraps between them, so a
+ * narrow column on a wall screen in a long language breaks the line in two
+ * and never cuts a figure off.
+ */
+export function DayLoadFigure({
+  bookedMinutes,
+  capacityMinutes,
+}: {
+  bookedMinutes: number
+  capacityMinutes: number
+}) {
+  const t = useTranslations('workBoard.board.load')
+  const load = dayLoad(bookedMinutes, capacityMinutes)
+  const over = load.overMinutes > 0
+
+  return (
+    <div className="mt-auto space-y-0.5 pt-1">
+      <DayLoadBar load={load} className="h-1" />
+      <p
+        className={cn(
+          'flex flex-wrap justify-center gap-x-1 text-center text-[10px] font-medium tabular-nums',
+          over ? 'text-red-700 dark:text-red-400' : 'text-muted-foreground'
+        )}
+      >
+        <span className="whitespace-nowrap" aria-hidden={capacityMinutes > 0}>
+          {formatDuration(bookedMinutes)}
+          {capacityMinutes > 0 ? ` / ${formatDuration(capacityMinutes)}` : ''}
+        </span>
+        {over && (
+          <span className="whitespace-nowrap font-semibold" aria-hidden>
+            {`· ${t('over', { amount: formatDuration(load.overMinutes) })}`}
+          </span>
+        )}
+        <DayLoadSpoken load={load} />
+      </p>
+    </div>
+  )
+}

+ 21 - 11
src/features/workboard/Components/LaneHeaderTooltip.tsx

@@ -3,7 +3,9 @@
 import { useTranslations } from 'next-intl'
 import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
 import type { WorkBoardJob } from '../Actions/boardActions'
-import { bookedMinutesOnDay } from '../utils/layout'
+import { type AwayByLaneDay, type ClosedByDay, laneDayHours } from '../hooks/useBoardCalendar'
+import { jobOverlapsDate } from '../utils/datetime'
+import { bookedMinutesOnDay, dayLoad } from '../utils/layout'
 import type { BoardLane } from '../utils/lanes'
 import { formatDuration } from './DurationSlider'
 
@@ -22,6 +24,8 @@ export function LaneHeaderTooltip({
   capacityMinutes,
   periodLabel,
   awayLabel,
+  closedByDay,
+  awayByLaneDay,
   children,
 }: {
   lane: BoardLane
@@ -33,15 +37,23 @@ export function LaneHeaderTooltip({
   periodLabel: string
   /** Why the technician is away, when they are. */
   awayLabel?: string
+  /** The workshop calendar for the days, so the total matches the day figures. */
+  closedByDay?: ClosedByDay
+  awayByLaneDay?: AwayByLaneDay
   children: React.ReactNode
 }) {
   const t = useTranslations('workBoard.lane')
   const tc = useTranslations('workshopCalendar')
 
-  const booked = days.reduce((sum, day) => sum + bookedMinutesOnDay(jobs, day), 0)
-  const jobCount = jobs.filter((job) => days.some((day) => touchesDay(job, day))).length
-  const pct = capacityMinutes > 0 ? Math.round((booked / capacityMinutes) * 100) : null
-  const free = capacityMinutes - booked
+  const booked = days.reduce(
+    (sum, day) =>
+      sum + bookedMinutesOnDay(jobs, day, laneDayHours(lane, day, closedByDay, awayByLaneDay)),
+    0
+  )
+  // Every job on the days, one that adds no hours on a closed day included.
+  const jobCount = jobs.filter((job) => days.some((day) => jobOverlapsDate(job, day))).length
+  const load = dayLoad(booked, capacityMinutes)
+  const pct = capacityMinutes > 0 ? Math.round(load.pct) : null
 
   return (
     <Tooltip>
@@ -58,8 +70,10 @@ export function LaneHeaderTooltip({
             <>
               <Row label={t('capacity')} value={formatDuration(capacityMinutes)} />
               <Row
-                label={free >= 0 ? t('free') : t('over')}
-                value={formatDuration(Math.abs(free))}
+                label={load.overMinutes > 0 ? t('over') : t('free')}
+                value={formatDuration(
+                  load.overMinutes > 0 ? load.overMinutes : capacityMinutes - booked
+                )}
               />
             </>
           )}
@@ -92,7 +106,3 @@ function Row({ label, value }: { label: string; value: string }) {
     </div>
   )
 }
-
-function touchesDay(job: WorkBoardJob, day: string): boolean {
-  return bookedMinutesOnDay([job], day) > 0
-}

+ 15 - 30
src/features/workboard/Components/WeekCardGrid.tsx

@@ -5,18 +5,20 @@ import {
   type BoardAway,
   type ClosedByDay,
   awayKey,
+  laneDayHours,
 } from '../hooks/useBoardCalendar'
 import { useDroppable } from '@dnd-kit/core'
 import { ClipboardCheck, Users, Wrench } from 'lucide-react'
 import { useTranslations } from 'next-intl'
 import { cn } from '@/lib/utils'
 import type { WorkBoardJob } from '../Actions/boardActions'
-import { getDurationMinutes, getJobDateRange, jobOverlapsDate } from '../utils/datetime'
+import { jobOverlapsDate } from '../utils/datetime'
+import { bookedMinutesOnDay } from '../utils/layout'
 import type { ClockFormat } from '../utils/clock'
 import { type BoardLane, isHelperLane } from '../utils/lanes'
 import { interactiveRow } from '@/lib/interactive-row'
 import { BoardJobCard, TeamCount } from './BoardJobCard'
-import { formatDuration } from './DurationSlider'
+import { DayLoadFigure } from './DayLoad'
 import { JobTooltip } from './JobTooltip'
 import { LaneHeaderTooltip } from './LaneHeaderTooltip'
 
@@ -100,6 +102,8 @@ export function WeekCardGrid({
                 days={days}
                 capacityMinutes={lane.dailyCapacity * days.length}
                 periodLabel={t('lanes.thisWeek')}
+                closedByDay={closedByDay}
+                awayByLaneDay={awayByLaneDay}
               >
                 <button
                   type="button"
@@ -124,6 +128,11 @@ export function WeekCardGrid({
                   date={day}
                   jobs={laneJobs.filter((job) => jobOverlapsDate(job, day))}
                   isToday={day === todayStr}
+                  booked={bookedMinutesOnDay(
+                    laneJobs,
+                    day,
+                    laneDayHours(lane, day, closedByDay, awayByLaneDay)
+                  )}
                   closedAllDay={!!closedByDay?.[day]?.allDay}
                   away={awayByLaneDay?.[awayKey(lane.id, day)]}
                   readOnly={readOnly}
@@ -146,6 +155,7 @@ function DayCell({
   lane,
   date,
   jobs,
+  booked,
   isToday,
   closedAllDay,
   away,
@@ -157,6 +167,8 @@ function DayCell({
   lane: BoardLane
   date: string
   jobs: WorkBoardJob[]
+  /** Minutes of work on the day, the same figure the timeline shows. */
+  booked: number
   isToday: boolean
   /** The workshop is closed the whole day. */
   closedAllDay?: boolean
@@ -173,12 +185,6 @@ function DayCell({
     disabled: readOnly,
   })
 
-  const booked = jobs.reduce((sum, job) => {
-    const { start, end } = getJobDateRange(job)
-    return start && end ? sum + getDurationMinutes(start, end) : sum
-  }, 0)
-  const pct = lane.dailyCapacity > 0 ? (booked / lane.dailyCapacity) * 100 : 0
-
   return (
     <div
       ref={setNodeRef}
@@ -231,28 +237,7 @@ function DayCell({
         )
       })}
 
-      {booked > 0 && (
-        <div className="mt-auto space-y-0.5 pt-1">
-          <div className="h-1 w-full overflow-hidden rounded-full bg-muted">
-            <div
-              className={cn(
-                'h-full rounded-full',
-                pct > 100 ? 'bg-red-500' : pct >= 75 ? 'bg-amber-500' : 'bg-emerald-500'
-              )}
-              style={{ width: `${Math.min(pct, 100)}%` }}
-            />
-          </div>
-          <p
-            className={cn(
-              'text-center text-[10px] font-medium tabular-nums',
-              pct > 100 ? 'text-red-500' : 'text-muted-foreground'
-            )}
-          >
-            {formatDuration(booked)}
-            {lane.dailyCapacity > 0 ? ` / ${formatDuration(lane.dailyCapacity)}` : ''}
-          </p>
-        </div>
-      )}
+      {booked > 0 && <DayLoadFigure bookedMinutes={booked} capacityMinutes={lane.dailyCapacity} />}
     </div>
   )
 }

+ 21 - 21
src/features/workboard/Components/WeekTimeline/index.tsx

@@ -1,6 +1,11 @@
 'use client'
 
-import { type AwayByLaneDay, type ClosedByDay, awayKey } from '../../hooks/useBoardCalendar'
+import {
+  type AwayByLaneDay,
+  type ClosedByDay,
+  awayKey,
+  laneDayHours,
+} from '../../hooks/useBoardCalendar'
 import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useDndMonitor } from '@dnd-kit/core'
 import { ChevronLeft, ChevronRight } from 'lucide-react'
@@ -22,11 +27,13 @@ import {
 import {
   MINUTES_IN_DAY,
   bookedMinutesOnDay,
+  dayLoad,
   computeTimeWindow,
   hourMarks,
   isUnscheduled,
   resolveJobOnDay,
 } from '../../utils/layout'
+import { DayLoadBar, DayLoadSpoken } from '../DayLoad'
 import { LaneHeaderTooltip } from '../LaneHeaderTooltip'
 import { UnscheduledStrip } from './UnscheduledStrip'
 import { WeekLaneColumn } from './WeekLaneColumn'
@@ -443,12 +450,15 @@ export function WeekTimeline({
                 {days.flatMap((day) =>
                   lanes.map((lane, laneIndex) => {
                     const isLastLane = laneIndex === lanes.length - 1
-                    const booked = bookedMinutesOnDay(byLane.get(lane.id) ?? [], day)
-                    const pct =
-                      lane.dailyCapacity > 0
-                        ? Math.round((booked / lane.dailyCapacity) * 100)
-                        : null
+                    const booked = bookedMinutesOnDay(
+                      byLane.get(lane.id) ?? [],
+                      day,
+                      laneDayHours(lane, day, closedByDay, awayByLaneDay)
+                    )
+                    const load = dayLoad(booked, lane.dailyCapacity)
                     const away = awayByLaneDay?.[awayKey(lane.id, day)]
+                    const loadId =
+                      lane.dailyCapacity > 0 ? `lane-load-${day}-${lane.id}` : undefined
                     return (
                       <LaneHeaderTooltip
                         key={`lane-${day}-${lane.id}`}
@@ -458,11 +468,14 @@ export function WeekTimeline({
                         capacityMinutes={lane.dailyCapacity}
                         periodLabel={dayFormatter.format(new Date(`${day}T12:00:00`))}
                         awayLabel={away?.label}
+                        closedByDay={closedByDay}
+                        awayByLaneDay={awayByLaneDay}
                       >
                         <button
                           type="button"
                           disabled={lane.isPlaceholder || readOnly || !onLaneClick}
                           onClick={() => onLaneClick?.(lane)}
+                          aria-describedby={loadId}
                           className={cn(
                             'sticky z-40 flex flex-col justify-center gap-1 border-b bg-background px-1.5 text-left disabled:cursor-default',
                             isLastLane ? 'border-r-2 border-r-border' : 'border-r'
@@ -484,22 +497,9 @@ export function WeekTimeline({
                               {away.label}
                             </span>
                           ) : (
-                            pct !== null && (
-                              <span className="h-0.5 w-full overflow-hidden rounded-full bg-muted">
-                                <span
-                                  className={cn(
-                                    'block h-full rounded-full',
-                                    pct > 100
-                                      ? 'bg-red-500'
-                                      : pct >= 75
-                                        ? 'bg-amber-500'
-                                        : 'bg-emerald-500'
-                                  )}
-                                  style={{ width: `${Math.min(pct, 100)}%` }}
-                                />
-                              </span>
-                            )
+                            lane.dailyCapacity > 0 && <DayLoadBar load={load} className="h-0.5" />
                           )}
+                          <DayLoadSpoken load={load} id={loadId} />
                         </button>
                       </LaneHeaderTooltip>
                     )

+ 19 - 0
src/features/workboard/hooks/useBoardCalendar.ts

@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl'
 import { getWorkshopCalendar } from '@/features/workshop-calendar/Actions/calendarActions'
 import type { WorkshopCalendar } from '@/features/workshop-calendar/Lib/calendar'
 import { type MinuteSpan, awayDay, closedDay } from '@/features/workshop-calendar/Lib/boardDays'
+import type { DayHours } from '../utils/layout'
 
 /** A day on the board that is closed for some or all of it. */
 export interface BoardClosed {
@@ -32,6 +33,24 @@ export type AwayByLaneDay = Record<string, BoardAway>
 
 export const awayKey = (laneId: string, date: string) => `${laneId}|${date}`
 
+/**
+ * One lane's working day as `bookedMinutesOnDay` reads it: when the workshop
+ * is closed, when the technician is away, and the lane's capacity. Every view
+ * builds it here, so they all count a day the same way.
+ */
+export function laneDayHours(
+  lane: { id: string; dailyCapacity: number },
+  date: string,
+  closedByDay?: ClosedByDay,
+  awayByLaneDay?: AwayByLaneDay
+): DayHours {
+  return {
+    closedSpans: closedByDay?.[date]?.spans,
+    awaySpans: awayByLaneDay?.[awayKey(lane.id, date)]?.spans,
+    capacityMinutes: lane.dailyCapacity,
+  }
+}
+
 /**
  * The workshop calendar for the days the board shows: what is closed each
  * day and, on a board grouped by technician, who is away. Read again when the

+ 105 - 8
src/features/workboard/utils/layout.ts

@@ -7,6 +7,7 @@
  * directly and reused by any view that draws jobs against a clock.
  */
 
+import type { MinuteSpan } from '@/features/workshop-calendar/Lib/boardDays'
 import type { WorkBoardJob } from '../Actions/boardActions'
 import { getJobDateRange } from './datetime'
 
@@ -217,26 +218,122 @@ export function snapToStep(mins: number, step: number, window: TimeWindow): numb
   return Math.max(window.startMins, Math.min(window.endMins, snapped))
 }
 
+/** What is known about one lane's working day, for counting the work on it. */
+export type DayHours = {
+  /**
+   * The parts of the day the workshop is closed, in minutes from midnight, its
+   * usual closed hours included. Leave out when the opening hours are not
+   * known (the workshop calendar has not loaded).
+   */
+  closedSpans?: MinuteSpan[]
+  /** The parts of the day the lane's technician is away. */
+  awaySpans?: MinuteSpan[]
+  /** The lane's daily capacity in minutes; 0 or missing when it has none. */
+  capacityMinutes?: number
+}
+
+/** The minutes of `from`-`to` left once every span is taken out of it. */
+function minutesOutside(from: number, to: number, spans: MinuteSpan[]): number {
+  let pieces: MinuteSpan[] = to > from ? [{ startMins: from, endMins: to }] : []
+  for (const cut of spans) {
+    const next: MinuteSpan[] = []
+    for (const piece of pieces) {
+      if (cut.endMins <= piece.startMins || cut.startMins >= piece.endMins) {
+        next.push(piece)
+        continue
+      }
+      if (cut.startMins > piece.startMins)
+        next.push({ startMins: piece.startMins, endMins: cut.startMins })
+      if (cut.endMins < piece.endMins) next.push({ startMins: cut.endMins, endMins: piece.endMins })
+    }
+    pieces = next
+  }
+  return pieces.reduce((sum, piece) => sum + piece.endMins - piece.startMins, 0)
+}
+
 /**
- * Minutes of work a lane carries on one day.
+ * Minutes of work a lane carries on one day: the one figure every view of a
+ * day shows (the card grid, the timeline's lane header and its tooltip), so
+ * two views of the same day cannot disagree.
+ *
+ * A job that starts and ends on the day counts every minute of it, the part
+ * outside opening hours included: a job that runs past closing time is still
+ * work someone has to do, and the utilisation figure is the one number that
+ * tells a planner whether the day is full.
+ *
+ * A job that runs over more than one day cannot be counted that way. Clipped
+ * to the calendar day it is 24 hours on every day it passes through, and
+ * counted whole it is its entire length on each of them (a seven week
+ * restoration once read "1117h / 8h" on a wall screen). Nobody works on it
+ * through the night, so on each day it touches it counts only the part of it
+ * inside the working day:
  *
- * Clamped to the calendar day rather than to the visible hours: a job that runs
- * past closing time is still work someone has to do, and the utilisation figure
- * is the one number that tells a planner whether the day is full.
+ * - the workshop's opening hours that day, less any closure, when `hours`
+ *   brings them. A closed day adds nothing.
+ * - less the time the lane's technician is away.
+ * - and never more than the lane's daily capacity, which is also the limit
+ *   when the opening hours are not known: one job cannot take more of a
+ *   person's day than their day.
+ *
+ * So a job passing through an ordinary day fills that day once, and three of
+ * them read as three days' work booked into one.
+ *
+ * Who a job counts for is not decided here: the caller passes the lane's
+ * jobs, and a job shared with helpers is in each of their lanes.
  */
-export function bookedMinutesOnDay(jobs: WorkBoardJob[], dateStr: string): number {
+export function bookedMinutesOnDay(
+  jobs: WorkBoardJob[],
+  dateStr: string,
+  hours: DayHours = {}
+): number {
   const dayStart = dayStartDate(dateStr)
   const dayEnd = new Date(dayStart)
   dayEnd.setDate(dayEnd.getDate() + 1)
+  const capacity = hours.capacityMinutes ?? 0
+  const notWorked = [...(hours.closedSpans ?? []), ...(hours.awaySpans ?? [])]
 
   let total = 0
   for (const job of jobs) {
     const { start, end } = getJobDateRange(job)
     if (!start || !end) continue
     if (!(start < dayEnd && end > dayStart)) continue
-    const from = start < dayStart ? dayStart : start
-    const to = end > dayEnd ? dayEnd : end
-    total += Math.max(0, Math.round((to.getTime() - from.getTime()) / 60000))
+
+    if (start >= dayStart && end <= dayEnd) {
+      total += Math.max(0, Math.round((end.getTime() - start.getTime()) / 60000))
+      continue
+    }
+
+    // Clock minutes, not time elapsed: the spans it is measured against are
+    // minutes on the day's clock.
+    const from = start <= dayStart ? 0 : minutesOfDay(start)
+    const to = end >= dayEnd ? MINUTES_IN_DAY : minutesOfDay(end)
+    const worked = minutesOutside(from, to, notWorked)
+    total += capacity > 0 ? Math.min(worked, capacity) : worked
   }
   return total
 }
+
+/** A day's booked minutes read against its capacity. */
+export type DayLoad = {
+  bookedMinutes: number
+  capacityMinutes: number
+  /** Booked as a share of capacity; 0 for a lane with no capacity. */
+  pct: number
+  /** How far past capacity the day is; 0 when it is not, or has no capacity. */
+  overMinutes: number
+}
+
+/**
+ * How full a day (or a week of days) is: the share that sizes and colours the
+ * bar and the minutes over capacity, worked out once so the card grid, the
+ * timeline and the lane tooltip cannot say different things about one day.
+ */
+export function dayLoad(bookedMinutes: number, capacityMinutes: number): DayLoad {
+  const hasCapacity = capacityMinutes > 0
+  return {
+    bookedMinutes,
+    capacityMinutes,
+    pct: hasCapacity ? (bookedMinutes / capacityMinutes) * 100 : 0,
+    overMinutes: hasCapacity ? Math.max(0, bookedMinutes - capacityMinutes) : 0,
+  }
+}