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

Show a calendar booking's description as the job's conditions and open Edit on double-click (#632)

* Show a booked job's description as its conditions and open Edit on double-click

A description typed when booking a work order from the calendar was saved
where nothing shows it. It now becomes the job's conditions, one line per
paragraph or list item, and the conditions are the only copy: the calendar
card shows them, and the booking dialog reads and writes them.

Double-clicking an item on the calendar opens it for editing instead of
switching to day view, and the card closes when the view or the day changes.

* Keep angle-bracketed text, allow long work lines and keep the card open on a double-click

Only HTML tag syntax is removed when a description becomes conditions, so
comparisons and addresses in angle brackets stay. The work lines take a
description of full length folded into them. A press on the chip a card
hangs off no longer counts as a press outside the card, so a double-click
on an item that is changed on the work order leaves its card open.
Bernt Christian Egeland 8 часов назад
Родитель
Сommit
eec2209176

+ 128 - 0
src/__tests__/features/calendar/booking-actions.test.ts

@@ -286,6 +286,55 @@ describe('createBooking: a work order', () => {
     expect(db.appointment.create).not.toHaveBeenCalled()
     expect(db.appointment.create).not.toHaveBeenCalled()
   })
   })
 
 
+  it('makes the description the conditions, a line per paragraph and list item, and keeps no other copy', async () => {
+    const result = await createBookingOnce(
+      booking({
+        kind: 'workOrder',
+        title: 'Brake job',
+        vehicleId: 'veh-1',
+        description:
+          '<p>Front brakes <strong>squeal</strong> when cold</p><ul><li><p>Oil service</p></li><li><p>Check wipers</p></li></ul>',
+      })
+    )
+
+    expect(result.success).toBe(true)
+    expect(jobData().title).toBe('Brake job')
+    expect(jobUpdate().data.concerns.create).toEqual([
+      { description: 'Front brakes squeal when cold', sortOrder: 0 },
+      { description: 'Oil service', sortOrder: 1 },
+      { description: 'Check wipers', sortOrder: 2 },
+    ])
+    expect(jobUpdate().data).not.toHaveProperty('description')
+  })
+
+  it('takes work lines as long as a full description folded into them', async () => {
+    const long = Array.from({ length: 100 }, (_, i) => `Line ${i} ${'x'.repeat(190)}`).join('\n')
+    expect(long.length).toBeGreaterThan(19_000)
+
+    const result = await createBookingOnce(
+      booking({ kind: 'workOrder', vehicleId: 'veh-1', work: `Brakes\n${long}` })
+    )
+
+    expect(result.success).toBe(true)
+    expect(jobUpdate().data.concerns.create).toHaveLength(101)
+  })
+
+  it('puts a description after the work lines, without saying anything twice', async () => {
+    await createBookingOnce(
+      booking({
+        kind: 'workOrder',
+        vehicleId: 'veh-1',
+        work: 'Oil service',
+        description: '<p>Oil service</p><p>Customer waits</p>',
+      })
+    )
+
+    expect(jobUpdate().data.concerns.create).toEqual([
+      { description: 'Oil service', sortOrder: 0 },
+      { description: 'Customer waits', sortOrder: 1 },
+    ])
+  })
+
   it('makes the title the only concern when no work lines are given', async () => {
   it('makes the title the only concern when no work lines are given', async () => {
     db.vehicle.findFirst.mockResolvedValue(null)
     db.vehicle.findFirst.mockResolvedValue(null)
 
 
@@ -340,6 +389,25 @@ describe('createBooking: an appointment made a work order', () => {
     expect(db.appointment.delete).toHaveBeenCalledWith({ where: { id: 'appt-1' } })
     expect(db.appointment.delete).toHaveBeenCalledWith({ where: { id: 'appt-1' } })
   })
   })
 
 
+  it("carries the appointment's description over as the job's conditions", async () => {
+    appointmentOnFile({ id: 'appt-1' })
+
+    await createBookingOnce(
+      booking({
+        kind: 'workOrder',
+        title: 'Tyre quote talk',
+        vehicleId: 'veh-1',
+        fromAppointmentId: 'appt-1',
+        description: '<p>Wants winter tyres</p><p>Has own rims</p>',
+      })
+    )
+
+    expect(jobUpdate().data.concerns.create).toEqual([
+      { description: 'Wants winter tyres', sortOrder: 0 },
+      { description: 'Has own rims', sortOrder: 1 },
+    ])
+  })
+
   it("refuses another workshop's appointment and creates nothing", async () => {
   it("refuses another workshop's appointment and creates nothing", async () => {
     db.appointment.findFirst.mockResolvedValue(null)
     db.appointment.findFirst.mockResolvedValue(null)
 
 
@@ -388,6 +456,24 @@ describe('the same booking sent twice', () => {
     expect(appointmentData().bookingToken).toBe(TOKEN)
     expect(appointmentData().bookingToken).toBe(TOKEN)
   })
   })
 
 
+  it('writes no conditions a second time for a description sent again', async () => {
+    alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
+
+    const result = await createBookingOnce(
+      booking({
+        kind: 'workOrder',
+        vehicleId: 'veh-1',
+        work: 'Brakes',
+        description: '<p>Customer waits</p>',
+      })
+    )
+
+    expect(result.success).toBe(true)
+    expect(result.data).toMatchObject({ kind: 'workOrder', id: 'job-1' })
+    expect(db.serviceRecord.update).not.toHaveBeenCalled()
+    expect(db.serviceConcern.createMany).not.toHaveBeenCalled()
+  })
+
   it('answers with the job already booked and books no second one', async () => {
   it('answers with the job already booked and books no second one', async () => {
     alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
     alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
 
 
@@ -762,6 +848,48 @@ describe('updateBooking: a booked job', () => {
     })
     })
   })
   })
 
 
+  it('keeps no description beside the conditions once the booking is saved', async () => {
+    db.serviceRecord.findFirst.mockResolvedValue(bookedJob())
+
+    await updateBooking(jobEdit({ work: 'Brakes\nCustomer waits' }))
+
+    expect(jobUpdate().data.description).toBeNull()
+    expect(db.serviceConcern.createMany).toHaveBeenCalledWith({
+      data: [
+        { serviceRecordId: 'job-1', description: 'Brakes', sortOrder: 0 },
+        { serviceRecordId: 'job-1', description: 'Customer waits', sortOrder: 1 },
+      ],
+    })
+  })
+
+  it('makes a description sent by a tab opened before the change conditions too', async () => {
+    db.serviceRecord.findFirst.mockResolvedValue(bookedJob())
+
+    await updateBooking(jobEdit({ work: 'Brakes', description: '<p>Customer waits</p>' }))
+
+    expect(jobUpdate().data.description).toBeNull()
+    expect(db.serviceConcern.createMany).toHaveBeenCalledWith({
+      data: [
+        { serviceRecordId: 'job-1', description: 'Brakes', sortOrder: 0 },
+        { serviceRecordId: 'job-1', description: 'Customer waits', sortOrder: 1 },
+      ],
+    })
+  })
+
+  it('leaves the description alone on a job with work recorded, where the conditions cannot change', async () => {
+    db.serviceRecord.findFirst.mockResolvedValue(
+      bookedJob({ concerns: [{ ...bookedJob().concerns[0], cause: 'Worn pads' }] })
+    )
+
+    const result = await updateBooking(
+      jobEdit({ title: 'Brakes, front', description: '<p>Customer waits</p>' })
+    )
+
+    expect(result.success).toBe(true)
+    expect(jobUpdate().data).not.toHaveProperty('description')
+    expect(db.serviceConcern.deleteMany).not.toHaveBeenCalled()
+  })
+
   it.each([
   it.each([
     ['a cause', { cause: 'Worn pads' }],
     ['a cause', { cause: 'Worn pads' }],
     ['a correction', { correction: 'Replaced pads' }],
     ['a correction', { correction: 'Replaced pads' }],

+ 66 - 0
src/__tests__/features/calendar/booking-dialog.test.tsx

@@ -463,6 +463,44 @@ describe('a new booking', () => {
     expect(toast.success).not.toHaveBeenCalled()
     expect(toast.success).not.toHaveBeenCalled()
   })
   })
 
 
+  it('books a work order with what it is about as conditions, and no description beside them', async () => {
+    await renderDialog()
+    fireEvent.change(titleField(), { target: { value: 'Brake job' } })
+    chooseKind('Work order')
+    await chooseCustomer()
+    // One field says what it is about: the conditions.
+    expect(screen.queryByPlaceholderText('Add description')).not.toBeInTheDocument()
+    addConcern('Front brakes squeal')
+
+    fireEvent.click(saveButton())
+
+    await waitFor(() => expect(createBooking).toHaveBeenCalled())
+    const sent = createBooking.mock.calls[0][0]
+    expect(sent.work).toBe('Front brakes squeal')
+    expect(sent.description).toBeUndefined()
+  })
+
+  it('takes a description already typed along as conditions when it becomes a work order, and back', async () => {
+    await renderDialog()
+    fireEvent.change(titleField(), { target: { value: 'Brake job' } })
+    chooseKind('Appointment')
+    fireEvent.change(screen.getByPlaceholderText('Add description'), {
+      target: { value: '<p>Front brakes squeal</p><ul><li><p>Oil service</p></li></ul>' },
+    })
+
+    chooseKind('Work order')
+
+    expect(screen.getByLabelText('Concern 1')).toHaveValue('Front brakes squeal')
+    expect(screen.getByLabelText('Concern 2')).toHaveValue('Oil service')
+
+    chooseKind('Appointment')
+
+    expect(screen.getByPlaceholderText('Add description')).toHaveValue(
+      '<p>Front brakes squeal</p><p>Oil service</p>'
+    )
+    expect(screen.queryByLabelText('Concern 1')).not.toBeInTheDocument()
+  })
+
   it('starts on the kind this person booked last', async () => {
   it('starts on the kind this person booked last', async () => {
     window.localStorage.setItem('torqvoice.calendar.bookingKind', 'appointment')
     window.localStorage.setItem('torqvoice.calendar.bookingKind', 'appointment')
     await renderDialog()
     await renderDialog()
@@ -708,6 +746,34 @@ describe('making an appointment a work order', () => {
     })
     })
     expect(sent.id).toBeUndefined()
     expect(sent.id).toBeUndefined()
   })
   })
+
+  it("opens with the appointment's description as the job's conditions", async () => {
+    getBooking.mockResolvedValue({
+      success: true,
+      data: loadedBooking({ description: '<p>Wants winter tyres</p><p>Has own rims</p>' }),
+    })
+    createBooking.mockResolvedValue({
+      success: true,
+      data: {
+        kind: 'workOrder',
+        id: 'job-1',
+        ref: '2026-1044',
+        vehicleId: null,
+        overbooked: false,
+      },
+    })
+    await renderDialog({ edit: { mode: 'convert', event: calendarEvent({}) } })
+
+    expect(await screen.findByLabelText('Concern 1')).toHaveValue('Wants winter tyres')
+    expect(screen.getByLabelText('Concern 2')).toHaveValue('Has own rims')
+
+    fireEvent.click(saveButton('Make work order'))
+
+    await waitFor(() => expect(createBooking).toHaveBeenCalled())
+    const sent = createBooking.mock.calls[0][0]
+    expect(sent.work).toBe('Wants winter tyres\nHas own rims')
+    expect(sent.description).toBeUndefined()
+  })
 })
 })
 
 
 describe('someone not on file yet', () => {
 describe('someone not on file yet', () => {

+ 40 - 0
src/__tests__/features/calendar/calendar-events-access.test.ts

@@ -93,6 +93,8 @@ beforeEach(() => {
       vehicleId: 'car-1',
       vehicleId: 'car-1',
       customer: { name: 'Kari' },
       customer: { name: 'Kari' },
       vehicle: { make: 'Volvo', model: 'V70', year: 2012, customer: null },
       vehicle: { make: 'Volvo', model: 'V70', year: 2012, customer: null },
+      description: null,
+      concerns: [{ description: 'Brake service' }],
       _count: { appointmentNotifications: 0 },
       _count: { appointmentNotifications: 0 },
     },
     },
   ] as never)
   ] as never)
