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

Fix clipped labels, repeated PDF mark, raw ids and other display issues (#687)

* Fix clipped labels, repeated PDF mark, raw ids and other display issues

* Pass the app's transaction client to the layout clean-up

* Keep the PDF mark on every page and lock layouts while a field is deleted
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
7ebc2300dd
34 измененных файлов с 1012 добавлено и 213 удалено
  1. 3 3
      messages/bg/laborPresets.json
  2. 2 2
      messages/de/laborPresets.json
  3. 7 7
      messages/en/laborPresets.json
  4. 2 2
      messages/es/laborPresets.json
  5. 2 2
      messages/fr/laborPresets.json
  6. 2 2
      messages/it/laborPresets.json
  7. 3 3
      messages/lt/laborPresets.json
  8. 2 2
      messages/nb/laborPresets.json
  9. 2 2
      messages/nl/laborPresets.json
  10. 2 2
      messages/pl/laborPresets.json
  11. 3 3
      messages/pt-BR/laborPresets.json
  12. 2 2
      messages/pt-PT/laborPresets.json
  13. 2 2
      messages/ru/laborPresets.json
  14. 2 2
      messages/tr/laborPresets.json
  15. 106 0
      src/__tests__/db/custom-field-delete-race.db.test.ts
  16. 159 0
      src/__tests__/features/custom-fields/delete-drops-layout-field.test.ts
  17. 97 0
      src/__tests__/features/dashboard-recent-cards.test.tsx
  18. 83 0
      src/__tests__/features/labor-presets/preset-counts.test.tsx
  19. 1 1
      src/__tests__/features/labor-presets/preset-item-name.test.tsx
  20. 127 15
      src/__tests__/features/settings/spec-pdf-print.test.tsx
  21. 29 0
      src/__tests__/lib/share-expiry.test.ts
  22. 12 4
      src/app/(authenticated)/(dashboard)/dashboard-client.tsx
  23. 5 2
      src/app/(authenticated)/customers/customers-client.tsx
  24. 7 16
      src/app/(authenticated)/labor-presets/labor-presets-client.tsx
  25. 9 4
      src/features/custom-fields/Actions/customFieldActions.ts
  26. 108 0
      src/features/custom-fields/Lib/dropFieldFromLayouts.ts
  27. 101 28
      src/features/invoice-designer/Spec/buildSpec.ts
  28. 3 7
      src/features/labor-presets/Components/LaborPresetPickerDialog.tsx
  29. 19 0
      src/features/labor-presets/Lib/presetTotals.ts
  30. 30 46
      src/features/quotes/Components/QuotePDF.tsx
  31. 30 46
      src/features/vehicles/Components/invoice-pdf/InvoicePDF.tsx
  32. 5 2
      src/features/vehicles/Components/service-detail/PaymentsSection.tsx
  33. 41 5
      src/features/vehicles/Components/service-edit/TotalsSection.tsx
  34. 4 1
      src/lib/share-expiry.ts

+ 3 - 3
messages/bg/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Описание",
     "itemCount": "Позиции",
     "type": "Тип",
-    "hrs": "ч",
-    "units": "ед."
+    "hoursCount": "{hours, number} ч",
+    "unitsCount": "{units, number} ед."
   },
   "empty": {
     "noMatch": "Няма пакети, съответстващи на търсенето.",
@@ -43,7 +43,7 @@
     "itemDescriptionPlaceholder": "Описание *",
     "addItem": "Добави позиция",
     "cancel": "Отказ",
-    "create": "Създай пакет",
+    "create": "Създай",
     "saveChanges": "Запази промените",
     "hourlyTag": "HR",
     "serviceTag": "SVC",

+ 2 - 2
messages/de/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Beschreibung",
     "itemCount": "Positionen",
     "type": "Typ",
-    "hrs": "Std.",
-    "units": "Einheit(en)"
+    "hoursCount": "{hours, number} Std.",
+    "unitsCount": "{units, number} Einheit(en)"
   },
   "empty": {
     "noMatch": "Keine Vorlagen entsprechen Ihrer Suche.",

+ 7 - 7
messages/en/laborPresets.json

@@ -6,12 +6,12 @@
     "description": "Description",
     "itemCount": "Items",
     "type": "Type",
-    "hrs": "hrs",
-    "units": "unit(s)"
+    "hoursCount": "{hours, plural, one {# hr} other {# hrs}}",
+    "unitsCount": "{units, plural, one {# unit} other {# units}}"
   },
   "empty": {
     "noMatch": "No packages match your search.",
-    "noPresets": "No labor packages yet. Click \"Add Package\" to create one."
+    "noPresets": "No labor packages yet. Click \"Add Labor Preset\" to create one."
   },
   "actions": {
     "edit": "Edit",
@@ -43,7 +43,7 @@
     "itemDescriptionPlaceholder": "Description *",
     "addItem": "Add Item",
     "cancel": "Cancel",
-    "create": "Create Package",
+    "create": "Create Preset",
     "saveChanges": "Save Changes",
     "hourlyTag": "HR",
     "serviceTag": "SVC",
@@ -61,10 +61,10 @@
     "title": "Select Labor Package",
     "search": "Search packages...",
     "noPackages": "No labor packages found.",
-    "items": "{count} items",
+    "items": "{count, plural, one {# item} other {# items}}",
     "totalHours": "{hours}h total",
-    "totalUnits": "{units} unit(s)",
-    "totalParts": "{count} parts"
+    "totalUnits": "{units, plural, one {# unit} other {# units}}",
+    "totalParts": "{count, plural, one {# part} other {# parts}}"
   },
   "errors": {
     "error": "Error",

+ 2 - 2
messages/es/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Descripción",
     "itemCount": "Elementos",
     "type": "Tipo",
-    "hrs": "h",
-    "units": "unidad(es)"
+    "hoursCount": "{hours, number} h",
+    "unitsCount": "{units, plural, one {# unidad} other {# unidades}}"
   },
   "empty": {
     "noMatch": "Ninguna plantilla coincide con su búsqueda.",

+ 2 - 2
messages/fr/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Description",
     "itemCount": "Éléments",
     "type": "Type",
-    "hrs": "h",
-    "units": "unité(s)"
+    "hoursCount": "{hours, number} h",
+    "unitsCount": "{units, plural, one {# unité} other {# unités}}"
   },
   "empty": {
     "noMatch": "Aucun modèle ne correspond à votre recherche.",

+ 2 - 2
messages/it/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Descrizione",
     "itemCount": "Voci",
     "type": "Tipo",
-    "hrs": "ore",
-    "units": "unità"
+    "hoursCount": "{hours, plural, one {# ora} other {# ore}}",
+    "unitsCount": "{units, number} unità"
   },
   "empty": {
     "noMatch": "Nessun modello corrisponde alla ricerca.",

+ 3 - 3
messages/lt/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Aprašymas",
     "itemCount": "Elementai",
     "type": "Tipas",
-    "hrs": "val.",
-    "units": "vnt."
+    "hoursCount": "{hours, number} val.",
+    "unitsCount": "{units, number} vnt."
   },
   "empty": {
     "noMatch": "Nėra šablonų, atitinkančių paiešką.",
@@ -43,7 +43,7 @@
     "itemDescriptionPlaceholder": "Aprašymas *",
     "addItem": "Pridėti elementą",
     "cancel": "Atšaukti",
-    "create": "Sukurti paketą",
+    "create": "Sukurti",
     "saveChanges": "Išsaugoti pakeitimus",
     "hourlyTag": "VAL",
     "serviceTag": "PSL",

+ 2 - 2
messages/nb/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Beskrivelse",
     "itemCount": "Elementer",
     "type": "Type",
-    "hrs": "timer",
-    "units": "enhet(er)"
+    "hoursCount": "{hours, number} t",
+    "unitsCount": "{units, plural, one {# enhet} other {# enheter}}"
   },
   "empty": {
     "noMatch": "Ingen maler samsvarer med søket ditt.",

+ 2 - 2
messages/nl/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Beschrijving",
     "itemCount": "Posten",
     "type": "Type",
-    "hrs": "u",
-    "units": "eenh."
+    "hoursCount": "{hours, number} u",
+    "unitsCount": "{units, number} eenh."
   },
   "empty": {
     "noMatch": "Geen sjablonen komen overeen met uw zoekopdracht.",

+ 2 - 2
messages/pl/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Opis",
     "itemCount": "Pozycje",
     "type": "Typ",
-    "hrs": "godz.",
-    "units": "szt."
+    "hoursCount": "{hours, number} godz.",
+    "unitsCount": "{units, number} szt."
   },
   "empty": {
     "noMatch": "Żadne szablony nie pasują do wyszukiwania.",

+ 3 - 3
messages/pt-BR/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Descrição",
     "itemCount": "Itens",
     "type": "Tipo",
-    "hrs": "h",
-    "units": "unidade(s)"
+    "hoursCount": "{hours, number} h",
+    "unitsCount": "{units, plural, one {# unidade} other {# unidades}}"
   },
   "empty": {
     "noMatch": "Nenhum modelo corresponde à sua pesquisa.",
@@ -41,7 +41,7 @@
     "itemDescriptionPlaceholder": "Descrição *",
     "addItem": "Adicionar item",
     "cancel": "Cancelar",
-    "create": "Criar pacote",
+    "create": "Criar",
     "saveChanges": "Salvar alterações",
     "itemQty": "Qtd",
     "itemQtyOrHours": "Unidade / Horas",

+ 2 - 2
messages/pt-PT/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Descrição",
     "itemCount": "Itens",
     "type": "Tipo",
-    "hrs": "h",
-    "units": "unidade(s)"
+    "hoursCount": "{hours, number} h",
+    "unitsCount": "{units, plural, one {# unidade} other {# unidades}}"
   },
   "empty": {
     "noMatch": "Nenhum modelo corresponde à sua pesquisa.",

+ 2 - 2
messages/ru/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Описание",
     "itemCount": "Позиции",
     "type": "Тип",
-    "hrs": "ч.",
-    "units": "усл."
+    "hoursCount": "{hours, number} ч.",
+    "unitsCount": "{units, number} усл."
   },
   "empty": {
     "noMatch": "Шаблоны не найдены.",

+ 2 - 2
messages/tr/laborPresets.json

@@ -6,8 +6,8 @@
     "description": "Açıklama",
     "itemCount": "Kalemler",
     "type": "Tür",
-    "hrs": "saat",
-    "units": "adet"
+    "hoursCount": "{hours, number} saat",
+    "unitsCount": "{units, number} adet"
   },
   "empty": {
     "noMatch": "Aramanızla eşleşen şablon bulunamadı.",

+ 106 - 0
src/__tests__/db/custom-field-delete-race.db.test.ts

@@ -0,0 +1,106 @@
+/**
+ * Two custom fields deleted at the same moment, on a real PostgreSQL
+ * (`npm run test:db` with E2E_DATABASE_URL set).
+ *
+ * Deleting a field takes it out of every saved layout. Each delete reads the
+ * layout, drops its field and writes the layout back. Two at once could both
+ * read the layout as it was, and the later write would put back the field
+ * the earlier one took out. The layout rows are locked before they are read,
+ * so the second waits for the first and reads what it wrote.
+ *
+ * It makes one person and one workshop of its own and removes them again.
+ */
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+const url = process.env.E2E_DATABASE_URL ?? ''
+const databaseName = url.split('/').pop()?.split('?')[0]?.toLowerCase() ?? ''
+if (url && !/test|e2e/.test(databaseName)) {
+  throw new Error(
+    `Refusing to use database "${databaseName}": its name must say test or e2e, like the rest of this suite.`
+  )
+}
+
+process.env.DATABASE_URL = url
+
+const stamp = randomUUID().slice(0, 8)
+
+let db: typeof import('@/lib/db')['db']
+let drop: typeof import('@/features/custom-fields/Lib/dropFieldFromLayouts')['dropFieldFromLayouts']
+let organizationId = ''
+let userId = ''
+
+const layout = {
+  sections: [
+    {
+      id: 'general',
+      visible: true,
+      order: 0,
+      fields: [
+        { id: 'cf_one', visible: true },
+        { id: 'cf_two', visible: true },
+        { id: 'cf_kept', visible: true },
+      ],
+    },
+  ],
+}
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  ;({ dropFieldFromLayouts: drop } = await import(
+    '@/features/custom-fields/Lib/dropFieldFromLayouts'
+  ))
+  const user = await db.user.create({
+    data: { name: `Fields ${stamp}`, email: `fields-${stamp}@example.com` },
+  })
+  userId = user.id
+  const organization = await db.organization.create({ data: { name: `Fields ${stamp}` } })
+  organizationId = organization.id
+  await db.appSetting.create({
+    data: {
+      userId,
+      organizationId,
+      key: 'invoice.layoutConfig',
+      value: JSON.stringify(layout),
+    },
+  })
+  await db.documentDesign.create({
+    data: { organizationId, documentType: 'invoice', name: 'Mine', layout, template: {} },
+  })
+})
+
+afterAll(async () => {
+  if (organizationId) await db.organization.delete({ where: { id: organizationId } })
+  if (userId) await db.user.delete({ where: { id: userId } })
+  await db.$disconnect()
+})
+
+const fieldsIn = (stored: unknown) => (stored as typeof layout).sections[0].fields.map((f) => f.id)
+
+describe('two custom fields deleted at once', () => {
+  it('leaves both out of the saved layouts', async () => {
+    const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+    // The first holds its transaction open after writing, long enough for the
+    // second to start and read. Without the lock the second reads the layout
+    // with the first field still in it, and writes that back.
+    const first = db.$transaction(
+      async (tx) => {
+        await drop(tx, organizationId, 'one')
+        await pause(800)
+      },
+      { timeout: 20_000 }
+    )
+    await pause(200)
+    const second = db.$transaction((tx) => drop(tx, organizationId, 'two'), {
+      timeout: 20_000,
+    })
+    await Promise.all([first, second])
+
+    const setting = await db.appSetting.findFirstOrThrow({
+      where: { organizationId, key: 'invoice.layoutConfig' },
+    })
+    expect(fieldsIn(JSON.parse(setting.value))).toEqual(['cf_kept'])
+    const design = await db.documentDesign.findFirstOrThrow({ where: { organizationId } })
+    expect(fieldsIn(design.layout)).toEqual(['cf_kept'])
+  })
+})

