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

Make plain appointments findable from search and the vehicle page (#630)

* Make plain appointments findable from search and the vehicle page

* Gate the appointment link on calendar access and reopen it when followed again

* Test the appointment link's access gate and repeat opening
Bernt Christian Egeland 8 часов назад
Родитель
Сommit
7dd7d2d6e0
42 измененных файлов с 1227 добавлено и 248 удалено
  1. 2 1
      messages/de/search.json
  2. 3 0
      messages/de/vehicles.json
  3. 2 1
      messages/en/search.json
  4. 3 0
      messages/en/vehicles.json
  5. 2 1
      messages/es/search.json
  6. 3 0
      messages/es/vehicles.json
  7. 2 1
      messages/fr/search.json
  8. 3 0
      messages/fr/vehicles.json
  9. 2 1
      messages/it/search.json
  10. 3 0
      messages/it/vehicles.json
  11. 2 1
      messages/lt/search.json
  12. 3 0
      messages/lt/vehicles.json
  13. 2 1
      messages/nb/search.json
  14. 3 0
      messages/nb/vehicles.json
  15. 2 1
      messages/nl/search.json
  16. 3 0
      messages/nl/vehicles.json
  17. 2 1
      messages/pl/search.json
  18. 3 0
      messages/pl/vehicles.json
  19. 2 1
      messages/pt-BR/search.json
  20. 3 0
      messages/pt-BR/vehicles.json
  21. 2 1
      messages/pt-PT/search.json
  22. 3 0
      messages/pt-PT/vehicles.json
  23. 2 1
      messages/ru/search.json
  24. 3 0
      messages/ru/vehicles.json
  25. 2 1
      messages/tr/search.json
  26. 3 0
      messages/tr/vehicles.json
  27. 79 0
      src/__tests__/features/calendar/linked-appointment-lookup.test.ts
  28. 103 0
      src/__tests__/features/calendar/linked-appointment.test.tsx
  29. 196 0
      src/__tests__/features/search/global-search-appointments.test.ts
  30. 71 0
      src/__tests__/features/vehicles/vehicle-appointments.test.tsx
  31. 21 3
      src/app/(authenticated)/calendar/page.tsx
  32. 8 0
      src/app/(authenticated)/vehicles/[id]/(detail)/page.tsx
  33. 29 1
      src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx
  34. 26 0
      src/features/calendar/Actions/getVehicleAppointments.ts
  35. 33 1
      src/features/calendar/Components/CalendarClient.tsx
  36. 59 0
      src/features/calendar/Components/LinkedAppointment.tsx
  37. 7 0
      src/features/calendar/Lib/appointmentLink.ts
  38. 93 0
      src/features/calendar/Lib/appointmentList.server.ts
  39. 24 0
      src/features/calendar/Lib/linkedAppointment.server.ts
  40. 280 229
      src/features/search/Actions/searchActions.ts
  41. 46 1
      src/features/search/Components/SearchCommand.tsx
  42. 87 0
      src/features/vehicles/Components/VehicleAppointments.tsx

+ 2 - 1
messages/de/search.json

@@ -13,7 +13,8 @@
     "settings": "Einstellungen",
     "pages": "Seiten",
     "actions": "Aktionen",
-    "integrations": "Integrationen"
+    "integrations": "Integrationen",
+    "appointments": "Termine"
   },
   "hints": {
     "navigate": "navigieren",

+ 3 - 0
messages/de/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Auf einen Blick",
     "lastVisit": "Letzter Besuch",
     "nextBooking": "Nächster Termin",
+    "appointments": "Termine",
+    "noUpcomingAppointments": "Nichts im Voraus gebucht",
+    "earlierAppointments": "Früher",
     "inspectionDueLabel": "Prüfung fällig",
     "otherVehicles": "Weitere Fahrzeuge: {count}",
     "otherVehiclesMarine": "Weitere Boote: {count}",

+ 2 - 1
messages/en/search.json

@@ -13,7 +13,8 @@
     "settings": "Settings",
     "pages": "Pages",
     "actions": "Actions",
-    "integrations": "Integrations"
+    "integrations": "Integrations",
+    "appointments": "Appointments"
   },
   "hints": {
     "navigate": "navigate",

+ 3 - 0
messages/en/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "At a glance",
     "lastVisit": "Last visit",
     "nextBooking": "Next booking",
+    "appointments": "Appointments",
+    "noUpcomingAppointments": "Nothing booked ahead",
+    "earlierAppointments": "Earlier",
     "inspectionDueLabel": "Inspection due",
     "otherVehicles": "Other vehicles: {count}",
     "otherVehiclesMarine": "Other boats: {count}",

+ 2 - 1
messages/es/search.json

@@ -13,7 +13,8 @@
     "settings": "Configuración",
     "pages": "Páginas",
     "actions": "Acciones",
-    "integrations": "Integraciones"
+    "integrations": "Integraciones",
+    "appointments": "Citas"
   },
   "hints": {
     "navigate": "navegar",

+ 3 - 0
messages/es/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "De un vistazo",
     "lastVisit": "Última visita",
     "nextBooking": "Próxima cita",
+    "appointments": "Citas",
+    "noUpcomingAppointments": "Nada reservado próximamente",
+    "earlierAppointments": "Anteriores",
     "inspectionDueLabel": "Inspección pendiente",
     "otherVehicles": "Otros vehículos: {count}",
     "otherVehiclesMarine": "Otras embarcaciones: {count}",

+ 2 - 1
messages/fr/search.json

@@ -13,7 +13,8 @@
     "settings": "Paramètres",
     "pages": "Pages",
     "actions": "Actions",
-    "integrations": "Intégrations"
+    "integrations": "Intégrations",
+    "appointments": "Rendez-vous"
   },
   "hints": {
     "navigate": "naviguer",

+ 3 - 0
messages/fr/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "En un coup d'œil",
     "lastVisit": "Dernière visite",
     "nextBooking": "Prochain rendez-vous",
+    "appointments": "Rendez-vous",
+    "noUpcomingAppointments": "Rien de prévu",
+    "earlierAppointments": "Précédents",
     "inspectionDueLabel": "Contrôle à effectuer",
     "otherVehicles": "Autres véhicules : {count}",
     "otherVehiclesMarine": "Autres bateaux : {count}",

+ 2 - 1
messages/it/search.json

@@ -13,7 +13,8 @@
     "settings": "Impostazioni",
     "pages": "Pagine",
     "actions": "Azioni",
-    "integrations": "Integrazioni"
+    "integrations": "Integrazioni",
+    "appointments": "Appuntamenti"
   },
   "hints": {
     "navigate": "naviga",

+ 3 - 0
messages/it/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "In breve",
     "lastVisit": "Ultima visita",
     "nextBooking": "Prossimo appuntamento",
+    "appointments": "Appuntamenti",
+    "noUpcomingAppointments": "Nessuna prenotazione in arrivo",
+    "earlierAppointments": "Precedenti",
     "inspectionDueLabel": "Scadenza revisione",
     "otherVehicles": "Altri veicoli: {count}",
     "otherVehiclesMarine": "Altre imbarcazioni: {count}",

+ 2 - 1
messages/lt/search.json

@@ -13,7 +13,8 @@
     "settings": "Nustatymai",
     "pages": "Puslapiai",
     "actions": "Veiksmai",
-    "integrations": "Integracijos"
+    "integrations": "Integracijos",
+    "appointments": "Susitikimai"
   },
   "hints": {
     "navigate": "naršyti",

+ 3 - 0
messages/lt/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Trumpai",
     "lastVisit": "Paskutinis apsilankymas",
     "nextBooking": "Kitas vizitas",
+    "appointments": "Susitikimai",
+    "noUpcomingAppointments": "Nieko neužsakyta į priekį",
+    "earlierAppointments": "Ankstesni",
     "inspectionDueLabel": "Apžiūros terminas",
     "otherVehicles": "Kitos transporto priemonės: {count}",
     "otherVehiclesMarine": "Kiti laivai: {count}",

+ 2 - 1
messages/nb/search.json

@@ -13,7 +13,8 @@
     "settings": "Innstillinger",
     "pages": "Sider",
     "actions": "Handlinger",
-    "integrations": "Integrasjoner"
+    "integrations": "Integrasjoner",
+    "appointments": "Avtaler"
   },
   "hints": {
     "navigate": "naviger",

+ 3 - 0
messages/nb/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Oversikt",
     "lastVisit": "Siste besøk",
     "nextBooking": "Neste time",
+    "appointments": "Avtaler",
+    "noUpcomingAppointments": "Ingenting booket fremover",
+    "earlierAppointments": "Tidligere",
     "inspectionDueLabel": "Frist for kontroll",
     "otherVehicles": "Andre kjøretøy: {count}",
     "otherVehiclesMarine": "Andre båter: {count}",

+ 2 - 1
messages/nl/search.json

@@ -13,7 +13,8 @@
     "settings": "Instellingen",
     "pages": "Pagina’s",
     "actions": "Acties",
-    "integrations": "Integraties"
+    "integrations": "Integraties",
+    "appointments": "Afspraken"
   },
   "hints": {
     "navigate": "navigeren",

+ 3 - 0
messages/nl/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "In één oogopslag",
     "lastVisit": "Laatste bezoek",
     "nextBooking": "Volgende afspraak",
+    "appointments": "Afspraken",
+    "noUpcomingAppointments": "Niets vooruit gepland",
+    "earlierAppointments": "Eerder",
     "inspectionDueLabel": "Keuring vervalt",
     "otherVehicles": "Andere voertuigen: {count}",
     "otherVehiclesMarine": "Andere boten: {count}",

+ 2 - 1
messages/pl/search.json

@@ -13,7 +13,8 @@
     "settings": "Ustawienia",
     "pages": "Strony",
     "actions": "Akcje",
-    "integrations": "Integracje"
+    "integrations": "Integracje",
+    "appointments": "Spotkania"
   },
   "hints": {
     "navigate": "nawiguj",

+ 3 - 0
messages/pl/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "W skrócie",
     "lastVisit": "Ostatnia wizyta",
     "nextBooking": "Następna wizyta",
+    "appointments": "Spotkania",
+    "noUpcomingAppointments": "Brak zaplanowanych wizyt",
+    "earlierAppointments": "Wcześniejsze",
     "inspectionDueLabel": "Termin przeglądu",
     "otherVehicles": "Inne pojazdy: {count}",
     "otherVehiclesMarine": "Inne łodzie: {count}",

+ 2 - 1
messages/pt-BR/search.json

@@ -13,7 +13,8 @@
     "settings": "Configurações",
     "pages": "Páginas",
     "actions": "Ações",
-    "integrations": "Integrações"
+    "integrations": "Integrações",
+    "appointments": "Compromissos"
   },
   "hints": {
     "navigate": "navegar",

+ 3 - 0
messages/pt-BR/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Resumo",
     "lastVisit": "Última visita",
     "nextBooking": "Próximo agendamento",
+    "appointments": "Compromissos",
+    "noUpcomingAppointments": "Nada agendado à frente",
+    "earlierAppointments": "Anteriores",
     "inspectionDueLabel": "Vencimento da inspeção",
     "otherVehicles": "Outros veículos: {count}",
     "otherVehiclesMarine": "Outras embarcações: {count}",

+ 2 - 1
messages/pt-PT/search.json

@@ -13,7 +13,8 @@
     "settings": "Definições",
     "pages": "Páginas",
     "actions": "Ações",
-    "integrations": "Integrações"
+    "integrations": "Integrações",
+    "appointments": "Marcações"
   },
   "hints": {
     "navigate": "navegar",

+ 3 - 0
messages/pt-PT/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Resumo",
     "lastVisit": "Última visita",
     "nextBooking": "Próxima marcação",
+    "appointments": "Marcações",
+    "noUpcomingAppointments": "Nada marcado para breve",
+    "earlierAppointments": "Anteriores",
     "inspectionDueLabel": "Inspeção até",
     "otherVehicles": "Outros veículos: {count}",
     "otherVehiclesMarine": "Outras embarcações: {count}",

+ 2 - 1
messages/ru/search.json

@@ -13,7 +13,8 @@
     "settings": "Настройки",
     "pages": "Страницы",
     "actions": "Действия",
-    "integrations": "Интеграции"
+    "integrations": "Интеграции",
+    "appointments": "Встречи"
   },
   "hints": {
     "navigate": "навигация",

+ 3 - 0
messages/ru/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Кратко",
     "lastVisit": "Последний визит",
     "nextBooking": "Следующая запись",
+    "appointments": "Встречи",
+    "noUpcomingAppointments": "Ничего не запланировано",
+    "earlierAppointments": "Ранее",
     "inspectionDueLabel": "Срок техосмотра",
     "otherVehicles": "Другие транспортные средства: {count}",
     "otherVehiclesMarine": "Другие лодки: {count}",

+ 2 - 1
messages/tr/search.json

@@ -13,7 +13,8 @@
     "settings": "Ayarlar",
     "pages": "Sayfalar",
     "actions": "İşlemler",
-    "integrations": "Entegrasyonlar"
+    "integrations": "Entegrasyonlar",
+    "appointments": "Randevular"
   },
   "hints": {
     "navigate": "gezin",

+ 3 - 0
messages/tr/vehicles.json

@@ -118,6 +118,9 @@
     "glance": "Bir bakışta",
     "lastVisit": "Son ziyaret",
     "nextBooking": "Sonraki randevu",
+    "appointments": "Randevular",
+    "noUpcomingAppointments": "İleriye dönük randevu yok",
+    "earlierAppointments": "Önceki",
     "inspectionDueLabel": "Muayene tarihi",
     "otherVehicles": "Diğer araçlar: {count}",
     "otherVehiclesMarine": "Diğer tekneler: {count}",

+ 79 - 0
src/__tests__/features/calendar/linked-appointment-lookup.test.ts

@@ -0,0 +1,79 @@
+/**
+ * A calendar link to one appointment opens it only for somebody in that
+ * workshop who may read the calendar. Anybody else gets the plain calendar,
+ * so the link does not tell them whether the id exists or which day it is.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('@/lib/db', () => ({
+  db: { appointment: { findFirst: vi.fn() } },
+}))
+
+import { getCachedMembership } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { findLinkedAppointment } from '@/features/calendar/Lib/linkedAppointment.server'
+
+const START = new Date('2026-11-24T09:30:00Z')
+const ROWS = [
+  { id: 'appt-a', organizationId: 'org-a', startAt: START },
+  { id: 'appt-b', organizationId: 'org-b', startAt: START },
+]
+
+const owner = { userId: 'user-a', isAdmin: true, organizationId: 'org-a' }
+const member = { userId: 'user-m', isAdmin: false, organizationId: 'org-a' }
+
+function memberMayRead(subjects: string[]) {
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: 'org-a',
+    role: 'member',
+    roleId: 'role-1',
+    customRole: {
+      isAdmin: false,
+      permissions: subjects.map((subject) => ({ action: 'read', subject })),
+    },
+  } as never)
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.mocked(db.appointment.findFirst).mockImplementation((async (args: {
+    where: { id: string; organizationId: string }
+  }) => {
+    const row = ROWS.find(
+      (r) => r.id === args.where.id && r.organizationId === args.where.organizationId
+    )
+    return row ? { id: row.id, startAt: row.startAt } : null
+  }) as never)
+})
+
+describe('findLinkedAppointment', () => {
+  it('opens the workshop’s own appointment', async () => {
+    expect(await findLinkedAppointment(owner, 'appt-a')).toEqual({ id: 'appt-a', startAt: START })
+  })
+
+  it('opens nothing for another workshop’s appointment', async () => {
+    expect(await findLinkedAppointment(owner, 'appt-b')).toBeNull()
+  })
+
+  it('opens nothing, and looks nothing up, for a member who cannot read the calendar', async () => {
+    memberMayRead(['dashboard', 'customers'])
+    expect(await findLinkedAppointment(member, 'appt-a')).toBeNull()
+    expect(db.appointment.findFirst).not.toHaveBeenCalled()
+  })
+
+  it('opens it for a member who can read the calendar', async () => {
+    memberMayRead(['services'])
+    expect(await findLinkedAppointment(member, 'appt-a')).toEqual({ id: 'appt-a', startAt: START })
+  })
+
+  it('ignores a missing or malformed id', async () => {
+    expect(await findLinkedAppointment(owner, undefined)).toBeNull()
+    expect(await findLinkedAppointment(owner, ['appt-a'])).toBeNull()
+    expect(await findLinkedAppointment(null, 'appt-a')).toBeNull()
+  })
+})

+ 103 - 0
src/__tests__/features/calendar/linked-appointment.test.tsx

@@ -0,0 +1,103 @@
+/**
+ * Following a link to an appointment opens its card, and following the same
+ * link again (from the search palette, while the calendar is open and the
+ * card was closed) opens it again. A card is not opened under a dialog that
+ * is still closing, which would take the focus and shut it at once.
+ */
+
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { CalendarEvent } from '@/features/calendar/Actions/calendarActions'
+
+vi.mock('@/components/date-settings-context', () => ({
+  useDateSettings: () => ({
+    dateFormat: 'MMM d, yyyy',
+    timeFormat: '24h',
+    timezone: '',
+    weekStartDay: 1,
+  }),
+}))
+vi.mock('@/components/currency-settings-context', () => ({
+  useFormatCurrency: () => (amount: number, code: string) => `${amount} ${code}`,
+}))
+vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn() }))
+vi.mock('@/features/scheduled-messages/Actions/scheduledMessageActions', () => ({
+  deleteScheduledMessage: vi.fn(),
+}))
+vi.mock('@/features/calendar/Actions/deleteAppointment', () => ({ deleteAppointment: vi.fn() }))
+vi.mock('@/features/vehicles/Actions/reminderActions', () => ({
+  toggleReminder: vi.fn(),
+  deleteReminder: vi.fn(),
+}))
+vi.mock('@/features/calendar/Components/useDayFormatter', () => ({
+  useDayFormatter: () => ({
+    dateTime: (date: Date, options: Intl.DateTimeFormatOptions) =>
+      new Intl.DateTimeFormat('en-US', options).format(date),
+  }),
+}))
+
+import { EventPeekProvider } from '@/features/calendar/Components/EventPeek'
+import { LinkedAppointment } from '@/features/calendar/Components/LinkedAppointment'
+
+const event: CalendarEvent = {
+  id: 'appt-a',
+  title: 'Talk about winter tyres',
+  date: '2026-11-24',
+  time: '10:30',
+  endTime: '11:00',
+  type: 'appointment',
+  status: 'booked',
+  vehicleId: 'car-1',
+  vehicleLabel: '2012 Volvo V70',
+  customerName: 'Test Testesen',
+  invoiceNumber: null,
+  amount: null,
+}
+
+function Calendar({ token, dialog = false }: { token: string; dialog?: boolean }) {
+  return (
+    <EventPeekProvider currencyCode="NOK">
+      {dialog && <div role="dialog">Search</div>}
+      <LinkedAppointment key={token} event={event} view="day" date="2026-11-24" />
+    </EventPeekProvider>
+  )
+}
+
+const card = () =>
+  screen.queryByRole('heading', { name: 'Talk about winter tyres' }) ??
+  screen.queryByText('Talk about winter tyres')
+
+beforeEach(() => {
+  window.history.replaceState(null, '', '/calendar?appointment=appt-a')
+})
+
+describe('LinkedAppointment', () => {
+  it('opens the card and takes the link out of the address', async () => {
+    render(<Calendar token="one" />)
+    await waitFor(() => expect(card()).toBeInTheDocument())
+    expect(window.location.search).toBe('?view=day&date=2026-11-24')
+  })
+
+  it('opens the card again when the same link is followed again', async () => {
+    const { rerender } = render(<Calendar token="one" />)
+    await waitFor(() => expect(card()).toBeInTheDocument())
+
+    fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
+    await waitFor(() => expect(card()).not.toBeInTheDocument())
+
+    rerender(<Calendar token="two" />)
+    await waitFor(() => expect(card()).toBeInTheDocument())
+  })
+
+  it('waits for a closing dialog before opening the card', async () => {
+    const { rerender } = render(<Calendar token="one" dialog />)
+    await act(async () => {
+      await new Promise((r) => setTimeout(r, 100))
+    })
+    expect(card()).not.toBeInTheDocument()
+
+    rerender(<Calendar token="one" />)
+    await waitFor(() => expect(card()).toBeInTheDocument())
+  })
+})

