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

Fix portal layout breaks, request text and chat event times (#607)

* Fix portal layout breaks, request text and event times found while recording

Headings and labels no longer break inside a word, the Garage board no longer
runs under the chat, a request's topic shows on its own line, an invoice event
in the chat shows the day it belongs to, and chat times are printed once on
the server so the page hydrates the same in every language.

* Keep chat invoice events and request topics honest, and steady the vault test

The chat's invoice events are filtered and stamped by the same date the
invoice page shows. A request's first paragraph is a topic only when it is one
of the booking form's own choices. The vault test tampers with a character
that always changes the sealed data.
Bernt Christian Egeland 7 часов назад
Родитель
Сommit
a0ee675f08
30 измененных файлов с 840 добавлено и 90 удалено
  1. 5 1
      src/__tests__/features/integrations/vault.test.ts
  2. 50 1
      src/__tests__/features/portal/chat-panel.test.tsx
  3. 63 4
      src/__tests__/features/portal/portal-chat-events.test.ts
  4. 132 0
      src/__tests__/features/portal/portal-walk-defects.test.tsx
  5. 84 0
      src/__tests__/features/portal/request-text.test.ts
  6. 55 0
      src/__tests__/features/quotes/record-quote-response.test.ts
  7. 23 3
      src/app/(authenticated)/(dashboard)/dashboard-client.tsx
  8. 6 1
      src/app/(authenticated)/(dashboard)/page.tsx
  9. 18 2
      src/app/(authenticated)/customers/[id]/customer-detail-client.tsx
  10. 9 1
      src/app/(authenticated)/customers/[id]/page.tsx
  11. 17 5
      src/app/(public)/portal/[orgId]/request-service/page.tsx
  12. 2 4
      src/features/customers/Actions/customerActions.ts
  13. 35 28
      src/features/portal/Components/Chat/PortalChatPanel.tsx
  14. 3 3
      src/features/portal/Components/Chat/PortalChatParts.tsx
  15. 12 1
      src/features/portal/Components/Chat/PortalChatSlot.tsx
  16. 78 0
      src/features/portal/Components/Chat/chatThread.ts
  17. 5 1
      src/features/portal/Components/Detail/PortalInspectionResults.tsx
  18. 3 1
      src/features/portal/Components/Detail/PortalPageParts.tsx
  19. 33 0
      src/features/portal/Components/Home/PortalRequestText.tsx
  20. 3 2
      src/features/portal/Components/Themes/Colour/Home.tsx
  21. 24 17
      src/features/portal/Components/Themes/Colour/parts.tsx
  22. 2 1
      src/features/portal/Components/Themes/Daylight/Home.tsx
  23. 10 4
      src/features/portal/Components/Themes/Garage/Home.tsx
  24. 3 3
      src/features/portal/Components/Themes/Garage/SignIn.tsx
  25. 7 3
      src/features/portal/Components/Themes/Print/Home.tsx
  26. 58 3
      src/features/portal/Lib/chat.server.ts
  27. 8 0
      src/features/portal/Lib/chatTypes.ts
  28. 50 0
      src/features/portal/Lib/requestText.ts
  29. 37 0
      src/features/portal/Lib/requestTopics.ts
  30. 5 1
      src/features/portal/portal-themes.css

+ 5 - 1
src/__tests__/features/integrations/vault.test.ts

@@ -42,7 +42,11 @@ describe('integration vault', () => {
 
   it('refuses tampered data and a different key', () => {
     const sealed = sealCredentials({ token: 'x' })
-    const tampered = `${sealed.slice(0, -2)}AA`
+    // One character in the middle, always to a different one: the tail can be
+    // padding, or already read "AA", and then nothing was tampered with.
+    const middle = Math.floor(sealed.length / 2)
+    const swapped = sealed[middle] === 'A' ? 'B' : 'A'
+    const tampered = `${sealed.slice(0, middle)}${swapped}${sealed.slice(middle + 1)}`
     expect(() => openCredentials(tampered)).toThrow()
     resetVaultKeyForTests()
     process.env.INTEGRATIONS_ENCRYPTION_KEY = 'b'.repeat(64)

+ 50 - 1
src/__tests__/features/portal/chat-panel.test.tsx

@@ -73,6 +73,7 @@ vi.mock('@/features/portal/Actions/getPortalUnread', () => ({
 }))
 
 import { PortalChatPanel } from '@/features/portal/Components/Chat/PortalChatPanel'
+import type { PortalChatStamps } from '@/features/portal/Components/Chat/chatThread'
 
 const message = (over: Partial<PortalChatMessage>): PortalChatMessage => ({
   id: 'm1',
@@ -90,6 +91,7 @@ const event = (over: Partial<PortalChatEvent>): PortalChatEvent => ({
   id: 'quote:q1',
   kind: 'quote',
   at: '2026-11-14T08:30:00Z',
+  dayOnly: false,
   vehicle: 'Volvo V60',
   title: 'Front brake pads and discs',
   amount: 'kr 6,480.00',
@@ -101,7 +103,12 @@ const event = (over: Partial<PortalChatEvent>): PortalChatEvent => ({
 
 function panel(
   messages: PortalChatMessage[] = [],
-  options: { callHref?: string | null; enabled?: boolean; events?: PortalChatEvent[] } = {}
+  options: {
+    callHref?: string | null
+    enabled?: boolean
+    events?: PortalChatEvent[]
+    stamps?: PortalChatStamps
+  } = {}
 ) {
   server.messages = messages
   server.events = options.events ?? []
@@ -117,6 +124,7 @@ function panel(
         initialMessages={messages}
         initialEvents={options.events}
         clock={{ timeZone: 'Europe/Oslo', timeFormat: '24h' }}
+        stamps={options.stamps}
       />
     </QueryClientProvider>
   )
@@ -522,3 +530,44 @@ describe('writing', () => {
     ).toBeInTheDocument()
   })
 })
+
+describe('when things happened', () => {
+  it('prints the day and no clock time for an invoice that only has a date', () => {
+    panel([message({})], {
+      events: [
+        event({
+          id: 'invoice:i1',
+          kind: 'invoice',
+          // The invoice's own date: midnight on 11 November in Oslo, not a moment anyone saw.
+          at: '2026-11-10T23:00:00Z',
+          dayOnly: true,
+          title: 'INV-2041',
+          amount: 'kr 2,732.63',
+          href: '/portal/fjordside/invoices/i1',
+          answerable: false,
+        }),
+      ],
+    })
+    const line = thread().getByRole('link', { name: /Invoice INV-2041/ })
+    expect(within(line).getByText('Nov 11')).toBeInTheDocument()
+    expect(line).not.toHaveTextContent('00:00')
+  })
+
+  it('shows the times the server printed as they are, so the page reads the same in the browser', () => {
+    // The server's copy of a language can print a time differently from the
+    // browser's ("9:05 a. m." with another kind of space). What arrived with
+    // the page is not printed again.
+    panel([message({})], {
+      stamps: {
+        '2026-11-14T08:05:00Z': {
+          time: 'as the server printed it',
+          day: 'server day',
+          shortDay: 'server short day',
+          dayWithYear: 'server day and year',
+        },
+      },
+    })
+    expect(thread().getByText('Jonas · as the server printed it')).toBeInTheDocument()
+    expect(thread().queryByText(/09:05/)).not.toBeInTheDocument()
+  })
+})

+ 63 - 4
src/__tests__/features/portal/portal-chat-events.test.ts

@@ -42,7 +42,8 @@ beforeEach(() => {
             invoiceNumber: 'INV-2041',
             totalAmount: 6480,
             issuedAt: new Date('2026-11-20T15:00:00Z'),
-            sentAt: null,
+            sentAt: new Date('2026-11-20T15:00:00Z'),
+            serviceDate: new Date('2026-11-19T07:00:00Z'),
             invoiceDueDate: null,
             manuallyPaid: false,
             payments: [],
@@ -91,6 +92,7 @@ describe('the events of a thread', () => {
         id: 'work_started:j1',
         kind: 'work_started',
         at: '2026-11-19T07:40:00.000Z',
+        dayOnly: false,
         vehicle: 'Volvo V60',
         title: 'Brake overhaul',
         amount: null,
@@ -102,6 +104,7 @@ describe('the events of a thread', () => {
         id: 'quote:q1',
         kind: 'quote',
         at: '2026-11-19T08:30:00.000Z',
+        dayOnly: false,
         vehicle: 'Volvo V60',
         title: 'Front brake pads and discs',
         amount: 'kr 6480.00',
@@ -113,6 +116,7 @@ describe('the events of a thread', () => {
         id: 'update:u1',
         kind: 'update',
         at: '2026-11-19T10:00:00.000Z',
+        dayOnly: false,
         vehicle: 'Volvo V60',
         title: 'Pads were down to 2 mm. See the photos.',
         amount: null,
@@ -124,6 +128,7 @@ describe('the events of a thread', () => {
         id: 'invoice:i1',
         kind: 'invoice',
         at: '2026-11-20T15:00:00.000Z',
+        dayOnly: false,
         vehicle: 'Volvo V60',
         title: 'INV-2041',
         amount: 'kr 6480.00',
@@ -185,7 +190,8 @@ describe('the events of a thread', () => {
     invoiceNumber: 'INV-2041',
     totalAmount: 6480,
     issuedAt: new Date('2026-11-10T15:00:00Z'),
-    sentAt: null,
+    sentAt: new Date('2026-11-10T15:00:00Z'),
+    serviceDate: new Date('2026-11-09T07:00:00Z'),
     invoiceDueDate: null,
     manuallyPaid: false,
     payments: [],
@@ -220,14 +226,67 @@ describe('the events of a thread', () => {
     )
   })
 
+  it('stands where the customer would look for it: when it was sent, else on its own date', async () => {
+    // Sent on the 18th: that moment, whatever day the sheet was frozen.
+    expect(
+      await invoiceEvent({
+        sentAt: new Date('2026-11-18T13:05:00Z'),
+        invoiceDate: new Date('2026-11-10T11:00:00Z'),
+        issuedAt: new Date('2026-11-12T03:47:00Z'),
+      })
+    ).toMatchObject({ at: '2026-11-18T13:05:00.000Z', dayOnly: false })
+    // Never sent: its own date, which is a day and not a time of day. When
+    // the sheet was frozen (a payment at 4:47 in the morning) is not shown.
+    expect(
+      await invoiceEvent({
+        sentAt: null,
+        invoiceDate: new Date('2026-11-10T11:00:00Z'),
+        issuedAt: new Date('2026-11-12T03:47:00Z'),
+      })
+    ).toMatchObject({ at: '2026-11-10T11:00:00.000Z', dayOnly: true })
+    // No invoice date: the day its page in the portal shows, the scheduled
+    // start and then the day of the work. Still a day, never the freeze time.
+    expect(
+      await invoiceEvent({
+        sentAt: null,
+        invoiceDate: null,
+        startDateTime: new Date('2026-11-08T07:00:00Z'),
+        issuedAt: new Date('2026-11-12T03:47:00Z'),
+      })
+    ).toMatchObject({ at: '2026-11-08T07:00:00.000Z', dayOnly: true })
+    expect(
+      await invoiceEvent({ sentAt: null, invoiceDate: null, startDateTime: null })
+    ).toMatchObject({ at: '2026-11-09T07:00:00.000Z', dayOnly: true })
+  })
+
+  it('asks only for invoices whose own place in the thread is inside the window', async () => {
+    await events()
+    const where = serviceRecord.findMany.mock.calls
+      .map(([args]) => args.where)
+      .find((one) => one.status === 'completed')
+    const since = new Date(now.getTime() - 30 * 86_400_000)
+    // A fallback date counts only for a row with no date of higher rank, and
+    // the freeze time is not asked about at all: twelve old invoices frozen
+    // this week can no longer fill the page and hide a recent one.
+    expect(where.AND[1]).toEqual({
+      OR: [
+        { sentAt: { gte: since } },
+        { sentAt: null, invoiceDate: { gte: since } },
+        { sentAt: null, invoiceDate: null, startDateTime: { gte: since } },
+        { sentAt: null, invoiceDate: null, startDateTime: null, serviceDate: { gte: since } },
+      ],
+    })
+    expect(JSON.stringify(where.AND[1])).not.toContain('issuedAt')
+  })
+
   it('goes back a month unless asked for more, and never past half a year', async () => {
-    expect(await invoiceEvent({ issuedAt: new Date('2026-10-01T10:00:00Z') })).toBeUndefined()
+    expect(await invoiceEvent({ sentAt: new Date('2026-10-01T10:00:00Z') })).toBeUndefined()
     const asked = (since: string) =>
       getPortalThreadEvents('org1', 'kari', 'fjordside', { now, since: new Date(since) })
     const kinds = async (since: string) => (await asked(since)).map((event) => event.kind)
     expect(await kinds('2026-09-01T00:00:00Z')).toContain('invoice')
     serviceRecord.findMany.mockImplementation(async ({ where }: { where: { status?: string } }) =>
-      where.status === 'completed' ? [invoice({ issuedAt: new Date('2026-01-05T10:00:00Z') })] : []
+      where.status === 'completed' ? [invoice({ sentAt: new Date('2026-01-05T10:00:00Z') })] : []
     )
     expect(await kinds('2025-01-01T00:00:00Z')).not.toContain('invoice')
   })

+ 132 - 0
src/__tests__/features/portal/portal-walk-defects.test.tsx

@@ -0,0 +1,132 @@
+/**
+ * What a walk through every portal screen found, pinned down.
+ *
+ * A browser decides where text wraps and jsdom does not, so the layout cases
+ * check the structure each fix rests on (which element may give way and which
+ * may not) and say why. The wording cases check what a customer reads.
+ */
+
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { render, screen, within } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import { format, fullHome } from './helpers/fixtures'
+
+vi.mock('next/navigation', () => ({
+  usePathname: () => '/portal/fjordside/dashboard',
+  useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
+}))
+vi.mock('next-intl/server', async () => (await import('./helpers/serverIntl')).serverIntl)
+vi.mock('@/features/portal/Actions/respondToPortalQuote', () => ({
+  respondToPortalQuote: vi.fn(async () => ({ success: true, data: { status: 'accepted' } })),
+}))
+
+import { PortalFacts } from '@/features/portal/Components/Detail/PortalPageParts'
+import { Home as Colour } from '@/features/portal/Components/Themes/Colour/Home'
+import { Home as Daylight } from '@/features/portal/Components/Themes/Daylight/Home'
+import { Home as Garage } from '@/features/portal/Components/Themes/Garage/Home'
+import { Home as Print } from '@/features/portal/Components/Themes/Print/Home'
+import type { PortalHomeProps } from '@/features/portal/Components/Themes/types'
+import type { PortalHomeData } from '@/features/portal/Lib/homeTypes'
+
+const HOMES = { Daylight, Garage, Print, Colour }
+type Theme = keyof typeof HOMES
+
+const home = async (
+  theme: Theme,
+  data: PortalHomeData,
+  chat: PortalHomeProps['chat'] = <p>The chat</p>
+) => render(await HOMES[theme]({ orgParam: 'fjordside', data, format, chat }))
+
+const classes = (element: Element | null) => (element?.getAttribute('class') ?? '').split(/\s+/)
+
+describe('a heading beside something wide', () => {
+  it('Colour: the panel name keeps its width and the car beside it is what gives way', async () => {
+    await home('Colour', fullHome)
+    const heading = screen.getByRole('heading', { name: 'Tyre hotel' })
+    // The name and its icon neither shrink nor start from nothing: a basis
+    // of zero is what let the car's name squeeze "Tyre hotel" to a letter a line.
+    const label = heading.closest('[data-panel-head-label]')
+    expect(classes(label)).toContain('flex-[1_0_auto]')
+    expect(classes(heading)).not.toContain('flex-1')
+    // The car's name may shrink, and is cut short when it must.
+    const aside = label?.parentElement?.querySelector('[data-panel-head-aside]') ?? null
+    expect(classes(aside)).toContain('min-w-0')
+    expect(classes(within(aside as HTMLElement).getByText('Toyota RAV4'))).toContain('truncate')
+  })
+
+  it('a label in a label and value row never gives way to its value', () => {
+    render(<PortalFacts facts={[{ label: 'Vehicle', value: '2022 Porsche 911 Carrera S' }]} />)
+    expect(classes(screen.getByText('Vehicle'))).toContain('shrink-0')
+    expect(classes(screen.getByText('2022 Porsche 911 Carrera S'))).toContain('min-w-0')
+  })
+
+  it('no box in the portal is sized as if a word could break at any letter', () => {
+    const css = readFileSync(join(process.cwd(), 'src/features/portal/portal-themes.css'), 'utf8')
+    const root = css.slice(css.indexOf('.portal-root {'), css.indexOf('.portal-scope {'))
+    expect(root).toContain('overflow-wrap: break-word')
+    expect(root).not.toMatch(/overflow-wrap:\s*anywhere/)
+  })
+})
+
+describe('Garage: the board beside the chat', () => {
+  it('stops at the chat from 1100 px: its right bleed exists only below that', async () => {
+    const { container } = await home('Garage', fullHome)
+    const board = classes(container.querySelector('[data-board]'))
+    // Each width range has its own right margin and none is an override of
+    // another: a px breakpoint is emitted before the rem ones, so "mr-0 from
+    // 1100 px" lost to "lg:-mx-10" and the board ran 40 px under the chat.
+    expect(board).toEqual(
+      expect.arrayContaining(['max-sm:-mr-4', 'sm:max-lg:-mr-6', 'lg:max-[1100px]:-mr-10'])
+    )
+    expect(board.some((name) => /(^|:)-mx-/.test(name))).toBe(false)
+    expect(board).not.toContain('min-[1100px]:mr-0')
+    expect(board).not.toContain('lg:-mr-10')
+  })
+
+  it('runs out to both edges when there is no chat', async () => {
+    const { container } = await home('Garage', fullHome, null)
+    expect(classes(container.querySelector('[data-board]'))).toEqual(
+      expect.arrayContaining(['-ml-4', 'lg:-ml-10', '-mr-4', 'lg:-mr-10'])
+    )
+  })
+})
+
+describe('a request sent with a quick choice', () => {
+  const data: PortalHomeData = {
+    ...fullHome,
+    requests: [
+      {
+        id: 'r1',
+        description: 'Something is wrong\n\nA knocking noise from the front left over bumps.',
+        vehicle: null,
+        createdAt: '2026-11-13T09:00:00Z',
+        preferredDate: null,
+      },
+      {
+        id: 'r2',
+        description: 'Could you check the wiper blades at the next visit?',
+        vehicle: null,
+        createdAt: '2026-11-12T09:00:00Z',
+        preferredDate: null,
+      },
+    ],
+  }
+
+  it.each(
+    Object.keys(HOMES) as Theme[]
+  )('%s: shows the choice on a line of its own and the words after it', async (theme) => {
+    await home(theme, data)
+    const sent = within(screen.getByRole('region', { name: 'Sent to the workshop' }))
+    const topic = sent.getByText('Something is wrong')
+    const words = sent.getByText('A knocking noise from the front left over bumps.')
+    expect(topic).not.toBe(words)
+    expect(topic).toHaveAttribute('data-request-topic')
+    expect(topic).not.toHaveTextContent('knocking')
+    // A request without a choice is its words alone.
+    expect(
+      sent.getByText('Could you check the wiper blades at the next visit?')
+    ).toBeInTheDocument()
+    expect(document.querySelectorAll('[data-request-topic]')).toHaveLength(1)
+  })
+})

+ 84 - 0
src/__tests__/features/portal/request-text.test.ts

@@ -0,0 +1,84 @@
+/**
+ * A request sent from the booking page starts with the quick choice the
+ * customer picked, then a blank line, then their own words. Shown as one
+ * paragraph the two ran together; every screen sets the choice apart.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { REQUEST_TOPIC_LABELS } from '@/features/portal/Lib/requestTopics'
+import { locales } from '@/i18n/config'
+import { requestTitle, splitRequestText } from '@/features/portal/Lib/requestText'
+
+describe('what a customer asked for, taken apart', () => {
+  it('sets the quick choice apart from the words after it', () => {
+    expect(
+      splitRequestText('Something is wrong\n\nA knocking noise from the front left over bumps.')
+    ).toEqual({
+      topic: 'Something is wrong',
+      body: 'A knocking noise from the front left over bumps.',
+    })
+  })
+
+  it('keeps the line breaks the customer typed in their own words', () => {
+    expect(splitRequestText('Tyre change\n\nWinter set.\n\nThey are in your tyre hotel.')).toEqual({
+      topic: 'Tyre change',
+      body: 'Winter set.\n\nThey are in your tyre hotel.',
+    })
+  })
+
+  it('is the words alone when there is no choice to set apart', () => {
+    expect(splitRequestText('Could you check the wiper blades?')).toEqual({
+      topic: null,
+      body: 'Could you check the wiper blades?',
+    })
+    // A choice with nothing after it is the whole request.
+    expect(splitRequestText('Service')).toEqual({ topic: null, body: 'Service' })
+    // One line break is a sentence going on, not a choice.
+    expect(splitRequestText('Brakes squeal\nmostly when cold')).toEqual({
+      topic: null,
+      body: 'Brakes squeal\nmostly when cold',
+    })
+    expect(splitRequestText(null)).toEqual({ topic: null, body: '' })
+  })
+
+  it('does not take a first paragraph the customer wrote themselves for a choice', () => {
+    // The form allows several paragraphs with nothing picked.
+    const own = 'Brakes squeal.\n\nOnly when cold.'
+    expect(splitRequestText(own)).toEqual({ topic: null, body: own })
+    expect(requestTitle(own)).toBe('Brakes squeal. Only when cold.')
+    const nearly = 'something is wrong\n\nA knocking noise.'
+    expect(splitRequestText(nearly)).toEqual({ topic: null, body: nearly })
+  })
+
+  it('knows the quick choices in every language the portal speaks', () => {
+    expect(splitRequestText('Noe er galt\n\nDet banker foran.')).toEqual({
+      topic: 'Noe er galt',
+      body: 'Det banker foran.',
+    })
+    // Straight from the message files, for every locale and every choice.
+    for (const locale of locales) {
+      const file = join(process.cwd(), 'messages', locale, 'portal.json')
+      const topics: Record<string, string> = JSON.parse(readFileSync(file, 'utf8')).book.topics
+      expect(Object.keys(topics).length).toBeGreaterThan(0)
+      for (const label of Object.values(topics)) {
+        expect(REQUEST_TOPIC_LABELS.has(label.trim()), `${locale}: ${label}`).toBe(true)
+      }
+    }
+  })
+})
+
+describe('the title of the work order made from a request', () => {
+  it('is one line with the choice set off from the words', () => {
+    expect(requestTitle('Brakes\n\nSquealing when cold.')).toBe('Brakes: Squealing when cold.')
+    expect(requestTitle('Could you check the wipers?')).toBe('Could you check the wipers?')
+  })
+
+  it('is cut to sixty characters', () => {
+    const title = requestTitle(
+      'Something is wrong\n\nA knocking noise from the front left over bumps, worse when cold.'
+    )
+    expect(title).toBe('Something is wrong: A knocking noise from the front left ...')
+    expect(title).toHaveLength(60)
+  })
+})

+ 55 - 0
src/__tests__/features/quotes/record-quote-response.test.ts

@@ -0,0 +1,55 @@
+// @vitest-environment node
+/**
+ * A customer's answer to a quote reaches the workshop's bell, and the
+ * notification opens that quote: not the dashboard, not the list.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/db', () => ({ db: { quote: { updateMany: vi.fn() } } }))
+vi.mock('@/lib/notify', () => ({ notify: vi.fn() }))
+
+import { recordQuoteResponse } from '@/features/quotes/Lib/recordQuoteResponse'
+import { db } from '@/lib/db'
+import { notify } from '@/lib/notify'
+
+const quote = {
+  id: 'q1',
+  organizationId: 'org1',
+  quoteNumber: 'Q-2026-010',
+  title: 'Suspension refresh',
+  customer: { name: 'Sarah Coleman' },
+}
+
+describe("a customer's answer in the workshop's bell", () => {
+  beforeEach(() => {
+    vi.clearAllMocks()
+    vi.mocked(db.quote.updateMany).mockResolvedValue({ count: 1 })
+  })
+
+  it('opens the quote when the customer asked for changes', async () => {
+    await recordQuoteResponse(quote, 'changes_requested', 'Without the rear arms?', {
+      from: ['sent'],
+    })
+    expect(notify).toHaveBeenCalledWith(
+      expect.objectContaining({
+        title: 'Quote Changes Requested',
+        entityType: 'quote',
+        entityId: 'q1',
+        entityUrl: '/quotes/q1',
+      })
+    )
+  })
+
+  it('opens the quote when the customer accepted it', async () => {
+    await recordQuoteResponse(quote, 'accepted', null, { from: ['sent'] })
+    expect(notify).toHaveBeenCalledWith(
+      expect.objectContaining({ title: 'Quote Accepted', entityUrl: '/quotes/q1' })
+    )
+  })
+
+  it('tells nobody about an answer that did not happen', async () => {
+    vi.mocked(db.quote.updateMany).mockResolvedValue({ count: 0 })
+    expect(await recordQuoteResponse(quote, 'accepted', null, { from: ['sent'] })).toBe(false)
+    expect(notify).not.toHaveBeenCalled()
+  })
+})

+ 23 - 3
src/app/(authenticated)/(dashboard)/dashboard-client.tsx

@@ -102,6 +102,7 @@ import { CalendarEventsCard } from '@/features/calendar/Components/CalendarEvent
 import { isEventDone } from '@/features/calendar/Components/calendar-utils'
 import type { CalendarEvent } from '@/features/calendar/Actions/calendarActions'
 import { ServiceRequestFiles } from '@/features/portal/Components/ServiceRequestFiles'
+import type { RequestTextParts } from '@/features/portal/Lib/requestText'
 
 interface ServiceItem {
   id: string
@@ -192,6 +193,8 @@ interface DashboardInspection {
 interface DashboardServiceRequest {
   id: string
   description: string
+  /** The description taken apart by the page: the quick choice, and the customer's words. */
+  words?: RequestTextParts
   preferredDate: Date | null
   /** Photos and video the customer sent from the portal, as stored file urls. */
   attachments?: string[]
@@ -285,6 +288,25 @@ const observationSeverityColors: Record<string, string> = {
   monitor: 'bg-blue-500/10 text-blue-500 border-blue-500/20',
 }
 
+/**
+ * What a customer wrote in a request from the portal. The quick choice they
+ * picked ("Something is wrong") is stored as the first line: it gets a line
+ * of its own, so it does not run into their words.
+ */
+function RequestWords({ text, words }: { text: string; words?: RequestTextParts }) {
+  const { topic, body } = words ?? { topic: null, body: text }
+  return (
+    <div className="mt-1.5 text-xs">
+      {topic && (
+        <p data-request-topic className="truncate font-medium">
+          {topic}
+        </p>
+      )}
+      <p className="line-clamp-2 text-muted-foreground">{body}</p>
+    </div>
+  )
+}
+
 export function DashboardClient({
   stats,
   currencyCode = DEFAULT_CURRENCY_CODE,
@@ -1284,9 +1306,7 @@ export function DashboardClient({
                             {tCustomerRequests('statusNew')}
                           </Badge>
                         </div>
-                        <p className="mt-1.5 line-clamp-2 text-xs text-muted-foreground">
-                          {req.description}
-                        </p>
+                        <RequestWords text={req.description} words={req.words} />
                         <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
                           <span>
                             {tCustomerRequests('submitted', {

+ 6 - 1
src/app/(authenticated)/(dashboard)/page.tsx

@@ -26,6 +26,7 @@ import { getRecentObservations } from '@/features/vehicles/Actions/findingAction
 import { getMyActiveJobs } from '@/features/vehicles/Actions/getMyActiveJobs'
 import { getOnboardingChecklist } from '@/features/onboarding/Actions/checklistActions'
 import { DashboardClient } from './dashboard-client'
+import { splitRequestText } from '@/features/portal/Lib/requestText'
 import { db } from '@/lib/db'
 import { sanitizeConfig, type CustomWidget } from '@/features/dashboard/custom-cards/registry'
 import { MyActiveJobs } from '@/features/vehicles/Components/MyActiveJobs'
@@ -199,7 +200,11 @@ export default async function DashboardPage() {
   // empty list would mean a portal nobody has used yet.
   const serviceRequests =
     portalAllowed && settings[SETTING_KEYS.PORTAL_ENABLED] === 'true'
-      ? (serviceRequestsResult?.success && serviceRequestsResult.data) || []
+      ? ((serviceRequestsResult?.success && serviceRequestsResult.data) || []).map((request) => ({
+          ...request,
+          // Taken apart here: the client card cannot know every language's quick choices.
+          words: splitRequestText(request.description),
+        }))
       : null
 
   const myJobs = myJobsResult.success && myJobsResult.data ? myJobsResult.data : []

+ 18 - 2
src/app/(authenticated)/customers/[id]/customer-detail-client.tsx

@@ -76,10 +76,17 @@ import { useServiceType } from '@/components/service-type-context'
 import { toast } from 'sonner'
 import { useServiceLabels } from '@/features/vehicles/Lib/useServiceLabels'
 import { ServiceRequestFiles } from '@/features/portal/Components/ServiceRequestFiles'
+import type { RequestTextParts } from '@/features/portal/Lib/requestText'
 
 interface ServiceRequestItem {
   id: string
   description: string
+  /**
+   * The description taken apart by the page: the quick choice the customer
+   * picked in the portal, and their own words. Without it the description is
+   * shown whole.
+   */
+  words?: RequestTextParts
   preferredDate: Date | null
   /** "morning" or "afternoon", when the customer said which suits. */
   preferredTime?: string | null
@@ -1169,6 +1176,8 @@ export function ServiceRequestCard({
 
   const canSms = smsEnabled && !!customerPhone
   const vehicleDisplay = `${request.vehicle.year} ${request.vehicle.make} ${request.vehicle.model}`
+  // A request from the portal can start with the quick choice the customer picked.
+  const words = request.words ?? { topic: null, body: request.description }
 
   return (
     <>
@@ -1183,8 +1192,15 @@ export function ServiceRequestCard({
                   {config.label}
                 </Badge>
               </div>
-              <p className="mt-1 text-sm text-muted-foreground whitespace-pre-wrap">
-                {request.description}
+              {words.topic && (
+                <p data-request-topic className="mt-1 text-sm font-medium">
+                  {words.topic}
+                </p>
+              )}
+              <p
+                className={`text-sm text-muted-foreground whitespace-pre-wrap ${words.topic ? 'mt-0.5' : 'mt-1'}`}
+              >
+                {words.body}
               </p>
               <div className="mt-2 flex gap-3 text-xs text-muted-foreground">
                 <span>{t('submitted', { date: formatDate(new Date(request.createdAt)) })}</span>

+ 9 - 1
src/app/(authenticated)/customers/[id]/page.tsx

@@ -14,6 +14,7 @@ import { isAiConfigured } from '@/features/integrations/Lib/ai'
 import { getOrgTelegramBotUsername } from '@/lib/telegram'
 import { channelEnabled } from '@/features/integrations/Lib/messaging'
 import { CustomerDetailClient } from './customer-detail-client'
+import { splitRequestText } from '@/features/portal/Lib/requestText'
 import { PageHeader } from '@/components/page-header'
 import { pageTitle } from '@/lib/page-title'
 
@@ -111,7 +112,14 @@ export default async function CustomerDetailPage({ params }: { params: Promise<{
       <PageHeader />
       <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
         <CustomerDetailClient
-          customer={result.data}
+          customer={{
+            ...result.data,
+            // Taken apart here: the client card cannot know every language's quick choices.
+            serviceRequests: result.data.serviceRequests?.map((request) => ({
+              ...request,
+              words: splitRequestText(request.description),
+            })),
+          }}
           unitSystem={
             ((settingsResult.success && settingsResult.data?.[SETTING_KEYS.UNIT_SYSTEM]) ||
               'imperial') as 'metric' | 'imperial'

+ 17 - 5
src/app/(public)/portal/[orgId]/request-service/page.tsx

@@ -22,6 +22,7 @@ import {
 import { readAttachments } from '@/features/portal/Lib/chat.server'
 import { portalFormat } from '@/features/portal/Lib/portalFormat'
 import { loadPortalLook } from '@/features/portal/Lib/portalLook.server'
+import { splitRequestText } from '@/features/portal/Lib/requestText'
 import { portalRequestBadge, portalStatusLabel } from '@/features/portal/Lib/statusLabels'
 import { loadPortalWorkshop } from '@/features/portal/Lib/workshop.server'
 import { db } from '@/lib/db'
@@ -160,6 +161,7 @@ export default async function PortalRequestServicePage({
                 {requests.map((req) => {
                   const badge = portalRequestBadge(req.status)
                   const files = readAttachments(org.id, req.attachments)
+                  const words = splitRequestText(req.description)
                   return (
                     <li
                       key={req.id}
@@ -169,8 +171,15 @@ export default async function PortalRequestServicePage({
                         <p className="text-base font-semibold">
                           {req.vehicle.make} {req.vehicle.model}
                         </p>
-                        <p className="mt-1 whitespace-pre-line break-words text-[15px]">
-                          {req.description}
+                        {words.topic && (
+                          <p data-request-topic className="mt-1 text-[15px] font-semibold">
+                            {words.topic}
+                          </p>
+                        )}
+                        <p
+                          className={`whitespace-pre-line break-words text-[15px] ${words.topic ? 'mt-0.5' : 'mt-1'}`}
+                        >
+                          {words.body}
                         </p>
                         {files.length > 0 && (
                           <ul
@@ -245,14 +254,17 @@ export default async function PortalRequestServicePage({
           {(workshop.phoneHref || look.messagesEnabled) && (
             <PortalPanel aria-labelledby="book-talk">
               <PortalSectionLabel id="book-talk">{t('talkTitle')}</PortalSectionLabel>
-              <div className="mt-3 flex flex-col gap-2.5 sm:flex-row lg:flex-col xl:flex-row">
+              {/* Side by side only where each fits on one line: a button whose
+                  words do not fit takes a row of its own instead of breaking
+                  the phone number in two. */}
+              <div className="mt-3 flex flex-wrap gap-2.5">
                 {workshop.phoneHref && workshop.phone && (
-                  <PortalLinkButton href={workshop.phoneHref} className="flex-1">
+                  <PortalLinkButton href={workshop.phoneHref} className="flex-[1_1_auto]">
                     {t('talkCall', { phone: workshop.phone })}
                   </PortalLinkButton>
                 )}
                 {look.messagesEnabled && (
-                  <PortalLinkButton href={`/portal/${orgId}/messages`} className="flex-1">
+                  <PortalLinkButton href={`/portal/${orgId}/messages`} className="flex-[1_1_auto]">
                     {tNav('messages')}
                   </PortalLinkButton>
                 )}

+ 2 - 4
src/features/customers/Actions/customerActions.ts

@@ -14,6 +14,7 @@ import { serviceDateOrderBy } from '@/lib/date-sort'
 import { clearedToNull } from '@/lib/clearable'
 import { Prisma } from '@/generated/prisma/client'
 import { NAME_FOLD, foldName, normalizeName } from '@/lib/name-similarity'
+import { requestTitle } from '@/features/portal/Lib/requestText'
 
 /**
  * A design a customer is being pointed at has to be this workshop's and an
@@ -484,10 +485,7 @@ export async function createWorkOrderFromRequest(requestId: string) {
       }
       const record = result.data
 
-      const truncatedTitle =
-        request.description.length > 60
-          ? request.description.slice(0, 57) + '...'
-          : request.description
+      const truncatedTitle = requestTitle(request.description)
 
       await db.serviceRecord.update({
         where: { id: record.id },

+ 35 - 28
src/features/portal/Components/Chat/PortalChatPanel.tsx

@@ -25,7 +25,13 @@ import {
   ChatViewer,
   type ChatViewerFile,
 } from './PortalChatParts'
-import { buildPortalThread, workshopDayKey } from './chatThread'
+import {
+  buildPortalThread,
+  type PortalChatStampKind,
+  type PortalChatStamps,
+  portalChatFormats,
+  workshopDayKey,
+} from './chatThread'
 import { useChatUploads } from './useChatUploads'
 import { useChatVisible } from './useChatVisible'
 import { usePortalThread } from './usePortalThread'
@@ -65,6 +71,12 @@ export interface PortalChatPanelProps {
   initialEvents?: PortalChatEvent[]
   /** How times are printed: the workshop's zone and its 12 or 24 hour clock. */
   clock: { timeZone: string; timeFormat: '12h' | '24h' }
+  /**
+   * The times and days of that first thread as the server printed them, so
+   * the page reads the same before and after the browser takes over. Optional:
+   * without it the browser prints them itself.
+   */
+  stamps?: PortalChatStamps
   /**
    * 'panel' sits in a box among other things and has its own header; 'page'
    * is the Messages page, where the page already says what this is, so the
@@ -86,6 +98,7 @@ export function PortalChatPanel({
   initialMessages,
   initialEvents,
   clock,
+  stamps,
   variant = 'panel',
 }: PortalChatPanelProps) {
   const t = useTranslations('portal.chat')
@@ -118,35 +131,29 @@ export function PortalChatPanel({
   // The workshop can turn the chat off while a customer has it open.
   const canWrite = enabled && thread.enabled
 
-  const formats = useMemo(() => {
-    const zone = { timeZone: clock.timeZone }
-    return {
-      time: new Intl.DateTimeFormat(locale, {
-        ...zone,
-        ...(clock.timeFormat === '24h'
-          ? { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }
-          : { hour: 'numeric', minute: '2-digit', hour12: true }),
-      }),
-      day: new Intl.DateTimeFormat(locale, {
-        ...zone,
-        weekday: 'long',
-        day: 'numeric',
-        month: 'long',
-      }),
-      dayWithYear: new Intl.DateTimeFormat(locale, {
-        ...zone,
-        day: 'numeric',
-        month: 'long',
-        year: 'numeric',
-      }),
-    }
-  }, [locale, clock.timeZone, clock.timeFormat])
+  const formats = useMemo(
+    () => portalChatFormats(locale, { timeZone: clock.timeZone, timeFormat: clock.timeFormat }),
+    [locale, clock.timeZone, clock.timeFormat]
+  )
+  /**
+   * A moment as the thread prints it. What the server already printed is
+   * shown as it is (see `PortalChatStamps`): printing it again here could
+   * give another text than the page arrived with.
+   */
+  const stamp = (iso: string, kind: PortalChatStampKind) =>
+    stamps?.[iso]?.[kind] ?? formats[kind].format(new Date(iso))
 
   const items = useMemo(
     () => buildPortalThread(thread.messages, thread.events, outgoing, clock.timeZone),
     [thread.messages, thread.events, outgoing, clock.timeZone]
   )
 
+  /**
+   * When an event happened, on the workshop's clock. One that is only a
+   * calendar day (an invoice on its own date) prints the day, never a time.
+   */
+  const eventWhen = (event: PortalChatEvent) => stamp(event.at, event.dayOnly ? 'shortDay' : 'time')
+
   /** "Today", "Yesterday", or the day in words, on the workshop's calendar. */
   const dayLabel = (iso: string) => {
     const key = workshopDayKey(iso, clock.timeZone)
@@ -157,7 +164,7 @@ export function PortalChatPanel({
     }
     const sameYear =
       key.slice(0, 4) === workshopDayKey(new Date(now).toISOString(), clock.timeZone).slice(0, 4)
-    return (sameYear ? formats.day : formats.dayWithYear).format(new Date(iso))
+    return stamp(iso, sameYear ? 'day' : 'dayWithYear')
   }
 
   // ── Keeping the newest message in view ──────────────────────────────────
@@ -344,7 +351,7 @@ export function PortalChatPanel({
                       key={item.key}
                       event={item.event}
                       workshopName={workshopName}
-                      time={formats.time.format(new Date(item.event.at))}
+                      time={eventWhen(item.event)}
                       t={t}
                     />
                   )
@@ -355,7 +362,7 @@ export function PortalChatPanel({
                       key={item.key}
                       kind={item.kind}
                       events={item.events}
-                      time={(iso) => formats.time.format(new Date(iso))}
+                      time={eventWhen}
                       t={t}
                     />
                   )
@@ -388,7 +395,7 @@ export function PortalChatPanel({
                     </div>
                     {item.closesRun && (
                       <p className={mine ? 'p-chat__meta p-chat__meta--me' : 'p-chat__meta'}>
-                        {who} · {formats.time.format(new Date(message.createdAt))}
+                        {who} · {stamp(message.createdAt, 'time')}
                         {message.id === seenId && ` · ${t('seen')}`}
                       </p>
                     )}

+ 3 - 3
src/features/portal/Components/Chat/PortalChatParts.tsx

@@ -278,8 +278,8 @@ export function ChatEventGroup({
 }: {
   kind: PortalChatEvent['kind']
   events: PortalChatEvent[]
-  /** Prints an event's time on the workshop's clock. */
-  time: (iso: string) => string
+  /** Prints when an event happened on the workshop's clock: a time, or the day for one without a time. */
+  time: (event: PortalChatEvent) => string
   t: Translate
 }) {
   const Icon = LINE_ICON[kind]
@@ -300,7 +300,7 @@ export function ChatEventGroup({
       </summary>
       <div className="p-chat__groupbody">
         {events.map((event) => (
-          <ChatEventLine key={event.id} event={event} time={time(event.at)} t={t} />
+          <ChatEventLine key={event.id} event={event} time={time(event)} t={t} />
         ))}
       </div>
     </details>

+ 12 - 1
src/features/portal/Components/Chat/PortalChatSlot.tsx

@@ -1,3 +1,4 @@
+import { getLocale } from 'next-intl/server'
 import { getCustomerSession } from '@/lib/customer-session'
 import { getPortalThreadEvents, portalEventsSince } from '../../Lib/chat.server'
 import {
@@ -6,6 +7,7 @@ import {
   type PortalChatMessage,
 } from '../../Lib/chatTypes'
 import { portalClock } from '../../Lib/workshop.server'
+import { portalChatStamps } from './chatThread'
 import { PortalChatPanel } from './PortalChatPanel'
 
 /**
@@ -36,10 +38,18 @@ export async function PortalChatSlot({
   messages: PortalChatMessage[]
   variant?: 'panel' | 'page'
 }) {
-  const [clock, events] = await Promise.all([
+  const [clock, events, locale] = await Promise.all([
     portalClock(organizationId),
     threadEvents(organizationId, orgParam, messages),
+    getLocale(),
   ])
+  // Printed here, once, and shown as they are in the browser: the two do not
+  // print a time alike in every language (see `PortalChatStamps`).
+  const stamps = portalChatStamps(
+    [...messages.map((message) => message.createdAt), ...(events ?? []).map((event) => event.at)],
+    locale,
+    clock
+  )
   return (
     <PortalChatPanel
       orgParam={orgParam}
@@ -49,6 +59,7 @@ export async function PortalChatSlot({
       initialMessages={messages}
       initialEvents={events}
       clock={clock}
+      stamps={stamps}
       variant={variant}
     />
   )

+ 78 - 0
src/features/portal/Components/Chat/chatThread.ts

@@ -148,3 +148,81 @@ function foldEvents(events: PortalChatEvent[], timeZone: string): Entry[] {
   }
   return entries
 }
+
+/** How the workshop prints its times: its zone and its 12 or 24 hour clock. */
+export interface PortalChatClock {
+  timeZone: string
+  timeFormat: '12h' | '24h'
+}
+
+/** The four ways the thread prints a moment, in the portal's language on the workshop's clock. */
+export type PortalChatStampKind = 'time' | 'day' | 'shortDay' | 'dayWithYear'
+
+/**
+ * The formatters behind every time and day in the thread. One function, so
+ * the server (which prints the first thread) and the browser (which prints
+ * what arrives later) ask for exactly the same thing.
+ */
+export function portalChatFormats(
+  locale: string,
+  clock: PortalChatClock
+): Record<PortalChatStampKind, Intl.DateTimeFormat> {
+  const zone = { timeZone: clock.timeZone }
+  return {
+    time: new Intl.DateTimeFormat(locale, {
+      ...zone,
+      ...(clock.timeFormat === '24h'
+        ? { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }
+        : { hour: 'numeric', minute: '2-digit', hour12: true }),
+    }),
+    day: new Intl.DateTimeFormat(locale, {
+      ...zone,
+      weekday: 'long',
+      day: 'numeric',
+      month: 'long',
+    }),
+    // The day alone, for an event that has no time of day.
+    shortDay: new Intl.DateTimeFormat(locale, { ...zone, day: 'numeric', month: 'short' }),
+    dayWithYear: new Intl.DateTimeFormat(locale, {
+      ...zone,
+      day: 'numeric',
+      month: 'long',
+      year: 'numeric',
+    }),
+  }
+}
+
+/**
+ * The times and days of a thread, already printed, by the moment they print.
+ *
+ * The server and the browser do not print a time alike: each has its own
+ * copy of the language data, and they disagree in small ways ("9:20 a. m."
+ * with one kind of space or another, "sept" or "sep"). A chat that printed
+ * its times on both sides was therefore one text on the server and another
+ * in the browser, which React refuses (error 418) in any language where the
+ * two copies differ. So the server prints the first thread's stamps once and
+ * hands them over, and the browser shows those as they are; it prints only
+ * what arrives after the page has loaded.
+ */
+export type PortalChatStamps = Record<string, Record<PortalChatStampKind, string>>
+
+export function portalChatStamps(
+  moments: string[],
+  locale: string,
+  clock: PortalChatClock
+): PortalChatStamps {
+  const formats = portalChatFormats(locale, clock)
+  const stamps: PortalChatStamps = {}
+  for (const iso of moments) {
+    if (stamps[iso]) continue
+    const date = new Date(iso)
+    if (Number.isNaN(date.getTime())) continue
+    stamps[iso] = {
+      time: formats.time.format(date),
+      day: formats.day.format(date),
+      shortDay: formats.shortDay.format(date),
+      dayWithYear: formats.dayWithYear.format(date),
+    }
+  }
+  return stamps
+}

+ 5 - 1
src/features/portal/Components/Detail/PortalInspectionResults.tsx

@@ -166,8 +166,12 @@ export async function PortalInspectionResults({
             {defects.map((item) => (
               <li
                 key={item.id}
+                // The card is the grade's own tint with its own ink, light in
+                // every theme. Quiet words inside it take that ink, a little
+                // lighter: the theme's own quiet colour is made for the
+                // theme's ground and vanished on the tint in the dark theme.
                 className={cn(
-                  'rounded-[var(--p-radius-field)] border p-3.5',
+                  'rounded-[var(--p-radius-field)] border p-3.5 [&_.p-muted]:text-current [&_.p-muted]:opacity-80',
                   CONDITION_TOKENS[item.condition as Condition]?.soft
                 )}
               >

+ 3 - 1
src/features/portal/Components/Detail/PortalPageParts.tsx

@@ -293,7 +293,9 @@ export function PortalFacts({
           key={fact.label}
           className="flex items-baseline justify-between gap-4 border-b py-2.5 last:border-b-0"
         >
-          <dt className="p-muted text-sm">{fact.label}</dt>
+          {/* The label keeps its words whole and never gives way; the value
+              takes what is left and wraps there. */}
+          <dt className="p-muted max-w-[55%] shrink-0 text-sm">{fact.label}</dt>
           <dd
             className={join(
               'min-w-0 break-words text-right text-[15px]',

+ 33 - 0
src/features/portal/Components/Home/PortalRequestText.tsx

@@ -0,0 +1,33 @@
+/**
+ * A request the customer sent, as the title of a row:
+ *
+ *     <PortalListRow title={<PortalRequestText text={request.description} />} … />
+ *
+ * The quick choice the customer picked ("Something is wrong") stands on a
+ * line of its own and their words follow under it, lighter, so the two never
+ * read as one sentence. A request without a choice is its words alone. The
+ * words are cut after three lines and keep the line breaks they were typed
+ * with. `className` sets the type of the leading line (a theme's row title).
+ */
+import { splitRequestText } from '../../Lib/requestText'
+
+export function PortalRequestText({ text, className }: { text: string; className?: string }) {
+  const { topic, body } = splitRequestText(text)
+  const lead = className ?? ''
+  if (!topic) {
+    return <span className={`${lead} line-clamp-3 whitespace-pre-line`.trim()}>{body}</span>
+  }
+  return (
+    <span className="flex flex-col gap-0.5">
+      <span data-request-topic className={lead || undefined}>
+        {topic}
+      </span>
+      <span
+        data-request-words
+        className="line-clamp-3 whitespace-pre-line text-[15px] font-normal leading-snug"
+      >
+        {body}
+      </span>
+    </span>
+  )
+}

+ 3 - 2
src/features/portal/Components/Themes/Colour/Home.tsx

@@ -28,6 +28,7 @@ import type {
   PortalWorkshop,
 } from '../../../Lib/homeTypes'
 import { PortalAcceptQuoteButton } from '../../Home/PortalAcceptQuoteButton'
+import { PortalRequestText } from '../../Home/PortalRequestText'
 import { portalHeroLine, portalJobLine, portalJobSteps, tireSeasonKey } from '../../Home/homeCopy'
 import { PortalBadge, PortalEmptyState, PortalLinkButton, PortalPanel } from '../../Ui'
 import type { PortalHomeProps } from '../types'
@@ -208,7 +209,7 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
                     {data.requests.map((request) => (
                       <TileRow
                         key={request.id}
-                        title={<span className="line-clamp-3">{request.description}</span>}
+                        title={<PortalRequestText text={request.description} />}
                         meta={joined([
                           t('requestSent', { day: format.day(request.createdAt) }),
                           request.vehicle?.label,
@@ -764,7 +765,7 @@ function TiresPanel({
         label={t('tires')}
         aside={
           first.vehicle && (
-            <span className="p-muted text-sm font-semibold">{first.vehicle.label}</span>
+            <span className="p-muted truncate text-sm font-semibold">{first.vehicle.label}</span>
           )
         }
       />

+ 24 - 17
src/features/portal/Components/Themes/Colour/parts.tsx

@@ -104,23 +104,30 @@ export function PanelHead({
 }) {
   return (
     <div className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
-      {plain ? (
-        <Icon className="h-5 w-5 shrink-0" aria-hidden />
-      ) : (
-        <span
-          aria-hidden
-          className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[10px] bg-[var(--p-accent)] text-[color:var(--p-on-accent)]"
-        >
-          <Icon className="h-4 w-4" strokeWidth={2.4} />
-        </span>
-      )}
-      <PortalSectionLabel
-        id={id}
-        className="min-w-0 flex-1 text-sm font-extrabold text-[color:var(--p-ink)]"
-      >
-        {label}
-      </PortalSectionLabel>
-      {aside}
+      {/* The icon and the name never give way: `flex-[1_0_auto]` keeps them at
+          the width of their words (a name longer than the panel wraps between
+          words). What stands beside them goes to a line of its own when the
+          two do not fit, and is cut short there if it is still too long. */}
+      <div data-panel-head-label className="flex max-w-full flex-[1_0_auto] items-center gap-2.5">
+        {plain ? (
+          <Icon className="h-5 w-5 shrink-0" aria-hidden />
+        ) : (
+          <span
+            aria-hidden
+            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[10px] bg-[var(--p-accent)] text-[color:var(--p-on-accent)]"
+          >
+            <Icon className="h-4 w-4" strokeWidth={2.4} />
+          </span>
+        )}
+        <PortalSectionLabel id={id} className="text-sm font-extrabold text-[color:var(--p-ink)]">
+          {label}
+        </PortalSectionLabel>
+      </div>
+      {aside ? (
+        <div data-panel-head-aside className="flex min-w-0 max-w-full items-center [&>*]:min-w-0">
+          {aside}
+        </div>
+      ) : null}
     </div>
   )
 }

+ 2 - 1
src/features/portal/Components/Themes/Daylight/Home.tsx

@@ -8,6 +8,7 @@ import type {
   PortalHomeTireSet,
 } from '../../../Lib/homeTypes'
 import { PortalAcceptQuoteButton } from '../../Home/PortalAcceptQuoteButton'
+import { PortalRequestText } from '../../Home/PortalRequestText'
 import { portalHeroLine, portalJobLine, portalJobSteps, tireSeasonKey } from '../../Home/homeCopy'
 import {
   PortalBadge,
@@ -188,7 +189,7 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
                   <PortalListRow
                     key={request.id}
                     as="li"
-                    title={<span className="line-clamp-3">{request.description}</span>}
+                    title={<PortalRequestText text={request.description} />}
                     meta={joined([
                       t('requestSent', { day: format.day(request.createdAt) }),
                       request.vehicle?.label,

+ 10 - 4
src/features/portal/Components/Themes/Garage/Home.tsx

@@ -11,6 +11,7 @@ import type {
 } from '../../../Lib/homeTypes'
 import { portalHeroLine, portalJobLine, portalJobSteps, tireSeasonKey } from '../../Home/homeCopy'
 import { PortalAcceptQuoteButton } from '../../Home/PortalAcceptQuoteButton'
+import { PortalRequestText } from '../../Home/PortalRequestText'
 import { PortalBadge, PortalEmptyState, PortalLinkButton, PortalListRow } from '../../Ui'
 import type { PortalHomeProps } from '../types'
 import { ACTION, ACTION_RULE, CELL, LABEL, Plate, SquareDot, TAG } from './parts'
@@ -57,10 +58,15 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
     <div className="p-shell flex flex-1 flex-col min-[1100px]:flex-row">
       {/* The board runs out through the container's gutters, so its rules reach
           the edge; each cell pads by the same gutter, so what it holds lines
-          up with the header. Beside the chat it stops at the chat's rule. */}
+          up with the header. Beside the chat it stops at the chat's rule: the
+          right bleed exists only below 1100 px there. Each width range gets
+          its own margin, none overrides another: Tailwind emits a px
+          breakpoint (`min-[1100px]`) before the rem ones (`lg`), so a later
+          "mr-0" lost and the board ran 40 px under the chat. */}
       <div
-        className={`@container -mx-4 flex min-w-0 flex-1 flex-col sm:-mx-6 lg:-mx-10 ${
-          chat ? 'min-[1100px]:mr-0' : ''
+        data-board
+        className={`@container -ml-4 flex min-w-0 flex-1 flex-col sm:-ml-6 lg:-ml-10 ${
+          chat ? 'max-sm:-mr-4 sm:max-lg:-mr-6 lg:max-[1100px]:-mr-10' : '-mr-4 sm:-mr-6 lg:-mr-10'
         }`}
       >
         {data.messages.enabled && (
@@ -222,7 +228,7 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
                   <PortalListRow
                     key={request.id}
                     as="li"
-                    title={<span className="line-clamp-3">{request.description}</span>}
+                    title={<PortalRequestText text={request.description} />}
                     meta={joined([
                       t('requestSent', { day: format.day(request.createdAt) }),
                       request.vehicle?.label,

+ 3 - 3
src/features/portal/Components/Themes/Garage/SignIn.tsx

@@ -66,7 +66,7 @@ export async function SignIn({
   return (
     <div className="grid flex-1 min-[1100px]:grid-cols-[minmax(0,7fr)_minmax(0,5fr)] min-[1100px]:grid-rows-[1fr_auto]">
       <header className="flex min-w-0 flex-col min-[1100px]:col-start-1 min-[1100px]:row-start-1">
-        <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 px-5 py-4 sm:px-8 min-[1100px]:min-h-24 min-[1100px]:px-12">
+        <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 px-5 py-4 sm:max-[1100px]:px-8 min-[1100px]:min-h-24 min-[1100px]:px-12">
           <div className="flex min-w-0 items-center gap-3.5">
             <PortalWorkshopMark name={workshop.name} logoUrl={workshop.logoUrl} size={44} />
             <h1 className="p-display min-w-0 text-[26px] leading-[1.05] tracking-[0.04em] sm:text-[32px]">
@@ -80,7 +80,7 @@ export async function SignIn({
         </div>
 
         <div
-          className={`@container relative mx-5 mb-5 flex flex-col overflow-hidden border border-[color:var(--p-line-strong)] bg-[var(--p-photo)] sm:mx-8 sm:mb-8 sm:min-h-[320px] sm:justify-end min-[1100px]:mx-12 min-[1100px]:flex-1 ${
+          className={`@container relative mx-5 mb-5 flex flex-col overflow-hidden border border-[color:var(--p-line-strong)] bg-[var(--p-photo)] sm:max-[1100px]:mx-8 sm:mb-8 sm:min-h-[320px] sm:justify-end min-[1100px]:mx-12 min-[1100px]:flex-1 ${
             coverUrl ? '' : 'min-h-[150px] justify-end'
           }`}
         >
@@ -124,7 +124,7 @@ export async function SignIn({
         </div>
       </header>
 
-      <main className="flex items-center border-t bg-[var(--p-surface)] px-5 py-10 sm:px-8 sm:py-14 min-[1100px]:col-start-2 min-[1100px]:row-span-2 min-[1100px]:row-start-1 min-[1100px]:border-l min-[1100px]:border-t-0 min-[1100px]:px-[clamp(40px,5vw,72px)]">
+      <main className="flex items-center border-t bg-[var(--p-surface)] px-5 py-10 sm:max-[1100px]:px-8 sm:py-14 min-[1100px]:col-start-2 min-[1100px]:row-span-2 min-[1100px]:row-start-1 min-[1100px]:border-l min-[1100px]:border-t-0 min-[1100px]:px-[clamp(40px,5vw,72px)]">
         {/* On this panel a field is cut into the ground behind it, as on the board. */}
         <div className="mx-auto flex w-full max-w-[520px] flex-col [--p-surface:var(--p-bg)]">
           <p className={`${TAG} self-start bg-[var(--p-accent)] text-[color:var(--p-on-accent)]`}>

+ 7 - 3
src/features/portal/Components/Themes/Print/Home.tsx

@@ -10,6 +10,7 @@ import type {
   PortalHomeTireSet,
 } from '../../../Lib/homeTypes'
 import { PortalAcceptQuoteButton } from '../../Home/PortalAcceptQuoteButton'
+import { PortalRequestText } from '../../Home/PortalRequestText'
 import { portalHeroLine, portalJobLine, portalJobSteps, tireSeasonKey } from '../../Home/homeCopy'
 import { PortalEmptyState, PortalLinkButton, PortalListRow } from '../../Ui'
 import type { PortalHomeProps } from '../types'
@@ -196,6 +197,11 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
                         key={car.id}
                         as="li"
                         href={car.url}
+                        // In a narrow column the mark ("In the workshop") goes
+                        // under the name instead of squeezing it to a word a
+                        // line: the name keeps 8.5rem, or the row less the
+                        // chevron where the column is narrower than that.
+                        className="flex-wrap gap-y-1 [&>span:first-child]:min-w-[min(8.5rem,calc(100%-2rem))] [&>svg]:ml-auto"
                         title={<span className={ROW_TITLE}>{car.label}</span>}
                         meta={joined([
                           car.licensePlate,
@@ -289,9 +295,7 @@ export async function Home({ orgParam, data, format, chat }: PortalHomeProps) {
                     <PortalListRow
                       key={request.id}
                       as="li"
-                      title={
-                        <span className={`${ROW_TITLE} line-clamp-3`}>{request.description}</span>
-                      }
+                      title={<PortalRequestText text={request.description} className={ROW_TITLE} />}
                       meta={joined([
                         t('requestSent', { day: format.day(request.createdAt) }),
                         request.vehicle?.label,

+ 58 - 3
src/features/portal/Lib/chat.server.ts

@@ -1,6 +1,7 @@
 import 'server-only'
 
 import { db } from '@/lib/db'
+import { effectiveInvoiceDate } from '@/lib/invoice-utils'
 import { zonedDayKey } from '@/lib/timezone'
 import { parseUploadUrl } from '@/lib/upload-url'
 import { workshopMoneyFormatter } from '@/lib/workshop-currency'
@@ -276,7 +277,10 @@ export async function getPortalThreadEvents(
         where: {
           ...mine,
           status: 'completed',
-          AND: [{ OR: [{ issuedAt: { gte: since } }, { sentAt: { gte: since } }] }],
+          AND: [
+            { OR: [{ issuedAt: { not: null } }, { sentAt: { not: null } }] },
+            invoiceEventWindow(since),
+          ],
         },
         select: {
           id: true,
@@ -285,6 +289,9 @@ export async function getPortalThreadEvents(
           totalAmount: true,
           issuedAt: true,
           sentAt: true,
+          invoiceDate: true,
+          startDateTime: true,
+          serviceDate: true,
           invoiceDueDate: true,
           manuallyPaid: true,
           payments: { select: { amount: true } },
@@ -306,6 +313,7 @@ export async function getPortalThreadEvents(
         id: `work_started:${job.id}`,
         kind: 'work_started',
         at: at.toISOString(),
+        dayOnly: false,
         vehicle: carName(job.vehicle),
         title: job.title || null,
         amount: null,
@@ -320,6 +328,7 @@ export async function getPortalThreadEvents(
         id: `update:${report.id}`,
         kind: 'update',
         at: report.sentAt.toISOString(),
+        dayOnly: false,
         vehicle: carName(report.serviceRecord?.vehicle),
         title: shorten(report.message) ?? shorten(report.title),
         amount: null,
@@ -335,6 +344,7 @@ export async function getPortalThreadEvents(
         id: `quote:${quote.id}`,
         kind: 'quote',
         at: at.toISOString(),
+        dayOnly: false,
         vehicle: carName(quote.vehicle),
         title: quote.title || quote.quoteNumber || null,
         amount: money(quote.totalAmount),
@@ -345,8 +355,8 @@ export async function getPortalThreadEvents(
     }
     const today = zonedDayKey(now, timeZone)
     for (const invoice of invoices) {
-      const at = invoice.issuedAt ?? invoice.sentAt
-      if (!at || at < since) continue
+      const { at, dayOnly } = invoiceEventTime(invoice)
+      if (at < since) continue
       // Overdue is owed money past its due day, and that day is the workshop's.
       const owed = portalPayment(invoice).balance > 0
       const overdue =
@@ -355,6 +365,7 @@ export async function getPortalThreadEvents(
         id: `invoice:${invoice.id}`,
         kind: 'invoice',
         at: at.toISOString(),
+        dayOnly,
         vehicle: carName(invoice.vehicle),
         title: invoice.invoiceNumber || invoice.title || null,
         amount: money(invoice.totalAmount),
@@ -370,6 +381,50 @@ export async function getPortalThreadEvents(
   }
 }
 
+/**
+ * When an invoice stands in the thread: the moment the customer would
+ * recognise.
+ *
+ * That is when it was sent to them, a real moment with a time of day. An
+ * invoice that was never sent (shared by link only, or paid at the counter)
+ * stands on its own date, the one printed on it and shown on its page in the
+ * portal (`effectiveInvoiceDate`: the invoice date, else the scheduled start,
+ * else the day of the work): a calendar day, so the chat shows the day and
+ * no clock time. `issuedAt` is never it: that is when the sheet was frozen,
+ * which can be a payment weeks after the work, and its time of day means
+ * nothing to a customer.
+ *
+ * `invoiceEventWindow` is the same precedence as a query: change both together.
+ */
+export function invoiceEventTime(invoice: {
+  sentAt: Date | null
+  invoiceDate?: Date | null
+  startDateTime?: Date | null
+  serviceDate: Date
+}): { at: Date; dayOnly: boolean } {
+  if (invoice.sentAt) return { at: invoice.sentAt, dayOnly: false }
+  return { at: effectiveInvoiceDate(invoice), dayOnly: true }
+}
+
+/**
+ * The invoices whose place in the thread (`invoiceEventTime`) is on or after
+ * `since`, as a Prisma filter. Each fallback only counts for a row that has
+ * no date of higher rank, so the rows the query returns are the rows that
+ * are drawn: a filter on any of the dates let old invoices in by a date that
+ * is not the one they stand on, and they used up the row limit before being
+ * dropped, hiding a recent invoice.
+ */
+export function invoiceEventWindow(since: Date) {
+  return {
+    OR: [
+      { sentAt: { gte: since } },
+      { sentAt: null, invoiceDate: { gte: since } },
+      { sentAt: null, invoiceDate: null, startDateTime: { gte: since } },
+      { sentAt: null, invoiceDate: null, startDateTime: null, serviceDate: { gte: since } },
+    ],
+  }
+}
+
 /**
  * From when a thread shows events. The window is `days` long, and it never
  * starts before the oldest loaded message while older messages are still

+ 8 - 0
src/features/portal/Lib/chatTypes.ts

@@ -57,6 +57,12 @@ export interface PortalChatEvent {
   kind: PortalChatEventKind
   /** When it happened. */
   at: string
+  /**
+   * `at` is a calendar day and not a moment: an invoice that was never sent
+   * stands on its own date, which has no time of day. The chat prints the day
+   * for it and never a clock time.
+   */
+  dayOnly: boolean
   /** "Volvo V60", when the record is about a car. */
   vehicle: string | null
   /** The job's, quote's or invoice's own title, or what the workshop wrote with an update. */
@@ -142,6 +148,8 @@ export const portalChatEventSchema = z.object({
   id: z.string(),
   kind: z.enum(['work_started', 'update', 'quote', 'invoice']),
   at: z.string(),
+  // Left out by a server from before the field existed: a moment, as before.
+  dayOnly: z.boolean().default(false),
   vehicle: z.string().nullable(),
   title: z.string().nullable(),
   amount: z.string().nullable(),

+ 50 - 0
src/features/portal/Lib/requestText.ts

@@ -0,0 +1,50 @@
+import { REQUEST_TOPIC_LABELS } from './requestTopics'
+
+/**
+ * What a customer sent from the booking page, taken apart for showing.
+ *
+ * The booking form offers quick choices ("Something is wrong", "Tyres") and
+ * stores the chosen one as the first line of the request's description, a
+ * blank line, then the customer's own words. Printed as one paragraph the two
+ * run together ("Something is wrong A knocking noise…"), so every place that
+ * shows a request shows the choice as a line of its own and the words after.
+ *
+ * A customer can also write several paragraphs without picking anything, so
+ * a short first paragraph proves nothing: the first line is a choice only
+ * when it is exactly one of the form's own labels, in any of the portal's
+ * languages (`requestTopics.ts`). Everything else is shown as it was written.
+ * A request has no column for the choice; with one, the form could send it
+ * apart from the words and none of this would be read back out of the text.
+ *
+ * Server only (it knows every language's labels): a client component is
+ * handed the parts by the page that renders it.
+ */
+
+export interface RequestTextParts {
+  /** The quick choice, when the request starts with one and words follow it. */
+  topic: string | null
+  /** The customer's words; the whole text when there is no choice to set apart. */
+  body: string
+}
+
+export function splitRequestText(text: string | null | undefined): RequestTextParts {
+  const whole = (text ?? '').trim()
+  const match = /^([^\r\n]+)\r?\n[ \t]*\r?\n([\s\S]+)$/.exec(whole)
+  if (!match) return { topic: null, body: whole }
+  const topic = match[1].trim()
+  const body = match[2].trim()
+  if (!body || !REQUEST_TOPIC_LABELS.has(topic)) return { topic: null, body: whole }
+  return { topic, body }
+}
+
+/**
+ * A request as one line, for the title of the work order made from it: the
+ * choice, a colon, then the words, cut to `max` characters. The stored text
+ * has a blank line between the two, which a title prints as a space, so the
+ * choice ran into the words there too.
+ */
+export function requestTitle(text: string | null | undefined, max = 60): string {
+  const { topic, body } = splitRequestText(text)
+  const line = (topic ? `${topic}: ${body}` : body).replace(/\s+/g, ' ').trim()
+  return line.length > max ? `${line.slice(0, max - 3)}...` : line
+}

+ 37 - 0
src/features/portal/Lib/requestTopics.ts

@@ -0,0 +1,37 @@
+import 'server-only'
+
+import de from '../../../../messages/de/portal.json'
+import en from '../../../../messages/en/portal.json'
+import es from '../../../../messages/es/portal.json'
+import fr from '../../../../messages/fr/portal.json'
+import it from '../../../../messages/it/portal.json'
+import lt from '../../../../messages/lt/portal.json'
+import nb from '../../../../messages/nb/portal.json'
+import nl from '../../../../messages/nl/portal.json'
+import pl from '../../../../messages/pl/portal.json'
+import ptBR from '../../../../messages/pt-BR/portal.json'
+import ptPT from '../../../../messages/pt-PT/portal.json'
+import ru from '../../../../messages/ru/portal.json'
+import tr from '../../../../messages/tr/portal.json'
+
+/**
+ * Every label a quick choice on the booking page can have ("Service",
+ * "Bremser", "Algo no va bien"), in every language the portal speaks.
+ *
+ * The booking form stores the chosen label as the first line of the request,
+ * in the customer's language, and a request has no column that says a choice
+ * was made. So a first line is a choice only when it is exactly one of these:
+ * read from the message files themselves (`portal.book.topics`), so a new
+ * choice or a corrected translation is known here without anyone remembering
+ * to add it. A test fails when a locale is missing from this list.
+ *
+ * Server only: this pulls every locale's portal messages in, which must
+ * never reach a browser.
+ */
+const PORTAL_MESSAGES = [de, en, es, fr, it, lt, nb, nl, pl, ptBR, ptPT, ru, tr]
+
+export const REQUEST_TOPIC_LABELS: ReadonlySet<string> = new Set(
+  PORTAL_MESSAGES.flatMap((messages) => Object.values(messages.book.topics)).map((label) =>
+    label.trim()
+  )
+)

+ 5 - 1
src/features/portal/portal-themes.css

@@ -399,7 +399,11 @@
     line-height: 1.5;
     font-variant-numeric: tabular-nums;
     -webkit-font-smoothing: antialiased;
-    overflow-wrap: anywhere;
+    /* A word too long for its line (an address, a part number) breaks rather
+       than run out of its box. `break-word`, not `anywhere`: with `anywhere`
+       a box may be sized as if every letter could stand alone, so a heading
+       or a label beside something wide was squeezed to one letter a line. */
+    overflow-wrap: break-word;
   }
   /* The same colours and type for content a library draws outside the root. */
   .portal-scope {