+ 159 - 0
src/__tests__/features/custom-fields/delete-drops-layout-field.test.ts

@@ -0,0 +1,159 @@
+/**
+ * @vitest-environment node
+ *
+ * Deleting a custom field used to leave it in the saved invoice layout: the
+ * definition was gone, but the arrangement still listed it, switched on, in
+ * General. It now leaves every arrangement that named it, and nothing else
+ * about those arrangements changes.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const state = vi.hoisted(() => ({
+  settings: [] as { id: string; key: string; value: string }[],
+  designs: [] as { id: string; layout: unknown }[],
+  writes: [] as { model: string; where: unknown; data: Record<string, unknown> }[],
+  deleted: [] as string[],
+}))
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(async () => ({ user: { id: 'user-a', email: 'a@x.test' } })),
+  getCachedMembership: vi.fn(async () => ({
+    organizationId: 'org-a',
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  })),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn(), auditDetails: vi.fn(() => undefined) }))
+vi.mock('@/lib/features', () => ({
+  requireFeature: vi.fn(),
+  getFeatures: vi.fn(async () => ({})),
+}))
+
+vi.mock('@/lib/db', () => {
+  const tx = {
+    // The row locks; what they guard is tested on a real database in
+    // src/__tests__/db/custom-field-delete-race.db.test.ts.
+    $queryRaw: async () => [],
+    user: { findUnique: async () => ({ isSuperAdmin: false }) },
+    customFieldDefinition: {
+      findFirst: async ({ where }: { where: { id: string; organizationId: string } }) =>
+        where.id === 'def-1' && where.organizationId === 'org-a'
+          ? { id: 'def-1', name: 'insurance_no' }
+          : null,
+      delete: async ({ where }: { where: { id: string } }) => {
+        state.deleted.push(where.id)
+        return {}
+      },
+    },
+    customFieldValue: { deleteMany: async () => ({ count: 0 }) },
+    appSetting: {
+      findMany: async ({ where }: { where: { organizationId: string } }) =>
+        where.organizationId === 'org-a' ? state.settings : [],
+      update: async (args: { where: unknown; data: Record<string, unknown> }) => {
+        state.writes.push({ model: 'appSetting', ...args })
+        return {}
+      },
+    },
+    documentDesign: {
+      findMany: async ({ where }: { where: { organizationId: string } }) =>
+        where.organizationId === 'org-a' ? state.designs : [],
+      update: async (args: { where: unknown; data: Record<string, unknown> }) => {
+        state.writes.push({ model: 'documentDesign', ...args })
+        return {}
+      },
+    },
+  }
+  return {
+    db: {
+      ...tx,
+      $transaction: async (fn: (client: typeof tx) => Promise<unknown>) => fn(tx),
+    },
+  }
+})
+
+import { deleteFieldDefinition } from '@/features/custom-fields/Actions/customFieldActions'
+import { layoutWithoutField } from '@/features/custom-fields/Lib/dropFieldFromLayouts'
+
+const layout = (generalVisible: boolean, extra: { id: string; visible: boolean }[] = []) => ({
+  version: 2,
+  sections: [
+    { id: 'header', visible: true, order: 0 },
+    {
+      id: 'customer',
+      visible: true,
+      order: 1,
+      fields: [{ id: 'customer_name', visible: true }, ...extra],
+    },
+    {
+      id: 'general',
+      visible: generalVisible,
+      order: 2,
+      fields: [
+        { id: 'cf_def-1', visible: true },
+        { id: 'cf_def-2', visible: true },
+      ],
+    },
+  ],
+})
+
+beforeEach(() => {
+  state.settings = []
+  state.designs = []
+  state.writes = []
+  state.deleted = []
+})
+
+describe('deleting a custom field', () => {
+  it('drops it from the saved invoice layout and the saved designs', async () => {
+    state.settings = [
+      { id: 's-1', key: 'invoice.layoutConfig', value: JSON.stringify(layout(true)) },
+      // A layout that never placed the field is not written at all.
+      {
+        id: 's-2',
+        key: 'quote.layoutConfig',
+        value: JSON.stringify({ sections: [{ id: 'general', visible: false, order: 0 }] }),
+      },
+    ]
+    state.designs = [{ id: 'd-1', layout: layout(false, [{ id: 'cf_def-1', visible: true }]) }]
+
+    expect((await deleteFieldDefinition('def-1')).success).toBe(true)
+    expect(state.deleted).toEqual(['def-1'])
+
+    expect(state.writes.map((w) => w.model)).toEqual(['appSetting', 'documentDesign'])
+    const invoice = JSON.parse(state.writes[0].data.value as string)
+    const general = invoice.sections.find((s: { id: string }) => s.id === 'general')
+    expect(general.fields).toEqual([{ id: 'cf_def-2', visible: true }])
+    // The section keeps the on/off the workshop gave it.
+    expect(general.visible).toBe(true)
+
+    const design = state.writes[1].data.layout as ReturnType<typeof layout>
+    expect(JSON.stringify(design)).not.toContain('cf_def-1')
+    expect(design.sections.find((s) => s.id === 'general')?.visible).toBe(false)
+  })
+
+  it('changes no layout for a field of another workshop', async () => {
+    state.settings = [
+      { id: 's-1', key: 'invoice.layoutConfig', value: JSON.stringify(layout(true)) },
+    ]
+    expect((await deleteFieldDefinition('def-other')).success).toBe(false)
+    expect(state.writes).toEqual([])
+  })
+})
+
+describe('a layout without one field', () => {
+  it('is null when the field was nowhere in it', () => {
+    expect(layoutWithoutField(layout(true), 'def-9')).toBeNull()
+    expect(layoutWithoutField(null, 'def-1')).toBeNull()
+    expect(layoutWithoutField({ sections: 'broken' }, 'def-1')).toBeNull()
+  })
+
+  it('keeps everything else as it was stored', () => {
+    const stored = layout(true, [{ id: 'cf_def-1', visible: false }])
+    const next = layoutWithoutField(stored, 'def-1') as ReturnType<typeof layout>
+    expect(next.version).toBe(2)
+    expect(next.sections.map((s) => s.visible)).toEqual([true, true, true])
+    expect(next.sections[1].fields).toEqual([{ id: 'customer_name', visible: true }])
+  })
+})

+ 97 - 0
src/__tests__/features/dashboard-recent-cards.test.tsx

@@ -0,0 +1,97 @@
+/**
+ * The dashboard's Recent Activity and Recent Observations cards speak the
+ * workshop's words: a record by a name somebody knows it by, never by its
+ * database id ("— cmwuyxad"), and a severity as High, Medium or Low rather
+ * than the stored key ("needs_work").
+ */
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/',
+  useSearchParams: () => new URLSearchParams(),
+}))
+
+// The grid waits for a measured width jsdom never reports; the cards are what
+// is under test, so they are drawn as a plain list.
+vi.mock('@/features/dashboard/Components/DashboardGrid', () => ({
+  DashboardGrid: ({ cardNodes }: { cardNodes: Record<string, React.ReactNode> }) => (
+    <div>
+      {Object.entries(cardNodes).map(([id, node]) => (
+        <section key={id}>{node}</section>
+      ))}
+    </div>
+  ),
+}))
+
+import { DashboardClient } from '@/app/(authenticated)/(dashboard)/dashboard-client'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+
+const show = (ui: React.ReactElement) => render(<ConfirmProvider>{ui}</ConfirmProvider>)
+
+const stats = {
+  isAdmin: true,
+  activeJobs: 0,
+  pendingJobs: 0,
+  totalParts: 0,
+  lowStockParts: 0,
+  totalCustomers: 0,
+  todaysServices: [],
+  recentServices: [],
+}
+
+const vehicle = { id: 'v-1', make: 'Ford', model: 'Ranger', year: 2022, licensePlate: 'ZZ22 WLK' }
+
+describe('the dashboard', () => {
+  it('names a record without printing its id', () => {
+    show(
+      <DashboardClient
+        stats={stats}
+        recentAuditLogs={[
+          {
+            id: 'log-1',
+            timestamp: new Date('2026-11-24T10:00:00Z'),
+            action: 'serviceRecord.update',
+            entity: 'ServiceRecord',
+            entityId: 'cmwuyxad0000abcd',
+            message: 'Updated service record 2026-1002',
+            user: { id: 'u-1', name: 'ZZ Agent Walker', email: null },
+          },
+        ]}
+      />
+    )
+    expect(screen.getByText('Updated service record 2026-1002')).toBeInTheDocument()
+    expect(screen.queryByText(/cmwuyxad/)).not.toBeInTheDocument()
+  })
+
+  it('shows an observation’s severity in words', () => {
+    show(
+      <DashboardClient
+        stats={stats}
+        recentObservations={[
+          {
+            id: 'o-1',
+            description: 'ZZ P0300',
+            severity: 'needs_work',
+            notes: null,
+            createdAt: new Date(),
+            vehicle,
+          },
+          {
+            id: 'o-2',
+            description: 'ZZ Rear pads at 3 mm',
+            severity: 'urgent',
+            notes: null,
+            createdAt: new Date(),
+            vehicle,
+          },
+        ]}
+      />
+    )
+    expect(screen.getAllByText('Medium').length).toBeGreaterThan(0)
+    expect(screen.getAllByText('High').length).toBeGreaterThan(0)
+    expect(screen.queryByText('needs_work')).not.toBeInTheDocument()
+    expect(screen.queryByText('urgent')).not.toBeInTheDocument()
+  })
+})

