Sfoglia il codice sorgente

Prevent a work order from being created twice (#629)

* Book once when a booking is sent twice, and reuse a draft that only has the shop fee

The booking dialog makes up a token each time it opens and sends it with
the booking. The job or appointment it books keeps the token, unique within
the workshop, so a second press of Book after a lost answer finds the first
booking instead of making another with the next job number. Two sends that
arrive together are settled by the database: the one refused answers with
what the other booked. The action is now createBookingOnce, so a tab opened
before this is asked to reload rather than book without a token.

The New work order page reuses the draft it made a moment ago only while
nothing is on it. A workshop with a shop fee has the fee as a labor line on
every new job, so the draft never counted as untouched and a second render
made a second job. The fee line no longer counts.

* Keep the booking token out of the AI column list and the restore map

The token only tells a booking sent twice from a new one while its dialog
is open, so the workshop chat does not read it and a restored job does not
carry it.

* Make sends of one booking take turns, whichever kind each is

A send made again as the other kind writes to the other table, where the
token's unique index does not refuse it. Each send now takes a lock on its
token inside the transaction and looks again before it books. A retry that
finds the source appointment already gone looks for the work order before
it reports the appointment missing.

* Take the block next dev wrote into AGENTS.md back out

* Expect a restored booking to come back without its token

The token only matters while the dialog that sent it is open, so a restore
leaves it out on purpose. The round trip test now lists that with the
reason.
Bernt Christian Egeland 8 ore fa
parent
commit
e3bc0554df

+ 18 - 0
prisma/migrations/20261118164615_booking_token/migration.sql

@@ -0,0 +1,18 @@
+/*
+  Warnings:
+
+  - A unique constraint covering the columns `[organizationId,bookingToken]` on the table `appointments` will be added. If there are existing duplicate values, this will fail.
+  - A unique constraint covering the columns `[organizationId,bookingToken]` on the table `service_records` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "appointments" ADD COLUMN     "bookingToken" TEXT;
+
+-- AlterTable
+ALTER TABLE "service_records" ADD COLUMN     "bookingToken" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "appointments_organizationId_bookingToken_key" ON "appointments"("organizationId", "bookingToken");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "service_records_organizationId_bookingToken_key" ON "service_records"("organizationId", "bookingToken");

+ 6 - 0
prisma/schema/appointments.prisma

@@ -27,6 +27,12 @@ model Appointment {
 
 
   notifications AppointmentNotification[]
   notifications AppointmentNotification[]
 
 
+  /// Made up by the booking dialog each time it opens and sent with the
+  /// booking, so a booking sent twice (the answer to the first was lost) is
+  /// found again instead of made again.
+  bookingToken String?
+
+  @@unique([organizationId, bookingToken])
   @@index([organizationId, startAt])
   @@index([organizationId, startAt])
   @@index([customerId])
   @@index([customerId])
   @@index([vehicleId])
   @@index([vehicleId])

+ 6 - 0
prisma/schema/service-records.prisma

@@ -195,6 +195,12 @@ model ServiceRecord {
   importBatchId String?
   importBatchId String?
   importBatch   ImportBatch? @relation(fields: [importBatchId], references: [id], onDelete: SetNull)
   importBatch   ImportBatch? @relation(fields: [importBatchId], references: [id], onDelete: SetNull)
 
 
+  /// Made up by the booking dialog each time it opens and sent with the
+  /// booking, so a booking sent twice (the answer to the first was lost) is
+  /// found again instead of made again. Only jobs booked there have one.
+  bookingToken String?
+
+  @@unique([organizationId, bookingToken])
   @@index([vehicleId])
   @@index([vehicleId])
   @@index([technicianId])
   @@index([technicianId])
   @@index([workBayId])
   @@index([workBayId])

+ 4 - 0
src/__tests__/db/backup-round-trip.db.test.ts

@@ -472,7 +472,10 @@ const OWNED_BY_WHOEVER_RESTORES =
   'The row is owned by whoever restores the backup: the column is required, and the account the file names may not exist here.'
   'The row is owned by whoever restores the backup: the column is required, and the account the file names may not exist here.'
 const PLATE_AS_STORED =
 const PLATE_AS_STORED =
   'A plate is stored in upper case with single spaces (normalizePlate), as the editor stores it, so a backup from before that rule restores in the same form.'
   'A plate is stored in upper case with single spaces (normalizePlate), as the editor stores it, so a backup from before that rule restores in the same form.'
+const BOOKING_TOKEN_SPENT =
+  'The token tells a booking sent twice from a new one while its dialog is still open. No dialog is waiting on a restored booking, so it comes back without one; empty tokens never collide, the unique index counts only the ones that are set.'
 const EXPECTED: Readonly<Record<string, string>> = {
 const EXPECTED: Readonly<Record<string, string>> = {
+  'Appointment.bookingToken': BOOKING_TOKEN_SPENT,
   'AppSetting.userId': OWNED_BY_WHOEVER_RESTORES,
   'AppSetting.userId': OWNED_BY_WHOEVER_RESTORES,
   'CustomFieldDefinition.userId': OWNED_BY_WHOEVER_RESTORES,
   'CustomFieldDefinition.userId': OWNED_BY_WHOEVER_RESTORES,
   'Customer.userId': OWNED_BY_WHOEVER_RESTORES,
   'Customer.userId': OWNED_BY_WHOEVER_RESTORES,
@@ -481,6 +484,7 @@ const EXPECTED: Readonly<Record<string, string>> = {
   'LaborPreset.userId': OWNED_BY_WHOEVER_RESTORES,
   'LaborPreset.userId': OWNED_BY_WHOEVER_RESTORES,
   'Quote.userId': OWNED_BY_WHOEVER_RESTORES,
   'Quote.userId': OWNED_BY_WHOEVER_RESTORES,
   'ScheduledMessage.createdById': OWNED_BY_WHOEVER_RESTORES,
   'ScheduledMessage.createdById': OWNED_BY_WHOEVER_RESTORES,
+  'ServiceRecord.bookingToken': BOOKING_TOKEN_SPENT,
   'StockMovement.userId': OWNED_BY_WHOEVER_RESTORES,
   'StockMovement.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireSet.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireSet.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireWarehouse.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireWarehouse.userId': OWNED_BY_WHOEVER_RESTORES,

+ 220 - 0
src/__tests__/db/booking-token.db.test.ts

@@ -0,0 +1,220 @@
+/**
+ * Booked once, on a real PostgreSQL (`npm run test:db` with E2E_DATABASE_URL
+ * set).
+ *
+ * Two things the unit tests can only describe. The booking token is unique
+ * within a workshop, so the second of two sends that arrive together is
+ * refused by the database rather than by a lookup that both passed; a job
+ * booked any other way has no token, and any number of those sit side by
+ * side. And the draft the "New work order" page just made is found again
+ * when all it carries is the workshop's shop fee.
+ *
+ * It makes one person and two workshops of its own and removes them again; it empties
+ * nothing.
+ */
+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.`
+  )
+}
+
+// Set before the app's modules load, so the client connects to the test database.
+process.env.DATABASE_URL = url
+
+const stamp = randomUUID().slice(0, 8)
+const TOKEN = `token-${randomUUID()}`
+const HOUR = 3_600_000
+const START = new Date('2026-11-18T09:00:00Z')
+
+let db: typeof import('@/lib/db')['db']
+let untouchedDraftWhere: typeof import('@/features/vehicles/Lib/untouchedDraft')['untouchedDraftWhere']
+let organizationId = ''
+let otherOrganizationId = ''
+let vehicleId = ''
+let userId = ''
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  ;({ untouchedDraftWhere } = await import('@/features/vehicles/Lib/untouchedDraft'))
+  organizationId = (await db.organization.create({ data: { name: `Booking ${stamp}` } })).id
+  otherOrganizationId = (await db.organization.create({ data: { name: `Other ${stamp}` } })).id
+  userId = (
+    await db.user.create({
+      data: { name: `Booking ${stamp}`, email: `booking-${stamp}@example.com` },
+    })
+  ).id
+  vehicleId = (
+    await db.vehicle.create({
+      data: { make: 'Volvo', model: '240', year: 1990, organizationId, userId },
+    })
+  ).id
+})
+
+afterAll(async () => {
+  // Jobs, appointments and the vehicle go with their workshop.
+  const ids = [organizationId, otherOrganizationId].filter(Boolean)
+  if (ids.length) await db.organization.deleteMany({ where: { id: { in: ids } } })
+  if (userId) await db.user.deleteMany({ where: { id: userId } })
+})
+
+const job = (org: string, bookingToken: string | null) =>
+  db.serviceRecord.create({ data: { title: 'Booked', organizationId: org, bookingToken } })
+
+const appointment = (org: string, bookingToken: string | null) =>
+  db.appointment.create({
+    data: {
+      title: 'Call',
+      organizationId: org,
+      bookingToken,
+      startAt: START,
+      endAt: new Date(START.getTime() + HOUR),
+    },
+  })
+
+describe('the booking token on PostgreSQL', () => {
+  it('lets a workshop book one job with a token and refuses the second', async () => {
+    await job(organizationId, TOKEN)
+
+    await expect(job(organizationId, TOKEN)).rejects.toMatchObject({ code: 'P2002' })
+    expect(await db.serviceRecord.count({ where: { organizationId, bookingToken: TOKEN } })).toBe(1)
+  })
+
+  it('lets a workshop book one appointment with a token and refuses the second', async () => {
+    await appointment(organizationId, TOKEN)
+
+    await expect(appointment(organizationId, TOKEN)).rejects.toMatchObject({ code: 'P2002' })
+    expect(await db.appointment.count({ where: { organizationId, bookingToken: TOKEN } })).toBe(1)
+  })
+
+  it('refuses one of two that arrive together', async () => {
+    const token = `together-${randomUUID()}`
+    const results = await Promise.allSettled([
+      job(organizationId, token),
+      job(organizationId, token),
+    ])
+
+    expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1)
+    expect(await db.serviceRecord.count({ where: { organizationId, bookingToken: token } })).toBe(1)
+  })
+
+  it('makes two sends of one token take turns, whichever kind each is', async () => {
+    const token = `turns-${randomUUID()}`
+    const key = `${organizationId}:${token}`
+    const order: string[] = []
+    const send = (name: string, book: () => Promise<unknown>) =>
+      db.$transaction(async (tx) => {
+        await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext('booking_token'), hashtext(${key}))`
+        // What the action does once it holds the lock: look, then book.
+        const booked =
+          (await tx.serviceRecord.count({ where: { organizationId, bookingToken: token } })) +
+          (await tx.appointment.count({ where: { organizationId, bookingToken: token } }))
+        if (booked > 0) {
+          order.push(`${name} found it`)
+          return
+        }
+        await new Promise((resolve) => setTimeout(resolve, 200))
+        await book()
+        order.push(`${name} booked`)
+      })
+
+    await Promise.all([
+      send('job', () => job(organizationId, token)),
+      send('appointment', () => appointment(organizationId, token)),
+    ])
+
+    expect(order.filter((line) => line.endsWith('booked'))).toHaveLength(1)
+    expect(order.filter((line) => line.endsWith('found it'))).toHaveLength(1)
+    const jobs = await db.serviceRecord.count({ where: { organizationId, bookingToken: token } })
+    const appointments = await db.appointment.count({
+      where: { organizationId, bookingToken: token },
+    })
+    expect(jobs + appointments).toBe(1)
+  })
+
+  it('is only unique within the workshop', async () => {
+    await expect(job(otherOrganizationId, TOKEN)).resolves.toBeTruthy()
+    await expect(appointment(otherOrganizationId, TOKEN)).resolves.toBeTruthy()
+  })
+
+  it('leaves jobs and appointments made any other way alone: none has a token', async () => {
+    await job(organizationId, null)
+    await job(organizationId, null)
+    await appointment(organizationId, null)
+    await appointment(organizationId, null)
+
+    expect(
+      await db.serviceRecord.count({ where: { organizationId, bookingToken: null } })
+    ).toBeGreaterThanOrEqual(2)
+  })
+})
+
+describe('the draft the New work order page just made, on PostgreSQL', () => {
+  const draft = (lines: { pricingType: string }[], parts = 0) =>
+    db.serviceRecord.create({
+      data: {
+        title: 'Draft',
+        status: 'pending',
+        organizationId,
+        vehicleId,
+        laborItems: {
+          create: lines.map((line) => ({
+            description: line.pricingType,
+            hours: 1,
+            rate: 10,
+            total: 10,
+            pricingType: line.pricingType,
+          })),
+        },
+        partItems: {
+          create: Array.from({ length: parts }, () => ({
+            name: 'Oil filter',
+            quantity: 1,
+            unitPrice: 10,
+            total: 10,
+          })),
+        },
+      },
+      select: { id: true },
+    })
+
+  const found = async () =>
+    (
+      await db.serviceRecord.findMany({
+        where: untouchedDraftWhere({ vehicleId, organizationId, now: new Date() }),
+        select: { id: true },
+      })
+    ).map((record) => record.id)
+
+  it('finds the one with nothing on it and the one with only the shop fee', async () => {
+    const empty = await draft([])
+    const feeOnly = await draft([{ pricingType: 'shopFee' }])
+    const worked = await draft([{ pricingType: 'shopFee' }, { pricingType: 'hourly' }])
+    const withPart = await draft([{ pricingType: 'shopFee' }], 1)
+
+    const ids = await found()
+
+    expect(ids).toContain(empty.id)
+    expect(ids).toContain(feeOnly.id)
+    expect(ids).not.toContain(worked.id)
+    expect(ids).not.toContain(withPart.id)
+  })
+
+  it("finds nothing from another workshop's side", async () => {
+    await draft([])
+
+    const ids = await db.serviceRecord.findMany({
+      where: untouchedDraftWhere({
+        vehicleId,
+        organizationId: otherOrganizationId,
+        now: new Date(),
+      }),
+    })
+
+    expect(ids).toHaveLength(0)
+  })
+})