@@ -216,6 +218,44 @@ describe('calendar events by role', () => {
     expect(appointment?.description).not.toContain('script')
     expect(appointment?.description).not.toContain('script')
   })
   })
 
 
+  const jobWith = async (extra: Record<string, unknown>) => {
+    const [row] = (await vi.mocked(db.serviceRecord.findMany).getMockImplementation()?.(
+      {} as never
+    )) as unknown as Record<string, unknown>[]
+    vi.mocked(db.serviceRecord.findMany).mockResolvedValue([{ ...row, ...extra }] as never)
+    signInAs('owner', [])
+    const res = await getCalendarEvents({ start: '2026-11-16', end: '2026-11-22' })
+    return res.data?.find((e) => e.type === 'service')
+  }
+
+  it('lists a job with its conditions, which are what the job is about', async () => {
+    const job = await jobWith({
+      concerns: [{ description: 'Front brakes squeal' }, { description: 'Oil service' }],
+    })
+    expect(job?.conditions).toEqual(['Front brakes squeal', 'Oil service'])
+    expect(job?.description).toBeNull()
+  })
+
+  it('does not repeat the title as the condition of a job booked with nothing more to say', async () => {
+    const job = await jobWith({ concerns: [{ description: 'Brake service' }] })
+    expect(job?.conditions).toEqual([])
+  })
+
+  it('keeps the description an older job carries, cleaned, unless it only repeats the conditions', async () => {
+    const kept = await jobWith({
+      concerns: [{ description: 'Brakes' }],
+      description: '<p>Customer waits in reception</p><script>x()</script>',
+    })
+    expect(kept?.description).toContain('Customer waits in reception')
+    expect(kept?.description).not.toContain('script')
+
+    const repeated = await jobWith({
+      concerns: [{ description: 'Brakes' }, { description: 'Oil service' }],
+      description: 'Brakes\nOil service',
+    })
+    expect(repeated?.description).toBeNull()
+  })
+
   it('refuses the calendar to a role that cannot read jobs', async () => {
   it('refuses the calendar to a role that cannot read jobs', async () => {
     signInAs('member', [read('quotes'), read('vehicles'), read('customers')])
     signInAs('member', [read('quotes'), read('vehicles'), read('customers')])
     const res = await getCalendarEvents({ start: '2026-11-16', end: '2026-11-22' })
     const res = await getCalendarEvents({ start: '2026-11-16', end: '2026-11-22' })

+ 85 - 0
src/__tests__/features/calendar/description-lines.test.ts

@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest'
+import {
+  descriptionLines,
+  linesAsDescription,
+  withoutRepeats,
+} from '@/features/calendar/Lib/appointment'
+import { bookingConcerns } from '@/features/calendar/Lib/booking.server'
+import { printedDescription } from '@/features/invoice-designer/Pdf/buildWorkOrderPrint'
+
+describe('a description as plain lines', () => {
+  it('gives a line per paragraph and list item, with the formatting gone', () => {
+    expect(
+      descriptionLines(
+        '<p>Front brakes <strong>squeal</strong> when cold</p><ul><li><p>Oil service</p></li><li><p>Check wipers</p></li></ul><p></p>'
+      )
+    ).toEqual(['Front brakes squeal when cold', 'Oil service', 'Check wipers'])
+  })
+
+  it('breaks a paragraph at its line breaks and reads what was escaped', () => {
+    expect(descriptionLines('<p>Tyres &lt; 3&nbsp;mm<br>Fish &amp; chips</p>')).toEqual([
+      'Tyres < 3 mm',
+      'Fish & chips',
+    ])
+  })
+
+  it('takes text that never was rich text as it is', () => {
+    expect(descriptionLines('Brakes\nOil service')).toEqual(['Brakes', 'Oil service'])
+  })
+
+  it('keeps comparisons and addresses in angle brackets, which are not formatting', () => {
+    expect(
+      descriptionLines('Pressure < 2 bar; voltage > 12 V\nMail <accounts@example.com> when done')
+    ).toEqual(['Pressure < 2 bar; voltage > 12 V', 'Mail <accounts@example.com> when done'])
+    expect(descriptionLines('<p>a <b>b</b> <span class="x">c</span><br/>d</p>')).toEqual([
+      'a b c',
+      'd',
+    ])
+  })
+
+  it('says nothing for a description that says nothing', () => {
+    expect(descriptionLines('<p></p>')).toEqual([])
+    expect(descriptionLines(null)).toEqual([])
+  })
+
+  it('goes back to a description a paragraph a line, escaped', () => {
+    expect(linesAsDescription(['Tyres < 3 mm', 'Oil'])).toBe('<p>Tyres &lt; 3 mm</p><p>Oil</p>')
+    expect(descriptionLines(linesAsDescription(['Tyres < 3 mm', 'Oil']))).toEqual([
+      'Tyres < 3 mm',
+      'Oil',
+    ])
+  })
+
+  it('adds only what is not already said', () => {
+    expect(withoutRepeats(['Brakes'], ['Brakes', 'Oil', 'Oil'])).toEqual(['Brakes', 'Oil'])
+  })
+})
+
+describe("a booked job's conditions", () => {
+  it('are the work lines, then what the description adds', () => {
+    expect(bookingConcerns('Brakes', '<p>Brakes</p><p>Customer waits</p>', 'Brake job')).toEqual([
+      'Brakes',
+      'Customer waits',
+    ])
+  })
+
+  it('are the title only when neither says anything', () => {
+    expect(bookingConcerns('', '<p></p>', ' Brake job ')).toEqual(['Brake job'])
+    expect(bookingConcerns(undefined, '<p>Squeals</p>', 'Brake job')).toEqual(['Squeals'])
+  })
+})
+
+describe('the description on the printed work order', () => {
+  it('prints one kept as rich text as its lines, not its tags', () => {
+    expect(printedDescription('<p>Front brakes squeal</p><ul><li><p>Oil</p></li></ul>')).toBe(
+      'Front brakes squeal\nOil'
+    )
+  })
+
+  it('leaves plain text as it was written', () => {
+    expect(printedDescription('Pressure < 2 bar\n\nSecond paragraph')).toBe(
+      'Pressure < 2 bar\n\nSecond paragraph'
+    )
+    expect(printedDescription(null)).toBeNull()
+  })
+})

+ 271 - 0
src/__tests__/features/calendar/event-peek.test.tsx

@@ -0,0 +1,271 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+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() }) }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn() }))
+vi.mock('@/features/scheduled-messages/Actions/scheduledMessageActions', () => ({
+  deleteScheduledMessage: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/reminderActions', () => ({
+  toggleReminder: vi.fn(),
+  deleteReminder: vi.fn(),
+}))
+vi.mock('@/features/calendar/Actions/deleteAppointment', () => ({ deleteAppointment: vi.fn() }))
+// The global next-intl mock has no useFormatter; the calendar's own wrapper
+// is what the components import, so give it a plain Intl formatter.
+vi.mock('@/features/calendar/Components/useDayFormatter', () => ({
+  useDayFormatter: () => ({
+    dateTime: (date: Date, options: Intl.DateTimeFormatOptions) =>
+      new Intl.DateTimeFormat('en-US', options).format(date),
+  }),
+}))
+
+import { CalendarDayCell } from '@/features/calendar/Components/CalendarDayCell'
+import { EventChip } from '@/features/calendar/Components/EventChip'
+import { type BookingEdit, EventPeekProvider } from '@/features/calendar/Components/EventPeek'
+
+beforeAll(() => {
+  // jsdom has no ResizeObserver; the day cell and Radix popovers need one.
+  class RO {
+    observe() {
+      return undefined
+    }
+    unobserve() {
+      return undefined
+    }
+    disconnect() {
+      return undefined
+    }
+  }
+  ;(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = RO
+  // jsdom lays nothing out; a day with no height folds every chip into "more".
+  Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
+    configurable: true,
+    get: () => 200,
+  })
+})
+
+const bookedJob: CalendarEvent = {
+  id: 'job-1',
+  title: 'Brake job',
+  date: '2026-09-03',
+  time: '09:00',
+  endTime: '10:00',
+  type: 'service',
+  status: 'scheduled',
+  vehicleId: 'v1',
+  vehicleLabel: '2019 Volvo V90',
+  customerName: 'Kari Nordmann',
+  invoiceNumber: '2026-1001',
+  amount: null,
+  conditions: ['Front brakes squeal when cold', 'Oil service'],
+}
+
+const startedJob: CalendarEvent = { ...bookedJob, id: 'job-2', title: 'Clutch', status: 'pending' }
+
+const appointment: CalendarEvent = {
+  id: 'appt-1',
+  title: 'Tyre quote talk',
+  date: '2026-09-03',
+  time: '11:00',
+  endTime: '11:30',
+  type: 'appointment',
+  status: 'booked',
+  vehicleId: null,
+  vehicleLabel: '',
+  customerName: 'Kari Nordmann',
+  invoiceNumber: null,
+  amount: null,
+  description: '<p>Wants winter tyres</p>',
+}
+
+const onEditBooking = vi.fn<(edit: BookingEdit) => void>()
+const onOpenDay = vi.fn()
+const onSelect = vi.fn()
+
+beforeEach(() => {
+  vi.clearAllMocks()
+})
+
+function Month({
+  events,
+  showing = 'month:2026-09-03',
+}: {
+  events: CalendarEvent[]
+  showing?: string
+}) {
+  return (
+    <EventPeekProvider currencyCode="NOK" onEditBooking={onEditBooking} showing={showing}>
+      <CalendarDayCell
+        date={new Date(2026, 8, 3)}
+        dateStr="2026-09-03"
+        events={events}
+        isCurrentMonth
+        isToday={false}
+        isSelected={false}
+        isWeekend={false}
+        actions={{
+          onNewWorkOrder: vi.fn(),
+          onBookAppointment: vi.fn(),
+          onNewReminder: vi.fn(),
+          onNewQuote: vi.fn(),
+          onScheduleMessage: vi.fn(),
+        }}
+        onSelect={onSelect}
+        onOpenDay={onOpenDay}
+      />
+    </EventPeekProvider>
+  )
+}
+
+const chip = (title: string) => screen.getByRole('button', { name: new RegExp(title) })
+
+/** A double-click as the browser sends it: two clicks, then the double-click. */
+async function doubleClick(el: HTMLElement) {
+  press(el, 1)
+  // The card listens for a press outside it from the next tick on.
+  await new Promise((resolve) => setTimeout(resolve, 20))
+  press(el, 2)
+  fireEvent.doubleClick(el, { detail: 2 })
+}
+
+/** One press of the mouse button, with everything the browser sends for it. */
+function press(el: HTMLElement, detail: number) {
+  fireEvent.pointerDown(el, { detail, button: 0 })
+  fireEvent.mouseDown(el, { detail, button: 0 })
+  fireEvent.pointerUp(el, { detail, button: 0 })
+  fireEvent.mouseUp(el, { detail, button: 0 })
+  fireEvent.click(el, { detail })
+}
+
+describe('the card a click on an event opens', () => {
+  it("shows a job's conditions where an appointment shows its description", async () => {
+    render(<Month events={[bookedJob, appointment]} />)
+
+    fireEvent.click(chip('Brake job'))
+    expect(await screen.findByText('Front brakes squeal when cold')).toBeInTheDocument()
+    expect(screen.getByText('Oil service')).toBeInTheDocument()
+
+    fireEvent.click(chip('Tyre quote talk'))
+    expect(await screen.findByText('Wants winter tyres')).toBeInTheDocument()
+  })
+
+  it('still shows the description an older job carries, after its conditions', async () => {
+    render(
+      <Month
+        events={[
+          {
+            ...bookedJob,
+            conditions: ['Brakes'],
+            description: '<p>Customer waits in reception</p>',
+          },
+        ]}
+      />
+    )
+
+    fireEvent.click(chip('Brake job'))
+
+    expect(await screen.findByText('Brakes')).toBeInTheDocument()
+    expect(screen.getByText('Customer waits in reception')).toBeInTheDocument()
+  })
+
+  it('closes when the calendar moves to another view or day', async () => {
+    const { rerender } = render(<Month events={[bookedJob]} />)
+    fireEvent.click(chip('Brake job'))
+    expect(await screen.findByText('Oil service')).toBeInTheDocument()
+
+    rerender(<Month events={[bookedJob]} showing="day:2026-09-03" />)
+
+    await waitFor(() => expect(screen.queryByText('Oil service')).not.toBeInTheDocument())
+  })
+
+  it('stays open while the calendar is redrawn on the same view and day', async () => {
+    const { rerender } = render(<Month events={[bookedJob]} />)
+    fireEvent.click(chip('Brake job'))
+    expect(await screen.findByText('Oil service')).toBeInTheDocument()
+
+    rerender(<Month events={[bookedJob]} />)
+
+    expect(screen.getByText('Oil service')).toBeInTheDocument()
+  })
+})
+
+describe('a double-click in the month', () => {
+  it('opens a booking for editing and leaves the view alone', async () => {
+    render(<Month events={[bookedJob, appointment]} />)
+
+    await doubleClick(chip('Brake job'))
+
+    expect(onEditBooking).toHaveBeenCalledTimes(1)
+    expect(onEditBooking).toHaveBeenCalledWith({ mode: 'edit', event: bookedJob })
+    expect(onOpenDay).not.toHaveBeenCalled()
+    // The card the first click opened is gone: the dialog took its place.
+    expect(screen.queryByText('Oil service')).not.toBeInTheDocument()
+
+    await doubleClick(chip('Tyre quote talk'))
+    expect(onEditBooking).toHaveBeenLastCalledWith({ mode: 'edit', event: appointment })
+    expect(onOpenDay).not.toHaveBeenCalled()
+  })
+
+  it('leaves the card open on a job that is changed on the work order, and the view alone', async () => {
+    render(<Month events={[startedJob]} />)
+
+    await doubleClick(chip('Clutch'))
+
+    expect(onEditBooking).not.toHaveBeenCalled()
+    expect(onOpenDay).not.toHaveBeenCalled()
+    expect(await screen.findByRole('link', { name: /Open work order/ })).toBeInTheDocument()
+  })
+
+  it('closes the card on a second, separate click on the same item', async () => {
+    render(<Month events={[startedJob]} />)
+
+    press(chip('Clutch'), 1)
+    expect(await screen.findByRole('link', { name: /Open work order/ })).toBeInTheDocument()
+    await new Promise((resolve) => setTimeout(resolve, 20))
+    press(chip('Clutch'), 1)
+
+    await waitFor(() =>
+      expect(screen.queryByRole('link', { name: /Open work order/ })).not.toBeInTheDocument()
+    )
+  })
+
+  it('still opens the day on the empty part of a day', () => {
+    render(<Month events={[bookedJob]} />)
+
+    fireEvent.doubleClick(screen.getByRole('gridcell'))
+
+    expect(onOpenDay).toHaveBeenCalledTimes(1)
+    expect(onEditBooking).not.toHaveBeenCalled()
+  })
+})
+
+describe('a double-click on the time grid and in a list', () => {
+  it.each([
+    'block',
+    'row',
+    'chip',
+  ] as const)('opens a booking for editing from a %s', async (variant) => {
+    render(
+      <EventPeekProvider currencyCode="NOK" onEditBooking={onEditBooking}>
+        <EventChip event={bookedJob} variant={variant} />
+      </EventPeekProvider>
+    )
+
+    await doubleClick(chip('Brake job'))
+
+    expect(onEditBooking).toHaveBeenCalledWith({ mode: 'edit', event: bookedJob })
+  })
+})