+ 83 - 0
src/__tests__/features/labor-presets/preset-counts.test.tsx

@@ -0,0 +1,83 @@
+/**
+ * The counts beside a labor preset read as English: "1 item", not "1 items",
+ * and a quarter hour is not rounded away ("1.25h", not "1.3h").
+ */
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import {
+  type LaborPresetOption,
+  LaborPresetPickerDialog,
+} from '@/features/labor-presets/Components/LaborPresetPickerDialog'
+import { presetTotals } from '@/features/labor-presets/Lib/presetTotals'
+
+const preset = (over: Partial<LaborPresetOption>): LaborPresetOption => ({
+  id: 'p-1',
+  name: 'ZZ Brake service',
+  description: null,
+  items: [],
+  parts: [],
+  ...over,
+})
+
+const item = (hours: number, pricingType = 'hourly', sortOrder = 0) => ({
+  description: 'ZZ line',
+  hours,
+  rate: 90,
+  pricingType,
+  sortOrder,
+})
+
+const part = {
+  name: 'ZZ pad set',
+  partNumber: null,
+  quantity: 1,
+  unit: null,
+  unitPrice: 40,
+  inventoryPartId: null,
+  sortOrder: 0,
+}
+
+function showPicker(presets: LaborPresetOption[]) {
+  render(
+    <LaborPresetPickerDialog
+      open
+      onOpenChange={vi.fn()}
+      laborPresets={presets}
+      onSelectPreset={vi.fn()}
+    />
+  )
+}
+
+describe('the labor preset picker', () => {
+  it('counts one item, one part and one unit in the singular', () => {
+    showPicker([preset({ items: [item(1, 'service')], parts: [part] })])
+    expect(screen.getByText('1 item')).toBeInTheDocument()
+    expect(screen.getByText('1 part')).toBeInTheDocument()
+    expect(screen.getByText('1 unit')).toBeInTheDocument()
+  })
+
+  it('counts more than one in the plural', () => {
+    showPicker([
+      preset({ items: [item(1, 'service'), item(1, 'service', 1)], parts: [part, part] }),
+    ])
+    expect(screen.getByText('2 items')).toBeInTheDocument()
+    expect(screen.getByText('2 parts')).toBeInTheDocument()
+    expect(screen.getByText('2 units')).toBeInTheDocument()
+  })
+
+  it('shows a quarter hour as it is', () => {
+    showPicker([preset({ items: [item(0.75), item(0.5, 'hourly', 1)] })])
+    expect(screen.getByText('1.25h total')).toBeInTheDocument()
+  })
+})
+
+describe('a preset’s totals', () => {
+  it('keeps two decimals and drops float noise', () => {
+    expect(presetTotals([item(0.1), item(0.2)])).toEqual({ totalHours: 0.3, totalUnits: 0 })
+    expect(presetTotals([item(1.125), item(0.004)])).toEqual({ totalHours: 1.13, totalUnits: 0 })
+    expect(presetTotals([item(2, 'service'), item(1.25)])).toEqual({
+      totalHours: 1.25,
+      totalUnits: 2,
+    })
+  })
+})