+ 3 - 0
src/__tests__/features/backup/restore-map-fields.test.ts

@@ -74,6 +74,8 @@ const LINKED_LATER =
   'The row it points at is restored later, so the link is written once it exists. Checked below.'
   'The row it points at is restored later, so the link is written once it exists. Checked below.'
 const IMPORT_BATCH =
 const IMPORT_BATCH =
   'Spreadsheet import batches are not in a backup; the id would point at nothing.'
   'Spreadsheet import batches are not in a backup; the id would point at nothing.'
+const BOOKING_TOKEN =
+  'Tells a booking sent twice from a new one while its dialog is still open. No dialog is waiting on a restored job.'
 
 
 /** Columns a map leaves out on purpose, by model, with what happens instead. */
 /** Columns a map leaves out on purpose, by model, with what happens instead. */
 const NOT_IN_THE_MAP: Readonly<Record<string, Readonly<Record<string, string>>>> = {
 const NOT_IN_THE_MAP: Readonly<Record<string, Readonly<Record<string, string>>>> = {
@@ -85,6 +87,7 @@ const NOT_IN_THE_MAP: Readonly<Record<string, Readonly<Record<string, string>>>>
     inspectionId: LINKED_LATER,
     inspectionId: LINKED_LATER,
     tireSetId: LINKED_LATER,
     tireSetId: LINKED_LATER,
     importBatchId: IMPORT_BATCH,
     importBatchId: IMPORT_BATCH,
+    bookingToken: BOOKING_TOKEN,
   },
   },
   Quote: {
   Quote: {
     warrantyStatus: WARRANTY,
     warrantyStatus: WARRANTY,

+ 202 - 16
src/__tests__/features/calendar/booking-actions.test.ts

@@ -26,6 +26,8 @@ vi.mock('@/features/inspection-reminders/Lib/booking', async (importOriginal) =>
 const db = vi.hoisted(() => ({
 const db = vi.hoisted(() => ({
   // The job number query: nothing yet in the workshop's format.
   // The job number query: nothing yet in the workshop's format.
   $queryRaw: async () => [],
   $queryRaw: async () => [],
+  // The lock that makes sends of one booking take turns.
+  $executeRaw: vi.fn(),
   user: { findUnique: vi.fn() },
   user: { findUnique: vi.fn() },
   auditLog: { create: vi.fn() },
   auditLog: { create: vi.fn() },
   vehicle: { findFirst: vi.fn() },
   vehicle: { findFirst: vi.fn() },
@@ -42,13 +44,15 @@ const db = vi.hoisted(() => ({
 }))
 }))
 vi.mock('@/lib/db', () => ({ db }))
 vi.mock('@/lib/db', () => ({ db }))
 
 
-import { createBooking } from '@/features/calendar/Actions/createBooking'
+import { createBookingOnce } from '@/features/calendar/Actions/createBooking'
 import { updateBooking } from '@/features/calendar/Actions/updateBooking'
 import { updateBooking } from '@/features/calendar/Actions/updateBooking'
 import { deleteAppointment } from '@/features/calendar/Actions/deleteAppointment'
 import { deleteAppointment } from '@/features/calendar/Actions/deleteAppointment'
 import type { SaveBookingInput } from '@/features/calendar/Schema/bookingSchema'
 import type { SaveBookingInput } from '@/features/calendar/Schema/bookingSchema'
 
 
 const ORG = 'org-1'
 const ORG = 'org-1'
 const USER = 'user-1'
 const USER = 'user-1'
+/** What one opened booking dialog sends with whatever it books. */
+const TOKEN = 'a3f1c2d4e5f60718293a4b5c6d7e8f90'
 
 
 function signInAs(
 function signInAs(
   role: 'owner' | 'member' = 'owner',
   role: 'owner' | 'member' = 'owner',
@@ -81,7 +85,11 @@ beforeEach(() => {
   })
   })
   db.customer.findFirst.mockResolvedValue({ id: 'cust-1', taxExempt: false })
   db.customer.findFirst.mockResolvedValue({ id: 'cust-1', taxExempt: false })
   // The newest numbered job, for the next job number.
   // The newest numbered job, for the next job number.
-  db.serviceRecord.findFirst.mockResolvedValue({ invoiceNumber: '2026-1043' })
+  // And nothing booked with this dialog's token yet.
+  db.serviceRecord.findFirst.mockImplementation(
+    async (args?: { where?: { bookingToken?: string } }) =>
+      args?.where?.bookingToken ? null : { invoiceNumber: '2026-1043' }
+  )
   db.serviceRecord.create.mockResolvedValue({ id: 'job-1' })
   db.serviceRecord.create.mockResolvedValue({ id: 'job-1' })
   db.serviceRecord.update.mockResolvedValue({
   db.serviceRecord.update.mockResolvedValue({
     id: 'job-1',
     id: 'job-1',
@@ -107,6 +115,7 @@ beforeEach(() => {
 function booking(overrides: Partial<SaveBookingInput> = {}): SaveBookingInput {
 function booking(overrides: Partial<SaveBookingInput> = {}): SaveBookingInput {
   return {
   return {
     kind: 'appointment',
     kind: 'appointment',
+    token: TOKEN,
     title: 'Call Kari',
     title: 'Call Kari',
     startDate: '2026-11-16',
     startDate: '2026-11-16',
     startTime: '09:30',
     startTime: '09:30',
@@ -117,6 +126,14 @@ function booking(overrides: Partial<SaveBookingInput> = {}): SaveBookingInput {
   }
   }
 }
 }
 
 
+/** The appointment a lookup by id finds; none is found by this dialog's token. */
+function appointmentOnFile(appointment: { id: string }) {
+  db.appointment.findFirst.mockImplementation(
+    async (args?: { where?: { bookingToken?: string } }) =>
+      args?.where?.bookingToken ? null : appointment
+  )
+}
+
 /** Something already on the calendar on Monday, 08:00 to 10:00 UTC. */
 /** Something already on the calendar on Monday, 08:00 to 10:00 UTC. */
 function held(resource: { workBayId?: string; technicianId?: string }, id = 'other-job') {
 function held(resource: { workBayId?: string; technicianId?: string }, id = 'other-job') {
   return {
   return {
@@ -136,7 +153,7 @@ const createdNotifications = () => db.appointmentNotification.createMany.mock.ca
 
 
 describe('createBooking: an appointment', () => {
 describe('createBooking: an appointment', () => {
   it("puts it on the workshop's clock with its title, description, customer and notifications", async () => {
   it("puts it on the workshop's clock with its title, description, customer and notifications", async () => {
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({
       booking({
         vehicleId: 'veh-1',
         vehicleId: 'veh-1',
         description: '<p>Bring the <strong>spare key</strong></p><script>alert(1)</script>',
         description: '<p>Bring the <strong>spare key</strong></p><script>alert(1)</script>',
@@ -192,14 +209,14 @@ describe('createBooking: an appointment', () => {
   })
   })
 
 
   it('keeps no description that says nothing', async () => {
   it('keeps no description that says nothing', async () => {
-    await createBooking(booking({ description: '<p>  </p>' }))
+    await createBookingOnce(booking({ description: '<p>  </p>' }))
     expect(appointmentData().description).toBeNull()
     expect(appointmentData().description).toBeNull()
   })
   })
 
 
   it("refuses another workshop's car and creates nothing", async () => {
   it("refuses another workshop's car and creates nothing", async () => {
     db.vehicle.findFirst.mockResolvedValue(null)
     db.vehicle.findFirst.mockResolvedValue(null)
 
 
-    const result = await createBooking(booking({ vehicleId: 'someone-elses-car' }))
+    const result = await createBookingOnce(booking({ vehicleId: 'someone-elses-car' }))
 
 
     expect(result.success).toBe(false)
     expect(result.success).toBe(false)
     expect(result.error).toBe('Vehicle not found')
     expect(result.error).toBe('Vehicle not found')
@@ -209,7 +226,7 @@ describe('createBooking: an appointment', () => {
 
 
 describe('createBooking: a work order', () => {
 describe('createBooking: a work order', () => {
   it('needs a car or a customer, and writes nothing without one', async () => {
   it('needs a car or a customer, and writes nothing without one', async () => {
-    const result = await createBooking(booking({ kind: 'workOrder', work: 'Brakes' }))
+    const result = await createBookingOnce(booking({ kind: 'workOrder', work: 'Brakes' }))
 
 
     expect(result.success).toBe(false)
     expect(result.success).toBe(false)
     expect(db.serviceRecord.create).not.toHaveBeenCalled()
     expect(db.serviceRecord.create).not.toHaveBeenCalled()
@@ -225,7 +242,7 @@ describe('createBooking: a work order', () => {
       closuresEnabled: false,
       closuresEnabled: false,
     })
     })
 
 
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({
       booking({
         kind: 'workOrder',
         kind: 'workOrder',
         title: 'Brake job',
         title: 'Brake job',
@@ -242,6 +259,7 @@ describe('createBooking: a work order', () => {
       ref: '2026-1044',
       ref: '2026-1044',
       vehicleId: 'veh-1',
       vehicleId: 'veh-1',
       overbooked: false,
       overbooked: false,
+      repeated: false,
     })
     })
     const job = jobData()
     const job = jobData()
     expect(job.organizationId).toBe(ORG)
     expect(job.organizationId).toBe(ORG)
@@ -271,7 +289,7 @@ describe('createBooking: a work order', () => {
   it('makes the title the only concern when no work lines are given', async () => {
   it('makes the title the only concern when no work lines are given', async () => {
     db.vehicle.findFirst.mockResolvedValue(null)
     db.vehicle.findFirst.mockResolvedValue(null)
 
 
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({ kind: 'workOrder', title: 'Winter tyres on', customerId: 'cust-1' })
       booking({ kind: 'workOrder', title: 'Winter tyres on', customerId: 'cust-1' })
     )
     )
 
 
@@ -291,7 +309,7 @@ describe('createBooking: a work order', () => {
       closuresEnabled: false,
       closuresEnabled: false,
     })
     })
 
 
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({ kind: 'workOrder', vehicleId: 'veh-1', work: 'Service' })
       booking({ kind: 'workOrder', vehicleId: 'veh-1', work: 'Service' })
     )
     )
 
 
@@ -303,9 +321,9 @@ describe('createBooking: a work order', () => {
 
 
 describe('createBooking: an appointment made a work order', () => {
 describe('createBooking: an appointment made a work order', () => {
   it('books the job and takes the appointment off the calendar', async () => {
   it('books the job and takes the appointment off the calendar', async () => {
-    db.appointment.findFirst.mockResolvedValue({ id: 'appt-1' })
+    appointmentOnFile({ id: 'appt-1' })
 
 
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({
       booking({
         kind: 'workOrder',
         kind: 'workOrder',
         vehicleId: 'veh-1',
         vehicleId: 'veh-1',
@@ -325,7 +343,7 @@ describe('createBooking: an appointment made a work order', () => {
   it("refuses another workshop's appointment and creates nothing", async () => {
   it("refuses another workshop's appointment and creates nothing", async () => {
     db.appointment.findFirst.mockResolvedValue(null)
     db.appointment.findFirst.mockResolvedValue(null)
 
 
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({
       booking({
         kind: 'workOrder',
         kind: 'workOrder',
         vehicleId: 'veh-1',
         vehicleId: 'veh-1',
@@ -341,9 +359,177 @@ describe('createBooking: an appointment made a work order', () => {
   })
   })
 })
 })
 
 
+describe('the same booking sent twice', () => {
+  /** What a lookup by the token finds once the first send has booked. */
+  function alreadyBooked(found: {
+    job?: { id: string; vehicleId: string | null; invoiceNumber: string | null }
+    appointment?: { id: string; title: string; vehicleId: string | null }
+  }) {
+    db.serviceRecord.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) =>
+        args?.where?.bookingToken ? (found.job ?? null) : { invoiceNumber: '2026-1044' }
+    )
+    db.appointment.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) =>
+        args?.where?.bookingToken ? (found.appointment ?? null) : null
+    )
+  }
+
+  it('keeps the token on the job it books', async () => {
+    const result = await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+
+    expect(result.success).toBe(true)
+    expect(jobUpdate().data.bookingToken).toBe(TOKEN)
+  })
+
+  it('keeps the token on the appointment it books', async () => {
+    await createBookingOnce(booking())
+
+    expect(appointmentData().bookingToken).toBe(TOKEN)
+  })
+
+  it('answers with the job already booked and books no second one', async () => {
+    alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
+
+    const result = await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+
+    expect(result.success).toBe(true)
+    expect(result.data).toMatchObject({ kind: 'workOrder', id: 'job-1', ref: '2026-1044' })
+    expect(db.serviceRecord.findFirst).toHaveBeenCalledWith(
+      expect.objectContaining({ where: { organizationId: ORG, bookingToken: TOKEN } })
+    )
+    expect(db.serviceRecord.create).not.toHaveBeenCalled()
+    expect(db.appointment.create).not.toHaveBeenCalled()
+  })
+
+  it('answers with the appointment already booked and books no second one', async () => {
+    alreadyBooked({ appointment: { id: 'appt-1', title: 'Call Kari', vehicleId: null } })
+
+    const result = await createBookingOnce(booking())
+
+    expect(result.success).toBe(true)
+    expect(result.data).toMatchObject({ kind: 'appointment', id: 'appt-1', ref: 'Call Kari' })
+    expect(db.appointment.findFirst).toHaveBeenCalledWith(
+      expect.objectContaining({ where: { organizationId: ORG, bookingToken: TOKEN } })
+    )
+    expect(db.appointment.create).not.toHaveBeenCalled()
+  })
+
+  it('does not write the booking into the audit log a second time', async () => {
+    alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
+
+    await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+    await new Promise((resolve) => setTimeout(resolve, 20))
+
+    expect(db.auditLog.create).not.toHaveBeenCalled()
+  })
+
+  it('finds the job when the appointment it was made from is already gone', async () => {
+    // The first send made the work order and removed the appointment.
+    alreadyBooked({ job: { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } })
+
+    const result = await createBookingOnce(
+      booking({ kind: 'workOrder', vehicleId: 'veh-1', fromAppointmentId: 'appt-1' })
+    )
+
+    expect(result.success).toBe(true)
+    expect(result.data?.id).toBe('job-1')
+    expect(db.serviceRecord.create).not.toHaveBeenCalled()
+  })
+
+  it('waits its turn and books nothing when the first send finishes meanwhile', async () => {
+    // Nothing booked when this send first looks. By the time it holds the
+    // lock the other send has finished, as either kind.
+    let turn = false
+    db.$executeRaw.mockImplementation(async () => {
+      turn = true
+      return 1
+    })
+    db.serviceRecord.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) =>
+        args?.where?.bookingToken ? null : { invoiceNumber: '2026-1043' }
+    )
+    db.appointment.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) =>
+        args?.where?.bookingToken && turn
+          ? { id: 'appt-first', title: 'Call Kari', vehicleId: null }
+          : null
+    )
+
+    const result = await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+
+    expect(result.success).toBe(true)
+    expect(result.data).toMatchObject({ kind: 'appointment', id: 'appt-first' })
+    expect(db.$executeRaw).toHaveBeenCalledTimes(1)
+    expect(db.serviceRecord.create).not.toHaveBeenCalled()
+  })
+
+  it('finds the job when the appointment goes between its two lookups', async () => {
+    // Not booked at the first look; the first send then commits, taking the
+    // appointment with it, before this one looks the appointment up.
+    let looks = 0
+    db.serviceRecord.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) => {
+        if (!args?.where?.bookingToken) return { invoiceNumber: '2026-1043' }
+        looks += 1
+        return looks > 1 ? { id: 'job-1', vehicleId: 'veh-1', invoiceNumber: '2026-1044' } : null
+      }
+    )
+    db.appointment.findFirst.mockResolvedValue(null)
+
+    const result = await createBookingOnce(
+      booking({ kind: 'workOrder', vehicleId: 'veh-1', fromAppointmentId: 'appt-1' })
+    )
+
+    expect(result.success).toBe(true)
+    expect(result.data?.id).toBe('job-1')
+    expect(db.serviceRecord.create).not.toHaveBeenCalled()
+  })
+
+  it("answers with the other send's job when both arrive together", async () => {
+    // Nothing booked when this send looks; the other one commits first and
+    // the database refuses this one the token.
+    let committed = false
+    db.serviceRecord.findFirst.mockImplementation(
+      async (args?: { where?: { bookingToken?: string } }) =>
+        args?.where?.bookingToken
+          ? committed
+            ? { id: 'job-first', vehicleId: 'veh-1', invoiceNumber: '2026-1044' }
+            : null
+          : { invoiceNumber: '2026-1043' }
+    )
+    db.serviceRecord.update.mockImplementation(async () => {
+      committed = true
+      throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' })
+    })
+
+    const result = await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+
+    expect(result.success).toBe(true)
+    expect(result.data).toMatchObject({ kind: 'workOrder', id: 'job-first', ref: '2026-1044' })
+  })
+
+  it('still fails when the database refuses it for another reason', async () => {
+    db.serviceRecord.update.mockRejectedValue(
+      Object.assign(new Error('Unique constraint failed'), { code: 'P2002' })
+    )
+
+    const result = await createBookingOnce(booking({ kind: 'workOrder', vehicleId: 'veh-1' }))
+
+    expect(result.success).toBe(false)
+  })
+
+  it('refuses a booking sent without a token', async () => {
+    const result = await createBookingOnce(booking({ token: undefined }))
+
+    expect(result.success).toBe(false)
+    expect(db.appointment.create).not.toHaveBeenCalled()
+  })
+})
+
 describe('notifications to the customer', () => {
 describe('notifications to the customer', () => {
   it('need somebody to go to', async () => {
   it('need somebody to go to', async () => {
-    const result = await createBooking(
+    const result = await createBookingOnce(
       booking({ notifications: [{ channel: 'customer_sms', amount: 1, unit: 'days' }] })
       booking({ notifications: [{ channel: 'customer_sms', amount: 1, unit: 'days' }] })
     )
     )
 
 
@@ -354,7 +540,7 @@ describe('notifications to the customer', () => {
   it('are refused on the demo, while a notice in the app is not', async () => {
   it('are refused on the demo, while a notice in the app is not', async () => {
     vi.stubEnv('DEMO_MODE', 'true')
     vi.stubEnv('DEMO_MODE', 'true')
     vi.resetModules()
     vi.resetModules()
-    const { createBooking: demoCreateBooking } = await import(
+    const { createBookingOnce: demoCreateBooking } = await import(
       '@/features/calendar/Actions/createBooking'
       '@/features/calendar/Actions/createBooking'
     )
     )
 
 
@@ -679,7 +865,7 @@ describe('who may book', () => {
   it('refuses a role that may not create jobs', async () => {
   it('refuses a role that may not create jobs', async () => {
     signInAs('member', [{ action: 'read', subject: 'services' }])
     signInAs('member', [{ action: 'read', subject: 'services' }])
 
 
-    const result = await createBooking(booking())
+    const result = await createBookingOnce(booking())
 
 
     expect(result.success).toBe(false)
     expect(result.success).toBe(false)
     expect(result.forbidden).toBe(true)
     expect(result.forbidden).toBe(true)
@@ -689,7 +875,7 @@ describe('who may book', () => {
   it('lets a role that may create jobs book', async () => {
   it('lets a role that may create jobs book', async () => {
     signInAs('member', [{ action: 'create', subject: 'services' }])
     signInAs('member', [{ action: 'create', subject: 'services' }])
 
 
-    const result = await createBooking(booking())
+    const result = await createBookingOnce(booking())
 
 
     expect(result.success).toBe(true)
     expect(result.success).toBe(true)
     expect(db.appointment.create).toHaveBeenCalledTimes(1)
     expect(db.appointment.create).toHaveBeenCalledTimes(1)

+ 42 - 2
src/__tests__/features/calendar/booking-dialog.test.tsx

@@ -4,7 +4,7 @@
  * that is still only a booking, and turns an appointment into a work order.
  * that is still only a booking, and turns an appointment into a work order.
  */
  */
 
 
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 import type { CalendarEvent } from '@/features/calendar/Actions/calendarActions'
 import type { CalendarEvent } from '@/features/calendar/Actions/calendarActions'
 import type { BookingForEdit } from '@/features/calendar/Actions/getBooking'
 import type { BookingForEdit } from '@/features/calendar/Actions/getBooking'
@@ -56,7 +56,9 @@ vi.mock('@/components/ui/rich-text-editor', () => ({
 }))
 }))
 
 
 const createBooking = vi.hoisted(() => vi.fn())
 const createBooking = vi.hoisted(() => vi.fn())
-vi.mock('@/features/calendar/Actions/createBooking', () => ({ createBooking }))
+vi.mock('@/features/calendar/Actions/createBooking', () => ({
+  createBookingOnce: createBooking,
+}))
 const updateBooking = vi.hoisted(() => vi.fn())
 const updateBooking = vi.hoisted(() => vi.fn())
 vi.mock('@/features/calendar/Actions/updateBooking', () => ({ updateBooking }))
 vi.mock('@/features/calendar/Actions/updateBooking', () => ({ updateBooking }))
 const getBooking = vi.hoisted(() => vi.fn())
 const getBooking = vi.hoisted(() => vi.fn())
@@ -303,6 +305,44 @@ describe('a new booking', () => {
     expect(onOpenChange).toHaveBeenCalledWith(false)
     expect(onOpenChange).toHaveBeenCalledWith(false)
   })
   })
 
 
+  it('sends the same token again when Book is pressed after a failure', async () => {
+    // The answer to the first send never arrived; the booking may be made.
+    createBooking.mockRejectedValueOnce(new Error('Failed to fetch'))
+    const { onSaved } = await renderDialog()
+    fireEvent.change(titleField(), { target: { value: 'Call Kari' } })
+    chooseKind('Appointment')
+
+    fireEvent.click(saveButton())
+    await waitFor(() => expect(toast.error).toHaveBeenCalled())
+    expect(onSaved).not.toHaveBeenCalled()
+    // Still filled in, to press again.
+    expect(titleField()).toHaveValue('Call Kari')
+    fireEvent.click(saveButton())
+    await waitFor(() => expect(onSaved).toHaveBeenCalled())
+
+    expect(createBooking).toHaveBeenCalledTimes(2)
+    const [first, second] = createBooking.mock.calls.map(([sent]) => sent.token)
+    expect(first).toMatch(/^[A-Za-z0-9_-]{16,64}$/)
+    expect(second).toBe(first)
+  })
+
+  it('sends a token of its own each time the dialog is opened', async () => {
+    await renderDialog()
+    fireEvent.change(titleField(), { target: { value: 'Call Kari' } })
+    chooseKind('Appointment')
+    fireEvent.click(saveButton())
+    await waitFor(() => expect(createBooking).toHaveBeenCalledTimes(1))
+    cleanup()
+
+    await renderDialog()
+    fireEvent.change(titleField(), { target: { value: 'Call Ola' } })
+    chooseKind('Appointment')
+    fireEvent.click(saveButton())
+    await waitFor(() => expect(createBooking).toHaveBeenCalledTimes(2))
+
+    expect(createBooking.mock.calls[1][0].token).not.toBe(createBooking.mock.calls[0][0].token)
+  })
+
   it('will not save without a title or with the end before the start', async () => {
   it('will not save without a title or with the end before the start', async () => {
     await renderDialog()
     await renderDialog()
     chooseKind('Appointment')
     chooseKind('Appointment')

+ 3 - 1
src/__tests__/features/calendar/booking-host.test.tsx

@@ -43,7 +43,9 @@ vi.mock('next/navigation', () => ({
   useSearchParams: () => new URLSearchParams(),
   useSearchParams: () => new URLSearchParams(),
 }))
 }))
 const createBooking = vi.hoisted(() => vi.fn())
 const createBooking = vi.hoisted(() => vi.fn())
-vi.mock('@/features/calendar/Actions/createBooking', () => ({ createBooking }))
+vi.mock('@/features/calendar/Actions/createBooking', () => ({
+  createBookingOnce: createBooking,
+}))
 vi.mock('@/features/calendar/Actions/updateBooking', () => ({ updateBooking: vi.fn() }))
 vi.mock('@/features/calendar/Actions/updateBooking', () => ({ updateBooking: vi.fn() }))
 vi.mock('@/features/calendar/Actions/getBooking', () => ({ getBooking: vi.fn() }))
 vi.mock('@/features/calendar/Actions/getBooking', () => ({ getBooking: vi.fn() }))
 vi.mock('@/features/calendar/Actions/getBookingOptions', () => ({
 vi.mock('@/features/calendar/Actions/getBookingOptions', () => ({

+ 82 - 0
src/__tests__/features/vehicles/untouched-draft.test.ts

@@ -0,0 +1,82 @@
+/**
+ * The "New work order" page makes the job as it loads, and goes to the draft
+ * it made a moment ago instead of making another when it is rendered twice.
+ * That only works while the draft still counts as untouched, which a
+ * workshop with a shop fee never saw: the fee is a labor line on every new
+ * job.
+ *
+ * Prisma is not run here, so the filter is read the way the database would
+ * read it, against drafts written out by hand.
+ */
+import { describe, expect, it } from 'vitest'
+import { SHOP_FEE_PRICING } from '@/features/settings/Lib/shopFee'
+import { untouchedDraftWhere } from '@/features/vehicles/Lib/untouchedDraft'
+
+const NOW = new Date('2026-11-18T10:00:00Z')
+
+type Draft = {
+  vehicleId: string
+  organizationId: string
+  status: string
+  createdAt: Date
+  partItems: { name: string }[]
+  laborItems: { pricingType: string }[]
+}
+
+function draft(overrides: Partial<Draft> = {}): Draft {
+  return {
+    vehicleId: 'veh-1',
+    organizationId: 'org-1',
+    status: 'pending',
+    createdAt: new Date(NOW.getTime() - 1000),
+    partItems: [],
+    laborItems: [],
+    ...overrides,
+  }
+}
+
+/** Whether the page would go to this draft rather than make a new job. */
+function reused(record: Draft): boolean {
+  const where = untouchedDraftWhere({ vehicleId: 'veh-1', organizationId: 'org-1', now: NOW })
+  const since = (where.createdAt as { gte: Date }).gte
+  const labor = where.laborItems as { none: { pricingType: { not: string } } }
+  const parts = where.partItems as { none: Record<string, never> }
+  expect(parts.none).toEqual({})
+  return (
+    record.vehicleId === where.vehicleId &&
+    record.organizationId === (where.vehicle as { organizationId: string }).organizationId &&
+    record.status === where.status &&
+    record.createdAt.getTime() >= since.getTime() &&
+    record.partItems.length === 0 &&
+    // none: no labor line that is anything other than the fee.
+    !record.laborItems.some((line) => line.pricingType !== labor.none.pricingType.not)
+  )
+}
+
+describe('the draft the New work order page just made', () => {
+  it('is reused when nothing is on it', () => {
+    expect(reused(draft())).toBe(true)
+  })
+
+  it('is reused when all it has is the shop fee the workshop adds to every job', () => {
+    expect(reused(draft({ laborItems: [{ pricingType: SHOP_FEE_PRICING }] }))).toBe(true)
+  })
+
+  it('is left alone once somebody has added labor, beside the fee or not', () => {
+    expect(reused(draft({ laborItems: [{ pricingType: 'hourly' }] }))).toBe(false)
+    expect(
+      reused(draft({ laborItems: [{ pricingType: SHOP_FEE_PRICING }, { pricingType: 'hourly' }] }))
+    ).toBe(false)
+  })
+
+  it('is left alone once somebody has added a part', () => {
+    expect(reused(draft({ partItems: [{ name: 'Oil filter' }] }))).toBe(false)
+  })
+
+  it('is left alone when it is older than a moment, another car, or another workshop', () => {
+    expect(reused(draft({ createdAt: new Date(NOW.getTime() - 6000) }))).toBe(false)
+    expect(reused(draft({ vehicleId: 'veh-2' }))).toBe(false)
+    expect(reused(draft({ organizationId: 'org-2' }))).toBe(false)
+    expect(reused(draft({ status: 'scheduled' }))).toBe(false)
+  })
+})

+ 4 - 10
src/app/(authenticated)/vehicles/[id]/service/new/page.tsx

@@ -1,5 +1,6 @@
 import { redirect } from 'next/navigation'
 import { redirect } from 'next/navigation'
 import { createDraftServiceRecord } from '@/features/vehicles/Actions/createDraftServiceRecord'
 import { createDraftServiceRecord } from '@/features/vehicles/Actions/createDraftServiceRecord'
+import { untouchedDraftWhere } from '@/features/vehicles/Lib/untouchedDraft'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
@@ -25,21 +26,14 @@ export default async function NewServicePage({
   // (created within the last 5 seconds, nothing on it yet), reuse it instead
   // (created within the last 5 seconds, nothing on it yet), reuse it instead
   // of creating a duplicate. This prevents double-creation from Next.js
   // of creating a duplicate. This prevents double-creation from Next.js
   // Server Component re-renders. The title is not part of the test any more:
   // Server Component re-renders. The title is not part of the test any more:
-  // it comes from the workshop's template now, not a fixed placeholder.
+  // it comes from the workshop's template now, not a fixed placeholder. Nor
+  // is the shop fee: see untouchedDraftWhere.
   let timeZone = 'UTC'
   let timeZone = 'UTC'
   const existingResult = await withAuth(
   const existingResult = await withAuth(
     async ({ organizationId }) => {
     async ({ organizationId }) => {
       timeZone = await workshopTimeZone(organizationId)
       timeZone = await workshopTimeZone(organizationId)
-      const fiveSecondsAgo = new Date(Date.now() - 5000)
       return db.serviceRecord.findFirst({
       return db.serviceRecord.findFirst({
-        where: {
-          vehicleId: id,
-          vehicle: { organizationId },
-          status: 'pending',
-          createdAt: { gte: fiveSecondsAgo },
-          partItems: { none: {} },
-          laborItems: { none: {} },
-        },
+        where: untouchedDraftWhere({ vehicleId: id, organizationId, now: new Date() }),
         select: { id: true },
         select: { id: true },
         orderBy: { createdAt: 'desc' },
         orderBy: { createdAt: 'desc' },
       })
       })

+ 1 - 0
src/features/ai/tools/workshop-columns.ts

@@ -22,6 +22,7 @@ export const HIDDEN_COLUMNS: readonly string[] = [
   'createdById',
   'createdById',
   'concernId',
   'concernId',
   'telegramChatId',
   'telegramChatId',
+  'bookingToken',
 ]
 ]
 
 
 export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {
 export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {

+ 145 - 20
src/features/calendar/Actions/createBooking.ts

@@ -1,6 +1,6 @@
 'use server'
 'use server'
 
 
-import { db } from '@/lib/db'
+import { db, type TxClient } from '@/lib/db'
 import { demoGuard } from '@/lib/demo'
 import { demoGuard } from '@/lib/demo'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import type { AuditEvent } from '@/lib/audit'
 import type { AuditEvent } from '@/lib/audit'
@@ -33,12 +33,29 @@ import {
  *
  *
  * An appointment can become a work order: the dialog opens on it, and the
  * An appointment can become a work order: the dialog opens on it, and the
  * appointment goes once the job exists, in the same transaction.
  * appointment goes once the job exists, in the same transaction.
+ *
+ * Booked once however often it is sent. The dialog makes up a token when it
+ * opens and sends it with the booking; what gets booked carries it, unique
+ * within the workshop. When the answer to the first send is lost (the
+ * network dropped, the server restarted under a deploy) the dialog shows a
+ * failure and stays filled in, and the second press finds the first booking
+ * by its token instead of making another with the next job number.
+ *
+ * Named `createBookingOnce` because the token is required: a tab opened
+ * before this existed calls `createBooking`, which is gone, and is asked to
+ * reload rather than book without one.
  */
  */
-export async function createBooking(input: SaveBookingInput) {
+export async function createBookingOnce(input: SaveBookingInput) {
   return withAuth(
   return withAuth(
     async ({ organizationId, userId }) => {
     async ({ organizationId, userId }) => {
       const data = saveBookingSchema.parse(input)
       const data = saveBookingSchema.parse(input)
       if (data.id) throw new Error('This booking already exists')
       if (data.id) throw new Error('This booking already exists')
+      const token = data.token
+      if (!token) throw new Error('This booking has no token')
+      // Before anything else is looked up: an appointment that became a work
+      // order the first time is gone by now, and must not read as an error.
+      const already = await bookedWith(organizationId, token)
+      if (already) return already
       // A message to the customer will go out from the workshop's own SMS or
       // A message to the customer will go out from the workshop's own SMS or
       // email, which the public demo must not do.
       // email, which the public demo must not do.
       if (data.notifications.some((n) => isCustomerChannel(n.channel))) demoGuard()
       if (data.notifications.some((n) => isCustomerChannel(n.channel))) demoGuard()
@@ -55,14 +72,23 @@ export async function createBooking(input: SaveBookingInput) {
             select: { id: true },
             select: { id: true },
           })
           })
         : null
         : null
-      if (data.fromAppointmentId && !from) throw new Error('Appointment not found')
+      if (data.fromAppointmentId && !from) {
+        // Gone because the first send finished between the two lookups and
+        // took it with it: then the work order is there by now.
+        const meanwhile = await bookedWith(organizationId, token)
+        if (meanwhile) return meanwhile
+        throw new Error('Appointment not found')
+      }
 
 
       if (data.kind === 'appointment') {
       if (data.kind === 'appointment') {
         if (from) throw new Error('An appointment becomes a work order, not another appointment')
         if (from) throw new Error('An appointment becomes a work order, not another appointment')
-        const created = await db.$transaction(async (tx) => {
+        const booking = db.$transaction(async (tx) => {
+          const earlier = await claimToken(tx, organizationId, token)
+          if (earlier) return earlier
           const appointment = await tx.appointment.create({
           const appointment = await tx.appointment.create({
             data: {
             data: {
               organizationId,
               organizationId,
+              bookingToken: token,
               title: data.title,
               title: data.title,
               description,
               description,
               startAt: start,
               startAt: start,
@@ -81,18 +107,23 @@ export async function createBooking(input: SaveBookingInput) {
           )
           )
           return appointment
           return appointment
         })
         })
+        const created = await booking.catch(theOneBooked(organizationId, token))
+        if ('kind' in created) return created
         return {
         return {
           kind: 'appointment' as const,
           kind: 'appointment' as const,
           id: created.id,
           id: created.id,
           ref: created.title,
           ref: created.title,
           vehicleId: created.vehicleId,
           vehicleId: created.vehicleId,
           overbooked: false,
           overbooked: false,
+          repeated: false,
         }
         }
       }
       }
 
 
       const minutes = Math.round((end.getTime() - start.getTime()) / 60_000)
       const minutes = Math.round((end.getTime() - start.getTime()) / 60_000)
       const { resource, full } = await resourceFor(organizationId, start, minutes)
       const { resource, full } = await resourceFor(organizationId, start, minutes)
-      const job = await db.$transaction(async (tx) => {
+      const booking = db.$transaction(async (tx) => {
+        const earlier = await claimToken(tx, organizationId, token)
+        if (earlier) return earlier
         const created = await createDraftRecord(
         const created = await createDraftRecord(
           { organizationId, userId },
           { organizationId, userId },
           {
           {
@@ -115,6 +146,7 @@ export async function createBooking(input: SaveBookingInput) {
           where: { id: created.id },
           where: { id: created.id },
           data: {
           data: {
             status: 'scheduled',
             status: 'scheduled',
+            bookingToken: token,
             description,
             description,
             concerns: {
             concerns: {
               create: bookingConcerns(data.work, data.title).map((text, sortOrder) => ({
               create: bookingConcerns(data.work, data.title).map((text, sortOrder) => ({
@@ -133,6 +165,8 @@ export async function createBooking(input: SaveBookingInput) {
         if (from) await tx.appointment.delete({ where: { id: from.id } })
         if (from) await tx.appointment.delete({ where: { id: from.id } })
         return record
         return record
       })
       })
+      const job = await booking.catch(theOneBooked(organizationId, token))
+      if ('kind' in job) return job
       // Booked all the same when everything is taken then: the office may
       // Booked all the same when everything is taken then: the office may
       // fill an hour the booking page would refuse. The dialog says so.
       // fill an hour the booking page would refuse. The dialog says so.
       return {
       return {
@@ -141,27 +175,118 @@ export async function createBooking(input: SaveBookingInput) {
         ref: job.invoiceNumber || job.id,
         ref: job.invoiceNumber || job.id,
         vehicleId: job.vehicleId,
         vehicleId: job.vehicleId,
         overbooked: full,
         overbooked: full,
+        repeated: false,
       }
       }
     },
     },
     {
     {
       requiredPermissions: [
       requiredPermissions: [
         { action: PermissionAction.CREATE, subject: PermissionSubject.SERVICES },
         { action: PermissionAction.CREATE, subject: PermissionSubject.SERVICES },
       ],
       ],
-      audit: ({ result }): AuditEvent =>
-        result.kind === 'appointment'
-          ? {
-              action: 'appointment.create',
-              entity: 'Appointment',
-              entityId: result.id,
-              details: { key: 'appointment_create', params: { title: result.ref } },
-            }
-          : {
-              action: 'service.create',
-              entity: 'ServiceRecord',
-              entityId: result.id,
-              details: { key: 'service_bookAppointment', params: { ref: result.ref } },
-              metadata: { serviceRecordId: result.id, vehicleId: result.vehicleId },
-            },
+      // Written down when it was booked, not again each time it is found.
+      audit: ({ result }): AuditEvent | null =>
+        result.repeated
+          ? null
+          : result.kind === 'appointment'
+            ? {
+                action: 'appointment.create',
+                entity: 'Appointment',
+                entityId: result.id,
+                details: { key: 'appointment_create', params: { title: result.ref } },
+              }
+            : {
+                action: 'service.create',
+                entity: 'ServiceRecord',
+                entityId: result.id,
+                details: { key: 'service_bookAppointment', params: { ref: result.ref } },
+                metadata: { serviceRecordId: result.id, vehicleId: result.vehicleId },
+              },
     }
     }
   )
   )
 }
 }
+
+/** What the dialog is told it booked. `repeated` when it was booked before. */
+type Booked = {
+  kind: 'appointment' | 'workOrder'
+  id: string
+  ref: string
+  vehicleId: string | null
+  overbooked: boolean
+  repeated: boolean
+}
+
+/** What this token already booked in this workshop, if it booked anything. */
+async function bookedWith(
+  organizationId: string,
+  token: string,
+  client: Pick<TxClient, 'serviceRecord' | 'appointment'> = db
+): Promise<Booked | null> {
+  const [job, appointment] = await Promise.all([
+    client.serviceRecord.findFirst({
+      where: { organizationId, bookingToken: token },
+      select: { id: true, vehicleId: true, invoiceNumber: true },
+    }),
+    client.appointment.findFirst({
+      where: { organizationId, bookingToken: token },
+      select: { id: true, title: true, vehicleId: true },
+    }),
+  ])
+  if (job) {
+    return {
+      kind: 'workOrder',
+      id: job.id,
+      ref: job.invoiceNumber || job.id,
+      vehicleId: job.vehicleId,
+      // Said the first time, if it was; nothing was taken from anyone now.
+      overbooked: false,
+      repeated: true,
+    }
+  }
+  if (appointment) {
+    return {
+      kind: 'appointment',
+      id: appointment.id,
+      ref: appointment.title,
+      vehicleId: appointment.vehicleId,
+      overbooked: false,
+      repeated: true,
+    }
+  }
+  return null
+}
+
+/**
+ * Makes sends of one booking take turns, and tells the one whose turn comes
+ * second what the first booked.
+ *
+ * The lookup before the transaction is passed by both of two sends that
+ * arrive together. The token is unique among jobs and among appointments,
+ * but a send made again as the other kind (the dialog stays open after a
+ * failure, and the kind can be switched) writes to the other table, where
+ * nothing refuses it. So each send waits here for any other with its token
+ * to finish, and then looks again.
+ */
+async function claimToken(
+  tx: TxClient,
+  organizationId: string,
+  token: string
+): Promise<Booked | null> {
+  await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext('booking_token'), hashtext(${`${organizationId}:${token}`}))`
+  return bookedWith(organizationId, token, tx)
+}
+
+/**
+ * Two sends of one booking that arrive together both find nothing booked
+ * and both write. The database lets one through and refuses the other its
+ * token, or, for an appointment being made a work order, finds the
+ * appointment already gone. The one refused answers with what the other
+ * booked; anything else that went wrong is still what went wrong.
+ */
+function theOneBooked(organizationId: string, token: string) {
+  return async (error: unknown): Promise<Booked> => {
+    const code = (error as { code?: string } | null)?.code
+    if (code !== 'P2002' && code !== 'P2025') throw error
+    const already = await bookedWith(organizationId, token)
+    if (!already) throw error
+    return already
+  }
+}

+ 8 - 3
src/features/calendar/Components/BookingDialog.tsx

@@ -52,7 +52,8 @@ import { plateFromSearch } from '@/features/vehicles/Lib/plate'
 import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
 import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
 import { VehicleCombobox } from '@/features/quotes/Components/VehicleCombobox'
 import { VehicleCombobox } from '@/features/quotes/Components/VehicleCombobox'
 import { createServiceMeeting } from '@/features/integrations/Actions/integrationActions'
 import { createServiceMeeting } from '@/features/integrations/Actions/integrationActions'
-import { createBooking } from '../Actions/createBooking'
+import { createBookingOnce } from '../Actions/createBooking'
+import { newBookingToken } from '../Lib/bookingToken'
 import { updateBooking } from '../Actions/updateBooking'
 import { updateBooking } from '../Actions/updateBooking'
 import { getBooking, type BookingForEdit } from '../Actions/getBooking'
 import { getBooking, type BookingForEdit } from '../Actions/getBooking'
 import { getBookingOptions, type BookingOptions } from '../Actions/getBookingOptions'
 import { getBookingOptions, type BookingOptions } from '../Actions/getBookingOptions'
@@ -278,6 +279,9 @@ function BookingForm({
   const [multiDay, setMultiDay] = useState(false)
   const [multiDay, setMultiDay] = useState(false)
   // Set by a press of the button that could not save.
   // Set by a press of the button that could not save.
   const [tried, setTried] = useState(false)
   const [tried, setTried] = useState(false)
+  // One for as long as this form is open, so pressing Book again after a
+  // failure that was really a lost answer finds the booking already made.
+  const [bookingToken] = useState(newBookingToken)
   const titleRef = useRef<HTMLInputElement>(null)
   const titleRef = useRef<HTMLInputElement>(null)
 
 
   // What the workshop offers, and the booking being changed.
   // What the workshop offers, and the booking being changed.
@@ -426,6 +430,7 @@ function BookingForm({
         kind,
         kind,
         id: editing?.id,
         id: editing?.id,
         fromAppointmentId: converting?.id,
         fromAppointmentId: converting?.id,
+        token: editing ? undefined : bookingToken,
         title: titleText.trim(),
         title: titleText.trim(),
         description,
         description,
         customerId: customerId || undefined,
         customerId: customerId || undefined,
@@ -442,9 +447,9 @@ function BookingForm({
           atTime: isDayUnit(r.unit) ? r.atTime : null,
           atTime: isDayUnit(r.unit) ? r.atTime : null,
         })),
         })),
       }
       }
-      const result: Awaited<ReturnType<typeof createBooking>> = editing
+      const result: Awaited<ReturnType<typeof updateBooking>> = editing
         ? await updateBooking(payload)
         ? await updateBooking(payload)
-        : await createBooking(payload)
+        : await createBookingOnce(payload)
       if (!result.success || !result.data) {
       if (!result.success || !result.data) {
         toast.error(result.error || t('failed'))
         toast.error(result.error || t('failed'))
         return
         return

+ 12 - 0
src/features/calendar/Lib/bookingToken.ts

@@ -0,0 +1,12 @@
+/**
+ * The token a booking dialog sends with what it books, so the same booking
+ * sent twice is booked once (see createBookingOnce).
+ *
+ * Not `crypto.randomUUID`: a self-hosted workshop on plain http has no
+ * secure context, and the browser leaves that function out there.
+ * `getRandomValues` is there either way.
+ */
+export function newBookingToken(): string {
+  const bytes = crypto.getRandomValues(new Uint8Array(16))
+  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
+}

+ 8 - 0
src/features/calendar/Schema/bookingSchema.ts

@@ -86,6 +86,14 @@ export const saveBookingSchema = z
     id: z.string().min(1).optional(),
     id: z.string().min(1).optional(),
     /** An appointment becoming a work order: removed once the job exists. */
     /** An appointment becoming a work order: removed once the job exists. */
     fromAppointmentId: z.string().min(1).optional(),
     fromAppointmentId: z.string().min(1).optional(),
+    /**
+     * A new booking only: made up by the dialog when it opens, so the same
+     * booking sent twice is booked once (see createBookingOnce).
+     */
+    token: z
+      .string()
+      .regex(/^[A-Za-z0-9_-]{16,64}$/)
+      .optional(),
     title: z.string().trim().min(1, 'Add a title').max(200),
     title: z.string().trim().min(1, 'Add a title').max(200),
     /** Rich text from the editor; cleaned on the server before it is kept. */
     /** Rich text from the editor; cleaned on the server before it is kept. */
     description: z.string().max(20_000).optional(),
     description: z.string().max(20_000).optional(),

+ 36 - 0
src/features/vehicles/Lib/untouchedDraft.ts

@@ -0,0 +1,36 @@
+import { SHOP_FEE_PRICING } from '@/features/settings/Lib/shopFee'
+import type { Prisma } from '@/generated/prisma/client'
+
+/** How long after it was made a draft still counts as the one just asked for. */
+const JUST_MADE_MS = 5000
+
+/**
+ * The draft the "New work order" page made a moment ago for this vehicle,
+ * when nobody has put anything on it yet.
+ *
+ * That page makes the job as it loads, so a second render of it would make a
+ * second job with the next number. It looks for this first and goes to it
+ * instead.
+ *
+ * "Nothing on it" leaves the shop fee out. A workshop that charges one gets
+ * the fee as a labor line on every new job (createDraftRecord), so a test for
+ * no labor lines at all never matched there and the second job was made.
+ */
+export function untouchedDraftWhere({
+  vehicleId,
+  organizationId,
+  now,
+}: {
+  vehicleId: string
+  organizationId: string
+  now: Date
+}): Prisma.ServiceRecordWhereInput {
+  return {
+    vehicleId,
+    vehicle: { organizationId },
+    status: 'pending',
+    createdAt: { gte: new Date(now.getTime() - JUST_MADE_MS) },
+    partItems: { none: {} },
+    laborItems: { none: { pricingType: { not: SHOP_FEE_PRICING } } },
+  }
+}