+ 196 - 0
src/__tests__/features/search/global-search-appointments.test.ts

@@ -0,0 +1,196 @@
+/**
+ * Plain appointments in the search palette: a workshop on the phone types the
+ * plate or what the visit is about and finds the booking, on its own clock,
+ * the coming ones first, and never another workshop's.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('@/lib/workshop-timezone', () => ({
+  workshopTimeZone: vi.fn(async () => 'Pacific/Auckland'),
+}))
+vi.mock('@/features/tire-hotel/Lib/tireHotelSettings', () => ({
+  isTireHotelEnabled: vi.fn(async () => false),
+}))
+vi.mock('@/features/vehicles/Lib/typeKeySetting', () => ({
+  isTypeKeyEnabled: vi.fn(async () => false),
+}))
+vi.mock('@/features/inventory/Lib/tagSearch.server', () => ({
+  partIdsWithTagContaining: vi.fn(async () => []),
+}))
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    auditLog: { create: vi.fn() },
+    vehicle: { findMany: vi.fn() },
+    customer: { findMany: vi.fn() },
+    serviceRecord: { findMany: vi.fn() },
+    inventoryPart: { findMany: vi.fn() },
+    quote: { findMany: vi.fn() },
+    reminder: { findMany: vi.fn() },
+    inspection: { findMany: vi.fn() },
+    tireSet: { findMany: vi.fn() },
+    appointment: { findMany: vi.fn() },
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { globalSearch } from '@/features/search/Actions/searchActions'
+
+const ORG = 'org-a'
+
+type Row = Record<string, unknown>
+
+/** Enough of Prisma's `where` to run the palette's query against a table. */
+function matches(row: unknown, where: unknown): boolean {
+  if (where === undefined) return true
+  const w = where as Record<string, unknown>
+  return Object.entries(w).every(([key, cond]) => {
+    if (key === 'AND') return (cond as unknown[]).every((c) => matches(row, c))
+    if (key === 'OR') return (cond as unknown[]).some((c) => matches(row, c))
+    const value = (row as Row | null)?.[key]
+    if (cond && typeof cond === 'object' && !(cond instanceof Date)) {
+      const c = cond as Record<string, unknown>
+      if ('contains' in c) {
+        return (
+          typeof value === 'string' &&
+          value.toLowerCase().includes(String(c.contains).toLowerCase())
+        )
+      }
+      if ('gte' in c) return value instanceof Date && value >= (c.gte as Date)
+      if ('lt' in c) return value instanceof Date && value < (c.lt as Date)
+      return value != null && matches(value, c)
+    }
+    return value === cond
+  })
+}
+
+const NOW = Date.now()
+const DAY = 24 * 60 * 60 * 1000
+
+const car = {
+  id: 'car-1',
+  make: 'Volvo',
+  model: 'V70',
+  year: 2012,
+  licensePlate: 'EK12345',
+  customer: { id: 'cust-1', name: 'Test Testesen' },
+}
+
+const APPOINTMENTS: Row[] = [
+  {
+    id: 'appt-past',
+    organizationId: ORG,
+    title: 'Test drive after repair',
+    description: null,
+    startAt: new Date(NOW - 7 * DAY),
+    customer: null,
+    vehicle: car,
+  },
+  {
+    id: 'appt-next',
+    organizationId: ORG,
+    title: 'Talk about winter tyres',
+    description: '<p>Bring the rims</p>',
+    // 10:30 in Auckland on a fixed day well ahead.
+    startAt: new Date('2099-03-10T21:30:00Z'),
+    customer: { id: 'cust-1', name: 'Test Testesen' },
+    vehicle: car,
+  },
+  {
+    id: 'appt-other-workshop',
+    organizationId: 'org-b',
+    title: 'Talk about winter tyres',
+    description: null,
+    startAt: new Date(NOW + 2 * DAY),
+    customer: null,
+    vehicle: { ...car, id: 'car-b' },
+  },
+]
+
+function signInAs(role: 'owner' | 'member', permissions: { action: string; subject: string }[]) {
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role,
+    roleId: role === 'member' ? 'role-1' : null,
+    customRole: role === 'member' ? { isAdmin: false, permissions } : null,
+  } as never)
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-a', email: 'a@x.com' },
+  } as never)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as never)
+  vi.mocked(db.auditLog.create).mockResolvedValue({} as never)
+  for (const model of [
+    db.vehicle,
+    db.customer,
+    db.serviceRecord,
+    db.inventoryPart,
+    db.quote,
+    db.reminder,
+    db.inspection,
+    db.tireSet,
+  ]) {
+    vi.mocked(model.findMany).mockResolvedValue([] as never)
+  }
+  vi.mocked(db.appointment.findMany).mockImplementation((async (args: {
+    where: unknown
+    orderBy: { startAt: 'asc' | 'desc' }
+    take: number
+  }) => {
+    const rows = APPOINTMENTS.filter((a) => matches(a, args.where)).sort(
+      (a, b) =>
+        ((a.startAt as Date).getTime() - (b.startAt as Date).getTime()) *
+        (args.orderBy.startAt === 'asc' ? 1 : -1)
+    )
+    return rows.slice(0, args.take)
+  }) as never)
+  signInAs('owner', [])
+})
+
+describe('appointments in the search palette', () => {
+  it('finds an appointment by the plate of its car, coming ones first', async () => {
+    const result = await globalSearch('ek12345')
+    expect(result.success).toBe(true)
+    expect(result.data?.appointments.map((a) => a.id)).toEqual(['appt-next', 'appt-past'])
+  })
+
+  it('finds an appointment by its title and shows it on the workshop clock', async () => {
+    const result = await globalSearch('winter tyres')
+    const found = result.data?.appointments ?? []
+    expect(found).toHaveLength(1)
+    expect(found[0]).toMatchObject({
+      id: 'appt-next',
+      title: 'Talk about winter tyres',
+      date: '2099-03-11',
+      time: '10:30',
+      upcoming: true,
+      customer: { name: 'Test Testesen' },
+      vehicle: { licensePlate: 'EK12345' },
+    })
+  })
+
+  it('never shows another workshop’s appointment', async () => {
+    const result = await globalSearch('winter tyres')
+    expect(result.data?.appointments.map((a) => a.id)).not.toContain('appt-other-workshop')
+    for (const [args] of vi.mocked(db.appointment.findMany).mock.calls) {
+      expect(JSON.stringify(args?.where)).toContain(`"organizationId":"${ORG}"`)
+    }
+  })
+
+  it('leaves appointments out for a role that cannot open the calendar', async () => {
+    signInAs('member', [{ action: 'read', subject: 'dashboard' }])
+    const result = await globalSearch('winter tyres')
+    expect(result.success).toBe(true)
+    expect(result.data?.appointments).toEqual([])
+    expect(db.appointment.findMany).not.toHaveBeenCalled()
+  })
+})