+ 1 - 1
src/__tests__/features/labor-presets/preset-item-name.test.tsx

@@ -38,7 +38,7 @@ function renderForm() {
 
 const save = async () => {
   await act(async () => {
-    fireEvent.click(screen.getByRole('button', { name: 'Create Package' }))
+    fireEvent.click(screen.getByRole('button', { name: 'Create Preset' }))
   })
 }
 

+ 127 - 15
src/__tests__/features/settings/spec-pdf-print.test.tsx

@@ -18,6 +18,7 @@ import { estimateBlockHeights } from '@/features/invoice-designer/Pdf/estimateHe
 import { lineCount } from '@/features/invoice-designer/Pdf/measure'
 import { InvoicePDF } from '@/features/vehicles/Components/invoice-pdf/InvoicePDF'
 import { QuotePDF } from '@/features/quotes/Components/QuotePDF'
+import { extractText } from 'unpdf'
 import {
   DESIGNER_LAYOUT_VERSION,
   getDefaultInvoiceLayout,
@@ -94,6 +95,22 @@ const workshop = {
 
 const settings = { currencyCode: 'EUR', bankAccount: 'XX00 1234 5678', orgNumber: '123 456 789' }
 
+/** The classic default layout with one section switched off. */
+function withoutSection(id: string) {
+  const layout = getDefaultInvoiceLayout()
+  layout.sections = layout.sections.map((s) => (s.id === id ? { ...s, visible: false } : s))
+  return layout
+}
+
+const MARK = 'data:image/png;base64,AAAA'
+
+/** The blocks of a printed sheet that carry the Torqvoice mark, and how often. */
+function blocksWithMark(spec: { blocks: { id: string }[] }) {
+  return spec.blocks
+    .filter((b) => JSON.stringify(b).includes(MARK))
+    .map((b) => ({ id: b.id, count: JSON.stringify(b).split(MARK).length - 1 }))
+}
+
 describe('the printed invoice follows the designed layout', () => {
   it('renders a valid PDF for every header style', async () => {
     for (const headerStyle of ['standard', 'compact', 'modern', 'framed']) {
@@ -231,26 +248,121 @@ describe('the printed invoice follows the designed layout', () => {
     }
   })
 
-  it("keeps each classic letterhead's own place for the Torqvoice mark", () => {
-    // The retired sheets did not agree on this: standard set the mark under
-    // the company block, compact right-aligned it below the rule, and the
-    // banner centred it. Flattening them moved it on a free workshop's
-    // invoice without anything failing.
-    const markAlign = (headerStyle: string) => {
+  it('prints the Torqvoice mark once, in the footer that repeats on every page', () => {
+    // The header, the totals and the footer each printed it, so page one of
+    // an invoice said "Powered by Torqvoice" three times.
+    for (const designer of [false, true]) {
+      for (const headerStyle of ['standard', 'compact', 'modern', 'framed']) {
+        const layout = getDefaultInvoiceLayout()
+        const spec = buildInvoicePrintSpec({
+          data: invoice,
+          workshop,
+          invoiceSettings: settings,
+          template: {
+            headerStyle,
+            layoutConfig: designer ? { ...layout, version: DESIGNER_LAYOUT_VERSION } : layout,
+          },
+          torqvoiceLogoDataUri: MARK,
+        })
+        expect(blocksWithMark(spec)).toEqual([{ id: 'footer', count: 1 }])
+        expect(spec.blocks.find((b) => b.id === 'footer')?.placement.mode).toBe('pinned')
+      }
+    }
+  })
+
+  it('gives the mark a repeating block of its own when the footer does not repeat', () => {
+    // A hidden footer, or one placed by hand on one page, is not on every
+    // sheet, and nor are the letterhead and the totals. The mark then stands
+    // at the foot of each sheet on its own; no section of the workshop's moves.
+    const anchoredFooter = getDefaultInvoiceLayout()
+    anchoredFooter.anchors = { footer: { x: 40, y: 700, width: 300, page: 1 } }
+    for (const layoutConfig of [withoutSection('footer'), anchoredFooter]) {
       const spec = buildInvoicePrintSpec({
         data: invoice,
         workshop,
         invoiceSettings: settings,
-        template: { headerStyle },
-        torqvoiceLogoDataUri: 'data:image/png;base64,AAAA',
+        template: { layoutConfig: { ...layoutConfig, version: DESIGNER_LAYOUT_VERSION } },
+        torqvoiceLogoDataUri: MARK,
       })
-      const header = JSON.stringify(spec.blocks.find((b) => b.id === 'header'))
-      const row = header.slice(header.indexOf('"header.branding"'))
-      return row.slice(0, row.indexOf('children')).match(/"justify":"(\w+)"/)?.[1]
+      expect(blocksWithMark(spec)).toEqual([{ id: 'branding', count: 1 }])
+      expect(spec.blocks.find((b) => b.id === 'branding')?.placement.mode).toBe('pinned')
+      const footer = spec.blocks.find((b) => b.id === 'footer')
+      if (footer) expect(footer.placement.mode).toBe('anchored')
+    }
+  })
+
+  it('prints the mark once on every page of a long invoice, photo pages included', async () => {
+    const pixel =
+      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=='
+    const long: InvoiceData = {
+      ...invoice,
+      partItems: Array.from({ length: 70 }, (_, i) => ({
+        partNumber: `P-${i}`,
+        name: `Part line ${i}`,
+        quantity: 1,
+        unitPrice: 10,
+        total: 10,
+      })),
+    }
+    const anchoredFooter = getDefaultInvoiceLayout()
+    anchoredFooter.anchors = { footer: { x: 40, y: 700, width: 300, page: 1 } }
+    const layouts = {
+      default: getDefaultInvoiceLayout(),
+      footerHidden: withoutSection('footer'),
+      footerAnchored: anchoredFooter,
+    }
+    for (const [name, layout] of Object.entries(layouts)) {
+      const buffer = await renderToBuffer(
+        (
+          <InvoicePDF
+            data={long}
+            workshop={workshop}
+            invoiceSettings={settings}
+            torqvoiceLogoDataUri={pixel}
+            template={{ layoutConfig: { ...layout, version: DESIGNER_LAYOUT_VERSION } }}
+            imageAttachments={[{ dataUri: pixel, fileName: 'disc.png' }]}
+          />
+        ) as React.ReactElement<DocumentProps>
+      )
+      const { totalPages, text } = await extractText(new Uint8Array(buffer), {
+        mergePages: false,
+      })
+      expect(totalPages, name).toBeGreaterThanOrEqual(3)
+      for (const [i, page] of text.entries()) {
+        expect(page.split('Powered by').length - 1, `${name}, page ${i + 1}`).toBe(1)
+      }
+    }
+    // Three multi-page PDFs: about two seconds alone, far more on a busy runner.
+  }, 60_000)
+
+  it('prints no mark at all for a sheet without branding', () => {
+    const spec = buildInvoicePrintSpec({ data: invoice, workshop, invoiceSettings: settings })
+    expect(blocksWithMark(spec)).toEqual([])
+  })
+
+  it('prints the photo pages as sheets of the same document', async () => {
+    // The photos used to be a page of their own with a footer of its own
+    // ("Testshop · INV-2026-0042") where the sheets before it had the
+    // workshop's footer and the mark.
+    const pixel =
+      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=='
+    const pages = async (imageAttachments: { dataUri: string; fileName: string }[]) => {
+      const buffer = await renderToBuffer(
+        (
+          <InvoicePDF
+            data={invoice}
+            workshop={workshop}
+            invoiceSettings={settings}
+            torqvoiceLogoDataUri={pixel}
+            imageAttachments={imageAttachments}
+          />
+        ) as React.ReactElement<DocumentProps>
+      )
+      expect(buffer.subarray(0, 5).toString()).toBe('%PDF-')
+      return buffer.toString('latin1').match(/\/Type \/Page\b/g)?.length ?? 0
     }
-    expect(markAlign('standard')).toBe('start')
-    expect(markAlign('compact')).toBe('end')
-    expect(markAlign('modern')).toBe('center')
+    // One more sheet of the same page, which carries its pinned footer.
+    expect(await pages([{ dataUri: pixel, fileName: 'disc.png' }])).toBe((await pages([])) + 1)
   })
 
   it('grows the framed band to cover everything standing on it', () => {
@@ -262,7 +374,7 @@ describe('the printed invoice follows the designed layout', () => {
         data: invoice,
         workshop,
         invoiceSettings: settings,
-        template: { headerStyle: 'framed' },
+        template: { headerStyle: 'framed', layoutConfig: withoutSection('footer') },
         ...extra,
       })
 

+ 29 - 0
src/__tests__/lib/share-expiry.test.ts

@@ -10,7 +10,9 @@ import {
   readShareExpiryRules,
   type ShareLinkFacts,
   shareExpiry,
+  shareOpenUntilDay,
 } from '@/lib/share-expiry'
+import { formatDate } from '@/lib/format'
 
 const ZONE = 'Pacific/Auckland'
 
@@ -150,3 +152,30 @@ describe('whether an invoice is paid, and when', () => {
     })
   })
 })
+
+describe('the day the share page says a link works until', () => {
+  // The end of 8 December in Auckland is 10:59:59.999 UTC.
+  const endOf8Dec = new Date('2026-12-08T10:59:59.999Z')
+  const now = new Date('2026-11-24T12:00:00Z')
+  const day = (at: Date) => {
+    const until = shareOpenUntilDay({ kind: 'date', at, source: 'document' }, ZONE, now)
+    return until ? formatDate(until, 'dd/MM/yyyy', ZONE) : null
+  }
+
+  it('is the day the link closes at the end of', () => {
+    expect(day(endOf8Dec)).toBe('08/12/2026')
+  })
+
+  it('is the same day when the close was stored without its last milliseconds', () => {
+    // 23:59:59 and 23:59 on 8 December. The staff page names 08/12 for
+    // both; the share page used to say "until 07/12/2026".
+    expect(day(new Date(endOf8Dec.getTime() - 999))).toBe('08/12/2026')
+    expect(day(new Date(endOf8Dec.getTime() - 59_999))).toBe('08/12/2026')
+  })
+
+  it('is the day before for a link that closes partway through a day', () => {
+    // 14 days to the minute: closing at 17:30 on the 8th, it is promised
+    // only through the 7th.
+    expect(day(new Date('2026-12-08T04:30:00Z'))).toBe('07/12/2026')
+  })
+})

+ 12 - 4
src/app/(authenticated)/(dashboard)/dashboard-client.tsx

@@ -387,6 +387,12 @@ export function DashboardClient({
   const tWorkOrders = useTranslations('workOrders')
   // The customer page already ships every label a service request needs.
   const tCustomerRequests = useTranslations('customers.serviceRequests')
+  // An observation's severity is stored as a key ("needs_work"); the work
+  // order and the observations page call it High, Medium or Low.
+  const severityLabel = (severity: string) => {
+    const key = `findings.severity.${severity}`
+    return tVehicles.has(key) ? tVehicles(key as 'findings.severity.urgent') : severity
+  }
   const distUnit = unitSystem === 'metric' ? 'km' : 'mi'
   const router = useRouter()
   const { formatDate } = useFormatDate()
@@ -2020,8 +2026,10 @@ export function DashboardClient({
                       // and returns a placeholder rather than throwing, so a catch
                       // never runs and the raw key reaches the screen.
                       const friendlyAction = tAudit.has(actionKey) ? tAudit(actionKey) : log.action
-                      const entityLabel =
-                        vehicleDisplay ?? quoteNumber ?? log.entityId?.substring(0, 8)
+                      // Only a name a person knows the record by. The record's
+                      // id meant nothing to anyone ("— cmwuyxad"), and the
+                      // line under it already names the record by its number.
+                      const entityLabel = vehicleDisplay ?? quoteNumber
                       const row = (
                         <>
                           <div className="min-w-0">
@@ -2102,7 +2110,7 @@ export function DashboardClient({
                               variant="outline"
                               className={`shrink-0 px-1.5 py-0 text-[10px] ${observationSeverityColors[obs.severity] || ''}`}
                             >
-                              {obs.severity}
+                              {severityLabel(obs.severity)}
                             </Badge>
                             <span className="min-w-0 max-w-full truncate font-mono text-[11px] text-muted-foreground">
                               {obs.vehicle.licensePlate ?? `${vehicleName(obs.vehicle)}`}
@@ -2145,7 +2153,7 @@ export function DashboardClient({
                                         variant="outline"
                                         className={`text-[10px] px-1.5 py-0 ${observationSeverityColors[obs.severity] || ''}`}
                                       >
-                                        {obs.severity}
+                                        {severityLabel(obs.severity)}
                                       </Badge>
                                     </TableCell>
                                     <TableCell className="py-1.5 font-mono text-xs text-muted-foreground truncate">

+ 5 - 2
src/app/(authenticated)/customers/customers-client.tsx

@@ -478,7 +478,7 @@ export function CustomersClient({
                   onClick={(e) => e.stopPropagation()}
                 />
               </TableHead>
-              <TableHead className="w-[80px]">
+              <TableHead className="w-[96px]">
                 <button
                   type="button"
                   className="flex items-center hover:text-foreground"
@@ -564,7 +564,10 @@ export function CustomersClient({
                           onClick={(e) => e.stopPropagation()}
                         />
                       </TableCell>
-                      <TableCell className="font-mono text-xs text-muted-foreground">
+                      <TableCell
+                        className="truncate font-mono text-xs text-muted-foreground"
+                        title={c.customerNumber || undefined}
+                      >
                         {c.customerNumber || '-'}
                       </TableCell>
                       <TableCell>

+ 7 - 16
src/app/(authenticated)/labor-presets/labor-presets-client.tsx

@@ -36,6 +36,7 @@ import { TableContextMenuHint } from '@/components/table-context-menu-hint'
 import { useGlassModal } from '@/components/glass-modal'
 import { useConfirm } from '@/components/confirm-dialog'
 import { LaborPresetForm } from '@/features/labor-presets/Components/LaborPresetForm'
+import { presetTotals } from '@/features/labor-presets/Lib/presetTotals'
 import {
   deleteLaborPreset,
   getLaborPreset,
@@ -230,10 +231,7 @@ export function LaborPresetsClient({
           </div>
         ) : (
           data.presets.map((preset) => {
-            const hourlyItems = preset.items.filter((i) => i.pricingType !== 'service')
-            const serviceItems = preset.items.filter((i) => i.pricingType === 'service')
-            const totalHours = hourlyItems.reduce((sum, i) => sum + i.hours, 0)
-            const totalUnits = serviceItems.reduce((sum, i) => sum + i.hours, 0)
+            const { totalHours, totalUnits } = presetTotals(preset.items)
             return (
               <div key={preset.id} className="flex items-start gap-2 rounded-lg border bg-card p-3">
                 <button
@@ -253,12 +251,12 @@ export function LaborPresetsClient({
                     </span>
                     {totalHours > 0 && (
                       <span className="inline-flex items-center rounded-md border border-emerald-500/30 bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600">
-                        {totalHours} {t('table.hrs')}
+                        {t('table.hoursCount', { hours: totalHours })}
                       </span>
                     )}
                     {totalUnits > 0 && (
                       <span className="inline-flex items-center rounded-md border border-blue-500/30 bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-medium text-blue-600">
-                        {totalUnits} {t('table.units')}
+                        {t('table.unitsCount', { units: totalUnits })}
                       </span>
                     )}
                   </div>
@@ -350,24 +348,17 @@ export function LaborPresetsClient({
                       <TableCell>{preset._count.items}</TableCell>
                       <TableCell className="hidden md:table-cell">
                         {(() => {
-                          const hourlyItems = preset.items.filter(
-                            (i) => i.pricingType !== 'service'
-                          )
-                          const serviceItems = preset.items.filter(
-                            (i) => i.pricingType === 'service'
-                          )
-                          const totalHours = hourlyItems.reduce((sum, i) => sum + i.hours, 0)
-                          const totalUnits = serviceItems.reduce((sum, i) => sum + i.hours, 0)
+                          const { totalHours, totalUnits } = presetTotals(preset.items)
                           return (
                             <div className="flex gap-1.5">
                               {totalHours > 0 && (
                                 <span className="inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium border-emerald-500/30 bg-emerald-500/10 text-emerald-600">
-                                  {totalHours} {t('table.hrs')}
+                                  {t('table.hoursCount', { hours: totalHours })}
                                 </span>
                               )}
                               {totalUnits > 0 && (
                                 <span className="inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium border-blue-500/30 bg-blue-500/10 text-blue-600">
-                                  {totalUnits} {t('table.units')}
+                                  {t('table.unitsCount', { units: totalUnits })}
                                 </span>
                               )}
                             </div>

+ 9 - 4
src/features/custom-fields/Actions/customFieldActions.ts

@@ -20,6 +20,7 @@ import {
   recordSubject,
 } from '../Lib/customFieldRecords.server'
 import { type CustomFieldError, judgeCustomFieldValues } from '../Lib/customFieldValueRules'
+import { dropFieldFromLayouts } from '../Lib/dropFieldFromLayouts'
 
 /**
  * Whose permission a record's custom fields fall under: the record's own.
@@ -153,12 +154,16 @@ export async function deleteFieldDefinition(fieldId: string) {
       })
       if (!field) throw new Error('Field not found')
 
-      await db.$transaction([
-        db.customFieldValue.deleteMany({ where: { fieldId } }),
-        db.customFieldDefinition.delete({ where: { id: fieldId } }),
-      ])
+      await db.$transaction(async (tx) => {
+        await tx.customFieldValue.deleteMany({ where: { fieldId } })
+        await tx.customFieldDefinition.delete({ where: { id: fieldId } })
+        // The layouts that placed it forget it too, or it stays switched on
+        // in a saved arrangement with no definition behind it.
+        await dropFieldFromLayouts(tx, organizationId, fieldId)
+      })
 
       revalidatePath('/settings/invoice')
+      revalidatePath('/settings/templates')
       return { fieldId, fieldName: field.name }
     },
     {

+ 108 - 0
src/features/custom-fields/Lib/dropFieldFromLayouts.ts

@@ -0,0 +1,108 @@
+import type { TxClient } from '@/lib/db'
+import { Prisma } from '@/generated/prisma/client'
+import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
+import { toCustomFieldId } from '@/features/settings/Schema/invoiceLayoutSchema'
+
+/**
+ * A layout as stored, with the one custom field taken out of every section.
+ * Returns null when the field was in none of them, so the caller writes
+ * nothing.
+ *
+ * Only the field goes. A section keeps the on/off the workshop gave it:
+ * switching General off because its last custom field went would undo a
+ * choice somebody may have made on purpose, and a General panel with
+ * nothing to print prints nothing.
+ *
+ * Works on the stored JSON, not the merged config: what is saved is what
+ * the workshop arranged, and merging defaults in here would write them back
+ * as if somebody had chosen them.
+ */
+export function layoutWithoutField(stored: unknown, definitionId: string): unknown | null {
+  if (!stored || typeof stored !== 'object') return null
+  const layout = stored as { sections?: unknown }
+  if (!Array.isArray(layout.sections)) return null
+  const cfId = toCustomFieldId(definitionId)
+  let changed = false
+  const sections = layout.sections.map((section) => {
+    const fields = (section as { fields?: unknown })?.fields
+    if (!Array.isArray(fields)) return section
+    const kept = fields.filter((f) => (f as { id?: unknown })?.id !== cfId)
+    if (kept.length === fields.length) return section
+    changed = true
+    return { ...(section as object), fields: kept }
+  })
+  return changed ? { ...layout, sections } : null
+}
+
+/** The settings rows that hold a document's arrangement. */
+const LAYOUT_KEYS = [
+  SETTING_KEYS.INVOICE_LAYOUT_CONFIG,
+  SETTING_KEYS.QUOTE_LAYOUT_CONFIG,
+  SETTING_KEYS.WORK_ORDER_LAYOUT_CONFIG,
+  SETTING_KEYS.CERTIFICATE_LAYOUT_CONFIG,
+]
+
+/**
+ * Takes a deleted custom field out of every arrangement that still names it:
+ * the document layouts in settings and the saved designs. Without this the
+ * field stayed in the saved layout after the definition was gone, and the
+ * designer listed a field that no longer existed.
+ *
+ * Designs frozen for an issued document (snapshots) are left as they are:
+ * paper a customer already holds does not change.
+ */
+export async function dropFieldFromLayouts(
+  tx: TxClient,
+  organizationId: string,
+  definitionId: string
+): Promise<void> {
+  // Two fields deleted at the same moment would each read the same layout,
+  // and the later write would put back the field the earlier one took out.
+  // The rows are locked before they are read, always in the same order
+  // (settings, then designs), so the second delete waits for the first and
+  // reads what it wrote.
+  await tx.$queryRaw(Prisma.sql`
+    SELECT count(*) FROM (
+      SELECT 1 FROM "public"."app_settings"
+      WHERE "organizationId" = ${organizationId} AND "key" IN (${Prisma.join(LAYOUT_KEYS)})
+      ORDER BY "id" FOR UPDATE
+    ) locked
+  `)
+  await tx.$queryRaw(Prisma.sql`
+    SELECT count(*) FROM (
+      SELECT 1 FROM "public"."document_designs"
+      WHERE "organizationId" = ${organizationId}
+      ORDER BY "id" FOR UPDATE
+    ) locked
+  `)
+  const settings = await tx.appSetting.findMany({
+    where: { organizationId, key: { in: LAYOUT_KEYS } },
+    select: { id: true, value: true },
+  })
+  for (const row of settings) {
+    let parsed: unknown
+    try {
+      parsed = JSON.parse(row.value)
+    } catch {
+      continue
+    }
+    const next = layoutWithoutField(parsed, definitionId)
+    if (next) {
+      await tx.appSetting.update({ where: { id: row.id }, data: { value: JSON.stringify(next) } })
+    }
+  }
+
+  const designs = await tx.documentDesign.findMany({
+    where: { organizationId },
+    select: { id: true, layout: true },
+  })
+  for (const design of designs) {
+    const next = layoutWithoutField(design.layout, definitionId)
+    if (next) {
+      await tx.documentDesign.update({
+        where: { id: design.id },
+        data: { layout: next as Prisma.InputJsonValue },
+      })
+    }
+  }
+}

+ 101 - 28
src/features/invoice-designer/Spec/buildSpec.ts

@@ -2270,9 +2270,9 @@ function footer(section: InvoiceSection, theme: DocumentTheme, data: DocumentDat
   if (data.branding) {
     // The workshop's own closing line stays on its own row, so the mark below
     // it reads as a signature on the sheet rather than a tail on their
-    // sentence. This is the one place the branding is meant to be seen: the
-    // header and totals carry it quietly, and three loud mentions on a
-    // customer's invoice would read as an advert rather than a credit.
+    // sentence. The footer is where the mark lives (see brandingHome): it
+    // repeats on every sheet, and the header and totals leave it out, since
+    // three mentions on a customer's invoice read as an advert, not a credit.
     if (note) {
       children.push({
         kind: 'text',
@@ -2280,29 +2280,7 @@ function footer(section: InvoiceSection, theme: DocumentTheme, data: DocumentDat
         style: { color: look.muted, fontSize: scale(size, 0.78), align: 'center' },
       })
     }
-    children.push({
-      kind: 'row',
-      gap: 4,
-      justify: 'center',
-      align: 'center',
-      children: [
-        {
-          node: {
-            kind: 'text',
-            text: label(data, 'poweredBy', 'Powered by'),
-            style: { color: look.muted, fontSize: scale(size, 0.9) },
-          },
-        },
-        { node: { kind: 'image', src: data.branding.logoDataUri, maxWidth: 22, maxHeight: 22 } },
-        {
-          node: {
-            kind: 'text',
-            text: 'Torqvoice',
-            style: { color: theme.primary, fontSize: scale(size, 1.35), bold: true },
-          },
-        },
-      ],
-    })
+    children.push(brandingMarkRow(data.branding.logoDataUri, data, look.muted, theme.primary, size))
   } else if (note) {
     children.push({
       kind: 'text',
@@ -2403,6 +2381,71 @@ function blockFor(
   }
 }
 
+/** The "Powered by Torqvoice" line as the foot of a sheet prints it. */
+function brandingMarkRow(
+  logoDataUri: string,
+  data: DocumentData,
+  muted: string | undefined,
+  primary: string,
+  size: number
+): Node {
+  return {
+    kind: 'row',
+    gap: 4,
+    justify: 'center',
+    align: 'center',
+    children: [
+      {
+        node: {
+          kind: 'text',
+          text: label(data, 'poweredBy', 'Powered by'),
+          style: { color: muted, fontSize: scale(size, 0.9) },
+        },
+      },
+      { node: { kind: 'image', src: logoDataUri, maxWidth: 22, maxHeight: 22 } },
+      {
+        node: {
+          kind: 'text',
+          text: 'Torqvoice',
+          style: { color: primary, fontSize: scale(size, 1.35), bold: true },
+        },
+      },
+    ],
+  }
+}
+
+/** The id of the block that carries the mark when the footer cannot. */
+export const BRANDING_BLOCK_ID = 'branding'
+
+type BrandingHome = 'footer' | typeof BRANDING_BLOCK_ID | null
+
+/**
+ * Where the "Powered by Torqvoice" mark prints: once on every sheet.
+ *
+ * The header, the totals and the footer each used to print it, so page one
+ * of an invoice carried it three times. The footer is the place when it
+ * repeats: shown, and pinned to the foot of every sheet. A footer the layout
+ * hides, or one placed by hand on one page, does not repeat, and nor do the
+ * header and the totals; the mark then gets a block of its own at the foot
+ * of every sheet, and the workshop's own sections stay where they were put.
+ * Whether a sheet carries the mark at all is decided before this, by
+ * whoever passes `branding` (licensing).
+ */
+export function brandingHome(
+  sections: InvoiceSection[],
+  data: DocumentData,
+  anchors: Record<string, unknown> = {}
+): BrandingHome {
+  if (!data.branding) return null
+  const footerRepeats = sections.some((s) => s.id === 'footer' && s.visible) && !anchors.footer
+  return footerRepeats ? 'footer' : BRANDING_BLOCK_ID
+}
+
+/** The data a section is built from: the mark only for the section that prints it. */
+function dataFor(sectionId: string, data: DocumentData, home: BrandingHome): DocumentData {
+  return data.branding && sectionId !== home ? { ...data, branding: undefined } : data
+}
+
 export function buildDocumentSpec(
   layout: InvoiceLayoutConfig,
   theme: DocumentTheme,
@@ -2426,9 +2469,10 @@ export function buildDocumentSpec(
   // Only the default placement rides the band; a letterhead somebody dragged
   // elsewhere leaves the band at its usual height.
   const headerSection = ordered.find((s) => s.id === 'header' && s.visible)
+  const home = brandingHome(ordered, data, anchors)
   const bandHeight =
     framed && headerSection && !anchors.header
-      ? framedBandHeight(headerSection, theme, data)
+      ? framedBandHeight(headerSection, theme, dataFor('header', data, home))
       : FRAMED.bandHeight
   const framedTop = bandHeight + FRAMED_BAND_GAP
 
@@ -2441,7 +2485,13 @@ export function buildDocumentSpec(
       (section.column ? (contentWidth - BLOCK_GAP) / 2 : contentWidth) -
         (section.style?.marginLeft ?? 0) -
         (section.style?.marginRight ?? 0)
-    const content = blockFor(section, theme, data, blockWidth, documentType)
+    const content = blockFor(
+      section,
+      theme,
+      dataFor(section.id, data, home),
+      blockWidth,
+      documentType
+    )
     if (!content) return
 
     const placement: Placement =
@@ -2505,6 +2555,29 @@ export function buildDocumentSpec(
     push(section)
   }
 
+  if (home === BRANDING_BLOCK_ID && data.branding) {
+    blocks.push({
+      id: BRANDING_BLOCK_ID,
+      label: 'branding',
+      synthetic: true,
+      placement: { mode: 'pinned', edge: 'bottom' },
+      text: { color: theme.text, fontFamily: theme.fontFamily, fontSize: theme.fontSize },
+      content: {
+        kind: 'stack',
+        id: BRANDING_BLOCK_ID,
+        children: [
+          brandingMarkRow(
+            data.branding.logoDataUri,
+            data,
+            theme.muted,
+            theme.primary,
+            theme.fontSize
+          ),
+        ],
+      },
+    })
+  }
+
   return {
     page: {
       width: 595,

+ 3 - 7
src/features/labor-presets/Components/LaborPresetPickerDialog.tsx

@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl'
 import { Input } from '@/components/ui/input'
 import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
 import { ChevronDown, ChevronRight, Search } from 'lucide-react'
+import { presetTotals } from '@/features/labor-presets/Lib/presetTotals'
 
 export interface LaborPresetOption {
   id: string
@@ -82,10 +83,7 @@ export function LaborPresetPickerDialog({
         </div>
         <div className="max-h-75 overflow-y-auto space-y-1">
           {filtered.map((preset) => {
-            const hourlyItems = preset.items.filter((i) => i.pricingType !== 'service')
-            const serviceItems = preset.items.filter((i) => i.pricingType === 'service')
-            const totalHours = hourlyItems.reduce((sum, i) => sum + i.hours, 0)
-            const totalUnits = serviceItems.reduce((sum, i) => sum + i.hours, 0)
+            const { totalHours, totalUnits } = presetTotals(preset.items)
             const isExpanded = expandedId === preset.id
             const hasDetails = preset.items.length > 1 || (preset.parts && preset.parts.length > 0)
 
@@ -120,9 +118,7 @@ export function LaborPresetPickerDialog({
                   </div>
                   <div className="flex items-center gap-3 shrink-0 text-xs text-muted-foreground">
                     {hasDetails && <span>{t('items', { count: preset.items.length })}</span>}
-                    {totalHours > 0 && (
-                      <span>{t('totalHours', { hours: totalHours.toFixed(1) })}</span>
-                    )}
+                    {totalHours > 0 && <span>{t('totalHours', { hours: totalHours })}</span>}
                     {totalUnits > 0 && <span>{t('totalUnits', { units: totalUnits })}</span>}
                     {preset.parts && preset.parts.length > 0 && (
                       <span>{t('totalParts', { count: preset.parts.length })}</span>

+ 19 - 0
src/features/labor-presets/Lib/presetTotals.ts

@@ -0,0 +1,19 @@
+/**
+ * Hours and units a labor preset adds to a job. A line priced per hour counts
+ * as hours, a line priced as a service counts as units. Each total is rounded
+ * to two decimals: 0.75 + 0.5 is 1.25 hours, which used to show as "1.3h",
+ * and a sum of floats such as 0.1 + 0.2 must not print its float noise.
+ */
+export function presetTotals(items: { hours: number; pricingType?: string | null }[]) {
+  let hours = 0
+  let units = 0
+  for (const item of items) {
+    if (item.pricingType === 'service') units += item.hours
+    else hours += item.hours
+  }
+  return { totalHours: round2(hours), totalUnits: round2(units) }
+}
+
+function round2(n: number) {
+  return Math.round(n * 100) / 100
+}

+ 30 - 46
src/features/quotes/Components/QuotePDF.tsx

@@ -1,10 +1,9 @@
 import { DEFAULT_CURRENCY_CODE } from '@/lib/currencies'
-import { Document, Image, Page, Text, View } from '@react-pdf/renderer'
+import { Document, Image, Text, View } from '@react-pdf/renderer'
 import {
   buildQuotePrintSpec,
   type QuotePrintData,
 } from '@/features/invoice-designer/Pdf/buildQuotePrint'
-import { pdfFamily } from '@/features/invoice-designer/Pdf/renderPdf'
 import { SpecPdfPage } from '@/features/invoice-designer/Pdf/SpecPdf'
 import type { InvoiceLayoutConfig } from '@/features/settings/Schema/invoiceLayoutSchema'
 import type { VisitConditionMap } from '@/features/condition-map/Lib/print'
@@ -103,53 +102,38 @@ export function QuotePDF({
     inspectionResults,
   })
 
-  const quoteNum = data.quoteNumber || 'QUOTE'
-  const shopName = workshop?.name || 'Torqvoice'
-  const fontFamily = pdfFamily(spec.page.fontFamily)
-
   return (
     <Document>
-      <SpecPdfPage spec={spec} />
-
-      {imageAttachments.length > 0 && (
-        <Page size="A4" style={{ padding: 40, fontFamily, fontSize: 9, color: '#111827' }}>
-          <Text style={{ fontSize: 12, fontWeight: 700, marginBottom: 10 }}>
-            {labels.quoteImages || 'Quote Images'}
-          </Text>
-          <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
-            {imageAttachments.map((img, i) => (
-              <View key={i} style={{ width: '48%', marginBottom: 8 }}>
-                <Image
-                  src={img.dataUri}
-                  style={{
-                    maxHeight: 250,
-                    borderRadius: 4,
-                    objectFit: 'contain',
-                    objectPosition: 'left',
-                  }}
-                />
-                <Text style={{ fontSize: 8, color: '#6b7280', marginTop: 2 }}>
-                  {img.description || img.fileName}
-                </Text>
-              </View>
-            ))}
+      {/* The pictures follow on the document's own sheets, so they carry the
+          same pinned footer as the pages before them instead of a footer
+          of their own. */}
+      <SpecPdfPage spec={spec}>
+        {imageAttachments.length > 0 && (
+          <View break>
+            <Text style={{ fontSize: 12, fontWeight: 700, marginBottom: 10 }}>
+              {labels.quoteImages || 'Quote Images'}
+            </Text>
+            <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
+              {imageAttachments.map((img, i) => (
+                <View key={i} style={{ width: '48%', marginBottom: 8 }}>
+                  <Image
+                    src={img.dataUri}
+                    style={{
+                      maxHeight: 250,
+                      borderRadius: 4,
+                      objectFit: 'contain',
+                      objectPosition: 'left',
+                    }}
+                  />
+                  <Text style={{ fontSize: 8, color: '#6b7280', marginTop: 2 }}>
+                    {img.description || img.fileName}
+                  </Text>
+                </View>
+              ))}
+            </View>
           </View>
-          <Text
-            fixed
-            style={{
-              position: 'absolute',
-              bottom: 16,
-              left: 40,
-              right: 40,
-              fontSize: 8,
-              color: '#6b7280',
-              textAlign: 'center',
-            }}
-          >
-            {quoteNum} · {shopName}
-          </Text>
-        </Page>
-      )}
+        )}
+      </SpecPdfPage>
     </Document>
   )
 }

+ 30 - 46
src/features/vehicles/Components/invoice-pdf/InvoicePDF.tsx

@@ -1,8 +1,7 @@
-import { Document, Image, Page, Text, View } from '@react-pdf/renderer'
+import { Document, Image, Text, View } from '@react-pdf/renderer'
 import { buildInvoicePrintSpec } from '@/features/invoice-designer/Pdf/buildInvoicePrint'
 import type { VisitConditionMap } from '@/features/condition-map/Lib/print'
 import type { InspectionResults } from '@/features/inspections/Lib/inspectionResults'
-import { pdfFamily } from '@/features/invoice-designer/Pdf/renderPdf'
 import { SpecPdfPage } from '@/features/invoice-designer/Pdf/SpecPdf'
 import type {
   ImageAttachment,
@@ -83,53 +82,38 @@ export function InvoicePDF({
     inspectionResults,
   })
 
-  const shopDisplayName = workshop?.name || data.shopName || 'Torqvoice'
-  const invoiceNum = data.invoiceNumber || `INV-${data.id.slice(-8).toUpperCase()}`
-  const fontFamily = pdfFamily(spec.page.fontFamily)
-
   return (
     <Document>
-      <SpecPdfPage spec={spec} />
-
-      {imageAttachments.length > 0 && (
-        <Page size="A4" style={{ padding: 40, fontFamily, fontSize: 9, color: '#111827' }}>
-          <Text style={{ fontSize: 12, fontWeight: 700, marginBottom: 10 }}>
-            {labels.serviceImages || 'Service Images'}
-          </Text>
-          <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
-            {imageAttachments.map((img, i) => (
-              <View key={i} style={{ width: '48%', marginBottom: 8 }}>
-                <Image
-                  src={img.dataUri}
-                  style={{
-                    maxHeight: 250,
-                    borderRadius: 4,
-                    objectFit: 'contain',
-                    objectPosition: 'left',
-                  }}
-                />
-                <Text style={{ fontSize: 8, color: '#6b7280', marginTop: 2 }}>
-                  {img.description || img.fileName}
-                </Text>
-              </View>
-            ))}
+      {/* The pictures follow on the document's own sheets, so they carry the
+          same pinned footer as the pages before them instead of a footer
+          of their own. */}
+      <SpecPdfPage spec={spec}>
+        {imageAttachments.length > 0 && (
+          <View break>
+            <Text style={{ fontSize: 12, fontWeight: 700, marginBottom: 10 }}>
+              {labels.serviceImages || 'Service Images'}
+            </Text>
+            <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 12 }}>
+              {imageAttachments.map((img, i) => (
+                <View key={i} style={{ width: '48%', marginBottom: 8 }}>
+                  <Image
+                    src={img.dataUri}
+                    style={{
+                      maxHeight: 250,
+                      borderRadius: 4,
+                      objectFit: 'contain',
+                      objectPosition: 'left',
+                    }}
+                  />
+                  <Text style={{ fontSize: 8, color: '#6b7280', marginTop: 2 }}>
+                    {img.description || img.fileName}
+                  </Text>
+                </View>
+              ))}
+            </View>
           </View>
-          <Text
-            fixed
-            style={{
-              position: 'absolute',
-              bottom: 16,
-              left: 40,
-              right: 40,
-              fontSize: 8,
-              color: '#6b7280',
-              textAlign: 'center',
-            }}
-          >
-            {shopDisplayName} · {invoiceNum}
-          </Text>
-        </Page>
-      )}
+        )}
+      </SpecPdfPage>
     </Document>
   )
 }

+ 5 - 2
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -156,7 +156,7 @@ export function PaymentsSection({
   const paymentForm = (
     <div
       ref={formRef}
-      className="space-y-3 rounded-lg border p-3"
+      className="@container space-y-3 rounded-lg border p-3"
       onKeyDown={(e) => {
         if (e.key === 'Enter' && e.target instanceof HTMLInputElement) {
           e.preventDefault()
@@ -164,7 +164,10 @@ export function PaymentsSection({
         }
       }}
     >
-      <div className="grid gap-3 sm:grid-cols-2">
+      {/* Two columns only where the form itself has room for them: in the
+          work order sidebar the screen is wide but the form is not, and two
+          columns there cut the date to "24/11/202". */}
+      <div className="grid gap-3 @xs:grid-cols-2">
         <div className="space-y-1">
           <Label htmlFor="paymentAmount" className="text-xs">
             {t('amount')}

+ 41 - 5
src/features/vehicles/Components/service-edit/TotalsSection.tsx

@@ -51,22 +51,57 @@ function Row({
   amount,
   className,
   testId,
+  stackControl = false,
 }: {
   label: React.ReactNode
   control?: React.ReactNode
   amount?: React.ReactNode
   className?: string
   testId?: string
+  /**
+   * A control too wide to share the line with its label in a narrow card
+   * (the work order sidebar is 320px at its narrowest): below the card's
+   * 22rem width it drops under the label and amount, so the label keeps
+   * its whole word instead of being cut to "Di".
+   */
+  stackControl?: boolean
 }) {
   return (
     <div
       data-totals-row
       data-testid={testId}
-      className={cn('col-span-3 grid grid-cols-subgrid items-center text-sm', className)}
+      className={cn(
+        'col-span-3 grid grid-cols-subgrid items-center text-sm',
+        stackControl && 'gap-y-1.5',
+        className
+      )}
     >
-      <span className="min-w-0 text-muted-foreground">{label}</span>
-      <span className="flex items-center justify-end gap-1.5">{control}</span>
-      <span className="text-right tabular-nums">{amount}</span>
+      {/* A row with nothing to change lends its label the control's column,
+          so "Parts cost (internal)" is not squeezed into the room beside the
+          widest field of the card. */}
+      <span
+        className={cn(
+          'min-w-0 text-muted-foreground',
+          (!control || stackControl) && 'col-span-2',
+          stackControl && '@[22rem]:col-span-1'
+        )}
+      >
+        {label}
+      </span>
+      {control && (
+        <span
+          className={cn(
+            'flex items-center justify-end gap-1.5',
+            stackControl &&
+              'col-span-3 row-start-2 @[22rem]:col-span-1 @[22rem]:col-start-2 @[22rem]:row-start-1'
+          )}
+        >
+          {control}
+        </span>
+      )}
+      <span className={cn('text-right tabular-nums', stackControl && 'col-start-3 row-start-1')}>
+        {amount}
+      </span>
     </div>
   )
 }
@@ -149,7 +184,7 @@ export function TotalsSection({
 
   const rows = (
     <div className="space-y-2" data-testid="totals">
-      <div className="grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-3 gap-y-2">
+      <div className="@container grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-3 gap-y-2">
         <Row label={t('parts')} amount={formatCurrency(displayPartsSubtotal, currencyCode)} />
         {partsCostSubtotal > 0 && (
           <Row
@@ -168,6 +203,7 @@ export function TotalsSection({
         />
 
         <Row
+          stackControl
           label={t('discount')}
           control={
             <>

+ 4 - 1
src/lib/share-expiry.ts

@@ -186,7 +186,10 @@ export function shareOpenUntilDay(
 ): Date | null {
   if (expiry.kind !== 'date' || isShareExpired(expiry, now)) return null
   const dayStart = startOfZonedDay(expiry.at, timeZone)
-  const endsTheDay = addZonedDays(expiry.at, 1, timeZone).getTime() - 1 === expiry.at.getTime()
+  // Within the day's last minute counts as its end: a close stored as
+  // 23:59:59 or 23:59, without the final milliseconds, used to promise the
+  // day before ("until 07/12" for a link the staff page said closes 08/12).
+  const endsTheDay = addZonedDays(expiry.at, 1, timeZone).getTime() - expiry.at.getTime() <= 60_000
   if (endsTheDay || dayStart.getTime() <= now.getTime()) return expiry.at
   return new Date(dayStart.getTime() - 1)
 }