+ 19 - 1
src/features/calendar/Actions/calendarActions.ts

@@ -8,6 +8,7 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { getManifest } from '@/integrations/registry'
 import { getManifest } from '@/integrations/registry'
 import { accessFor } from '@/lib/viewer-access'
 import { accessFor } from '@/lib/viewer-access'
 import { sanitizeHtml } from '@/lib/sanitize-html'
 import { sanitizeHtml } from '@/lib/sanitize-html'
+import { descriptionLines } from '../Lib/appointment'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { addZonedDays, zonedDate, zonedDayKey, zonedParts } from '@/lib/timezone'
 import { addZonedDays, zonedDate, zonedDayKey, zonedParts } from '@/lib/timezone'
 import { loadWorkshopCalendar } from '@/features/workshop-calendar/Lib/loadCalendar.server'
 import { loadWorkshopCalendar } from '@/features/workshop-calendar/Lib/loadCalendar.server'
@@ -42,8 +43,13 @@ export type CalendarEvent = {
   customerName: string | null
   customerName: string | null
   invoiceNumber: string | null
   invoiceNumber: string | null
   amount: number | null
   amount: number | null
-  /** Only on appointments: what it is about, as cleaned rich text. */
+  /**
+   * What it is about, as cleaned rich text. An appointment's description; on
+   * a job only what an older booking still carries beside its conditions.
+   */
   description?: string | null
   description?: string | null
+  /** Only on jobs: the conditions, the one copy of what the job is about. */
+  conditions?: string[]
   /** Appointments and booked jobs: how many notifications go out before it. */
   /** Appointments and booked jobs: how many notifications go out before it. */
   notificationCount?: number
   notificationCount?: number
   /** Only on external events: whether it fills the day, where it came from. */
   /** Only on external events: whether it fills the day, where it came from. */
@@ -122,6 +128,8 @@ export async function getCalendarEvents(params: { start: string; end: string })
               totalAmount: true,
               totalAmount: true,
               cost: true,
               cost: true,
               vehicleId: true,
               vehicleId: true,
+              description: true,
+              concerns: { orderBy: { sortOrder: 'asc' }, select: { description: true } },
               _count: { select: { appointmentNotifications: true } },
               _count: { select: { appointmentNotifications: true } },
               customer: { select: { name: true } },
               customer: { select: { name: true } },
               vehicle: {
               vehicle: {
@@ -387,6 +395,14 @@ export async function getCalendarEvents(params: { start: string; end: string })
                 ? toTimeStr(s.endDateTime, timeZone)
                 ? toTimeStr(s.endDateTime, timeZone)
                 : '23:59'
                 : '23:59'
               : null
               : null
+          // A job booked with nothing to say has its title as its one
+          // condition, which the card already shows as the title.
+          const conditions = s.concerns
+            .map((c) => c.description.trim())
+            .filter((line, i, all) => line && !(all.length === 1 && line === s.title.trim()))
+          // A description from before the conditions were the one copy is
+          // still shown, unless it only repeats them.
+          const legacy = descriptionLines(s.description).some((line) => !conditions.includes(line))
           return {
           return {
             id: s.id,
             id: s.id,
             title: s.title,
             title: s.title,
@@ -400,6 +416,8 @@ export async function getCalendarEvents(params: { start: string; end: string })
             customerName: (s.customer ?? s.vehicle?.customer)?.name ?? null,
             customerName: (s.customer ?? s.vehicle?.customer)?.name ?? null,
             invoiceNumber: s.invoiceNumber,
             invoiceNumber: s.invoiceNumber,
             amount: s.totalAmount > 0 ? s.totalAmount : s.cost > 0 ? s.cost : null,
             amount: s.totalAmount > 0 ? s.totalAmount : s.cost > 0 ? s.cost : null,
+            conditions,
+            description: legacy && s.description ? sanitizeHtml(s.description) : null,
             notificationCount: s._count.appointmentNotifications,
             notificationCount: s._count.appointmentNotifications,
           }
           }
         }),
         }),