+ 71 - 0
src/__tests__/features/vehicles/vehicle-appointments.test.tsx

@@ -0,0 +1,71 @@
+/**
+ * The vehicle page answers "is this car booked?": its appointments in the
+ * rail, the coming ones first, each opening the calendar on that booking.
+ */
+
+import { describe, expect, it, vi } from 'vitest'
+import { render, screen, within } from '@testing-library/react'
+
+vi.mock('@/components/date-settings-context', () => ({
+  useDateSettings: () => ({
+    dateFormat: 'MMM d, yyyy',
+    timeFormat: '24h',
+    timezone: 'Europe/Oslo',
+    weekStartDay: 1,
+  }),
+}))
+
+import { VehicleAppointments } from '@/features/vehicles/Components/VehicleAppointments'
+
+const upcoming = {
+  id: 'appt-next',
+  title: 'Talk about winter tyres',
+  startAt: '2026-11-24T09:30:00Z',
+  date: '2026-11-24',
+  time: '10:30',
+  upcoming: true,
+}
+const past = {
+  id: 'appt-past',
+  title: 'Test drive after repair',
+  startAt: '2026-11-10T13:00:00Z',
+  date: '2026-11-10',
+  time: '14:00',
+  upcoming: false,
+}
+
+describe('VehicleAppointments', () => {
+  it('lists coming appointments with their day and time, linked to the calendar', () => {
+    render(<VehicleAppointments appointments={[upcoming, past]} />)
+
+    expect(screen.getByRole('heading', { name: 'Appointments' })).toBeInTheDocument()
+    const next = screen.getByRole('link', { name: /Talk about winter tyres/ })
+    expect(next).toHaveAttribute('href', '/calendar?appointment=appt-next')
+    expect(next).toHaveTextContent('Nov 24, 2026 · 10:30')
+    expect(screen.queryByText('Nothing booked ahead')).not.toBeInTheDocument()
+  })
+
+  it('shows past appointments after the coming ones, under Earlier', () => {
+    render(<VehicleAppointments appointments={[upcoming, past]} />)
+
+    const links = screen.getAllByRole('link').map((l) => l.textContent)
+    expect(links[0]).toContain('Talk about winter tyres')
+    expect(links[1]).toContain('Test drive after repair')
+    const earlier = screen.getByText('Earlier')
+    const pastList = earlier.nextElementSibling as HTMLElement
+    expect(within(pastList).getByRole('link')).toHaveAttribute(
+      'href',
+      '/calendar?appointment=appt-past'
+    )
+  })
+
+  it('says nothing is booked ahead when only past appointments remain', () => {
+    render(<VehicleAppointments appointments={[past]} />)
+    expect(screen.getByText('Nothing booked ahead')).toBeInTheDocument()
+  })
+
+  it('leaves the section out for a car with no appointments', () => {
+    const { container } = render(<VehicleAppointments appointments={[]} />)
+    expect(container).toBeEmptyDOMElement()
+  })
+})

