Jelajahi Sumber

Add a customer from the work order when its vehicle has none (#660)

* Add a customer from the work order when its vehicle has none

The Customer box of a work order whose vehicle has no owner said "No customer on this work order." and offered nothing. The sentence and an "Add customer" button under it now open the customer picker the vehicle form uses, with its way to add a new customer; the one picked becomes the vehicle's owner and the box fills in at once.

Someone who may not edit vehicles, a locked invoice and a job with no vehicle keep the sentence alone.

* Keep the vehicle's mileage when an update does not send it

The update schema inherited the new vehicle's mileage default of 0, which zod fills in even on an optional field. An update that left the reading out, as adding a customer from the work order does, wrote 0 over it and marked it as typed by hand. The update schema now has no default, so only what was sent is written; a new vehicle still starts at 0.

* Keep adding a customer apart from the work order's own form

Typing in the customer search marked the work order edited, and saving a new customer from the picker submitted the work order too: both are portalled out of the form in the document but bubble to it in React. The Customer box's picker is now its own island, as the files card is.

The customer shown before the page reads the job again is dropped once the saved one arrives or the job is on another vehicle, so an owner removed elsewhere no longer hides "Add customer".

Who is offered the button now follows the rule the save itself applies: it reads the page's auth context, so a super admin is recognised, and a member with no custom role is not offered what would be refused.
Bernt Christian Egeland 5 hari lalu
induk
melakukan
a94f82340e

+ 4 - 0
messages/bg/service.json

@@ -687,6 +687,10 @@
     "email": "Имейл",
     "notSet": "Не е зададено",
     "noCustomer": "Към тази работна поръчка няма клиент.",
+    "addCustomer": "Добави клиент",
+    "addCustomerHint": "Избраният клиент става собственик на това превозно средство.",
+    "addCustomerHintMarine": "Избраният клиент става собственик на този плавателен съд.",
+    "addCustomerFailed": "Клиентът не можа да бъде добавен. Опитайте отново.",
     "invoiceTitle": "Фактура и плащане",
     "filesTitle": "Файлове и мултимедия",
     "activity": {

+ 4 - 0
messages/de/service.json

@@ -687,6 +687,10 @@
     "email": "E-Mail",
     "notSet": "Nicht angegeben",
     "noCustomer": "Kein Kunde auf diesem Arbeitsauftrag.",
+    "addCustomer": "Kunde hinzufügen",
+    "addCustomerHint": "Der ausgewählte Kunde wird Halter dieses Fahrzeugs.",
+    "addCustomerHintMarine": "Der ausgewählte Kunde wird Halter dieses Wasserfahrzeugs.",
+    "addCustomerFailed": "Der Kunde konnte nicht hinzugefügt werden. Versuchen Sie es erneut.",
     "invoiceTitle": "Rechnung & Zahlung",
     "filesTitle": "Dateien & Medien",
     "activity": {

+ 4 - 0
messages/en/service.json

@@ -687,6 +687,10 @@
     "email": "Email",
     "notSet": "Not set",
     "noCustomer": "No customer on this work order.",
+    "addCustomer": "Add customer",
+    "addCustomerHint": "The customer you pick becomes the owner of this vehicle.",
+    "addCustomerHintMarine": "The customer you pick becomes the owner of this vessel.",
+    "addCustomerFailed": "Could not add the customer. Try again.",
     "invoiceTitle": "Invoice & payment",
     "filesTitle": "Files & media",
     "activity": {

+ 4 - 0
messages/es/service.json

@@ -687,6 +687,10 @@
     "email": "Correo electrónico",
     "notSet": "Sin definir",
     "noCustomer": "No hay cliente en esta orden de trabajo.",
+    "addCustomer": "Agregar cliente",
+    "addCustomerHint": "El cliente que elijas pasa a ser el propietario de este vehículo.",
+    "addCustomerHintMarine": "El cliente que elijas pasa a ser el propietario de esta embarcación.",
+    "addCustomerFailed": "No se pudo agregar el cliente. Inténtalo de nuevo.",
     "invoiceTitle": "Factura y pago",
     "filesTitle": "Archivos y multimedia",
     "activity": {

+ 4 - 0
messages/fr/service.json

@@ -687,6 +687,10 @@
     "email": "E-mail",
     "notSet": "Non renseigné",
     "noCustomer": "Aucun client sur cet ordre de travail.",
+    "addCustomer": "Ajouter un client",
+    "addCustomerHint": "Le client choisi devient le propriétaire de ce véhicule.",
+    "addCustomerHintMarine": "Le client choisi devient le propriétaire de ce bateau.",
+    "addCustomerFailed": "Impossible d'ajouter le client. Réessayez.",
     "invoiceTitle": "Facture et paiement",
     "filesTitle": "Fichiers et médias",
     "activity": {

+ 4 - 0
messages/it/service.json

@@ -687,6 +687,10 @@
     "email": "Email",
     "notSet": "Non impostato",
     "noCustomer": "Nessun cliente su questo ordine di lavoro.",
+    "addCustomer": "Aggiungi cliente",
+    "addCustomerHint": "Il cliente scelto diventa il proprietario di questo veicolo.",
+    "addCustomerHintMarine": "Il cliente scelto diventa il proprietario di questa imbarcazione.",
+    "addCustomerFailed": "Impossibile aggiungere il cliente. Riprova.",
     "invoiceTitle": "Fattura e pagamento",
     "filesTitle": "File e media",
     "activity": {

+ 4 - 0
messages/lt/service.json

@@ -687,6 +687,10 @@
     "email": "El. paštas",
     "notSet": "Nenustatyta",
     "noCustomer": "Šiame darbo užsakyme nėra kliento.",
+    "addCustomer": "Pridėti klientą",
+    "addCustomerHint": "Pasirinktas klientas tampa šios transporto priemonės savininku.",
+    "addCustomerHintMarine": "Pasirinktas klientas tampa šio laivo savininku.",
+    "addCustomerFailed": "Nepavyko pridėti kliento. Bandykite dar kartą.",
     "invoiceTitle": "Sąskaita ir mokėjimas",
     "filesTitle": "Failai ir nuotraukos",
     "activity": {

+ 4 - 0
messages/nb/service.json

@@ -687,6 +687,10 @@
     "email": "E-post",
     "notSet": "Ikke satt",
     "noCustomer": "Ingen kunde på denne arbeidsordren.",
+    "addCustomer": "Legg til kunde",
+    "addCustomerHint": "Kunden du velger blir eier av dette kjøretøyet.",
+    "addCustomerHintMarine": "Kunden du velger blir eier av dette fartøyet.",
+    "addCustomerFailed": "Kunne ikke legge til kunden. Prøv igjen.",
     "invoiceTitle": "Faktura og betaling",
     "filesTitle": "Filer og media",
     "activity": {

+ 4 - 0
messages/nl/service.json

@@ -687,6 +687,10 @@
     "email": "E-mail",
     "notSet": "Niet ingevuld",
     "noCustomer": "Geen klant op deze werkorder.",
+    "addCustomer": "Klant toevoegen",
+    "addCustomerHint": "De klant die je kiest wordt de eigenaar van dit voertuig.",
+    "addCustomerHintMarine": "De klant die je kiest wordt de eigenaar van dit vaartuig.",
+    "addCustomerFailed": "Kan de klant niet toevoegen. Probeer het opnieuw.",
     "invoiceTitle": "Factuur en betaling",
     "filesTitle": "Bestanden en media",
     "activity": {

+ 4 - 0
messages/pl/service.json

@@ -687,6 +687,10 @@
     "email": "E-mail",
     "notSet": "Nie ustawiono",
     "noCustomer": "To zlecenie nie ma klienta.",
+    "addCustomer": "Dodaj klienta",
+    "addCustomerHint": "Wybrany klient zostanie właścicielem tego pojazdu.",
+    "addCustomerHintMarine": "Wybrany klient zostanie właścicielem tej jednostki pływającej.",
+    "addCustomerFailed": "Nie udało się dodać klienta. Spróbuj ponownie.",
     "invoiceTitle": "Faktura i płatność",
     "filesTitle": "Pliki i multimedia",
     "activity": {

+ 4 - 0
messages/pt-BR/service.json

@@ -687,6 +687,10 @@
     "email": "E-mail",
     "notSet": "Não definido",
     "noCustomer": "Nenhum cliente nesta ordem de serviço.",
+    "addCustomer": "Adicionar cliente",
+    "addCustomerHint": "O cliente escolhido passa a ser o proprietário deste veículo.",
+    "addCustomerHintMarine": "O cliente escolhido passa a ser o proprietário desta embarcação.",
+    "addCustomerFailed": "Não foi possível adicionar o cliente. Tente novamente.",
     "invoiceTitle": "Fatura e pagamento",
     "filesTitle": "Arquivos e mídia",
     "activity": {

+ 4 - 0
messages/pt-PT/service.json

@@ -687,6 +687,10 @@
     "email": "E-mail",
     "notSet": "Não definido",
     "noCustomer": "Nenhum cliente nesta ordem de serviço.",
+    "addCustomer": "Adicionar cliente",
+    "addCustomerHint": "O cliente escolhido passa a ser o proprietário desta viatura.",
+    "addCustomerHintMarine": "O cliente escolhido passa a ser o proprietário desta embarcação.",
+    "addCustomerFailed": "Não foi possível adicionar o cliente. Tente novamente.",
     "invoiceTitle": "Fatura e pagamento",
     "filesTitle": "Ficheiros e multimédia",
     "activity": {

+ 4 - 0
messages/ru/service.json

@@ -687,6 +687,10 @@
     "email": "Эл. почта",
     "notSet": "Не указано",
     "noCustomer": "В этом заказ-наряде нет клиента.",
+    "addCustomer": "Добавить клиента",
+    "addCustomerHint": "Выбранный клиент станет владельцем этого транспортного средства.",
+    "addCustomerHintMarine": "Выбранный клиент станет владельцем этого судна.",
+    "addCustomerFailed": "Не удалось добавить клиента. Попробуйте снова.",
     "invoiceTitle": "Счёт и оплата",
     "filesTitle": "Файлы и медиа",
     "activity": {

+ 4 - 0
messages/tr/service.json

@@ -687,6 +687,10 @@
     "email": "E-posta",
     "notSet": "Belirtilmedi",
     "noCustomer": "Bu iş emrinde müşteri yok.",
+    "addCustomer": "Müşteri ekle",
+    "addCustomerHint": "Seçtiğiniz müşteri bu aracın sahibi olur.",
+    "addCustomerHintMarine": "Seçtiğiniz müşteri bu teknenin sahibi olur.",
+    "addCustomerFailed": "Müşteri eklenemedi. Tekrar deneyin.",
     "invoiceTitle": "Fatura ve ödeme",
     "filesTitle": "Dosyalar ve medya",
     "activity": {

+ 154 - 0
src/__tests__/features/vehicles/vehicle-update-partial.test.ts

@@ -0,0 +1,154 @@
+/**
+ * Putting a customer on a vehicle from the work order sends the vehicle's id
+ * and the customer, nothing else. The update schema used to inherit the new
+ * vehicle's `mileage` default of 0, which zod fills in even on an optional
+ * field: the save wrote 0 over the reading and marked it as typed by hand.
+ * An update writes only what it was sent.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+
+vi.mock('@/lib/resolve-upload-path', () => ({
+  resolveUploadPath: vi.fn((url: string) => `/uploads/${url}`),
+}))
+
+// These tests are about workshop scoping, not files: the file manager and the
+// files a delete collects have tests of their own (src/__tests__/lib/files).
+vi.mock('@/lib/files/collect', () => ({
+  serviceRecordFileUrls: vi.fn(async () => []),
+  inspectionFileUrls: vi.fn(async () => []),
+  vehicleFileUrls: vi.fn(async () => []),
+  quoteFileUrls: vi.fn(async () => []),
+  tireSetFileUrls: vi.fn(async () => []),
+  inventoryPartFileUrls: vi.fn(async () => []),
+}))
+vi.mock('@/lib/files/manager', () => ({
+  releaseFiles: vi.fn(async () => ({ removed: [], kept: [], skipped: [] })),
+  parseStoredFileUrl: vi.fn(() => null),
+}))
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    vehicle: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      updateMany: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    customer: { findFirst: vi.fn(), count: vi.fn() },
+    quote: { findMany: vi.fn().mockResolvedValue([]) },
+    serviceRecord: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      delete: vi.fn(),
+    },
+    serviceAttachment: {
+      findFirst: vi.fn(),
+      delete: vi.fn(),
+    },
+    servicePart: { findMany: vi.fn() },
+    inventoryPart: { updateMany: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
+import { createVehicleSchema, updateVehicleSchema } from '@/features/vehicles/Schema/vehicleSchema'
+
+const mockSession = vi.mocked(getCachedSession)
+const mockMembership = vi.mocked(getCachedMembership)
+const mockUserFindUnique = vi.mocked(db.user.findUnique)
+
+const ORG_A = 'org-a'
+const ORG_B = 'org-b'
+
+function setupOrgAOwner() {
+  mockSession.mockResolvedValue({ user: { id: 'user-a', email: 'a@example.com' } } as any)
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any)
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([] as any)
+  setupOrgAOwner()
+  vi.mocked(db.vehicle.findFirst).mockResolvedValue({
+    year: 2013,
+    make: 'Land Rover',
+    model: 'Evoque',
+    licensePlate: '094425-113-16',
+    vin: null,
+    imageUrl: null,
+    mileage: 50000,
+  } as any)
+  vi.mocked(db.customer.findFirst).mockResolvedValue({ id: 'cus-1' } as any)
+  vi.mocked(db.customer.count).mockResolvedValue(1 as any)
+  vi.mocked(db.vehicle.updateMany).mockResolvedValue({ count: 1 } as any)
+})
+
+describe('the update schema', () => {
+  it('leaves out the reading when it was not sent', () => {
+    const parsed = updateVehicleSchema.parse({ id: 'veh-a', customerId: 'cus-1' })
+    expect(parsed).toEqual({ id: 'veh-a', customerId: 'cus-1' })
+    expect('mileage' in parsed).toBe(false)
+  })
+
+  it('adds nothing to an update that names only the vehicle', () => {
+    expect(updateVehicleSchema.parse({ id: 'veh-a' })).toEqual({ id: 'veh-a' })
+  })
+
+  it('keeps a reading that was sent, a zero too', () => {
+    expect(updateVehicleSchema.parse({ id: 'veh-a', mileage: '51200' }).mileage).toBe(51200)
+    expect(updateVehicleSchema.parse({ id: 'veh-a', mileage: 0 }).mileage).toBe(0)
+    expect(() => updateVehicleSchema.parse({ id: 'veh-a', mileage: -1 })).toThrow()
+  })
+
+  it('still starts a new vehicle at 0', () => {
+    const parsed = createVehicleSchema.parse({ make: 'Land Rover', model: 'Evoque', year: 2013 })
+    expect(parsed.mileage).toBe(0)
+  })
+})
+
+describe('updateVehicle with only a customer', () => {
+  it('writes the customer and leaves the reading and where it came from alone', async () => {
+    const result = await updateVehicle({ id: 'veh-a', customerId: 'cus-1' })
+
+    expect(result.success).toBe(true)
+    const call = vi.mocked(db.vehicle.updateMany).mock.calls[0][0]
+    expect(call.where).toEqual({ id: 'veh-a', organizationId: ORG_A })
+    const data = call.data as Record<string, unknown>
+    expect(data.customerId).toBe('cus-1')
+    expect(data.mileage).toBeUndefined()
+    expect('readingJobId' in data).toBe(false)
+    expect('readingBeforeJob' in data).toBe(false)
+    // Nothing but the customer is written.
+    const written = Object.entries(data).filter(([, value]) => value !== undefined)
+    expect(written).toEqual([['customerId', 'cus-1']])
+    expect(result.data?.fields).toEqual(['customerId'])
+  })
+
+  it('marks a reading typed on the vehicle form as set by hand, as before', async () => {
+    await updateVehicle({ id: 'veh-a', mileage: 51200 })
+
+    const data = vi.mocked(db.vehicle.updateMany).mock.calls[0][0].data as Record<string, unknown>
+    expect(data.mileage).toBe(51200)
+    expect(data.readingJobId).toBeNull()
+    expect(data.readingBeforeJob).toBeNull()
+  })
+})

+ 303 - 0
src/__tests__/features/vehicles/work-order-add-customer.test.tsx

@@ -0,0 +1,303 @@
+/**
+ * The Customer box on a work order whose vehicle has no owner. It used to say
+ * "No customer on this work order." and nothing else, and a new workshop
+ * clicked that sentence five times before giving up. Now the sentence and an
+ * "Add customer" button open the customer picker; the customer picked is put
+ * on the vehicle and the box fills in. Someone who may not edit vehicles, and
+ * a locked invoice, keep the sentence alone.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { createPortal } from 'react-dom'
+
+// Radix measures the popover's anchor; jsdom has no ResizeObserver, and
+// nothing here needs measuring.
+// biome-ignore lint/suspicious/noEmptyBlockStatements: a stub that measures nothing
+const noop = () => {}
+vi.stubGlobal(
+  'ResizeObserver',
+  class {
+    observe = noop
+    unobserve = noop
+    disconnect = noop
+  }
+)
+Element.prototype.scrollIntoView = noop
+
+const { updateVehicle, searchCustomers } = vi.hoisted(() => ({
+  updateVehicle: vi.fn(),
+  searchCustomers: vi.fn(),
+}))
+
+vi.mock('@/features/quotes/Components/VehicleCombobox', () => ({ VehicleCombobox: () => null }))
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn() }) }))
+vi.mock('@/features/vehicles/Actions/vehicleActions', () => ({ updateVehicle }))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  searchCustomers,
+  createCustomer: vi.fn(),
+}))
+// The new-customer form is its own screen with its own tests; here it stands
+// in as what it is to the page around it: a form in a portal, outside the
+// work order's form in the document and inside it in React's tree.
+vi.mock('@/features/customers/Components/CustomerForm', () => ({
+  CustomerForm: ({
+    open,
+    defaults,
+    onCreated,
+  }: {
+    open: boolean
+    defaults?: { name?: string }
+    onCreated?: (c: { id: string; name: string; company: string | null }) => void
+  }) =>
+    open
+      ? createPortal(
+          <form
+            aria-label="new customer"
+            onSubmit={(e) => {
+              e.preventDefault()
+              onCreated?.({ id: 'cus-new', name: defaults?.name ?? '', company: null })
+            }}
+          >
+            <button type="submit">save new customer</button>
+          </form>,
+          document.body
+        )
+      : null,
+}))
+
+import { BookingAccessProvider } from '@/components/booking-launcher'
+import { ServiceTypeProvider } from '@/components/service-type-context'
+import { JobFactsCard } from '@/features/vehicles/Components/service-page/modern/JobFactsCard'
+
+type Props = React.ComponentProps<typeof JobFactsCard>
+
+const SENTENCE = 'No customer on this work order.'
+const VEHICLE = {
+  id: 'veh-1',
+  make: 'Land Rover',
+  model: 'Evoque',
+  year: 2013,
+  vin: null,
+  licensePlate: '094425-113-16',
+  mileage: 50000,
+  customer: null,
+}
+
+type Over = Partial<Props> & {
+  marine?: boolean
+  canAddCustomer?: boolean
+  noVehicle?: boolean
+  /** The customer the saved vehicle has, as the page read it. */
+  owner?: { id: string; name: string } | null
+}
+
+/** The card inside the work order's form, as the page mounts it. */
+function renderCard(over: Over = {}) {
+  const onCustomerAdded = vi.fn()
+  const onFormSubmit = vi.fn((e: React.FormEvent) => e.preventDefault())
+  const onFormInput = vi.fn()
+  const tree = (now: Over) => {
+    const { marine, canAddCustomer = true, noVehicle, owner = null, ...props } = now
+    const card = (
+      <BookingAccessProvider value={{ canBook: true, canAddCustomer }}>
+        <form aria-label="work order" onSubmit={onFormSubmit} onInput={onFormInput}>
+          <JobFactsCard
+            record={
+              {
+                id: 'job-1',
+                vehicle: noVehicle ? null : { ...VEHICLE, customer: owner },
+                customer: null,
+              } as unknown as Props['record']
+            }
+            currencyCode="EUR"
+            initialData={
+              { id: 'job-1', mileage: 50000, lastReading: 50000 } as Props['initialData']
+            }
+            vehicleName="2013 Land Rover Evoque"
+            selectedVehicleId={noVehicle ? null : 'veh-1'}
+            setSelectedVehicleId={vi.fn()}
+            techName=""
+            canSetCustomer
+            onCustomerAdded={onCustomerAdded}
+            {...props}
+          />
+        </form>
+      </BookingAccessProvider>
+    )
+    return marine ? <ServiceTypeProvider serviceType="marine">{card}</ServiceTypeProvider> : card
+  }
+  const view = render(tree(over))
+  return {
+    onCustomerAdded,
+    onFormSubmit,
+    onFormInput,
+    /** The page read the job again and hands the card what it found. */
+    reread: (next: Over) => view.rerender(tree({ ...over, ...next })),
+  }
+}
+
+beforeEach(() => {
+  updateVehicle.mockReset().mockResolvedValue({ success: true, data: { id: 'veh-1' } })
+  searchCustomers.mockReset().mockResolvedValue({
+    success: true,
+    data: [{ id: 'cus-1', name: 'Yacine Benali', company: null }],
+  })
+})
+
+describe('a work order whose vehicle has no customer', () => {
+  it('keeps the sentence and offers a button to add a customer', () => {
+    renderCard()
+    expect(screen.getByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Add customer' })).toBeInTheDocument()
+  })
+
+  it('puts the customer picked on the vehicle and fills the box', async () => {
+    const { onCustomerAdded } = renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    expect(
+      screen.getByText('The customer you pick becomes the owner of this vehicle.')
+    ).toBeInTheDocument()
+    fireEvent.click(await screen.findByText('Yacine Benali'))
+
+    await waitFor(() =>
+      expect(updateVehicle).toHaveBeenCalledWith({ id: 'veh-1', customerId: 'cus-1' })
+    )
+    expect(await screen.findByRole('link', { name: 'Yacine Benali' })).toHaveAttribute(
+      'href',
+      '/customers/cus-1'
+    )
+    expect(screen.queryByText(SENTENCE)).not.toBeInTheDocument()
+    expect(onCustomerAdded).toHaveBeenCalledTimes(1)
+  })
+
+  it('opens the picker from a click on the sentence itself', async () => {
+    renderCard()
+    fireEvent.click(screen.getByText(SENTENCE))
+    expect(await screen.findByText('Yacine Benali')).toBeInTheDocument()
+  })
+
+  it('adds a new customer from the picker, starting from what was searched for', async () => {
+    renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    fireEvent.change(await screen.findByPlaceholderText('Search customers...'), {
+      target: { value: 'Karim' },
+    })
+    fireEvent.click(screen.getByRole('button', { name: 'Add Customer' }))
+    fireEvent.submit(screen.getByRole('form', { name: 'new customer' }))
+
+    await waitFor(() =>
+      expect(updateVehicle).toHaveBeenCalledWith({ id: 'veh-1', customerId: 'cus-new' })
+    )
+    expect(await screen.findByRole('link', { name: 'Karim' })).toBeInTheDocument()
+  })
+
+  it('does not offer a new customer to someone who may not add one', async () => {
+    renderCard({ canAddCustomer: false })
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    await screen.findByText('Yacine Benali')
+    expect(screen.queryByRole('button', { name: 'Add Customer' })).not.toBeInTheDocument()
+  })
+
+  it('says so and keeps the box empty when the save is refused', async () => {
+    updateVehicle.mockResolvedValue({ success: false, error: 'Vehicle not found' })
+    const { onCustomerAdded } = renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    fireEvent.click(await screen.findByText('Yacine Benali'))
+
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalled())
+    expect(await screen.findByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.queryByRole('link', { name: 'Yacine Benali' })).not.toBeInTheDocument()
+    expect(onCustomerAdded).not.toHaveBeenCalled()
+  })
+
+  it('leaves the work order alone while a customer is searched for and added', async () => {
+    const { onFormSubmit, onFormInput } = renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    // Typing in the search is not an edit of the work order.
+    fireEvent.input(await screen.findByPlaceholderText('Search customers...'), {
+      target: { value: 'Karim' },
+    })
+    expect(onFormInput).not.toHaveBeenCalled()
+
+    // Saving the new customer's form does not submit the work order's.
+    fireEvent.click(screen.getByRole('button', { name: 'Add Customer' }))
+    fireEvent.submit(screen.getByRole('form', { name: 'new customer' }))
+    await waitFor(() =>
+      expect(updateVehicle).toHaveBeenCalledWith({ id: 'veh-1', customerId: 'cus-new' })
+    )
+    expect(onFormSubmit).not.toHaveBeenCalled()
+    expect(onFormInput).not.toHaveBeenCalled()
+  })
+
+  it('still counts a reading typed in the same card as an edit of the work order', () => {
+    const { onFormInput } = renderCard()
+    fireEvent.input(screen.getByLabelText('Mileage'), { target: { value: '50100' } })
+    expect(onFormInput).toHaveBeenCalled()
+  })
+
+  it('offers to add a customer again when the owner is later taken off the vehicle', async () => {
+    const { reread } = renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    fireEvent.click(await screen.findByText('Yacine Benali'))
+    expect(await screen.findByRole('link', { name: 'Yacine Benali' })).toBeInTheDocument()
+
+    // The page reads the job again and has the saved owner; later the owner is
+    // removed on the vehicle's own page, and the next read finds none.
+    reread({ owner: { id: 'cus-1', name: 'Yacine Benali' } })
+    expect(screen.getByRole('link', { name: 'Yacine Benali' })).toBeInTheDocument()
+    reread({ owner: null })
+    await waitFor(() => expect(screen.getByText(SENTENCE)).toBeInTheDocument())
+    expect(screen.queryByRole('link', { name: 'Yacine Benali' })).not.toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Add customer' })).toBeInTheDocument()
+  })
+
+  it('does not show the customer added to one vehicle on another', async () => {
+    const { reread } = renderCard()
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    fireEvent.click(await screen.findByText('Yacine Benali'))
+    expect(await screen.findByRole('link', { name: 'Yacine Benali' })).toBeInTheDocument()
+
+    // The job was saved onto another vehicle, one with no owner.
+    reread({
+      record: {
+        id: 'job-1',
+        vehicle: { ...VEHICLE, id: 'veh-2', customer: null },
+        customer: null,
+      } as unknown as Props['record'],
+    })
+    await waitFor(() => expect(screen.getByText(SENTENCE)).toBeInTheDocument())
+    // And back: what was added the first time is not brought out again.
+    reread({})
+    expect(screen.getByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.queryByRole('link', { name: 'Yacine Benali' })).not.toBeInTheDocument()
+  })
+
+  it('speaks of the vessel in a marine workshop', () => {
+    renderCard({ marine: true })
+    fireEvent.click(screen.getByRole('button', { name: 'Add customer' }))
+    expect(
+      screen.getByText('The customer you pick becomes the owner of this vessel.')
+    ).toBeInTheDocument()
+  })
+
+  it('shows the sentence alone to someone who may not edit vehicles', () => {
+    renderCard({ canSetCustomer: false })
+    expect(screen.getByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.queryByRole('button', { name: 'Add customer' })).not.toBeInTheDocument()
+    fireEvent.click(screen.getByText(SENTENCE))
+    expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+  })
+
+  it('shows the sentence alone on a locked invoice, where the vehicle cannot be changed either', () => {
+    renderCard({ locked: true })
+    expect(screen.getByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.queryByRole('button', { name: 'Add customer' })).not.toBeInTheDocument()
+  })
+
+  it('shows the sentence alone on a job with no vehicle to put the customer on', () => {
+    renderCard({ noVehicle: true })
+    expect(screen.getByText(SENTENCE)).toBeInTheDocument()
+    expect(screen.queryByRole('button', { name: 'Add customer' })).not.toBeInTheDocument()
+  })
+})

+ 128 - 0
src/__tests__/lib/vehicle-access.test.ts

@@ -0,0 +1,128 @@
+/**
+ * The work order offers "Add customer" only to someone `updateVehicle` would
+ * let through. `canEditVehicles` answers ahead of time what `withAuth` will
+ * answer when the button is pressed, so the two are asked the same question
+ * here for every kind of account and must agree.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    auditLog: { create: vi.fn() },
+  },
+}))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn(async () => undefined) }))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { getAuthContext } from '@/lib/get-auth-context'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { canEditVehicles } from '@/lib/vehicle-access'
+import { withAuth } from '@/lib/with-auth'
+
+const UPDATE_VEHICLES = { action: PermissionAction.UPDATE, subject: PermissionSubject.VEHICLES }
+const READ_VEHICLES = { action: PermissionAction.READ, subject: PermissionSubject.VEHICLES }
+const UPDATE_CUSTOMERS = { action: PermissionAction.UPDATE, subject: PermissionSubject.CUSTOMERS }
+
+interface Account {
+  who: string
+  role: string
+  superAdmin?: boolean
+  /** A session a workshop minted: none of the account's platform rights. */
+  scoped?: boolean
+  customRole?: { isAdmin?: boolean; permissions: { action: string; subject: string }[] } | null
+  allowed: boolean
+}
+
+const ACCOUNTS: Account[] = [
+  { who: 'the owner', role: 'owner', allowed: true },
+  { who: 'an admin', role: 'admin', allowed: true },
+  {
+    who: 'an admin with a custom role that lacks it',
+    role: 'admin',
+    customRole: { permissions: [READ_VEHICLES] },
+    allowed: true,
+  },
+  { who: 'a super admin who is a plain member', role: 'member', superAdmin: true, allowed: true },
+  {
+    who: 'a super admin with a custom role that lacks it',
+    role: 'member',
+    superAdmin: true,
+    customRole: { permissions: [READ_VEHICLES] },
+    allowed: true,
+  },
+  {
+    who: 'a super admin on a session bound to one workshop, with no role',
+    role: 'member',
+    superAdmin: true,
+    scoped: true,
+    allowed: false,
+  },
+  { who: 'a member with no custom role', role: 'member', customRole: null, allowed: false },
+  {
+    who: 'a member whose custom role may update vehicles',
+    role: 'member',
+    customRole: { permissions: [READ_VEHICLES, UPDATE_VEHICLES] },
+    allowed: true,
+  },
+  {
+    who: 'a member whose custom role may only read vehicles',
+    role: 'member',
+    customRole: { permissions: [READ_VEHICLES, UPDATE_CUSTOMERS] },
+    allowed: false,
+  },
+  {
+    who: 'a member whose custom role has no permissions',
+    role: 'member',
+    customRole: { permissions: [] },
+    allowed: false,
+  },
+  {
+    who: 'a member whose custom role is marked as admin',
+    role: 'member',
+    customRole: { isAdmin: true, permissions: [] },
+    allowed: true,
+  },
+]
+
+function signIn(account: Account) {
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-1', email: 'someone@example.com' },
+    session: account.scoped ? { organizationId: 'org-1' } : {},
+  } as never)
+  vi.mocked(db.user.findUnique).mockResolvedValue({
+    isSuperAdmin: account.superAdmin ?? false,
+  } as never)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: 'org-1',
+    role: account.role,
+    roleId: account.customRole ? 'role-1' : null,
+    customRole: account.customRole ?? null,
+  } as never)
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+})
+
+describe('who is offered "Add customer" on a work order', () => {
+  it.each(ACCOUNTS)('$who: $allowed, and the save agrees', async (account) => {
+    signIn(account)
+
+    const offered = await canEditVehicles(await getAuthContext())
+    const saved = await withAuth(async () => 'saved', { requiredPermissions: [UPDATE_VEHICLES] })
+
+    expect(offered).toBe(account.allowed)
+    expect(saved.success).toBe(account.allowed)
+  })
+
+  it('offers nothing to nobody', async () => {
+    expect(await canEditVehicles(null)).toBe(false)
+  })
+})

+ 4 - 1
src/features/quotes/Components/CustomerCombobox.tsx

@@ -42,6 +42,8 @@ interface CustomerComboboxProps {
   disabled?: boolean
   /** The chosen customer's initials in a circle before the name, as an owner is shown */
   showAvatar?: boolean
+  /** Starts with the list open, for a picker shown because it was asked for */
+  defaultOpen?: boolean
 }
 
 export function CustomerCombobox({
@@ -55,8 +57,9 @@ export function CustomerCombobox({
   footer,
   disabled = false,
   showAvatar = false,
+  defaultOpen = false,
 }: CustomerComboboxProps) {
-  const [open, setOpen] = useState(false)
+  const [open, setOpen] = useState(defaultOpen)
   const [search, setSearch] = useState('')
   const [options, setOptions] = useState<CustomerOption[]>([])
   const [searching, setSearching] = useState(false)

+ 2 - 0
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -90,6 +90,7 @@ export function ServicePageClient({
   onlinePayments = false,
   workOrderStatuses = [],
   canAddStatus = false,
+  canSetCustomer = false,
   videoCall = { link: null, providers: [] },
   tireThresholds,
   defaultTaxRate,
@@ -723,6 +724,7 @@ export function ServicePageClient({
                   {...sidebarProps}
                   workOrderStatuses={workOrderStatuses}
                   canAddStatus={canAddStatus}
+                  canSetCustomer={canSetCustomer}
                   onNotifyForStatus={handleNotifyForStatus}
                   locked={lockState.locked}
                   lockedLabel={t('invoice.lockedFieldsetLabel')}

+ 4 - 0
src/features/vehicles/Components/service-page/ServiceRecordPage.tsx

@@ -48,6 +48,7 @@ import {
 import { invoiceDesignPrintsConditionMap } from '@/features/invoices/Lib/assembleInvoicePrint'
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
 import { canEditSettings } from '@/lib/settings-access'
+import { canEditVehicles } from '@/lib/vehicle-access'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
 import { listDesignOptions } from '@/features/invoice-designer/Actions/documentDesignActions'
 import { rendersFromIssue } from '@/features/invoices/Lib/issuedInvoice'
@@ -189,6 +190,8 @@ export async function ServiceRecordPage({
   // Whether the status menus offer the way to add a status. Somebody who
   // cannot change settings is better off not seeing a link that turns them away.
   const canAddStatus = await canEditSettings(session?.user?.id ?? '', membership?.role)
+  // Whether a job whose vehicle has no owner offers to add one.
+  const canSetCustomer = await canEditVehicles(authContext)
 
   const [currentUser, features, aiProvider, dictation, tireHotel] = await Promise.all([
     session?.user?.id
@@ -510,6 +513,7 @@ export async function ServiceRecordPage({
         tireHotelEnabled={tireHotel.enabled}
         onlinePayments={onlinePayments}
         canAddStatus={canAddStatus}
+        canSetCustomer={canSetCustomer}
         workOrderStatuses={
           workOrderStatusesResult.success && workOrderStatusesResult.data
             ? workOrderStatusesResult.data

+ 162 - 0
src/features/vehicles/Components/service-page/modern/AddJobCustomer.tsx

@@ -0,0 +1,162 @@
+'use client'
+
+import { useId, useState } from 'react'
+import { useTranslations } from 'next-intl'
+import { Loader2, Plus, UserPlus } from 'lucide-react'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import { useBookingAccess } from '@/components/booking-launcher'
+import { useServiceType } from '@/components/service-type-context'
+import { handleGated } from '@/components/upgrade-gate'
+import { CustomerForm } from '@/features/customers/Components/CustomerForm'
+import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
+import { updateVehicle } from '../../../Actions/vehicleActions'
+import type { ServiceDetail } from '../../service-detail/types'
+
+type JobCustomer = NonNullable<ServiceDetail['customer']>
+
+/** The customer added from the work order, and the vehicle it was put on. */
+export interface AddedCustomer {
+  vehicleId: string
+  customer: JobCustomer
+}
+
+interface PickedCustomer {
+  id: string
+  name: string
+  company: string | null
+}
+
+/**
+ * The Customer box of a job whose vehicle has no owner. The sentence used to
+ * be all there was, and people clicked it expecting to add one: now it and
+ * the button under it open the customer picker the vehicle form uses, with
+ * the same way to add a new customer. The customer picked becomes the
+ * vehicle's owner, which is where a work order reads its customer from.
+ */
+export function AddJobCustomer({
+  vehicleId,
+  onAdded,
+}: {
+  vehicleId: string
+  onAdded: (customer: JobCustomer) => void
+}) {
+  const t = useTranslations('service.modern')
+  const tv = useTranslations('vehicles.form')
+  const isMarine = useServiceType() === 'marine'
+  const { canAddCustomer } = useBookingAccess()
+  const sentenceId = useId()
+  const [picking, setPicking] = useState(false)
+  const [saving, setSaving] = useState(false)
+  const [showCustomerForm, setShowCustomerForm] = useState(false)
+  // What was typed in the search when "Add customer" was chosen: the new
+  // customer's form starts from it.
+  const [newName, setNewName] = useState('')
+
+  const save = async (picked: PickedCustomer) => {
+    setSaving(true)
+    // An action that cannot reach the server throws instead of answering, so
+    // it is reported the way a refusal is and the picker comes back.
+    const result = await updateVehicle({ id: vehicleId, customerId: picked.id }).catch(() => null)
+    setSaving(false)
+    if (!result?.success) {
+      if (!result || !handleGated(result)) toast.error(result?.error || t('addCustomerFailed'))
+      return
+    }
+    // Enough to fill the box at once; the page reads the rest (phone, email)
+    // when it loads the job again.
+    onAdded({
+      id: picked.id,
+      name: picked.name,
+      company: picked.company,
+      email: null,
+      phone: null,
+      address: null,
+      telegramChatId: null,
+    })
+  }
+
+  return (
+    // Its own island inside the work order's form, as the files card is: the
+    // picker's search and the new customer's form are portalled out of the
+    // document's form but still bubble to it in React, where typing would
+    // mark the work order edited and saving the customer would submit it.
+    <div
+      className="space-y-2"
+      onInput={(e) => e.stopPropagation()}
+      onSubmit={(e) => e.stopPropagation()}
+    >
+      {/* A second way in for the mouse: the sentence is where people clicked.
+          The button under it is the control the keyboard reaches. */}
+      <p
+        id={sentenceId}
+        className={
+          picking ? 'text-sm text-muted-foreground' : 'cursor-pointer text-sm text-muted-foreground'
+        }
+        onClick={picking ? undefined : () => setPicking(true)}
+      >
+        {t('noCustomer')}
+      </p>
+      {saving ? (
+        <div className="flex h-9 items-center" role="status" aria-label={t('addCustomer')}>
+          <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+        </div>
+      ) : picking ? (
+        <>
+          <CustomerCombobox
+            defaultOpen
+            showAvatar
+            value=""
+            placeholder={tv('searchCustomers')}
+            noneLabel={tv('noCustomer')}
+            emptyLabel={tv('noCustomerFound')}
+            onChange={(_id, picked) => {
+              if (picked) void save(picked)
+              else setPicking(false)
+            }}
+            footer={
+              canAddCustomer
+                ? (close, search) => (
+                    <div className="border-t p-1">
+                      <button
+                        type="button"
+                        className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
+                        onClick={() => {
+                          close()
+                          setNewName(search.trim())
+                          setShowCustomerForm(true)
+                        }}
+                      >
+                        <Plus className="h-4 w-4" />
+                        {tv('addCustomer')}
+                      </button>
+                    </div>
+                  )
+                : undefined
+            }
+          />
+          <p className="text-xs text-muted-foreground">
+            {isMarine ? t('addCustomerHintMarine') : t('addCustomerHint')}
+          </p>
+        </>
+      ) : (
+        <Button
+          type="button"
+          variant="outline"
+          size="sm"
+          aria-describedby={sentenceId}
+          onClick={() => setPicking(true)}
+        >
+          <UserPlus className="mr-1.5 h-3.5 w-3.5" />
+          {t('addCustomer')}
+        </Button>
+      )}
+      <CustomerForm
+        open={showCustomerForm}
+        onOpenChange={setShowCustomerForm}
+        defaults={newName ? { name: newName } : undefined}
+        onCreated={(created) => void save(created)}
+      />
+    </div>
+  )
+}

+ 36 - 1
src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx

@@ -27,6 +27,7 @@ import { setServiceRecordReference } from '@/features/customer-reference/Actions
 import { ReadingNotice, useReadingNotice } from '../../ReadingNotice'
 import { ReadingQuestion } from '../../ReadingQuestion'
 import { readingNeedsAnswer } from '../../../Lib/vehicleReading'
+import { AddJobCustomer, type AddedCustomer } from './AddJobCustomer'
 
 interface JobFactsCardProps {
   record: ServiceDetail
@@ -58,6 +59,13 @@ interface JobFactsCardProps {
   /** The Reference / PO box, as it is typed and once it has saved. */
   onReferenceChange?: (reference: string) => void
   onReferenceSaved?: () => void
+  /**
+   * The viewer may edit vehicles, so a job whose vehicle has no owner offers
+   * to add one. Without it the empty Customer box is the sentence alone.
+   */
+  canSetCustomer?: boolean
+  /** A customer was put on the vehicle: the page reads the job again. */
+  onCustomerAdded?: () => void
 }
 
 function initials(name: string): string {
@@ -148,6 +156,8 @@ export function JobFactsCard({
   distanceUnit,
   confirmedReading = null,
   onConfirmReading,
+  canSetCustomer = false,
+  onCustomerAdded,
 }: JobFactsCardProps) {
   const referenceEnabled = useCustomerReferenceEnabled()
   const t = useTranslations('service')
@@ -184,8 +194,23 @@ export function JobFactsCard({
     }
   }
 
-  const customer = record.customer ?? record.vehicle?.customer ?? null
+  // The customer just added here, shown until the page has read the job again.
+  const [addedCustomer, setAddedCustomer] = useState<AddedCustomer | null>(null)
   const vehicle = record.vehicle
+  const savedCustomer = record.customer ?? vehicle?.customer ?? null
+  const customer =
+    savedCustomer ??
+    (addedCustomer?.vehicleId === vehicle?.id ? (addedCustomer?.customer ?? null) : null)
+  // It stands in only until the page has the saved one, and only for the
+  // vehicle it was put on. Kept past that, an owner removed elsewhere would
+  // come back here on the next read and hide "Add customer".
+  const savedCustomerId = savedCustomer?.id ?? null
+  const savedVehicleId = vehicle?.id ?? null
+  useEffect(() => {
+    setAddedCustomer((added) =>
+      added && (savedCustomerId || added.vehicleId !== savedVehicleId) ? null : added
+    )
+  }, [savedCustomerId, savedVehicleId])
   // The picker can point the job at another vehicle before the save; the facts
   // on this card describe the saved one, so say which is which while they differ.
   const vehicleChanged = Boolean(vehicle && selectedVehicleId && selectedVehicleId !== vehicle.id)
@@ -295,6 +320,16 @@ export function JobFactsCard({
                 </div>
               </dl>
             </>
+          ) : vehicle && canSetCustomer && !locked ? (
+            // The owner is the vehicle's, so a job with no vehicle (or one the
+            // viewer may not edit, or a locked invoice) keeps the sentence alone.
+            <AddJobCustomer
+              vehicleId={vehicle.id}
+              onAdded={(added) => {
+                setAddedCustomer({ vehicleId: vehicle.id, customer: added })
+                onCustomerAdded?.()
+              }}
+            />
           ) : (
             <p className="text-sm text-muted-foreground">{t('modern.noCustomer')}</p>
           )}

+ 4 - 0
src/features/vehicles/Components/service-page/modern/ModernDetails.tsx

@@ -49,6 +49,8 @@ export interface ModernDetailsProps
   workOrderStatuses?: WorkOrderStatusOption[]
   /** The viewer may change settings, so the status menus offer to add a status. */
   canAddStatus?: boolean
+  /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
+  canSetCustomer?: boolean
   /** Offers to tell the customer about a status that asks for it. */
   onNotifyForStatus?: (status: WorkOrderStatusOption) => void
   /**
@@ -370,6 +372,8 @@ export function ModernDetails(props: ModernDetailsProps) {
                   distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
                   confirmedReading={formState.confirmedReading}
                   onConfirmReading={formState.confirmReading}
+                  canSetCustomer={props.canSetCustomer}
+                  onCustomerAdded={() => router.refresh()}
                 />
 
                 <Lockable locked={locked}>

+ 2 - 0
src/features/vehicles/Components/service-page/service-page-types.ts

@@ -132,6 +132,8 @@ export interface ServicePageClientProps {
   workOrderStatuses?: WorkOrderStatusOption[]
   /** The viewer may change settings, so the status menus offer to add a status. */
   canAddStatus?: boolean
+  /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
+  canSetCustomer?: boolean
   /** The work order's video call, and the connected services that could add one. */
   videoCall?: ServiceVideoCall
   /** The workshop's tread limits, so a set checked in here grades correctly. */

+ 4 - 0
src/features/vehicles/Schema/vehicleSchema.ts

@@ -66,6 +66,10 @@ export const createVehicleSchema = z.object({
 
 export const updateVehicleSchema = createVehicleSchema.partial().extend({
   id: z.string(),
+  // Without the new vehicle's default: zod fills a default in even on an
+  // optional field, so an update that did not send the reading (adding a
+  // customer from the work order) came out with `mileage: 0` and wiped it.
+  mileage: z.coerce.number().min(0).optional(),
 })
 
 export type CreateVehicleInput = z.infer<typeof createVehicleSchema>

+ 26 - 0
src/lib/vehicle-access.ts

@@ -0,0 +1,26 @@
+import { getCachedMembership } from '@/lib/cached-session'
+import { hasAllPermissions, PermissionAction, PermissionSubject } from '@/lib/permissions'
+import type { AuthContext } from '@/lib/with-auth'
+
+/**
+ * Whether this person may edit vehicles, which is what putting a customer on
+ * one is. The answer `withAuth` gives `updateVehicle`, asked ahead of time so
+ * a page does not offer a button that would be refused.
+ *
+ * Takes the page's auth context (`getAuthContext`), which already knows a
+ * super admin from a session bound to one workshop. As in `withAuth`: super
+ * admins, owners, admins and custom roles marked as admin always pass,
+ * whatever else their role says. Everyone else needs UPDATE on vehicles from
+ * their custom role, and a member with no custom role has no permissions.
+ */
+export async function canEditVehicles(
+  context: Pick<AuthContext, 'userId' | 'isAdmin'> | null | undefined
+): Promise<boolean> {
+  if (!context) return false
+  if (context.isAdmin) return true
+
+  const membership = await getCachedMembership(context.userId)
+  return hasAllPermissions(membership?.customRole?.permissions ?? [], [
+    { action: PermissionAction.UPDATE, subject: PermissionSubject.VEHICLES },
+  ])
+}