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

Date a work order the day it is opened and free its slot when completed (#681)

* Date a work order the day it is opened and free its slot when completed

* Keep an unlinked reading at its typed time and let a finished job hold no slot

* Give the equipment unlink tests readings with ids and typed times
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
2cc65d7007

+ 11 - 2
src/__tests__/api/tech-equipment.test.ts

@@ -147,8 +147,16 @@ vi.mock('@/lib/db', () => {
       }),
     },
     meterReading: {
-      // Every reading the job took, as the unlink asks which jobs it touches.
-      findMany: vi.fn(async () => [{ serviceRecordId: JOB.id }]),
+      // Every reading the job took, as the unlink asks which jobs it touches:
+      // typed a day before the job's date, which is the date it keeps.
+      findMany: vi.fn(async () => [
+        {
+          id: 'r-lift',
+          serviceRecordId: JOB.id,
+          readAt: new Date('2026-11-19T08:00:00Z'),
+          createdAt: new Date('2026-11-19T08:05:00Z'),
+        },
+      ]),
       updateMany: vi.fn(async (args: unknown) => {
         state.unlinked.push(args)
         return { count: 1 }
@@ -416,6 +424,7 @@ describe('setting what a job works on', () => {
           organizationId: 'org-1',
           vehicleMeter: { equipmentItemId: { in: ['lift'] } },
           serviceRecordId: JOB.id,
+          id: { in: ['r-lift'] },
         },
         // At the date it counts at now, so it stays where it was in the history.
         data: { serviceRecordId: null, readAt: new Date('2026-11-20T08:00:00Z') },

+ 18 - 3
src/__tests__/features/equipment/equipment-server.test.ts

@@ -440,9 +440,23 @@ describe('what a work order works on', () => {
     db.equipmentItem.findMany.mockResolvedValue([
       { id: 'item-2', vehicleId: 'veh-A', removedAt: null },
     ])
-    db.meterReading.findMany.mockResolvedValueOnce([{ serviceRecordId: 'job-1' }])
+    // The job is booked ahead (opened after closing time, slot next
+    // morning): the reading leaves it at the moment it was typed, never at
+    // the booking still to come.
+    db.meterReading.findMany.mockResolvedValueOnce([
+      {
+        id: 'r-1',
+        serviceRecordId: 'job-1',
+        readAt: new Date('2099-04-01T07:00:00Z'),
+        createdAt: new Date('2026-03-31T17:30:00Z'),
+      },
+    ])
     db.serviceRecord.findMany.mockResolvedValueOnce([
-      { id: 'job-1', startDateTime: null, serviceDate: new Date('2026-04-01T09:00:00Z') },
+      {
+        id: 'job-1',
+        startDateTime: new Date('2099-04-01T07:00:00Z'),
+        serviceDate: new Date('2026-03-31T00:00:00Z'),
+      },
     ])
     expect((await setJobEquipment({ id: 'job-1', itemIds: ['item-2'] })).success).toBe(true)
     expect(db.serviceRecordEquipment.deleteMany).toHaveBeenCalledWith({
@@ -453,8 +467,9 @@ describe('what a work order works on', () => {
         organizationId: 'org-1',
         vehicleMeter: { equipmentItemId: { in: ['item-1'] } },
         serviceRecordId: 'job-1',
+        id: { in: ['r-1'] },
       },
-      data: { serviceRecordId: null, readAt: new Date('2026-04-01T09:00:00Z') },
+      data: { serviceRecordId: null, readAt: new Date('2026-03-31T17:30:00Z') },
     })
   })
 

+ 45 - 2
src/__tests__/features/meters/meters-server.test.ts

@@ -552,7 +552,14 @@ describe('a reading let go of by its job', () => {
     serviceDate: new Date('2026-04-01T09:00:00Z'),
   }
   beforeEach(() => {
-    db.meterReading.findMany.mockResolvedValue([{ serviceRecordId: 'job-1' }])
+    db.meterReading.findMany.mockResolvedValue([
+      {
+        id: 'r-1',
+        serviceRecordId: 'job-1',
+        readAt: new Date('2026-02-01T09:00:00Z'),
+        createdAt: new Date('2026-02-01T10:00:00Z'),
+      },
+    ])
     db.serviceRecord.findMany.mockResolvedValue([rescheduled])
   })
 
@@ -569,6 +576,7 @@ describe('a reading let go of by its job', () => {
       where: {
         organizationId: 'org-1',
         serviceRecordId: 'job-1',
+        id: { in: ['r-1'] },
         NOT: {
           OR: [
             { vehicleMeter: { vehicleId: 'veh-B' } },
@@ -589,7 +597,7 @@ describe('a reading let go of by its job', () => {
       jobIds: ['job-1'],
     })
     expect(db.meterReading.updateMany).toHaveBeenCalledWith({
-      where: { organizationId: 'org-1', serviceRecordId: 'job-1' },
+      where: { organizationId: 'org-1', serviceRecordId: 'job-1', id: { in: ['r-1'] } },
       data: { serviceRecordId: null, readAt: new Date('2026-04-01T07:30:00Z') },
     })
   })
@@ -605,6 +613,7 @@ describe('a reading let go of by its job', () => {
         organizationId: 'org-1',
         vehicleMeter: { equipmentItemId: { in: ['item-1'] } },
         serviceRecordId: 'job-1',
+        id: { in: ['r-1'] },
       },
       data: { serviceRecordId: null, readAt: new Date('2026-04-01T09:00:00Z') },
     })
@@ -636,6 +645,40 @@ describe('a reading let go of by its job', () => {
     expect(db.meterReading.findMany).toHaveBeenCalledTimes(3)
   })
 
+  it('keeps a reading on a job booked ahead at the moment it was typed, not in the future', async () => {
+    // A job opened after closing time, booked into tomorrow morning, deleted
+    // before then: the reading taken as the car came in is dated when typed.
+    vi.useFakeTimers({ toFake: ['Date'] })
+    vi.setSystemTime(new Date('2026-11-24T18:45:00Z'))
+    try {
+      db.meterReading.findMany.mockResolvedValue([
+        {
+          id: 'r-1',
+          serviceRecordId: 'job-1',
+          readAt: new Date('2026-11-25T07:00:00Z'),
+          createdAt: new Date('2026-11-24T18:42:00Z'),
+        },
+      ])
+      db.serviceRecord.findMany.mockResolvedValue([
+        {
+          id: 'job-1',
+          startDateTime: new Date('2026-11-25T07:00:00Z'),
+          serviceDate: new Date('2026-11-24T00:00:00Z'),
+        },
+      ])
+      await unlinkMeterReadingsOfDeletedJobs(db as never, {
+        organizationId: 'org-1',
+        jobIds: ['job-1'],
+      })
+      expect(db.meterReading.updateMany).toHaveBeenCalledWith({
+        where: { organizationId: 'org-1', serviceRecordId: 'job-1', id: { in: ['r-1'] } },
+        data: { serviceRecordId: null, readAt: new Date('2026-11-24T18:42:00Z') },
+      })
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+
   it('touches nothing when the job took no readings', async () => {
     db.meterReading.findMany.mockResolvedValue([])
     await unlinkMeterReadingsOfDeletedJobs(db as never, {

+ 91 - 0
src/__tests__/features/vehicles/schedule-times-follow-server.test.tsx

@@ -0,0 +1,91 @@
+/**
+ * Completing a job ends a booked slot still ahead of it, on the server. The
+ * work order's time card kept showing tomorrow's slot until the page was
+ * reloaded; it now shows the times the job holds once the page refreshes.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+
+// biome-ignore lint/suspicious/noEmptyBlockStatements: a stub that measures nothing
+const noop = () => {}
+vi.stubGlobal(
+  'ResizeObserver',
+  class {
+    observe = noop
+    unobserve = noop
+    disconnect = noop
+  }
+)
+
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }))
+vi.mock('@/components/date-settings-context', () => ({
+  useDateSettings: () => ({ dateFormat: 'yyyy-MM-dd', timeFormat: '24h', timezone: 'UTC' }),
+}))
+vi.mock('@/features/team/Components/AddPersonDialog', () => ({ AddPersonDialog: () => null }))
+// The picker shows the time it holds, which is all this test reads.
+vi.mock('@/components/ui/datetime-picker', () => ({
+  DateTimePicker: ({ value }: { value?: Date }) => (
+    <output data-testid="picked">{value ? value.toISOString() : ''}</output>
+  ),
+}))
+vi.mock('@/features/workboard/Actions/technicianActions', () => ({ createTechnician: vi.fn() }))
+vi.mock('@/features/workboard/Actions/boardActions', () => ({
+  addJobHelper: vi.fn(),
+  removeJobHelper: vi.fn(),
+  assignTechnician: vi.fn(),
+  scheduleJob: vi.fn(),
+  checkSlotAvailability: vi.fn(),
+  findNextSlot: vi.fn(),
+  getTechnicianDayLoad: vi.fn(),
+  setPromisedTime: vi.fn(),
+  updateServiceTimes: vi.fn(),
+}))
+
+import {
+  checkSlotAvailability,
+  getTechnicianDayLoad,
+} from '@/features/workboard/Actions/boardActions'
+import { WorkOrderLayoutProvider } from '@/components/work-order-layout-context'
+import { ScheduleTimesSection } from '@/features/vehicles/Components/service-edit/ScheduleTimesSection'
+
+function card(start: string, end: string) {
+  return (
+    <WorkOrderLayoutProvider value={true}>
+      <ScheduleTimesSection
+        serviceRecordId="job-1"
+        technicians={[]}
+        initialStartDateTime={start}
+        initialEndDateTime={end}
+        initialTechnicianId={null}
+        initialHelperIds={[]}
+      />
+    </WorkOrderLayoutProvider>
+  )
+}
+
+beforeEach(() => {
+  vi.mocked(checkSlotAvailability).mockResolvedValue({
+    success: true,
+    data: { conflicts: [], closures: [], closedWeekday: false },
+  } as never)
+  vi.mocked(getTechnicianDayLoad).mockResolvedValue({
+    success: true,
+    data: { minutes: {}, away: {} },
+  } as never)
+})
+
+describe('the time card on a job that was just completed', () => {
+  it('shows the times the server moved the job to', async () => {
+    const { rerender } = render(card('2026-11-25T07:00:00.000Z', '2026-11-25T08:00:00.000Z'))
+    expect(screen.getAllByTestId('picked').map((p) => p.textContent)).toContain(
+      '2026-11-25T07:00:00.000Z'
+    )
+
+    rerender(card('2026-11-24T18:48:00.000Z', '2026-11-24T18:48:00.000Z'))
+
+    const shown = (await screen.findAllByTestId('picked')).map((p) => p.textContent)
+    expect(shown).toContain('2026-11-24T18:48:00.000Z')
+    expect(shown).not.toContain('2026-11-25T07:00:00.000Z')
+  })
+})

+ 21 - 0
src/__tests__/features/workboard/availability.test.ts

@@ -41,6 +41,12 @@ describe('overlapping in time', () => {
     // Back to back is the normal way a bay is used, not a clash.
     expect(overlaps(at(1, 9), at(1, 11), at(1, 11), at(1, 13))).toBe(false)
   })
+
+  it('never counts a job that holds no time, as one completed before its slot does', () => {
+    // Completed at 10:00, start and end both moved to then.
+    expect(overlaps(at(1, 10), at(1, 10), at(1, 9), at(1, 11))).toBe(false)
+    expect(overlaps(at(1, 9), at(1, 11), at(1, 10), at(1, 10))).toBe(false)
+  })
 })
 
 describe('what counts as a clash', () => {
@@ -59,6 +65,21 @@ describe('what counts as a clash', () => {
     expect(c.map((b) => b.id)).toEqual(['job-1'])
   })
 
+  it('does not clash with a job completed at 10:00 before its slot', () => {
+    const done = booking({
+      id: 'done',
+      start: at(1, 10),
+      end: at(1, 10),
+      technicianId: 't2',
+      workBayId: 'bay2',
+    })
+    const c = findConflicts(
+      { start: at(1, 9), end: at(1, 11), technicianId: 't2', workBayId: 'bay2' },
+      [done]
+    )
+    expect(c).toEqual([])
+  })
+
   it('clashes when the same bay is already occupied', () => {
     const c = findConflicts({ start: at(1, 10), end: at(1, 12), workBayId: 'bay1' }, existing)
     expect(c.map((b) => b.id)).toEqual(['job-1'])

+ 256 - 0
src/__tests__/features/workorders/work-order-dated-the-day-opened.test.ts

@@ -0,0 +1,256 @@
+/**
+ * A work order is dated the day it is opened, on the workshop's calendar,
+ * even when the first free slot is tomorrow morning. A car taken in after
+ * closing time was dated the next day everywhere the job's date is read: the
+ * list, the vehicle's "last visit" (in 13 hours), the portal, the readings
+ * taken with it. And a job completed before its booked slot kept holding
+ * tomorrow's time on the calendar.
+ *
+ * The workshop is in Auckland, far from UTC, and it is 18:30 there, after
+ * closing (the shop works 07:00 to 15:00).
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn() }))
+vi.mock('@/lib/notification-bus', () => ({ notificationBus: { publish: vi.fn(), emit: vi.fn() } }))
+vi.mock('@/lib/workshop-timezone', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/lib/workshop-timezone')>()),
+  workshopTimeZone: async () => 'Pacific/Auckland',
+}))
+vi.mock('@/features/meters/Lib/requiredMeters.server', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/features/meters/Lib/requiredMeters.server')>()),
+  assertRequiredMetersRead: vi.fn(async () => undefined),
+}))
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    vehicle: { findFirst: vi.fn(), count: vi.fn() },
+    appSetting: { findMany: vi.fn(), updateMany: vi.fn() },
+    organization: { findUnique: vi.fn() },
+    serviceRecord: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), update: vi.fn() },
+    workOrderStatus: { findFirst: vi.fn() },
+    inspection: { findMany: vi.fn() },
+    technician: { findFirst: vi.fn() },
+    workshopClosure: { findMany: vi.fn() },
+    technicianAbsence: { findMany: vi.fn() },
+    $queryRaw: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { createDraftRecord } from '@/features/vehicles/Lib/createDraftRecord'
+import { updateServiceStatus } from '@/features/vehicles/Actions/serviceActions'
+import { slotOnCompletion } from '@/features/work-order-statuses/Lib/stages'
+import { effectiveReadAt } from '@/features/meters/Lib/readingTime'
+import { getVehicleGlance } from '@/features/vehicles/Actions/getVehicleGlance'
+
+const ORG = 'org-1'
+const USER = 'user-1'
+// Tuesday 24 November 2026, 18:30 in Auckland (NZDT, UTC+13).
+const NOW = new Date('2026-11-24T05:30:00.000Z')
+// Midnight starting Tuesday 24 November in Auckland: the day the job opened.
+const TODAY = '2026-11-23T11:00:00.000Z'
+// Wednesday 25 November, 07:00 in Auckland: the next free slot.
+const TOMORROW_OPENING = '2026-11-24T18:00:00.000Z'
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(NOW)
+  vi.mocked(getCachedSession).mockResolvedValue({ user: { id: USER, email: 'a@b.c' } } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false, name: 'Desk' } as any)
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([
+    { key: 'workshop.timezone', value: 'Pacific/Auckland' },
+  ] as any)
+  vi.mocked(db.organization.findUnique).mockResolvedValue({ name: 'Shop' } as any)
+  vi.mocked(db.vehicle.findFirst).mockResolvedValue({ licensePlate: 'AB123' } as any)
+  vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null)
+  vi.mocked(db.serviceRecord.findMany).mockResolvedValue([])
+  vi.mocked(db.inspection.findMany).mockResolvedValue([])
+  vi.mocked(db.workshopClosure.findMany).mockResolvedValue([])
+  vi.mocked(db.technicianAbsence.findMany).mockResolvedValue([])
+  vi.mocked(db.$queryRaw).mockResolvedValue([{ highest: null }] as any)
+  vi.mocked(db.serviceRecord.create).mockImplementation((async (args: any) => ({
+    id: 'job-1',
+    ...args.data,
+  })) as any)
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+function created() {
+  return vi.mocked(db.serviceRecord.create).mock.calls[0][0].data as any
+}
+
+describe('a work order opened after closing time', () => {
+  it('is dated today and booked into the next free slot tomorrow', async () => {
+    await createDraftRecord(
+      { organizationId: ORG, userId: USER },
+      { vehicleId: 'veh-1', customerId: null, customerExempt: false, title: 'Brakes' }
+    )
+
+    expect(created().serviceDate.toISOString()).toBe(TODAY)
+    expect(created().startDateTime.toISOString()).toBe(TOMORROW_OPENING)
+    expect(created().endDateTime.toISOString()).toBe('2026-11-24T19:00:00.000Z')
+  })
+
+  it('keeps the day of a time somebody chose, a booking next week', async () => {
+    const start = new Date('2026-12-01T20:00:00.000Z') // Wed 2 Dec, 09:00 Auckland
+    await createDraftRecord(
+      { organizationId: ORG, userId: USER },
+      {
+        vehicleId: 'veh-1',
+        customerId: null,
+        customerExempt: false,
+        title: 'Service',
+        startDateTime: start,
+        endDateTime: new Date(start.getTime() + 3_600_000),
+      }
+    )
+
+    expect(created().serviceDate.toISOString()).toBe('2026-12-01T11:00:00.000Z')
+    expect(created().startDateTime).toEqual(start)
+  })
+
+  it("keeps the day of a customer's preferred date", async () => {
+    // Asked for Friday 27 November (Auckland).
+    const asked = new Date('2026-11-26T11:00:00.000Z')
+    await createDraftRecord(
+      { organizationId: ORG, userId: USER },
+      {
+        vehicleId: 'veh-1',
+        customerId: null,
+        customerExempt: false,
+        title: 'Request',
+        bookFrom: asked,
+      }
+    )
+
+    expect(created().startDateTime.toISOString()).toBe('2026-11-26T18:00:00.000Z')
+    expect(created().serviceDate.toISOString()).toBe('2026-11-26T11:00:00.000Z')
+  })
+})
+
+describe('completing a job', () => {
+  const job = (start: string, end: string, status = 'in-progress') => ({
+    status,
+    startDateTime: new Date(start),
+    endDateTime: new Date(end),
+  })
+
+  it('lets go of a booked slot that has not started yet', () => {
+    expect(
+      slotOnCompletion(job(TOMORROW_OPENING, '2026-11-24T19:00:00.000Z'), 'completed', NOW)
+    ).toEqual({ startDateTime: NOW, endDateTime: NOW })
+  })
+
+  it('ends a slot still running now, keeping its start', () => {
+    expect(
+      slotOnCompletion(
+        job('2026-11-24T05:00:00.000Z', '2026-11-24T06:00:00.000Z'),
+        'completed',
+        NOW
+      )
+    ).toEqual({ endDateTime: NOW })
+  })
+
+  it('leaves a slot already over as it is', () => {
+    expect(
+      slotOnCompletion(
+        job('2026-11-23T20:00:00.000Z', '2026-11-23T21:00:00.000Z'),
+        'completed',
+        NOW
+      )
+    ).toEqual({})
+  })
+
+  it('leaves the slot alone for any other move, or a job already completed', () => {
+    const ahead = job(TOMORROW_OPENING, '2026-11-24T19:00:00.000Z')
+    expect(slotOnCompletion(ahead, 'waiting-parts', NOW)).toEqual({})
+    expect(slotOnCompletion({ ...ahead, status: 'completed' }, 'completed', NOW)).toEqual({})
+  })
+
+  it('frees the calendar when the status is changed to completed', async () => {
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue({
+      id: 'job-1',
+      title: 'Brakes',
+      status: 'pending',
+      vehicleId: 'veh-1',
+      vehicle: null,
+      startDateTime: new Date(TOMORROW_OPENING),
+      endDateTime: new Date('2026-11-24T19:00:00.000Z'),
+    } as any)
+
+    const result = await updateServiceStatus('job-1', 'completed')
+
+    expect(result.success).toBe(true)
+    expect(vi.mocked(db.serviceRecord.update)).toHaveBeenCalledWith({
+      where: { id: 'job-1' },
+      data: expect.objectContaining({
+        status: 'completed',
+        startDateTime: NOW,
+        endDateTime: NOW,
+      }),
+    })
+  })
+})
+
+describe('a reading taken with a job booked tomorrow', () => {
+  const typed = new Date('2026-11-24T05:20:00.000Z')
+  const onJob = (startDateTime: Date) => ({
+    readAt: new Date(TOMORROW_OPENING),
+    createdAt: typed,
+    serviceRecord: { startDateTime, serviceDate: new Date(TODAY) },
+  })
+
+  it('is dated when it was typed while the job is still ahead', () => {
+    expect(effectiveReadAt(onJob(new Date(TOMORROW_OPENING)), NOW)).toEqual(typed)
+  })
+
+  it('follows the job once the job has come', () => {
+    expect(effectiveReadAt(onJob(NOW), NOW)).toEqual(NOW)
+  })
+})
+
+describe("the vehicle's last visit", () => {
+  const done = (id: string, start: string) => ({
+    id,
+    status: 'completed',
+    serviceDate: new Date(TODAY),
+    startDateTime: new Date(start),
+    totalAmount: 0,
+    cost: 0,
+    manuallyPaid: false,
+    sentAt: null,
+    issuedAt: null,
+    payments: [],
+  })
+
+  it('is never a visit still to come', async () => {
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue({ id: 'veh-1', customerId: null } as any)
+    vi.mocked(db.serviceRecord.findMany).mockResolvedValue([
+      done('last-week', '2026-11-16T20:00:00.000Z'),
+      // Completed before its slot, as a job was before the slot was freed.
+      done('ahead', TOMORROW_OPENING),
+    ] as any)
+
+    const result = await getVehicleGlance('veh-1')
+
+    expect(result.success && result.data?.lastVisitJobId).toBe('last-week')
+  })
+})

+ 5 - 2
src/app/api/v1/tech/jobs/[id]/status/route.ts

@@ -1,4 +1,4 @@
-import { statusColumns } from '@/features/work-order-statuses/Lib/stages'
+import { slotOnCompletion, statusColumns } from '@/features/work-order-statuses/Lib/stages'
 import { z } from 'zod'
 import { announceJobStatusChanged } from '@/features/vehicles/Lib/jobEvents'
 import { db } from '@/lib/db'
@@ -54,6 +54,8 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
           id: true,
           status: true,
           title: true,
+          startDateTime: true,
+          endDateTime: true,
           vehicleId: true,
           // Enough for the board to draw the card if this puts the job back
           // in its unassigned list.
@@ -101,7 +103,8 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
         where: { id: job.id },
         // The phone moves the stage; a status of the workshop's own belonged
         // to the stage it left.
-        data: statusColumns(status),
+        // and a finished job lets go of booked time still ahead of it.
+        data: { ...statusColumns(status), ...slotOnCompletion(job, status) },
         select: { id: true, status: true },
       })
 

+ 20 - 8
src/features/meters/Lib/jobMeterReading.server.ts

@@ -225,7 +225,9 @@ type UnlinkTx = {
  * date the job had when the reading was typed, before a reschedule. The date it
  * counts at today is written with the unlink, in the same statement, so the
  * reading stays where it was in the history and the current reading does not
- * change.
+ * change. That is `effectiveReadAt`, not the job's own date: a reading on a
+ * job booked into tomorrow counts from when it was typed, and the job's date
+ * written here put it back in the future once the job let go of it.
  */
 async function unlinkReadingsFromJobs(
   tx: UnlinkTx,
@@ -237,20 +239,30 @@ async function unlinkReadingsFromJobs(
     // replaced that with "any job", which let one job's change take the
     // readings of every other job with it.
     where: { AND: [where, { organizationId, serviceRecordId: { not: null } }] },
-    select: { serviceRecordId: true },
-    distinct: ['serviceRecordId'],
+    select: { id: true, serviceRecordId: true, readAt: true, createdAt: true },
   })
-  const jobIds = linked.flatMap((r) => (r.serviceRecordId ? [r.serviceRecordId] : []))
+  const jobIds = [...new Set(linked.flatMap((r) => (r.serviceRecordId ? [r.serviceRecordId] : [])))]
   if (jobIds.length === 0) return
   const jobs = await tx.serviceRecord.findMany({
     where: { id: { in: jobIds }, organizationId },
     select: { id: true, ...READING_JOB_DATES },
   })
+  const now = new Date()
   for (const job of jobs) {
-    await tx.meterReading.updateMany({
-      where: { ...where, organizationId, serviceRecordId: job.id },
-      data: { serviceRecordId: null, readAt: jobReadingDate(job) },
-    })
+    // The readings of this job by the date each counts at now; usually one.
+    const byDate = new Map<number, string[]>()
+    for (const reading of linked) {
+      if (reading.serviceRecordId !== job.id) continue
+      const at = effectiveReadAt({ ...reading, serviceRecord: job }, now).getTime()
+      byDate.set(at, [...(byDate.get(at) ?? []), reading.id])
+    }
+    for (const [at, ids] of byDate) {
+      await tx.meterReading.updateMany({
+        // Still this job's: one taken off it meanwhile is not dated again.
+        where: { ...where, organizationId, serviceRecordId: job.id, id: { in: ids } },
+        data: { serviceRecordId: null, readAt: new Date(at) },
+      })
+    }
   }
 }
 

+ 21 - 5
src/features/meters/Lib/readingTime.ts

@@ -5,12 +5,28 @@ import { jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
  * it starts, else its service day), read from the job as it is now, so a job
  * that is rescheduled carries its readings with it and there is no second date
  * to keep in step. Any other reading is dated when it was typed for.
+ *
+ * Never in the future, though: a job opened after closing time is booked into
+ * tomorrow morning, and the reading taken as the car came in was dated
+ * tomorrow, in the meter's history and against the readings around it. While
+ * the job's time is still ahead, its reading counts from when it was typed;
+ * once that time comes (or the job is completed, which ends its booking now),
+ * it follows the job again. A reading typed before a job was moved to a day
+ * since gone by still goes with the job.
  */
-export function effectiveReadAt(row: {
-  readAt: Date
-  serviceRecord?: { startDateTime: Date | null; serviceDate: Date } | null
-}): Date {
-  return row.serviceRecord ? jobReadingDate(row.serviceRecord) : row.readAt
+export function effectiveReadAt(
+  row: {
+    readAt: Date
+    createdAt: Date
+    serviceRecord?: { startDateTime: Date | null; serviceDate: Date } | null
+  },
+  now = new Date()
+): Date {
+  if (!row.serviceRecord) return row.readAt
+  const jobDate = jobReadingDate(row.serviceRecord)
+  return jobDate.getTime() > now.getTime() && jobDate.getTime() > row.createdAt.getTime()
+    ? row.createdAt
+    : jobDate
 }
 
 /** The job fields `effectiveReadAt` needs, for a Prisma select. */

+ 3 - 1
src/features/vehicles/Actions/getVehicleGlance.ts

@@ -88,7 +88,9 @@ export async function getVehicleGlance(vehicleId: string) {
         if (done) {
           doneJobs += 1
           const at = job.startDateTime ?? job.serviceDate
-          if (!lastVisit || at > lastVisit) {
+          // A visit that has not started is not the last one: a job
+          // completed before its booked slot read "Last visit in 13 hours".
+          if (at <= now && (!lastVisit || at > lastVisit)) {
             lastVisit = at
             lastVisitJobId = job.id
           }

+ 11 - 2
src/features/vehicles/Actions/serviceActions.ts

@@ -39,7 +39,11 @@ import { withAuth } from '@/lib/with-auth'
 import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
 import { createServiceSchema, updateServiceSchema } from '../Schema/serviceSchema'
 import { revalidatePath } from 'next/cache'
-import { isSystemStatus, statusColumns } from '@/features/work-order-statuses/Lib/stages'
+import {
+  isSystemStatus,
+  slotOnCompletion,
+  statusColumns,
+} from '@/features/work-order-statuses/Lib/stages'
 import { onInventoryChanged } from '@/features/inventory/Lib/onInventoryChanged'
 import { randomUUID } from 'crypto'
 import { releaseFiles } from '@/lib/files/manager'
@@ -885,6 +889,10 @@ export async function updateServiceRecord(input: unknown) {
             ...(recordData.status !== undefined && recordData.status !== existing.status
               ? { customStatusId: null, customStatusSince: null }
               : {}),
+            // Completed by this save: booked time still ahead is let go.
+            ...(recordData.status !== undefined
+              ? slotOnCompletion(existing, recordData.status)
+              : {}),
             taxComponents: restated?.taxComponents,
             ...(savedTax ? { taxableSubtotal: savedTax.taxableSubtotal } : {}),
             // Attaching a vehicle to a counter sale: the direct customer link is
@@ -1174,7 +1182,8 @@ export async function updateServiceStatus(
 
       await db.serviceRecord.update({
         where: { id: recordId },
-        data: statusColumns(status, custom),
+        // A finished job lets go of booked time still ahead of it.
+        data: { ...statusColumns(status, custom), ...slotOnCompletion(record, status) },
       })
 
       notificationBus.emit('workboard', {

+ 8 - 0
src/features/vehicles/Components/service-edit/ScheduleTimesSection.tsx

@@ -197,6 +197,14 @@ export function ScheduleTimesSection({
   const [endDateTime, setEndDateTime] = useState<Date | undefined>(
     initialEndDateTime ? new Date(initialEndDateTime) : new Date(Date.now() + 3600000)
   )
+  // Moved by the server, not here: completing a job ends a booked slot still
+  // ahead of it, and the page showed the old times until it was reloaded.
+  const startKey = initialStartDateTime ? new Date(initialStartDateTime).getTime() : null
+  const endKey = initialEndDateTime ? new Date(initialEndDateTime).getTime() : null
+  useEffect(() => {
+    if (startKey !== null) setStartDateTime(new Date(startKey))
+    if (endKey !== null) setEndDateTime(new Date(endKey))
+  }, [startKey, endKey])
 
   const [promisedAt, setPromisedAt] = useState<Date | undefined>(
     initialPromisedAt ? new Date(initialPromisedAt) : undefined

+ 12 - 3
src/features/vehicles/Lib/createDraftRecord.ts

@@ -189,12 +189,14 @@ export async function createDraftRecord(
   // no slot to find and nothing to search past. Only work on a vehicle is
   // scheduled around what the shop already has booked.
   const isShopWork = opts.shopWork ?? !!opts.vehicleId
+  // A day the job was asked for: a customer's preferred date, still ahead.
+  const askedFrom = opts.bookFrom && opts.bookFrom.getTime() > now.getTime() ? opts.bookFrom : null
   if (opts.startDateTime || !isShopWork) {
     defaultStart =
       opts.startDateTime ??
       atZonedTime(now, settingsMap['workboard.workDayStart'] || '07:00', timeZone)
   } else {
-    const from = opts.bookFrom && opts.bookFrom.getTime() > now.getTime() ? opts.bookFrom : now
+    const from = askedFrom ?? now
     const { bookings, hours } = await loadBookingContext(organizationId, from)
     const slot = nextAvailableSlot({
       from,
@@ -216,8 +218,15 @@ export async function createDraftRecord(
       defaultStart = atZonedTime(from, hours.start || '07:00', timeZone)
     }
   }
-  // serviceDate should be date-only (start of the workshop's day)
-  const serviceDate = startOfZonedDay(defaultStart, timeZone)
+  // The job is dated the day it is opened, on the workshop's calendar, even
+  // when the first free slot is tomorrow: a car taken in after closing time
+  // was otherwise dated the next morning. A time or a day somebody chose (a
+  // booking, the board, a customer's preferred date) still dates it. The
+  // slot itself stays where it was found. Date-only: the workshop's midnight.
+  const serviceDate = startOfZonedDay(
+    opts.startDateTime || askedFrom ? defaultStart : now,
+    timeZone
+  )
 
   // Named from the template once everything it can mention is known: the
   // number just allocated, the car, its owner, the technician and the day.

+ 23 - 0
src/features/work-order-statuses/Lib/stages.ts

@@ -134,3 +134,26 @@ export function statusColumns(
     customStatusSince: custom ? now : null,
   }
 }
+
+/**
+ * What a job's booked time becomes when it is completed: a slot that has not
+ * ended yet ends now, and one that has not started yet starts now too, so a
+ * finished job stops holding calendar time it no longer needs (a job opened
+ * after closing time was booked into the next morning and kept that morning
+ * after it was done). A slot already over is left as it is, and so is a job
+ * that was completed already.
+ */
+export function slotOnCompletion(
+  job: { status: string; startDateTime: Date | null; endDateTime: Date | null },
+  nextStatus: string,
+  now = new Date()
+): { startDateTime?: Date; endDateTime?: Date } {
+  if (nextStatus !== 'completed' || job.status === 'completed') return {}
+  if (!job.endDateTime || job.endDateTime.getTime() <= now.getTime()) return {}
+  return {
+    endDateTime: now,
+    ...(job.startDateTime && job.startDateTime.getTime() > now.getTime()
+      ? { startDateTime: now }
+      : {}),
+  }
+}

+ 8 - 1
src/features/workboard/Lib/availability.ts

@@ -85,8 +85,15 @@ export interface WorkingHours {
   calendar?: WorkshopCalendar
 }
 
-/** Two half-open intervals overlap when each starts before the other ends. */
+/**
+ * Two half-open intervals overlap when each starts before the other ends. One
+ * that holds no time at all overlaps nothing: a job completed before its
+ * booked slot ends at the moment it was finished, start and end the same,
+ * and it held the technician and the bay against whatever was booked around
+ * that moment.
+ */
 export function overlaps(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
+  if (aStart.getTime() >= aEnd.getTime() || bStart.getTime() >= bEnd.getTime()) return false
   return aStart.getTime() < bEnd.getTime() && aEnd.getTime() > bStart.getTime()
 }