+ 21 - 3
src/app/(authenticated)/calendar/page.tsx

@@ -1,4 +1,6 @@
+import { randomUUID } from 'node:crypto'
 import { cookies } from 'next/headers'
+import { findLinkedAppointment } from '@/features/calendar/Lib/linkedAppointment.server'
 import { resolveCurrencyCode } from '@/lib/currencies'
 import { getCalendarEvents } from '@/features/calendar/Actions/calendarActions'
 import { getDisplaySettings } from '@/features/settings/Actions/settingsActions'
@@ -33,7 +35,7 @@ export function generateMetadata() {
 export default async function CalendarPage({
   searchParams,
 }: {
-  searchParams: Promise<{ view?: string; date?: string }>
+  searchParams: Promise<{ view?: string; date?: string; appointment?: string }>
 }) {
   const params = await searchParams
   const ctx = await getAuthContext()
@@ -42,8 +44,13 @@ export default async function CalendarPage({
   // ring in the next day at 01:00 Oslo time.
   const todayStr = zonedDayKey(new Date(), timeZone)
 
-  const view: CalendarView = isCalendarView(params.view) ? params.view : 'month'
-  const date = parseDateKey(params.date) ?? parseDateKey(todayStr) ?? new Date()
+  // A link to one appointment (from search, a vehicle's page) opens its day
+  // with its card up; see findLinkedAppointment for who may follow one.
+  const linked = await findLinkedAppointment(ctx, params.appointment)
+  const linkedDay = linked ? zonedDayKey(linked.startAt, timeZone) : null
+
+  const view: CalendarView = isCalendarView(params.view) ? params.view : linked ? 'day' : 'month'
+  const date = parseDateKey(linkedDay ?? params.date) ?? parseDateKey(todayStr) ?? new Date()
 
   const messageChannels = ctx ? await getAvailableChannels(ctx.organizationId) : []
   const settingsResult = await getDisplaySettings([
@@ -96,11 +103,22 @@ export default async function CalendarPage({
 
   const events = eventsResult.success && eventsResult.data ? eventsResult.data : []
 
+  // A token for this one request, so the same link followed again while the
+  // calendar is open (from search, say) goes back to the day and reopens it.
+  const linkedEvent = linked
+    ? events.find((e) => e.type === 'appointment' && e.id === linked.id)
+    : undefined
+  const linkedAppointment =
+    linkedEvent && linkedDay
+      ? { event: linkedEvent, date: linkedDay, view, token: randomUUID() }
+      : null
+
   return (
     <>
       <PageHeader />
       <div className="flex min-h-0 flex-1 flex-col gap-4 p-4 pt-0">
         <CalendarClient
+          linkedAppointment={linkedAppointment}
           initialEvents={events}
           initialRange={rangeKeys}
           initialView={view}

+ 8 - 0
src/app/(authenticated)/vehicles/[id]/(detail)/page.tsx

@@ -12,6 +12,7 @@ import { getVehicleQuotes } from '@/features/quotes/Actions/quoteActions'
 import { getVehicleFindings } from '@/features/vehicles/Actions/findingActions'
 import { getVehicleJobWarnings } from '@/features/vehicles/Actions/getVehicleJobWarnings'
 import { getVehicleGlance } from '@/features/vehicles/Actions/getVehicleGlance'
+import { getVehicleAppointments } from '@/features/calendar/Actions/getVehicleAppointments'
 import { getFeatures } from '@/lib/features'
 import { findSafetyConnection } from '@/features/integrations/Lib/vehicle-safety'
 import { isAiConfigured } from '@/features/integrations/Lib/ai'
@@ -95,6 +96,7 @@ export default async function VehicleDetailPage({
     jobWarningsResult,
     feedNotesResult,
     glanceResult,
+    appointmentsResult,
   ] = await Promise.all([
     getVehicle(id),
     // The new page shows the vehicle's history as one feed, so it asks for all
@@ -126,6 +128,9 @@ export default async function VehicleDetailPage({
     // Last visit, next booking and what is owed, over every work order and
     // not only the ones a search has left in the list.
     classic ? null : readIfAllowed(access, S.SERVICES, () => getVehicleGlance(id)),
+    // Plain appointments, which have no work order and so are not in the
+    // feed: the rail lists them so nobody scrolls the calendar to find one.
+    classic ? null : readIfAllowed(access, S.SERVICES, () => getVehicleAppointments(id)),
   ])
 
   if (!result.success || !result.data) {
@@ -277,6 +282,9 @@ export default async function VehicleDetailPage({
               jobWarningsResult?.success && jobWarningsResult.data ? jobWarningsResult.data : []
             }
             glance={glanceResult?.success && glanceResult.data ? glanceResult.data : null}
+            appointments={
+              appointmentsResult?.success && appointmentsResult.data ? appointmentsResult.data : []
+            }
             feedNotes={
               feedNotesResult?.success && feedNotesResult.data
                 ? feedNotesResult.data.records

+ 29 - 1
src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx

@@ -17,6 +17,11 @@ import { useGlassModal } from '@/components/glass-modal'
 import { VehicleForm } from '@/features/vehicles/Components/VehicleForm'
 import { NoteForm } from '@/features/vehicles/Components/NoteForm'
 import { ReminderForm } from '@/features/vehicles/Components/ReminderForm'
+import { appointmentHref } from '@/features/calendar/Lib/appointmentLink'
+import {
+  type VehicleAppointment,
+  VehicleAppointments,
+} from '@/features/vehicles/Components/VehicleAppointments'
 import { FindingForm } from '@/features/vehicles/Components/FindingForm'
 import { VehicleSafetyPanel } from '@/features/vehicles/Components/VehicleSafetyPanel'
 import { VehicleActivityFeed, type FeedFilter } from './vehicle-activity-feed'
@@ -362,6 +367,7 @@ export function VehicleDetailClient({
   jobWarnings = NO_WARNINGS,
   feedNotes,
   glance = null,
+  appointments = [],
 }: {
   vehicle: VehicleDetail
   paginatedServices: PaginatedServices
@@ -378,6 +384,8 @@ export function VehicleDetailClient({
   feedNotes?: PaginatedNotes['records']
   /** Last visit, next booking, what is owed; null for a role that may not read work orders. */
   glance?: VehicleGlance | null
+  /** Coming appointments, then the last few; empty for a role that may not read the calendar. */
+  appointments?: VehicleAppointment[]
   currencyCode?: string
   unitSystem?: 'metric' | 'imperial'
   predictionData?: {
@@ -610,6 +618,14 @@ export function VehicleDetailClient({
 
   const openFindings = paginatedFindings.records.filter((f) => f.status === 'open')
   const activeReminders = vehicle.reminders.filter((r) => !r.isCompleted)
+  // An appointment with no job behind it is a booking too: "Next booking"
+  // shows it when it comes before the next booked work order.
+  const firstAppointment = appointments.find((a) => a.upcoming)
+  const nextAppointment =
+    firstAppointment &&
+    (!glance?.nextBooking || new Date(firstAppointment.startAt) < new Date(glance.nextBooking))
+      ? firstAppointment
+      : null
 
   const optionLabel = (value: string | null, known: Set<string>) => {
     if (!value) return null
@@ -1208,7 +1224,11 @@ export function VehicleDetailClient({
 
                     <dt className="text-muted-foreground">{t('nextBooking')}</dt>
                     <dd className="min-w-0 tabular-nums">
-                      {glance.nextBooking && glance.nextBookingJobId ? (
+                      {nextAppointment ? (
+                        <Link href={appointmentHref(nextAppointment.id)} className={RAIL_LINK}>
+                          {formatDateTime(new Date(nextAppointment.startAt))}
+                        </Link>
+                      ) : glance.nextBooking && glance.nextBookingJobId ? (
                         <Link
                           href={`/vehicles/${vehicle.id}/service/${glance.nextBookingJobId}`}
                           className={RAIL_LINK}
@@ -1433,6 +1453,14 @@ export function VehicleDetailClient({
                 </>
               )}
 
+              {/* "Is this car booked?" answered without the calendar. */}
+              {appointments.length > 0 && (
+                <>
+                  <div className="mx-1.5 my-3 h-px bg-border" />
+                  <VehicleAppointments appointments={appointments} />
+                </>
+              )}
+
               <div className="mx-1.5 my-3 h-px bg-border" />
 
               {/* What is still to do: observations nobody has dealt with, reminders not yet due. */}

+ 26 - 0
src/features/calendar/Actions/getVehicleAppointments.ts

@@ -0,0 +1,26 @@
+'use server'
+
+import { withAuth } from '@/lib/with-auth'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { workshopTimeZone } from '@/lib/workshop-timezone'
+import { listAppointments } from '../Lib/appointmentList.server'
+
+/**
+ * A vehicle's appointments for its page: the coming ones, then the last few,
+ * so "is this car booked?" is answered without opening the calendar.
+ * Reading them is reading the calendar, which follows reading jobs.
+ */
+export async function getVehicleAppointments(vehicleId: string) {
+  return withAuth(
+    async ({ organizationId }) => {
+      if (typeof vehicleId !== 'string' || !vehicleId) return []
+      return listAppointments(
+        { organizationId, vehicleId },
+        { timeZone: await workshopTimeZone(organizationId), upcoming: 5, past: 3 }
+      )
+    },
+    {
+      requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.SERVICES }],
+    }
+  )
+}

+ 33 - 1
src/features/calendar/Components/CalendarClient.tsx

@@ -45,6 +45,7 @@ import { CalendarToolbar, type CreateKind } from './CalendarToolbar'
 import type { DayActions } from './DayContextMenu'
 import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
 import { type BookingEdit, EventPeekProvider } from './EventPeek'
+import { LinkedAppointment } from './LinkedAppointment'
 import { MonthView } from './MonthView'
 import { ScheduleView } from './ScheduleView'
 import { TimeGridView } from './TimeGridView'
@@ -69,6 +70,17 @@ interface CalendarClientProps {
   timeOff?: { technicians: TechnicianOption[] } | null
   /** The viewing preferences from the cookie; null when none are stored yet. */
   initialPreferences?: CalendarPreferences | null
+  /**
+   * An appointment a link asked for: the calendar goes to its day and opens
+   * its card. `token` is new on every request, so following the same link
+   * again while the calendar is open does it again.
+   */
+  linkedAppointment?: {
+    event: CalendarEvent
+    date: string
+    view: CalendarView
+    token: string
+  } | null
 }
 
 const ALL_TYPES: CalendarEventType[] = [
@@ -110,6 +122,7 @@ export default function CalendarClient({
   messageChannels,
   timeOff = null,
   initialPreferences = null,
+  linkedAppointment = null,
 }: CalendarClientProps) {
   const t = useTranslations('calendar')
   const tWorkOrders = useTranslations('workOrders.list')
@@ -211,6 +224,15 @@ export default function CalendarClient({
     window.history.replaceState(window.history.state, '', `${pathname}?${params.toString()}`)
   }, [view, dateStr, pathname])
 
+  // A followed appointment link moves the calendar to its day.
+  const linkToken = linkedAppointment?.token
+  useEffect(() => {
+    if (!linkedAppointment) return
+    const day = parseDateKey(linkedAppointment.date)
+    setView(linkedAppointment.view)
+    if (day) setDate(day)
+  }, [linkToken])
+
   // ── Derived data ───────────────────────────────────────────────────────
   const counts = useMemo(() => {
     const c: Record<CalendarEventType, number> = {
@@ -559,7 +581,17 @@ export default function CalendarClient({
               onFilterChange={setTypeShown}
             />
           )}
-          <div className="flex min-h-0 min-w-0 flex-1 flex-col">{body}</div>
+          <div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
+            {body}
+            {linkedAppointment && (
+              <LinkedAppointment
+                key={linkedAppointment.token}
+                event={linkedAppointment.event}
+                view={linkedAppointment.view}
+                date={linkedAppointment.date}
+              />
+            )}
+          </div>
         </div>
       </div>
 

+ 59 - 0
src/features/calendar/Components/LinkedAppointment.tsx

@@ -0,0 +1,59 @@
+'use client'
+
+import { useEffect, useRef } from 'react'
+import type { CalendarEvent } from '../Actions/calendarActions'
+import { useEventPeek } from './EventPeek'
+
+/**
+ * Opens the card of the appointment a link asked for, once. The card is
+ * anchored to a point near the top of the view rather than to the chip,
+ * which knows nothing of links; closing it leaves the day on screen.
+ *
+ * It waits for any dialog to finish closing first: a link followed from the
+ * search palette arrives while the palette hands focus back, and a card
+ * opened then would close again at once. Then the link leaves the address,
+ * so a refresh does not open the card a second time.
+ */
+export function LinkedAppointment({
+  event,
+  view,
+  date,
+}: {
+  event: CalendarEvent
+  view: string
+  date: string
+}) {
+  const { openPeek } = useEventPeek()
+  const anchor = useRef<HTMLSpanElement>(null)
+  const opened = useRef(false)
+  useEffect(() => {
+    if (opened.current) return
+    const started = Date.now()
+    let frame = 0
+    const tryOpen = () => {
+      const dialogOpen = document.querySelector('[role="dialog"]') !== null
+      if (dialogOpen && Date.now() - started < 2000) {
+        frame = requestAnimationFrame(tryOpen)
+        return
+      }
+      if (opened.current || !anchor.current) return
+      opened.current = true
+      const params = new URLSearchParams({ view, date })
+      window.history.replaceState(
+        window.history.state,
+        '',
+        `${window.location.pathname}?${params.toString()}`
+      )
+      openPeek(event, anchor.current)
+    }
+    frame = requestAnimationFrame(tryOpen)
+    return () => cancelAnimationFrame(frame)
+  }, [event, view, date, openPeek])
+  return (
+    <span
+      ref={anchor}
+      aria-hidden
+      className="pointer-events-none absolute top-16 left-1/2 h-0 w-0"
+    />
+  )
+}

+ 7 - 0
src/features/calendar/Lib/appointmentLink.ts

@@ -0,0 +1,7 @@
+/**
+ * The calendar opened on one appointment: its day, with its card open. An
+ * appointment has no page of its own, so this is how anything else links to one.
+ */
+export function appointmentHref(id: string): string {
+  return `/calendar?appointment=${encodeURIComponent(id)}`
+}

+ 93 - 0
src/features/calendar/Lib/appointmentList.server.ts

@@ -0,0 +1,93 @@
+import 'server-only'
+import type { Prisma } from '@/generated/prisma/client'
+import { db } from '@/lib/db'
+import { zonedDayKey, zonedParts } from '@/lib/timezone'
+
+/** One appointment as a list shows it, on the workshop's clock. */
+export type AppointmentListItem = {
+  id: string
+  title: string
+  startAt: Date
+  /** YYYY-MM-DD on the workshop's clock. */
+  date: string
+  /** HH:MM on the workshop's clock. */
+  time: string
+  /** Whether it has not started yet. */
+  upcoming: boolean
+  customer: { id: string; name: string } | null
+  vehicle: {
+    id: string
+    make: string
+    model: string
+    year: number
+    licensePlate: string | null
+  } | null
+}
+
+function clock(date: Date, timeZone: string): string {
+  const p = zonedParts(date, timeZone)
+  return `${String(p.hour).padStart(2, '0')}:${String(p.minute).padStart(2, '0')}`
+}
+
+/**
+ * Appointments matching `where`, the coming ones first, soonest first, then
+ * the ones already past, latest first. Somebody looking one up is nearly
+ * always asking about the next visit, but last week's must still be found.
+ * `where` must already be scoped to the organization.
+ */
+export async function listAppointments(
+  where: Prisma.AppointmentWhereInput & { organizationId: string },
+  options: { timeZone: string; upcoming: number; past: number; now?: Date }
+): Promise<AppointmentListItem[]> {
+  const now = options.now ?? new Date()
+  const select = {
+    id: true,
+    title: true,
+    startAt: true,
+    customer: { select: { id: true, name: true } },
+    vehicle: {
+      select: {
+        id: true,
+        make: true,
+        model: true,
+        year: true,
+        licensePlate: true,
+        customer: { select: { id: true, name: true } },
+      },
+    },
+  } satisfies Prisma.AppointmentSelect
+
+  const [upcoming, past] = await Promise.all([
+    db.appointment.findMany({
+      where: { AND: [where, { startAt: { gte: now } }] },
+      select,
+      orderBy: { startAt: 'asc' },
+      take: options.upcoming,
+    }),
+    db.appointment.findMany({
+      where: { AND: [where, { startAt: { lt: now } }] },
+      select,
+      orderBy: { startAt: 'desc' },
+      take: options.past,
+    }),
+  ])
+
+  return [...upcoming, ...past].map((a) => ({
+    id: a.id,
+    title: a.title,
+    startAt: a.startAt,
+    date: zonedDayKey(a.startAt, options.timeZone),
+    time: clock(a.startAt, options.timeZone),
+    upcoming: a.startAt >= now,
+    customer: a.customer ?? a.vehicle?.customer ?? null,
+    vehicle: a.vehicle
+      ? {
+          id: a.vehicle.id,
+          make: a.vehicle.make,
+          model: a.vehicle.model,
+          year: a.vehicle.year,
+          licensePlate: a.vehicle.licensePlate,
+        }
+      : null,
+  }))
+}

+ 24 - 0
src/features/calendar/Lib/linkedAppointment.server.ts

@@ -0,0 +1,24 @@
+import 'server-only'
+import { db } from '@/lib/db'
+import type { AuthContext } from '@/lib/with-auth'
+import { PermissionSubject } from '@/lib/permissions'
+import { accessFor } from '@/lib/viewer-access'
+
+/**
+ * The appointment a calendar link asks for, or null. Only the viewer's own
+ * workshop's, and only for somebody who may read the calendar (seeing it is
+ * reading jobs): any other id, one since deleted, or a viewer without that
+ * read gets the calendar as if the link named no appointment at all, so a
+ * link never tells anyone whether an id exists or which day it is on.
+ */
+export async function findLinkedAppointment(
+  ctx: Pick<AuthContext, 'userId' | 'isAdmin' | 'organizationId'> | null,
+  id: unknown
+): Promise<{ id: string; startAt: Date } | null> {
+  if (!ctx || typeof id !== 'string' || !id) return null
+  if (!(await accessFor(ctx)).reads(PermissionSubject.SERVICES)) return null
+  return db.appointment.findFirst({
+    where: { id, organizationId: ctx.organizationId },
+    select: { id: true, startAt: true },
+  })
+}

+ 280 - 229
src/features/search/Actions/searchActions.ts

@@ -9,6 +9,9 @@ import { searchYear } from '@/features/vehicles/Lib/searchYear'
 import { searchWordsOf, typeKeySearchTerms } from '@/features/vehicles/Lib/typeKey'
 import { partIdsWithTagContaining } from '@/features/inventory/Lib/tagSearch.server'
 import { isTypeKeyEnabled } from '@/features/vehicles/Lib/typeKeySetting'
+import { accessFor } from '@/lib/viewer-access'
+import { workshopTimeZone } from '@/lib/workshop-timezone'
+import { listAppointments } from '@/features/calendar/Lib/appointmentList.server'
 
 export async function getRecentCustomers() {
   return withAuth(
@@ -37,7 +40,8 @@ export async function getRecentCustomers() {
 
 export async function globalSearch(query: string) {
   return withAuth(
-    async ({ organizationId }) => {
+    async (ctx) => {
+      const { organizationId } = ctx
       if (!query || query.trim().length < 2) {
         return {
           vehicles: [],
@@ -48,6 +52,7 @@ export async function globalSearch(query: string) {
           reminders: [],
           inspections: [],
           tireSets: [],
+          appointments: [],
         }
       }
 
@@ -91,116 +96,99 @@ export async function globalSearch(query: string) {
       // Only searched when the module is on, so a shop without it pays nothing.
       const tireHotelOn = await isTireHotelEnabled(organizationId)
 
-      const [vehicles, customers, services, parts, quotes, reminders, inspections, tireSets] =
-        await Promise.all([
-          db.vehicle.findMany({
-            where: vehicleWhere,
-            select: {
-              id: true,
-              make: true,
-              model: true,
-              year: true,
-              licensePlate: true,
-              hsn: true,
-              tsn: true,
-            },
-            take: 10,
-          }),
-          (async () => {
-            // For phone-like queries, use raw SQL to strip formatting before matching
-            if (isPhoneLike) {
-              const phoneCustomers = await db.$queryRaw<
-                {
-                  id: string
-                  name: string
-                  email: string | null
-                  phone: string | null
-                  company: string | null
-                }[]
-              >`
+      // Appointments live on the calendar, and seeing the calendar is reading
+      // jobs: a role that cannot open it is not shown them here either.
+      const appointmentsOn = (await accessFor(ctx)).reads(PermissionSubject.SERVICES)
+
+      const [
+        vehicles,
+        customers,
+        services,
+        parts,
+        quotes,
+        reminders,
+        inspections,
+        tireSets,
+        appointments,
+      ] = await Promise.all([
+        db.vehicle.findMany({
+          where: vehicleWhere,
+          select: {
+            id: true,
+            make: true,
+            model: true,
+            year: true,
+            licensePlate: true,
+            hsn: true,
+            tsn: true,
+          },
+          take: 10,
+        }),
+        (async () => {
+          // For phone-like queries, use raw SQL to strip formatting before matching
+          if (isPhoneLike) {
+            const phoneCustomers = await db.$queryRaw<
+              {
+                id: string
+                name: string
+                email: string | null
+                phone: string | null
+                company: string | null
+              }[]
+            >`
             SELECT id, name, email, phone, company
             FROM "public"."customers"
             WHERE "organizationId" = ${organizationId}
               AND REGEXP_REPLACE(phone, '[^0-9]', '', 'g') LIKE ${'%' + digitsOnly + '%'}
             LIMIT 10
           `
-              // Fetch vehicles for matched customers
-              const customerIds = phoneCustomers.map((c) => c.id)
-              const customerVehicles =
-                customerIds.length > 0
-                  ? await db.vehicle.findMany({
-                      where: { customerId: { in: customerIds }, isArchived: false },
-                      select: {
-                        id: true,
-                        make: true,
-                        model: true,
-                        year: true,
-                        licensePlate: true,
-                        customerId: true,
-                      },
-                      take: 25,
-                      orderBy: { updatedAt: 'desc' },
-                    })
-                  : []
-              return phoneCustomers.map((c) => ({
-                ...c,
-                vehicles: customerVehicles
-                  .filter((v) => v.customerId === c.id)
-                  .slice(0, 5)
-                  .map(({ customerId: _, ...v }) => v),
-              }))
-            }
-            // Standard text search
-            return db.customer.findMany({
-              where: {
-                organizationId,
-                AND: words.map((word) => ({
-                  OR: [
-                    { name: { contains: word, mode } },
-                    { email: { contains: word, mode } },
-                    { phone: { contains: word, mode } },
-                    { company: { contains: word, mode } },
-                  ],
-                })),
-              },
-              select: {
-                id: true,
-                name: true,
-                email: true,
-                phone: true,
-                company: true,
-                vehicles: {
-                  where: { isArchived: false },
-                  select: {
-                    id: true,
-                    make: true,
-                    model: true,
-                    year: true,
-                    licensePlate: true,
-                  },
-                  take: 5,
-                  orderBy: { updatedAt: 'desc' },
-                },
-              },
-              take: 10,
-            })
-          })(),
-          db.serviceRecord.findMany({
+            // Fetch vehicles for matched customers
+            const customerIds = phoneCustomers.map((c) => c.id)
+            const customerVehicles =
+              customerIds.length > 0
+                ? await db.vehicle.findMany({
+                    where: { customerId: { in: customerIds }, isArchived: false },
+                    select: {
+                      id: true,
+                      make: true,
+                      model: true,
+                      year: true,
+                      licensePlate: true,
+                      customerId: true,
+                    },
+                    take: 25,
+                    orderBy: { updatedAt: 'desc' },
+                  })
+                : []
+            return phoneCustomers.map((c) => ({
+              ...c,
+              vehicles: customerVehicles
+                .filter((v) => v.customerId === c.id)
+                .slice(0, 5)
+                .map(({ customerId: _, ...v }) => v),
+            }))
+          }
+          // Standard text search
+          return db.customer.findMany({
             where: {
               organizationId,
               AND: words.map((word) => ({
                 OR: [
-                  { title: { contains: word, mode } },
-                  { invoiceNumber: { contains: word, mode } },
-                  { techName: { contains: word, mode } },
+                  { name: { contains: word, mode } },
+                  { email: { contains: word, mode } },
+                  { phone: { contains: word, mode } },
+                  { company: { contains: word, mode } },
                 ],
               })),
             },
             select: {
               id: true,
-              title: true,
-              invoiceNumber: true,
-              vehicle: {
+              name: true,
+              email: true,
+              phone: true,
+              company: true,
+              vehicles: {
+                where: { isArchived: false },
                 select: {
                   id: true,
                   make: true,
@@ -208,137 +196,212 @@ export async function globalSearch(query: string) {
                   year: true,
                   licensePlate: true,
                 },
+                take: 5,
+                orderBy: { updatedAt: 'desc' },
               },
             },
             take: 10,
-          }),
-          (async () => {
-            // Tags are a text array Prisma cannot search by "contains", so the
-            // parts a word finds in a tag are looked up first, per word, for
-            // the first few words of a query.
-            const tagged = await Promise.all(
-              words.map((word, i) =>
-                i < 8 ? partIdsWithTagContaining(organizationId, word) : Promise.resolve([])
-              )
-            )
-            return db.inventoryPart.findMany({
-              where: {
-                organizationId,
-                isArchived: false,
-                AND: words.map((word, i) => ({
-                  OR: [
-                    { name: { contains: word, mode } },
-                    { partNumber: { contains: word, mode } },
-                    { supplier: { contains: word, mode } },
-                    { id: { in: tagged[i] } },
-                  ],
-                })),
-              },
+          })
+        })(),
+        db.serviceRecord.findMany({
+          where: {
+            organizationId,
+            AND: words.map((word) => ({
+              OR: [
+                { title: { contains: word, mode } },
+                { invoiceNumber: { contains: word, mode } },
+                { techName: { contains: word, mode } },
+              ],
+            })),
+          },
+          select: {
+            id: true,
+            title: true,
+            invoiceNumber: true,
+            vehicle: {
               select: {
                 id: true,
-                name: true,
-                partNumber: true,
-                quantity: true,
-                trackStock: true,
-                unit: true,
+                make: true,
+                model: true,
+                year: true,
+                licensePlate: true,
               },
-              take: 10,
-            })
-          })(),
-          db.quote.findMany({
+            },
+          },
+          take: 10,
+        }),
+        (async () => {
+          // Tags are a text array Prisma cannot search by "contains", so the
+          // parts a word finds in a tag are looked up first, per word, for
+          // the first few words of a query.
+          const tagged = await Promise.all(
+            words.map((word, i) =>
+              i < 8 ? partIdsWithTagContaining(organizationId, word) : Promise.resolve([])
+            )
+          )
+          return db.inventoryPart.findMany({
             where: {
               organizationId,
-              AND: words.map((word) => ({
+              isArchived: false,
+              AND: words.map((word, i) => ({
                 OR: [
-                  { title: { contains: word, mode } },
-                  { quoteNumber: { contains: word, mode } },
-                  { customer: { name: { contains: word, mode } } },
+                  { name: { contains: word, mode } },
+                  { partNumber: { contains: word, mode } },
+                  { supplier: { contains: word, mode } },
+                  { id: { in: tagged[i] } },
                 ],
               })),
             },
             select: {
               id: true,
-              title: true,
-              quoteNumber: true,
-              status: true,
+              name: true,
+              partNumber: true,
+              quantity: true,
+              trackStock: true,
+              unit: true,
             },
             take: 10,
-          }),
-          db.reminder.findMany({
-            where: {
-              organizationId,
-              AND: words.map((word) => ({
-                OR: [
-                  { title: { contains: word, mode } },
-                  { description: { contains: word, mode } },
-                  { vehicle: { make: { contains: word, mode } } },
-                  { vehicle: { model: { contains: word, mode } } },
-                  { vehicle: { licensePlate: { contains: word, mode } } },
-                  ...typeKeyMatch(word).map((vehicle) => ({ vehicle })),
-                  { customer: { name: { contains: word, mode } } },
-                ],
-              })),
-            },
-            select: {
-              id: true,
-              title: true,
-              dueDate: true,
-              isCompleted: true,
-              customer: { select: { id: true, name: true } },
-              vehicle: {
-                select: {
-                  id: true,
-                  make: true,
-                  model: true,
-                  year: true,
-                  licensePlate: true,
-                },
+          })
+        })(),
+        db.quote.findMany({
+          where: {
+            organizationId,
+            AND: words.map((word) => ({
+              OR: [
+                { title: { contains: word, mode } },
+                { quoteNumber: { contains: word, mode } },
+                { customer: { name: { contains: word, mode } } },
+              ],
+            })),
+          },
+          select: {
+            id: true,
+            title: true,
+            quoteNumber: true,
+            status: true,
+          },
+          take: 10,
+        }),
+        db.reminder.findMany({
+          where: {
+            organizationId,
+            AND: words.map((word) => ({
+              OR: [
+                { title: { contains: word, mode } },
+                { description: { contains: word, mode } },
+                { vehicle: { make: { contains: word, mode } } },
+                { vehicle: { model: { contains: word, mode } } },
+                { vehicle: { licensePlate: { contains: word, mode } } },
+                ...typeKeyMatch(word).map((vehicle) => ({ vehicle })),
+                { customer: { name: { contains: word, mode } } },
+              ],
+            })),
+          },
+          select: {
+            id: true,
+            title: true,
+            dueDate: true,
+            isCompleted: true,
+            customer: { select: { id: true, name: true } },
+            vehicle: {
+              select: {
+                id: true,
+                make: true,
+                model: true,
+                year: true,
+                licensePlate: true,
               },
             },
-            take: 10,
-          }),
-          db.inspection.findMany({
-            where: {
-              organizationId,
-              AND: words.map((word) => ({
-                OR: [
-                  { template: { name: { contains: word, mode } } },
-                  { notes: { contains: word, mode } },
-                  { vehicle: { make: { contains: word, mode } } },
-                  { vehicle: { model: { contains: word, mode } } },
-                  { vehicle: { licensePlate: { contains: word, mode } } },
-                  ...typeKeyMatch(word).map((vehicle) => ({ vehicle })),
-                ],
-              })),
+          },
+          take: 10,
+        }),
+        db.inspection.findMany({
+          where: {
+            organizationId,
+            AND: words.map((word) => ({
+              OR: [
+                { template: { name: { contains: word, mode } } },
+                { notes: { contains: word, mode } },
+                { vehicle: { make: { contains: word, mode } } },
+                { vehicle: { model: { contains: word, mode } } },
+                { vehicle: { licensePlate: { contains: word, mode } } },
+                ...typeKeyMatch(word).map((vehicle) => ({ vehicle })),
+              ],
+            })),
+          },
+          select: {
+            id: true,
+            status: true,
+            createdAt: true,
+            template: { select: { name: true } },
+            vehicle: {
+              select: {
+                id: true,
+                make: true,
+                model: true,
+                year: true,
+                licensePlate: true,
+              },
             },
-            select: {
-              id: true,
-              status: true,
-              createdAt: true,
-              template: { select: { name: true } },
-              vehicle: {
-                select: {
-                  id: true,
-                  make: true,
-                  model: true,
-                  year: true,
-                  licensePlate: true,
+          },
+          take: 10,
+        }),
+        tireHotelOn
+          ? db.tireSet.findMany({
+              where: {
+                organizationId,
+                AND: words.map((word) => ({
+                  OR: [
+                    { reference: { contains: word, mode } },
+                    { brand: { contains: word, mode } },
+                    { size: { contains: word, mode } },
+                    { location: { code: { contains: word, mode } } },
+                    { customer: { name: { contains: word, mode } } },
+                    { vehicle: { make: { contains: word, mode } } },
+                    { vehicle: { model: { contains: word, mode } } },
+                    { vehicle: { licensePlate: { contains: word, mode } } },
+                    ...typeKeyMatch(word).map((vehicle) => ({ vehicle })),
+                  ],
+                })),
+              },
+              select: {
+                id: true,
+                reference: true,
+                season: true,
+                size: true,
+                quantity: true,
+                status: true,
+                location: { select: { code: true } },
+                customer: { select: { id: true, name: true } },
+                vehicle: {
+                  select: {
+                    id: true,
+                    make: true,
+                    model: true,
+                    year: true,
+                    licensePlate: true,
+                  },
                 },
               },
-            },
-            take: 10,
-          }),
-          tireHotelOn
-            ? db.tireSet.findMany({
-                where: {
+              // Stored sets first: a released set is history, and the desk is
+              // almost always asking about something still on a shelf.
+              orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
+              take: 10,
+            })
+          : Promise.resolve([]),
+        // The phone rings and somebody asks "when am I booked?": found by
+        // what it is, who it is with or the car, the coming ones first.
+        appointmentsOn
+          ? (async () =>
+              listAppointments(
+                {
                   organizationId,
                   AND: words.map((word) => ({
                     OR: [
-                      { reference: { contains: word, mode } },
-                      { brand: { contains: word, mode } },
-                      { size: { contains: word, mode } },
-                      { location: { code: { contains: word, mode } } },
+                      { title: { contains: word, mode } },
+                      { description: { contains: word, mode } },
                       { customer: { name: { contains: word, mode } } },
+                      { vehicle: { customer: { name: { contains: word, mode } } } },
                       { vehicle: { make: { contains: word, mode } } },
                       { vehicle: { model: { contains: word, mode } } },
                       { vehicle: { licensePlate: { contains: word, mode } } },
@@ -346,34 +409,22 @@ export async function globalSearch(query: string) {
                     ],
                   })),
                 },
-                select: {
-                  id: true,
-                  reference: true,
-                  season: true,
-                  size: true,
-                  quantity: true,
-                  status: true,
-                  location: { select: { code: true } },
-                  customer: { select: { id: true, name: true } },
-                  vehicle: {
-                    select: {
-                      id: true,
-                      make: true,
-                      model: true,
-                      year: true,
-                      licensePlate: true,
-                    },
-                  },
-                },
-                // Stored sets first: a released set is history, and the desk is
-                // almost always asking about something still on a shelf.
-                orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
-                take: 10,
-              })
-            : Promise.resolve([]),
-        ])
+                { timeZone: await workshopTimeZone(organizationId), upcoming: 6, past: 4 }
+              ))()
+          : Promise.resolve([]),
+      ])
 
-      return { vehicles, customers, services, parts, quotes, reminders, inspections, tireSets }
+      return {
+        vehicles,
+        customers,
+        services,
+        parts,
+        quotes,
+        reminders,
+        inspections,
+        tireSets,
+        appointments,
+      }
     },
     {
       requiredPermissions: [

+ 46 - 1
src/features/search/Components/SearchCommand.tsx

@@ -5,6 +5,7 @@ import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useRef, useS
 import { useTranslations } from 'next-intl'
 import {
   Bell,
+  CalendarClock,
   Car,
   ClipboardCheck,
   CornerDownLeft,
@@ -60,6 +61,8 @@ import {
   normalizeFaultCode,
 } from '@/features/fault-codes/Lib/codes'
 import type { OemSearchHit } from '@/features/fault-codes/Lib/types'
+import { appointmentHref } from '@/features/calendar/Lib/appointmentLink'
+import { useFormatDate } from '@/lib/use-format-date'
 
 type Vehicle = {
   id: string
@@ -128,6 +131,17 @@ interface SearchResult {
     customer: { id: string; name: string } | null
     vehicle: Vehicle | null
   }[]
+  /** `date` (YYYY-MM-DD) and `time` (HH:MM) are on the workshop's clock. */
+  appointments?: {
+    id: string
+    title: string
+    startAt: Date | string
+    date: string
+    time: string
+    upcoming: boolean
+    customer: { id: string; name: string } | null
+    vehicle: Vehicle | null
+  }[]
 }
 
 /** The palette's fault code groups, asked for on their own beside the normal search. */
@@ -165,6 +179,7 @@ const EMPTY: SearchResult = {
   reminders: [],
   inspections: [],
   tireSets: [],
+  appointments: [],
 }
 
 type RecentCustomer = {
@@ -332,6 +347,7 @@ function iconForHref(href: string): LucideIcon {
   if (href.startsWith('/tire-hotel')) return Disc3
   if (href.startsWith('/inspections')) return ClipboardCheck
   if (href.startsWith('/reminders')) return Bell
+  if (href.startsWith('/calendar')) return CalendarClock
   if (href.startsWith('/settings')) return Search
   return Wrench
 }
@@ -358,6 +374,7 @@ export function SearchCommand({
   const tShortcuts = useTranslations('settings.shortcuts')
   const { openHelp: openShortcutsHelp } = useShortcuts()
   const tFault = useTranslations('faultCodes.search')
+  const { formatDate, formatTime } = useFormatDate()
   const tCodes = useTranslations('faultCodes')
   const typeKeyEnabled = useTypeKeyEnabled()
   const plateLookup = usePlateLookupAccess()
@@ -683,7 +700,8 @@ export function SearchCommand({
     results.quotes.length > 0 ||
     results.reminders.length > 0 ||
     results.inspections.length > 0 ||
-    results.tireSets.length > 0
+    results.tireSets.length > 0 ||
+    (results.appointments?.length ?? 0) > 0
   // The palette's fault code rows: the service's codes for what was typed, and
   // the whole code itself when the service has nothing for it, so Enter still
   // opens its page.
@@ -1028,6 +1046,33 @@ export function SearchCommand({
             })}
           </CommandGroup>
         )}
+        {hasQuery && results.appointments && results.appointments.length > 0 && (
+          <CommandGroup heading={t('groups.appointments')}>
+            {results.appointments.map((a) => {
+              const when = `${formatDate(a.startAt)} ${formatTime(a.startAt)}`
+              const subtitle = [
+                when,
+                a.customer?.name,
+                a.vehicle && !a.customer ? vehicleLine(a.vehicle) : null,
+              ]
+                .filter(Boolean)
+                .join(' · ')
+              return (
+                <Row
+                  key={a.id}
+                  value={`appointment:${a.id}`}
+                  onSelect={() => pickRecord(appointmentHref(a.id), a.title, subtitle)}
+                  icon={CalendarClock}
+                  title={
+                    <span className={cn(!a.upcoming && 'text-muted-foreground')}>{a.title}</span>
+                  }
+                  subtitle={subtitle}
+                  trailing={a.vehicle?.licensePlate}
+                />
+              )
+            })}
+          </CommandGroup>
+        )}
         {hasQuery && results.quotes.length > 0 && (
           <CommandGroup heading={tNav('quotes')}>
             {results.quotes.map((q) => (

+ 87 - 0
src/features/vehicles/Components/VehicleAppointments.tsx

@@ -0,0 +1,87 @@
+'use client'
+
+import Link from 'next/link'
+import { useTranslations } from 'next-intl'
+import { CalendarClock } from 'lucide-react'
+import { useFormatDate } from '@/lib/use-format-date'
+import { cn } from '@/lib/utils'
+import { appointmentHref } from '@/features/calendar/Lib/appointmentLink'
+
+export type VehicleAppointment = {
+  id: string
+  title: string
+  startAt: Date | string
+  /** YYYY-MM-DD on the workshop's clock. */
+  date: string
+  /** HH:MM on the workshop's clock. */
+  time: string
+  upcoming: boolean
+}
+
+/**
+ * The vehicle's appointments in the call sheet's rail: what is coming, then
+ * the last few, each opening the calendar on that appointment. Left out when
+ * the car has none, like the rest of the rail's optional sections.
+ */
+export function VehicleAppointments({ appointments }: { appointments: VehicleAppointment[] }) {
+  const t = useTranslations('vehicles.detail')
+  const { formatDate, formatTime } = useFormatDate()
+
+  if (appointments.length === 0) return null
+
+  const upcoming = appointments.filter((a) => a.upcoming)
+  const past = appointments.filter((a) => !a.upcoming)
+
+  // The workshop's own date format and clock, like the rest of the rail.
+  const when = (a: VehicleAppointment) => `${formatDate(a.startAt)} · ${formatTime(a.startAt)}`
+
+  const row = (a: VehicleAppointment) => (
+    <li key={a.id}>
+      <Link
+        href={appointmentHref(a.id)}
+        className="flex w-full items-start gap-2.5 rounded-lg px-1.5 py-1.5 text-left transition-colors hover:bg-muted/50"
+      >
+        <CalendarClock
+          aria-hidden
+          className={cn(
+            'mt-[3px] h-3.5 w-3.5 shrink-0',
+            a.upcoming ? 'text-pink-700 dark:text-pink-400' : 'text-muted-foreground'
+          )}
+        />
+        <span className="min-w-0">
+          <span
+            className={cn(
+              'block truncate text-[13px] font-medium leading-snug',
+              !a.upcoming && 'text-muted-foreground'
+            )}
+          >
+            {a.title}
+          </span>
+          <span className="block text-xs tabular-nums text-muted-foreground">{when(a)}</span>
+        </span>
+      </Link>
+    </li>
+  )
+
+  return (
+    <section aria-labelledby="vehicle-appointments">
+      <h2 id="vehicle-appointments" className="px-1.5 pb-1 text-[13px] font-semibold">
+        {t('appointments')}
+      </h2>
+      {upcoming.length === 0 && (
+        <p className="px-1.5 pb-1 text-[13px] text-muted-foreground">
+          {t('noUpcomingAppointments')}
+        </p>
+      )}
+      {upcoming.length > 0 && <ul className="space-y-0.5">{upcoming.map(row)}</ul>}
+      {past.length > 0 && (
+        <>
+          <p className="px-1.5 pt-2 pb-0.5 text-xs text-muted-foreground">
+            {t('earlierAppointments')}
+          </p>
+          <ul className="space-y-0.5">{past.map(row)}</ul>
+        </>
+      )}
+    </section>
+  )
+}