+ 8 - 5
src/features/calendar/Actions/createBooking.ts

@@ -147,12 +147,15 @@ export async function createBookingOnce(input: SaveBookingInput) {
           data: {
           data: {
             status: 'scheduled',
             status: 'scheduled',
             bookingToken: token,
             bookingToken: token,
-            description,
+            // What was typed as a description is the job's conditions: one
+            // copy, on the work order, the print and the technician's phone.
             concerns: {
             concerns: {
-              create: bookingConcerns(data.work, data.title).map((text, sortOrder) => ({
-                description: text,
-                sortOrder,
-              })),
+              create: bookingConcerns(data.work, description, data.title).map(
+                (text, sortOrder) => ({
+                  description: text,
+                  sortOrder,
+                })
+              ),
             },
             },
           },
           },
           select: { id: true, vehicleId: true, invoiceNumber: true },
           select: { id: true, vehicleId: true, invoiceNumber: true },

+ 10 - 2
src/features/calendar/Actions/getBooking.ts

@@ -7,6 +7,7 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { zonedDateInput, zonedTimeInput } from '@/lib/timezone'
 import { zonedDateInput, zonedTimeInput } from '@/lib/timezone'
 import { serviceVideoLink } from '@/features/integrations/Lib/video-call'
 import { serviceVideoLink } from '@/features/integrations/Lib/video-call'
+import { descriptionLines, withoutRepeats } from '../Lib/appointment'
 import { BOOKING_KINDS, type BookingKind, type NotificationChannel } from '../Schema/bookingSchema'
 import { BOOKING_KINDS, type BookingKind, type NotificationChannel } from '../Schema/bookingSchema'
 
 
 const vehicleSelect = {
 const vehicleSelect = {
@@ -156,12 +157,19 @@ export async function getBooking(input: { kind: BookingKind; id: string }) {
         kind,
         kind,
         id: job.id,
         id: job.id,
         title: job.title,
         title: job.title,
-        description: job.description ?? '',
+        // A job keeps no description beside its conditions.
+        description: '',
         // A job on a car finds its customer through the car.
         // A job on a car finds its customer through the car.
         customer: job.customer ?? job.vehicle?.customer ?? null,
         customer: job.customer ?? job.vehicle?.customer ?? null,
         vehicle: job.vehicle,
         vehicle: job.vehicle,
         ...times(job.startDateTime, end),
         ...times(job.startDateTime, end),
-        work: job.concerns.map((c) => c.description).join('\n'),
+        // A description from before the conditions were the one copy is
+        // offered as conditions, and becomes them when this is saved. Not
+        // once work is recorded: the lines cannot change here then.
+        work: withoutRepeats(
+          job.concerns.map((c) => c.description),
+          recorded ? [] : descriptionLines(job.description)
+        ).join('\n'),
         notifications: job.appointmentNotifications as BookingForEdit['notifications'],
         notifications: job.appointmentNotifications as BookingForEdit['notifications'],
         locked: { who: Boolean(job.vehicle), work: recorded },
         locked: { who: Boolean(job.vehicle), work: recorded },
         meeting: await serviceVideoLink(organizationId, job.id),
         meeting: await serviceVideoLink(organizationId, job.id),

+ 24 - 18
src/features/calendar/Actions/updateBooking.ts

@@ -33,9 +33,11 @@ import {
  * - The car can be added to a booking made for a customer whose car was not
  * - The car can be added to a booking made for a customer whose car was not
  *   on file. A different car or customer is changed on the work order, where
  *   on file. A different car or customer is changed on the work order, where
  *   the prices and tax that follow the customer are worked out again.
  *   the prices and tax that follow the customer are worked out again.
- * - The work lines are the job's concerns. They are replaced only while
- *   nobody has recorded anything on them; after that they are the job's
- *   history and are changed on the work order.
+ * - The work lines are the job's concerns, and the only copy of what the job
+ *   is about. They are replaced only while nobody has recorded anything on
+ *   them; after that they are the job's history and are changed on the work
+ *   order. A description an older job still carries becomes concerns too the
+ *   first time the booking is saved here.
  */
  */
 export async function updateBooking(input: SaveBookingInput) {
 export async function updateBooking(input: SaveBookingInput) {
   return withAuth(
   return withAuth(
@@ -134,21 +136,25 @@ export async function updateBooking(input: SaveBookingInput) {
         throw new Error('Change the customer on the work order')
         throw new Error('Change the customer on the work order')
       }
       }
 
 
-      const lines = bookingConcerns(data.work, data.title)
+      const recorded = job.concerns.some(
+        (c) =>
+          c.cause ||
+          c.correction ||
+          c.confirmation ||
+          c.confirmedAt ||
+          c._count.findings > 0 ||
+          c._count.attachments > 0
+      )
+      // The conditions are the one copy of what the job is about. The dialog
+      // offers a description an older job still carries as work lines
+      // (`getBooking`), so what is saved here is all of it and the
+      // description goes. A tab opened before this still sends one, and it is
+      // folded in the same way. Once work is recorded the conditions are the
+      // job's history: nothing is folded in and the description stays.
+      const lines = bookingConcerns(data.work, recorded ? null : description, data.title)
       const workChanged = lines.join('\n') !== job.concerns.map((c) => c.description).join('\n')
       const workChanged = lines.join('\n') !== job.concerns.map((c) => c.description).join('\n')
-      if (workChanged) {
-        const recorded = job.concerns.some(
-          (c) =>
-            c.cause ||
-            c.correction ||
-            c.confirmation ||
-            c.confirmedAt ||
-            c._count.findings > 0 ||
-            c._count.attachments > 0
-        )
-        if (recorded) {
-          throw new Error('Work is recorded on these concerns. Change them on the work order.')
-        }
+      if (workChanged && recorded) {
+        throw new Error('Work is recorded on these concerns. Change them on the work order.')
       }
       }
 
 
       const moved =
       const moved =
@@ -172,7 +178,7 @@ export async function updateBooking(input: SaveBookingInput) {
           where: { id: job.id },
           where: { id: job.id },
           data: {
           data: {
             title: data.title,
             title: data.title,
-            description,
+            ...(recorded ? {} : { description: null }),
             startDateTime: start,
             startDateTime: start,
             endDateTime: end,
             endDateTime: end,
             ...(who ?? {}),
             ...(who ?? {}),

+ 51 - 27
src/features/calendar/Components/BookingDialog.tsx

@@ -72,6 +72,12 @@ import {
 } from '../Schema/bookingSchema'
 } from '../Schema/bookingSchema'
 import { MAX_APPOINTMENT_MINUTES } from '../Schema/appointmentSchema'
 import { MAX_APPOINTMENT_MINUTES } from '../Schema/appointmentSchema'
 import { minutesToTime, timeToMinutes } from '../Lib/calendar-range'
 import { minutesToTime, timeToMinutes } from '../Lib/calendar-range'
+import {
+  appointmentConcerns,
+  descriptionLines,
+  linesAsDescription,
+  withoutRepeats,
+} from '../Lib/appointment'
 import type { BookingEdit } from './EventPeek'
 import type { BookingEdit } from './EventPeek'
 import { ConcernListEditor } from './ConcernListEditor'
 import { ConcernListEditor } from './ConcernListEditor'
 
 
@@ -308,14 +314,15 @@ function BookingForm({
         const b = booking.data
         const b = booking.data
         setLoaded(b)
         setLoaded(b)
         setTitleText(b.title)
         setTitleText(b.title)
-        setDescription(b.description)
+        // An appointment made a work order: what it says becomes the job's
+        // conditions, which are the only copy a job keeps.
+        setDescription(converting ? '' : b.description)
         setCustomerId(b.customer?.id ?? '')
         setCustomerId(b.customer?.id ?? '')
         setCustomerInitial(b.customer)
         setCustomerInitial(b.customer)
         setVehicleId(b.vehicle?.id ?? '')
         setVehicleId(b.vehicle?.id ?? '')
         setVehicleInitial(b.vehicle)
         setVehicleInitial(b.vehicle)
         setVehicleCustomerId(b.vehicle?.customerId ?? null)
         setVehicleCustomerId(b.vehicle?.customerId ?? null)
-        // An appointment made a work order: its words become the work needed.
-        setWork(converting ? '' : b.work)
+        setWork(converting ? descriptionLines(b.description).join('\n') : b.work)
         setStart({ date: b.startDate, time: b.startTime })
         setStart({ date: b.startDate, time: b.startTime })
         setEnd({ date: b.endDate, time: b.endTime })
         setEnd({ date: b.endDate, time: b.endTime })
         setRows(
         setRows(
@@ -399,6 +406,19 @@ function BookingForm({
             : null
             : null
 
 
   const chooseKind = (next: BookingKind) => {
   const chooseKind = (next: BookingKind) => {
+    // What it is about is one text, kept the way the kind keeps it: an
+    // appointment's description, a job's conditions. It follows the kind, so
+    // nothing typed is left behind in a field that is no longer shown.
+    if (next !== kind) {
+      if (next === 'workOrder') {
+        setWork(withoutRepeats(appointmentConcerns(work), descriptionLines(description)).join('\n'))
+        setDescription('')
+      } else {
+        const lines = appointmentConcerns(work)
+        if (lines.length > 0) setDescription(description + linesAsDescription(lines))
+        setWork('')
+      }
+    }
     setKind(next)
     setKind(next)
     if (!edit) {
     if (!edit) {
       try {
       try {
@@ -432,7 +452,7 @@ function BookingForm({
         fromAppointmentId: converting?.id,
         fromAppointmentId: converting?.id,
         token: editing ? undefined : bookingToken,
         token: editing ? undefined : bookingToken,
         title: titleText.trim(),
         title: titleText.trim(),
-        description,
+        description: isWorkOrder ? undefined : description,
         customerId: customerId || undefined,
         customerId: customerId || undefined,
         vehicleId: vehicleId || undefined,
         vehicleId: vehicleId || undefined,
         work: isWorkOrder ? work : undefined,
         work: isWorkOrder ? work : undefined,
@@ -738,14 +758,33 @@ function BookingForm({
                   </p>
                   </p>
                 )}
                 )}
               </Row>
               </Row>
-              <Row icon={AlignLeft} label={t('description')}>
-                <RichTextEditor
-                  content={description}
-                  onChange={setDescription}
-                  placeholder={t('descriptionPlaceholder')}
-                  contentClassName="min-h-[8rem] max-h-[30vh]"
-                />
-              </Row>
+              {/* What it is about, in the same place for both kinds: a
+                  description on an appointment, and on a work order the
+                  conditions, which are the only copy the job keeps. */}
+              {isWorkOrder ? (
+                <Row icon={ListChecks} label={t('work')}>
+                  <ConcernListEditor
+                    value={work}
+                    onChange={setWork}
+                    disabled={lockedWork}
+                    placeholder={isMarine ? t('addConcernMarine') : t('addConcern')}
+                  />
+                  {(lockedWork || work.trim() === '') && (
+                    <p className="px-2 text-xs text-muted-foreground">
+                      {lockedWork ? t('workLocked') : t('workEmptyHint')}
+                    </p>
+                  )}
+                </Row>
+              ) : (
+                <Row icon={AlignLeft} label={t('description')}>
+                  <RichTextEditor
+                    content={description}
+                    onChange={setDescription}
+                    placeholder={t('descriptionPlaceholder')}
+                    contentClassName="min-h-[8rem] max-h-[30vh]"
+                  />
+                </Row>
+              )}
             </div>
             </div>
 
 
             <div className="min-w-0 space-y-4">
             <div className="min-w-0 space-y-4">
@@ -781,21 +820,6 @@ function BookingForm({
                   )}
                   )}
                 </div>
                 </div>
               </Row>
               </Row>
-              {isWorkOrder && (
-                <Row icon={ListChecks} label={t('work')}>
-                  <ConcernListEditor
-                    value={work}
-                    onChange={setWork}
-                    disabled={lockedWork}
-                    placeholder={isMarine ? t('addConcernMarine') : t('addConcern')}
-                  />
-                  {(lockedWork || work.trim() === '') && (
-                    <p className="px-2 text-xs text-muted-foreground">
-                      {lockedWork ? t('workLocked') : t('workEmptyHint')}
-                    </p>
-                  )}
-                </Row>
-              )}
               {isWorkOrder && video.length > 0 && (
               {isWorkOrder && video.length > 0 && (
                 <Row icon={Video} label={t('video')}>
                 <Row icon={Video} label={t('video')}>
                   {loaded?.meeting ? (
                   {loaded?.meeting ? (

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

@@ -530,6 +530,7 @@ export default function CalendarClient({
       currencyCode={currencyCode}
       currencyCode={currencyCode}
       onRefresh={refresh}
       onRefresh={refresh}
       onEditAbsence={timeOff ? editAbsence : undefined}
       onEditAbsence={timeOff ? editAbsence : undefined}
+      showing={`${view}:${toLocalDateStr(date)}`}
       onEditBooking={(edit) => {
       onEditBooking={(edit) => {
         setBookingEdit(edit)
         setBookingEdit(edit)
         setShowAppointmentDialog(true)
         setShowAppointmentDialog(true)

+ 4 - 0
src/features/calendar/Components/CalendarDayCell.tsx

@@ -145,6 +145,10 @@ export function CalendarDayCell({
                 align="start"
                 align="start"
                 className="w-72 p-2"
                 className="w-72 p-2"
                 onOpenAutoFocus={(e) => e.preventDefault()}
                 onOpenAutoFocus={(e) => e.preventDefault()}
+                // The list is drawn elsewhere on the page but still inside
+                // the day as far as React goes: a double-click in it is not
+                // one on the day.
+                onDoubleClick={(e) => e.stopPropagation()}
               >
               >
                 <div className="mb-1.5 flex items-baseline justify-between px-1">
                 <div className="mb-1.5 flex items-baseline justify-between px-1">
                   <span className="text-sm font-semibold">
                   <span className="text-sm font-semibold">

+ 18 - 3
src/features/calendar/Components/EventChip.tsx

@@ -9,7 +9,7 @@ import { cn } from '@/lib/utils'
 import { timeToMinutes } from '../Lib/calendar-range'
 import { timeToMinutes } from '../Lib/calendar-range'
 import { eventPalette, isEventDone, openEndedSide } from './calendar-utils'
 import { eventPalette, isEventDone, openEndedSide } from './calendar-utils'
 import { EventContextMenu } from './EventContextMenu'
 import { EventContextMenu } from './EventContextMenu'
-import { useEventPeek } from './EventPeek'
+import { isEditableBooking, useEventPeek } from './EventPeek'
 import type { CalendarEvent } from '../Actions/calendarActions'
 import type { CalendarEvent } from '../Actions/calendarActions'
 
 
 /**
 /**
@@ -21,7 +21,8 @@ import type { CalendarEvent } from '../Actions/calendarActions'
  * - `row`   a list row for the schedule view and the day sheet
  * - `row`   a list row for the schedule view and the day sheet
  *
  *
  * Every shape opens the same peek card on click and the same menu on
  * Every shape opens the same peek card on click and the same menu on
- * right-click, so nothing here links out.
+ * right-click, so nothing here links out. A double-click opens a booking
+ * that can still be changed in the booking dialog.
  */
  */
 export function EventChip({
 export function EventChip({
   event,
   event,
@@ -38,7 +39,7 @@ export function EventChip({
   compact?: boolean
   compact?: boolean
 }) {
 }) {
   const { timeFormat } = useDateSettings()
   const { timeFormat } = useDateSettings()
-  const { openPeek } = useEventPeek()
+  const { openPeek, editBooking } = useEventPeek()
   const palette = eventPalette(event)
   const palette = eventPalette(event)
   const done = isEventDone(event)
   const done = isEventDone(event)
   const start = event.time ? formatClock(timeToMinutes(event.time), timeFormat) : null
   const start = event.time ? formatClock(timeToMinutes(event.time), timeFormat) : null
@@ -58,8 +59,18 @@ export function EventChip({
 
 
   const onClick = (e: MouseEvent<HTMLButtonElement>) => {
   const onClick = (e: MouseEvent<HTMLButtonElement>) => {
     e.stopPropagation()
     e.stopPropagation()
+    // The second click of a double-click: the first opened the card, and
+    // this one would close it again.
+    if (e.detail > 1) return
     openPeek(event, e.currentTarget)
     openPeek(event, e.currentTarget)
   }
   }
+  // A double-click changes the booking, as in a desktop calendar. It stops
+  // here either way: the day underneath opens day view on a double-click,
+  // and that is for the empty part of a day.
+  const onDoubleClick = (e: MouseEvent<HTMLButtonElement>) => {
+    e.stopPropagation()
+    if (editBooking && isEditableBooking(event)) editBooking({ mode: 'edit', event })
+  }
   // The day underneath has a menu of its own; a right-click on the event
   // The day underneath has a menu of its own; a right-click on the event
   // must open the event's, not both.
   // must open the event's, not both.
   const onContextMenu = (e: MouseEvent<HTMLButtonElement>) => e.stopPropagation()
   const onContextMenu = (e: MouseEvent<HTMLButtonElement>) => e.stopPropagation()
@@ -72,6 +83,7 @@ export function EventChip({
       <button
       <button
         type="button"
         type="button"
         onClick={onClick}
         onClick={onClick}
+        onDoubleClick={onDoubleClick}
         onContextMenu={onContextMenu}
         onContextMenu={onContextMenu}
         title={label}
         title={label}
         style={style}
         style={style}
@@ -95,6 +107,7 @@ export function EventChip({
       <button
       <button
         type="button"
         type="button"
         onClick={onClick}
         onClick={onClick}
+        onDoubleClick={onDoubleClick}
         onContextMenu={onContextMenu}
         onContextMenu={onContextMenu}
         title={label}
         title={label}
         style={style}
         style={style}
@@ -117,6 +130,7 @@ export function EventChip({
       <button
       <button
         type="button"
         type="button"
         onClick={onClick}
         onClick={onClick}
+        onDoubleClick={onDoubleClick}
         onContextMenu={onContextMenu}
         onContextMenu={onContextMenu}
         title={range ? `${range} ${event.title}` : event.title}
         title={range ? `${range} ${event.title}` : event.title}
         style={style}
         style={style}
@@ -153,6 +167,7 @@ export function EventChip({
       <button
       <button
         type="button"
         type="button"
         onClick={onClick}
         onClick={onClick}
+        onDoubleClick={onDoubleClick}
         onContextMenu={onContextMenu}
         onContextMenu={onContextMenu}
         style={style}
         style={style}
         className={cn(
         className={cn(

+ 44 - 5
src/features/calendar/Components/EventPeek.tsx

@@ -98,15 +98,27 @@ export function EventPeekProvider({
   onRefresh,
   onRefresh,
   onEditAbsence,
   onEditAbsence,
   onEditBooking,
   onEditBooking,
+  showing,
   children,
   children,
 }: {
 }: {
   currencyCode: string
   currencyCode: string
   onRefresh?: () => void
   onRefresh?: () => void
   onEditAbsence?: PeekActions['onEditAbsence']
   onEditAbsence?: PeekActions['onEditAbsence']
   onEditBooking?: PeekActions['onEditBooking']
   onEditBooking?: PeekActions['onEditBooking']
+  /**
+   * What the calendar is showing: the view and the day. The card closes when
+   * it changes, because the chip it hangs off is no longer on the screen and
+   * a card with nothing to hang off lands in the corner.
+   */
+  showing?: string
   children: ReactNode
   children: ReactNode
 }) {
 }) {
   const [peek, setPeek] = useState<PeekState | null>(null)
   const [peek, setPeek] = useState<PeekState | null>(null)
+  const [shown, setShown] = useState(showing)
+  if (shown !== showing) {
+    setShown(showing)
+    if (peek) setPeek(null)
+  }
   const [external, setExternal] = useState<CalendarEvent | null>(null)
   const [external, setExternal] = useState<CalendarEvent | null>(null)
   // Radix measures the anchor through a ref, so the clicked element is handed
   // Radix measures the anchor through a ref, so the clicked element is handed
   // over as one; a new object each time so the popper re-measures.
   // over as one; a new object each time so the popper re-measures.
@@ -157,6 +169,14 @@ export function EventPeekProvider({
           collisionPadding={12}
           collisionPadding={12}
           className="w-[22rem] max-w-[calc(100vw-1.5rem)] p-0 shadow-xl"
           className="w-[22rem] max-w-[calc(100vw-1.5rem)] p-0 shadow-xl"
           onOpenAutoFocus={(e) => e.preventDefault()}
           onOpenAutoFocus={(e) => e.preventDefault()}
+          // The chip the card hangs off is not its trigger as far as the
+          // popover knows, so a press on it counts as one outside and would
+          // close the card before the chip's own click is heard. The chip
+          // decides: a click closes the card, a double-click leaves it or
+          // opens the booking.
+          onInteractOutside={(e) => {
+            if (peek?.anchor.contains(e.target as Node)) e.preventDefault()
+          }}
         >
         >
           {peek && (
           {peek && (
             <PeekCard
             <PeekCard
@@ -274,6 +294,7 @@ function PeekCard({
         : formatClock(timeToMinutes(event.time), timeFormat)
         : formatClock(timeToMinutes(event.time), timeFormat)
       : t('events.external.allDay')
       : t('events.external.allDay')
   const done = isEventDone(event)
   const done = isEventDone(event)
+  const conditions = event.conditions ?? []
 
 
   return (
   return (
     <div className="overflow-hidden rounded-md">
     <div className="overflow-hidden rounded-md">
@@ -361,11 +382,29 @@ function PeekCard({
           )}
           )}
         </dl>
         </dl>
 
 
-        {event.description && (
-          <div
-            className="notes-content mt-3 max-h-40 overflow-y-auto border-t pt-3 text-sm"
-            dangerouslySetInnerHTML={{ __html: sanitizeHtml(event.description) }}
-          />
+        {/* What it is about, under the divider: an appointment's description,
+            a job's conditions. A job from before the conditions were the one
+            copy can still carry a description, which is shown after them. */}
+        {(conditions.length > 0 || event.description) && (
+          <div className="mt-3 max-h-40 space-y-2 overflow-y-auto border-t pt-3 text-sm">
+            {conditions.length === 1 && <p className="break-words">{conditions[0]}</p>}
+            {conditions.length > 1 && (
+              <ul aria-label={t('appointment.work')} className="list-disc space-y-0.5 pl-5">
+                {conditions.map((line, i) => (
+                  // Plain lines with no id; the order is what they are.
+                  <li key={i} className="break-words">
+                    {line}
+                  </li>
+                ))}
+              </ul>
+            )}
+            {event.description && (
+              <div
+                className="notes-content"
+                dangerouslySetInnerHTML={{ __html: sanitizeHtml(event.description) }}
+              />
+            )}
+          </div>
         )}
         )}
 
 
         <div className="mt-4 flex flex-wrap items-center justify-end gap-2">
         <div className="mt-4 flex flex-wrap items-center justify-end gap-2">

+ 49 - 0
src/features/calendar/Lib/appointment.ts

@@ -21,3 +21,52 @@ export function appointmentTitle(work: string): string {
   const first = appointmentConcerns(work)[0] ?? work.trim()
   const first = appointmentConcerns(work)[0] ?? work.trim()
   return first.length > TITLE_LENGTH ? `${first.slice(0, TITLE_LENGTH - 3)}...` : first
   return first.length > TITLE_LENGTH ? `${first.slice(0, TITLE_LENGTH - 3)}...` : first
 }
 }
+
+const ENTITIES: Record<string, string> = {
+  nbsp: ' ',
+  amp: '&',
+  lt: '<',
+  gt: '>',
+  quot: '"',
+  apos: "'",
+  '#39': "'",
+}
+
+/**
+ * A description as plain lines: one per paragraph, list item or line break,
+ * with the formatting gone. This is how what was typed as a description
+ * becomes a job's conditions, which are plain text. Text that was never rich
+ * text comes back as its own lines.
+ */
+export function descriptionLines(html: string | null | undefined): string[] {
+  if (!html) return []
+  return appointmentConcerns(
+    html
+      .replace(/<br\s*\/?>|<\/(p|li|div|h[1-6]|blockquote|pre|tr)>/gi, '\n')
+      // Only what is written as a tag: "pressure < 2 bar, voltage > 12 V" and
+      // "<post@example.com>" are the customer's words and stay.
+      .replace(/<\/?[a-z][a-z0-9]*(\s[^<>]*)?\/?>/gi, '')
+      .replace(/&(nbsp|amp|lt|gt|quot|apos|#39);/g, (_, name: string) => ENTITIES[name])
+  )
+}
+
+/** Plain lines as the description an appointment keeps: a paragraph each. */
+export function linesAsDescription(lines: string[]): string {
+  return lines
+    .map(
+      (line) => `<p>${line.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</p>`
+    )
+    .join('')
+}
+
+/** `more` after `lines`, leaving out what is already said word for word. */
+export function withoutRepeats(lines: string[], more: string[]): string[] {
+  const seen = new Set(lines)
+  const all = [...lines]
+  for (const line of more) {
+    if (seen.has(line)) continue
+    seen.add(line)
+    all.push(line)
+  }
+  return all
+}

+ 12 - 4
src/features/calendar/Lib/booking.server.ts

@@ -8,7 +8,7 @@ import {
   freeResources,
   freeResources,
 } from '@/features/inspection-reminders/Lib/booking'
 } from '@/features/inspection-reminders/Lib/booking'
 import type { BookingNotification } from '../Schema/bookingSchema'
 import type { BookingNotification } from '../Schema/bookingSchema'
-import { appointmentConcerns } from './appointment'
+import { appointmentConcerns, descriptionLines, withoutRepeats } from './appointment'
 
 
 /*
 /*
  * The parts of booking from the calendar that more than one action needs. A
  * The parts of booking from the calendar that more than one action needs. A
@@ -110,9 +110,17 @@ export function cleanDescription(html: string | undefined): string | null {
   return text ? clean : null
   return text ? clean : null
 }
 }
 
 
-/** A booked job's concerns: the work lines, or the title when none were given. */
-export function bookingConcerns(work: string | undefined, title: string): string[] {
-  const lines = appointmentConcerns(work ?? '')
+/**
+ * A booked job's conditions: the work lines, then what the description says
+ * that they do not, as plain lines. The title only when neither says anything.
+ * A job keeps no description of its own, so the conditions are the one copy.
+ */
+export function bookingConcerns(
+  work: string | undefined,
+  description: string | null | undefined,
+  title: string
+): string[] {
+  const lines = withoutRepeats(appointmentConcerns(work ?? ''), descriptionLines(description))
   return lines.length > 0 ? lines : [title.trim()]
   return lines.length > 0 ? lines : [title.trim()]
 }
 }
 
 

+ 6 - 2
src/features/calendar/Schema/bookingSchema.ts

@@ -99,8 +99,12 @@ export const saveBookingSchema = z
     description: z.string().max(20_000).optional(),
     description: z.string().max(20_000).optional(),
     customerId: z.string().min(1).optional(),
     customerId: z.string().min(1).optional(),
     vehicleId: z.string().min(1).optional(),
     vehicleId: z.string().min(1).optional(),
-    /** Work order only: what needs doing, one concern per line. */
-    work: z.string().max(4000).optional(),
+    /**
+     * Work order only: what needs doing, one concern per line. Room for the
+     * lines a job had and a description of full length folded into them, so
+     * a booking that could be saved before can still be.
+     */
+    work: z.string().max(24_000).optional(),
     /** YYYY-MM-DD and HH:MM on the workshop's clock, and days that exist. */
     /** YYYY-MM-DD and HH:MM on the workshop's clock, and days that exist. */
     startDate: z.string().refine(isDateKey, 'Pick a valid date'),
     startDate: z.string().refine(isDateKey, 'Pick a valid date'),
     startTime: z.string().refine(isTime, 'Pick a valid time'),
     startTime: z.string().refine(isTime, 'Pick a valid time'),

+ 17 - 1
src/features/invoice-designer/Pdf/buildWorkOrderPrint.ts

@@ -10,6 +10,7 @@ import { documentLaborLines, isShopFeeLine } from '@/features/settings/Lib/shopF
 import { documentNumbers, serviceTypeName } from '@/lib/document-numbers'
 import { documentNumbers, serviceTypeName } from '@/lib/document-numbers'
 import { calculateTotals, discountAmountFor } from '@/lib/tax'
 import { calculateTotals, discountAmountFor } from '@/lib/tax'
 import { parseTaxComponents } from '@/lib/tax-components'
 import { parseTaxComponents } from '@/lib/tax-components'
+import { descriptionLines } from '@/features/calendar/Lib/appointment'
 import { taxLines } from './taxLines'
 import { taxLines } from './taxLines'
 import { printFigures } from './printFigures'
 import { printFigures } from './printFigures'
 import {
 import {
@@ -125,6 +126,21 @@ export function plainTextHtml(text: string | null | undefined): string | undefin
     .join('')
     .join('')
 }
 }
 
 
+/**
+ * A job's description as the print takes it: plain text. One booked from the
+ * calendar before the conditions took its place was kept as rich text, and
+ * would print with its tags showing; it prints as its lines instead.
+ */
+export function printedDescription(text: string | null | undefined): string | null | undefined {
+  if (
+    !text ||
+    !/<\/?(p|br|ul|ol|li|h[1-6]|div|blockquote|strong|em|u|s|a|span)\b[^>]*>/i.test(text)
+  ) {
+    return text
+  }
+  return descriptionLines(text).join('\n')
+}
+
 /**
 /**
  * The layout the print follows: the saved work order design filled out with
  * The layout the print follows: the saved work order design filled out with
  * the work order's defaults, and any custom field no section claims put in
  * the work order's defaults, and any custom field no section claims put in
@@ -477,7 +493,7 @@ export function buildWorkOrderPrintSpec(input: WorkOrderPrintInput): DocumentSpe
         description: concern.description,
         description: concern.description,
         detail: concern.correction?.trim() || undefined,
         detail: concern.correction?.trim() || undefined,
       })),
       })),
-      description: { html: plainTextHtml(data.description) },
+      description: { html: plainTextHtml(printedDescription(data.description)) },
       checklist,
       checklist,
       qr: job.qrDataUri
       qr: job.qrDataUri
         ? { dataUri: job.qrDataUri, label: L('scanToOpen', 'Scan to open this work order') }
         ? { dataUri: job.qrDataUri, label: L('scanToOpen', 'Scan to open this work order') }