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

Use the workshop's day as today in the payment form, the expired dates prompt and the report range (#676)

* Use the workshop's day as today in the payment form, the expired dates prompt and the report range

* Type the payment callback in the workshop day test
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
631df5643d

+ 96 - 0
src/__tests__/features/reports/report-range-workshop-today.test.tsx

@@ -0,0 +1,96 @@
+/**
+ * The Reports page opens on "this year up to today", and today is the
+ * workshop's day. It used to end on the viewer's browser day: somebody in
+ * London looking at an Auckland workshop had a range ending on the 24th and
+ * lost everything the workshop had dated the 25th.
+ */
+import { act, render, screen } from '@testing-library/react'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { DateSettingsProvider } from '@/components/date-settings-context'
+
+const { getRevenueReport } = vi.hoisted(() => ({
+  getRevenueReport: vi.fn(async (_params: unknown) => ({ success: false })),
+}))
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
+  useSearchParams: () => new URLSearchParams(),
+  usePathname: () => '/reports',
+}))
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+vi.mock('@/features/reports/Actions/reportActions', () => {
+  const none = async () => ({ success: false })
+  return {
+    getRevenueReport: (params: unknown) => getRevenueReport(params),
+    getServiceReport: none,
+    getCustomerReport: none,
+    getInventoryReport: none,
+    getTechnicianReport: none,
+    getPartsUsageReport: none,
+    getJobAnalyticsReport: none,
+    getCustomerRetentionReport: none,
+    getTaxReport: none,
+    getPastDueInvoicesReport: none,
+    getVehicleReport: none,
+    getTechnicianTimeReport: none,
+  }
+})
+vi.mock('@react-pdf/renderer', () => ({ pdf: vi.fn() }))
+vi.mock('@/features/reports/Components/ReportPDF', () => ({ ReportPDF: () => null }))
+
+import ReportsClient from '@/app/(authenticated)/reports/reports-client'
+
+// The viewer's browser is in London.
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Europe/London'
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+})
+beforeEach(() => {
+  getRevenueReport.mockClear()
+})
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+async function openReports(zone: string, now: string) {
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(new Date(now))
+  await act(async () => {
+    render(
+      <DateSettingsProvider dateFormat="dd/MM/yyyy" timeFormat="24h" timezone={zone}>
+        <ReportsClient currencyCode="NZD" primaryColor="#d97706" organizationName="Test" />
+      </DateSettingsProvider>
+    )
+  })
+}
+
+describe('the default report range', () => {
+  it("ends on the Auckland workshop's today for a viewer in London", async () => {
+    // 16:00 on 24 November in London, 05:00 on the 25th in Auckland.
+    await openReports('Pacific/Auckland', '2026-11-24T16:00:00Z')
+    expect(screen.getByText(/Jan 01, 2026 – Nov 25, 2026/)).toBeInTheDocument()
+    expect(getRevenueReport).toHaveBeenCalledWith(
+      expect.objectContaining({ startDate: '2026-01-01', endDate: '2026-11-25' })
+    )
+  })
+
+  it("ends on the Los Angeles workshop's today, a day behind London", async () => {
+    // 06:00 on 25 November in London, 22:00 on the 24th in Los Angeles.
+    await openReports('America/Los_Angeles', '2026-11-25T06:00:00Z')
+    expect(screen.getByText(/Jan 01, 2026 – Nov 24, 2026/)).toBeInTheDocument()
+    expect(getRevenueReport).toHaveBeenCalledWith(
+      expect.objectContaining({ startDate: '2026-01-01', endDate: '2026-11-24' })
+    )
+  })
+
+  it("starts on the workshop's new year while London is still in the old one", async () => {
+    // 12:00 UTC on 31 December is already 1 January 2027 in Auckland.
+    await openReports('Pacific/Auckland', '2026-12-31T12:00:00Z')
+    expect(getRevenueReport).toHaveBeenCalledWith(
+      expect.objectContaining({ startDate: '2027-01-01', endDate: '2027-01-01' })
+    )
+  })
+})

+ 294 - 0
src/__tests__/features/vehicles/expired-dates-workshop-today.test.tsx

@@ -0,0 +1,294 @@
+/**
+ * The expired-dates prompt before an invoice goes out. "Today" is the
+ * workshop's day: it used to be the UTC day, so at 05:00 in Auckland
+ * "Update to today's date" wrote yesterday (24/11, due 08/12) and, west of
+ * UTC, an invoice dated earlier today read as expired in the evening.
+ */
+import { useState } from 'react'
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { DateSettingsProvider } from '@/components/date-settings-context'
+
+const membership = vi.hoisted(() => ({ value: null as unknown }))
+const { updateServiceRecord, handleDownloadPDF } = vi.hoisted(() => ({
+  updateServiceRecord: vi.fn(async (_data: unknown) => ({ success: true })),
+  handleDownloadPDF: vi.fn(),
+}))
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedMembership: async () => membership.value,
+}))
+vi.mock('@/features/inspections/Components/NewInspectionDialog', () => ({
+  NewInspectionDialog: () => null,
+}))
+
+const deleteFinding = vi.fn()
+const router = { push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }
+
+vi.mock('next/navigation', () => ({ useRouter: () => router }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/vehicles/Actions/findingActions', () => ({
+  deleteFinding: (id: string) => deleteFinding(id),
+}))
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecordTitle: vi.fn(),
+  updateServiceStatus: vi.fn(),
+  updateServiceRecord: (data: unknown) => updateServiceRecord(data),
+}))
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+vi.mock('@/features/email/Actions/emailActions', () => ({ sendInvoiceEmail: vi.fn() }))
+vi.mock('@/features/settings/Actions/documentLockActions', () => ({
+  setInvoiceEditUnlocked: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/lookupPartByBarcode', () => ({
+  lookupPartByBarcode: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn() }))
+vi.mock('@/hooks/use-hardware-scanner', () => ({ useHardwareScanner: () => undefined }))
+vi.mock('@/hooks/use-save-shortcut', () => ({ useSaveShortcut: () => undefined }))
+vi.mock('@/features/realtime/hooks', () => ({ useLiveRecord: () => undefined }))
+
+const { passThrough } = vi.hoisted(() => ({
+  passThrough: ({ children }: { children?: React.ReactNode }) => children,
+}))
+vi.mock('@/features/settings/Components/ShopFeeContext', () => ({ ShopFeeProvider: passThrough }))
+vi.mock('@/features/settings/Components/LineTaxContext', () => ({ LineTaxProvider: passThrough }))
+vi.mock('@/features/settings/Components/WorkshopTaxOffer', () => ({
+  useTaxOfferValue: () => null,
+  WorkshopTaxOfferProvider: passThrough,
+}))
+vi.mock('@/features/fault-codes/Components/FaultCodesOnJob', () => ({
+  FaultCodesJobProvider: passThrough,
+}))
+vi.mock('@/components/document-lock-banner', () => ({ DocumentLockBanner: () => null }))
+vi.mock('@/features/vehicles/Components/service-page/InvoiceDesignMenu', () => ({
+  InvoiceDesignMenu: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/PayCodeButton', () => ({
+  PayCodeButton: () => null,
+}))
+vi.mock('@/features/messaging/Components/SendDocumentDialog', () => ({
+  SendDocumentDialog: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ImageCarousel', () => ({
+  ImageCarousel: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ShareDialog', () => ({
+  ShareDialog: () => null,
+}))
+vi.mock('@/components/notify-customer-dialog', () => ({ NotifyCustomerDialog: () => null }))
+vi.mock('@/components/pdf-preview-dialog', () => ({ PdfPreviewDialog: () => null }))
+vi.mock('@/features/vehicles/Components/service-edit/InventoryPickerDialog', () => ({
+  InventoryPickerDialog: () => null,
+}))
+vi.mock('@/components/barcode-scanner-dialog', () => ({ BarcodeScannerDialog: () => null }))
+vi.mock('@/features/labor-presets/Components/LaborPresetPickerDialog', () => ({
+  LaborPresetPickerDialog: () => null,
+}))
+vi.mock('@/features/status-reports/Components/StatusReportList', () => ({
+  StatusReportList: () => null,
+}))
+/** The header's Download PDF, which asks about expired dates first. */
+vi.mock('@/features/vehicles/Components/service-page/ServiceHeaderActions', () => ({
+  ServiceHeaderActions: ({ onDownloadPDF }: { onDownloadPDF: () => void }) => (
+    <button type="button" onClick={onDownloadPDF}>
+      Download PDF
+    </button>
+  ),
+}))
+vi.mock('@/features/vehicles/Components/service-page/LaborAddedBanner', () => ({
+  LaborAddedBanner: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/LeaveUnsavedDialog', () => ({
+  LeaveUnsavedDialog: () => null,
+}))
+vi.mock('@/features/realtime/Components/PresenceChips', () => ({ PresenceChips: () => null }))
+
+type Line = { description: string }
+
+vi.mock('@/features/vehicles/Components/service-page/modern/ModernDetails', () => ({
+  ModernDetails: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/ObservationsManager', () => ({
+  ObservationsManager: () => null,
+}))
+
+/** The form state, with real lines and nothing else the page needs here. */
+vi.mock('@/features/vehicles/Components/service-page/useServiceFormState', () => ({
+  useServiceFormState: () => {
+    const [laborItems, setLaborItems] = useState<Line[]>([])
+    return {
+      laborItems,
+      dirtySetLaborItems: setLaborItems,
+      dirtySetPartItems: vi.fn(),
+      dirtySetType: vi.fn(),
+      concerns: [],
+      status: 'pending',
+      paymentStatus: 'unpaid',
+      taxRate: 0,
+      type: 'repair',
+      warranty: { warrantyStatus: 'none' },
+      vehicleName: '2019 Volvo V70',
+      hasUnsavedChanges: false,
+      isDirty: () => false,
+      loading: false,
+      showSaved: false,
+      balanceDue: 0,
+      formRef: { current: null },
+      blockedLeave: null,
+      laborAddedElsewhere: [],
+      partsAddedElsewhere: [],
+      imageAttachments: [],
+      showPresetPicker: false,
+      showInventoryPicker: false,
+      showBarcodeScanner: false,
+      setShowPresetPicker: vi.fn(),
+      setShowInventoryPicker: vi.fn(),
+      setShowBarcodeScanner: vi.fn(),
+      setStatus: vi.fn(),
+      markDirty: vi.fn(),
+      flashSaved: vi.fn(),
+      saveNow: vi.fn(),
+      stayOnPage: vi.fn(),
+      leaveWithoutSaving: vi.fn(),
+      applyLaborAddedElsewhere: vi.fn(),
+      applyPartsAddedElsewhere: vi.fn(),
+    }
+  },
+}))
+vi.mock('@/features/vehicles/Components/service-page/useServiceActions', () => ({
+  useServiceActions: () => ({
+    carouselIndex: null,
+    setCarouselIndex: vi.fn(),
+    downloading: false,
+    handleDelete: vi.fn(),
+    handleDownloadPDF: () => handleDownloadPDF(),
+    handleSubmit: vi.fn(),
+    saveNow: vi.fn(),
+    paymentNotifyMessage: '',
+    showPaymentNotifyDialog: false,
+    setShowPaymentNotifyDialog: vi.fn(),
+    showEmailDialog: false,
+    setShowEmailDialog: vi.fn(),
+    showShareDialog: false,
+    setShowShareDialog: vi.fn(),
+  }),
+}))
+
+import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
+
+// The browser is in London; the workshops are not.
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Europe/London'
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+})
+beforeEach(() => {
+  updateServiceRecord.mockClear()
+  handleDownloadPDF.mockClear()
+})
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+function renderPage({
+  zone,
+  now,
+  invoiceDate,
+  invoiceDueDate,
+}: {
+  zone: string
+  now: string
+  invoiceDate: string
+  invoiceDueDate: string
+}) {
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(new Date(now))
+  const props = {
+    record: {
+      id: 'job1',
+      title: 'Annual service',
+      invoiceNumber: 'WO-1001',
+      customer: null,
+      vehicle: { id: 'v1', year: 2019, make: 'Volvo', model: 'V70', customer: null },
+      publicToken: null,
+    },
+    vehicleId: 'v1',
+    organizationId: 'org1',
+    lockState: { locked: false, unlockedAt: null },
+    canUnlock: false,
+    canTakePayment: true,
+    currencyCode: 'NZD',
+    unitSystem: 'metric',
+    defaultDueDays: 14,
+    initialData: { invoiceDate, invoiceDueDate },
+    openObservations: [],
+  }
+  // Only what this part of the page reads is given.
+  render(
+    <DateSettingsProvider dateFormat="dd/MM/yyyy" timeFormat="24h" timezone={zone}>
+      <ServicePageClient {...(props as unknown as Parameters<typeof ServicePageClient>[0])} />
+    </DateSettingsProvider>
+  )
+}
+
+async function download() {
+  await act(async () => {
+    fireEvent.click(screen.getByRole('button', { name: 'Download PDF' }))
+  })
+}
+
+async function updateToToday() {
+  await act(async () => {
+    fireEvent.click(screen.getByRole('button', { name: "Update to today's date" }))
+  })
+  return updateServiceRecord.mock.calls[0]?.[0]
+}
+
+describe('the expired dates prompt in Auckland at 05:00 on 25 November (16:00 UTC on the 24th)', () => {
+  const auckland = { zone: 'Pacific/Auckland', now: '2026-11-24T16:00:00Z' }
+
+  it("calls yesterday's invoice date expired and moves it to the workshop's today", async () => {
+    renderPage({ ...auckland, invoiceDate: '2026-11-24', invoiceDueDate: '2026-12-08' })
+    await download()
+    expect(screen.getByText('Invoice Dates Expired')).toBeInTheDocument()
+    expect(await updateToToday()).toEqual({
+      id: 'job1',
+      invoiceDate: '2026-11-25',
+      invoiceDueDate: '2026-12-09',
+    })
+    expect(handleDownloadPDF).toHaveBeenCalled()
+  })
+
+  it("does not ask about an invoice dated the workshop's today", async () => {
+    renderPage({ ...auckland, invoiceDate: '2026-11-25', invoiceDueDate: '2026-12-09' })
+    await download()
+    expect(screen.queryByText('Invoice Dates Expired')).toBeNull()
+    expect(handleDownloadPDF).toHaveBeenCalled()
+  })
+})
+
+describe('the expired dates prompt in Los Angeles at 22:00 on 24 November (06:00 UTC on the 25th)', () => {
+  const losAngeles = { zone: 'America/Los_Angeles', now: '2026-11-25T06:00:00Z' }
+
+  it('does not call an invoice dated earlier today expired', async () => {
+    renderPage({ ...losAngeles, invoiceDate: '2026-11-24', invoiceDueDate: '2026-12-08' })
+    await download()
+    expect(screen.queryByText('Invoice Dates Expired')).toBeNull()
+    expect(handleDownloadPDF).toHaveBeenCalled()
+  })
+
+  it("moves an old invoice to the workshop's today, not the UTC one", async () => {
+    renderPage({ ...losAngeles, invoiceDate: '2026-11-20', invoiceDueDate: '2026-11-23' })
+    await download()
+    expect(await updateToToday()).toEqual({
+      id: 'job1',
+      invoiceDate: '2026-11-24',
+      invoiceDueDate: '2026-12-08',
+    })
+  })
+})

+ 100 - 0
src/__tests__/features/vehicles/payment-date-workshop-today.test.tsx

@@ -0,0 +1,100 @@
+/**
+ * The payment form starts on the workshop's today. It used to start on the UTC
+ * day: at 05:00 on 25 November in Auckland the form said 24 November, the
+ * payment was stored on the 24th, and near a month end Collected in reports
+ * counted the money in the wrong month.
+ *
+ * The date field's placeholder is the same day, worked out the same way on
+ * the server and in the browser, so the page no longer hydrates with a
+ * different placeholder than the server drew.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { DateSettingsProvider } from '@/components/date-settings-context'
+import { DateInput } from '@/components/ui/date-input'
+import { PaymentsSection } from '@/features/vehicles/Components/service-detail/PaymentsSection'
+
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+
+// The browser doing the rendering is in London, the workshop elsewhere.
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Europe/London'
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+})
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+function at(instant: string) {
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(new Date(instant))
+}
+
+function Section({
+  zone,
+  onCreatePayment,
+}: {
+  zone: string
+  onCreatePayment: (data: { date: string }) => Promise<boolean>
+}) {
+  return (
+    <DateSettingsProvider dateFormat="dd/MM/yyyy" timeFormat="24h" timezone={zone}>
+      <PaymentsSection
+        payments={[]}
+        paymentStatus="unpaid"
+        manuallyPaid={false}
+        totalPaid={0}
+        displayTotal={250}
+        balanceDue={250}
+        currencyCode="NZD"
+        onCreatePayment={onCreatePayment}
+        onDeletePayment={vi.fn()}
+        onTogglePaid={vi.fn()}
+        paymentLoading={false}
+        deletingPayment={null}
+      />
+    </DateSettingsProvider>
+  )
+}
+
+async function openAndSave(zone: string) {
+  const onCreatePayment = vi.fn(async (_payment: unknown) => true)
+  render(<Section zone={zone} onCreatePayment={onCreatePayment} />)
+  fireEvent.click(screen.getByRole('button', { name: 'Record Payment' }))
+  const shown = (screen.getByLabelText('Date') as HTMLInputElement).value
+  await act(async () => {
+    fireEvent.click(screen.getByRole('button', { name: 'Save Payment' }))
+  })
+  return { shown, saved: onCreatePayment.mock.calls[0]?.[0] }
+}
+
+describe('the payment form', () => {
+  it("starts on the workshop's day in Auckland, a day ahead of UTC", async () => {
+    at('2026-11-24T16:00:00Z')
+    const { shown, saved } = await openAndSave('Pacific/Auckland')
+    expect(shown).toBe('25/11/2026')
+    expect(saved).toMatchObject({ amount: 250, date: '2026-11-25' })
+  })
+
+  it("starts on the workshop's day in Los Angeles, a day behind UTC", async () => {
+    at('2026-11-25T06:00:00Z')
+    const { shown, saved } = await openAndSave('America/Los_Angeles')
+    expect(shown).toBe('24/11/2026')
+    expect(saved).toMatchObject({ date: '2026-11-24' })
+  })
+})
+
+describe('an empty date field', () => {
+  it("shows the workshop's today as its placeholder", () => {
+    at('2026-11-24T16:00:00Z')
+    render(
+      <DateSettingsProvider dateFormat="dd/MM/yyyy" timeFormat="24h" timezone="Pacific/Auckland">
+        <DateInput id="d" value="" onChange={vi.fn()} />
+      </DateSettingsProvider>
+    )
+    expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', '25/11/2026')
+  })
+})

+ 113 - 0
src/__tests__/features/workshop-today-defaults.test.tsx

@@ -0,0 +1,113 @@
+/**
+ * Date fields that start on "today" start on the workshop's today, and the
+ * scheduled-message dialog shows and checks its time on the workshop's clock,
+ * which is the clock the server reads it back on. The browser here is in
+ * London; the workshop is in Auckland, at 05:00 on 25 November while London
+ * and UTC are still at 16:00 on the 24th.
+ */
+import { render, screen } from '@testing-library/react'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { DateSettingsProvider } from '@/components/date-settings-context'
+
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+vi.mock('@/features/scheduled-messages/Actions/scheduledMessageActions', () => ({
+  createScheduledMessage: vi.fn(),
+  updateScheduledMessage: vi.fn(),
+}))
+vi.mock('@/features/whatsapp/Actions/whatsappActions', () => ({
+  getWhatsappTemplateState: vi.fn(async () => ({ success: true, data: { ready: true } })),
+}))
+vi.mock('@/features/quotes/Components/CustomerCombobox', () => ({ CustomerCombobox: () => null }))
+vi.mock('@/features/status-reports/Actions/createStatusReport', () => ({
+  createStatusReport: vi.fn(),
+}))
+vi.mock('@/components/video-recorder-dialog', () => ({ VideoRecorderDialog: () => null }))
+vi.mock('@/hooks/use-mobile', () => ({ useIsMobile: () => false }))
+vi.mock('@/hooks/use-native-camera', () => ({ useNativeCamera: () => false }))
+
+import { ScheduleMessageDialog } from '@/features/scheduled-messages/Components/ScheduleMessageDialog'
+import { CreateStatusReportDialog } from '@/features/status-reports/Components/CreateStatusReportDialog'
+
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Europe/London'
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+})
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+function inAuckland(children: React.ReactNode) {
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(new Date('2026-11-24T16:00:00Z'))
+  return render(
+    <DateSettingsProvider dateFormat="yyyy-MM-dd" timeFormat="24h" timezone="Pacific/Auckland">
+      {children}
+    </DateSettingsProvider>
+  )
+}
+
+describe('scheduling a message', () => {
+  it("starts a new message on the workshop's today", () => {
+    inAuckland(<ScheduleMessageDialog open onOpenChange={vi.fn()} availableChannels={['email']} />)
+    expect(screen.getByLabelText('Date')).toHaveValue('2026-11-25')
+  })
+
+  it('shows a saved message at the time the workshop set, not London time', () => {
+    inAuckland(
+      <ScheduleMessageDialog
+        open
+        onOpenChange={vi.fn()}
+        availableChannels={['email']}
+        message={{
+          id: 'm1',
+          channel: 'email',
+          subject: 'Your car is ready',
+          body: 'Hello',
+          recipient: 'someone@example.com',
+          // 09:00 on 26 November in Auckland.
+          sendAt: new Date('2026-11-25T20:00:00Z'),
+          frequency: 'once',
+          endDate: null,
+          customer: null,
+        }}
+      />
+    )
+    expect(screen.getByLabelText('Date')).toHaveValue('2026-11-26')
+    expect(screen.getByLabelText('Time')).toHaveValue('09:00')
+    expect(screen.queryByText(/already passed/)).toBeNull()
+  })
+
+  it("calls 04:00 on the workshop's today past, which London would call tomorrow", () => {
+    inAuckland(
+      <ScheduleMessageDialog
+        open
+        onOpenChange={vi.fn()}
+        availableChannels={['email']}
+        defaultDate="2026-11-25"
+        defaultTime="04:00"
+      />
+    )
+    expect(screen.getByText(/already passed/)).toBeInTheDocument()
+  })
+})
+
+describe('a status report link', () => {
+  it("expires two weeks from the workshop's today", () => {
+    inAuckland(
+      <CreateStatusReportDialog
+        open
+        onOpenChange={vi.fn()}
+        serviceRecordId="job1"
+        vehicleName="2019 Volvo V70"
+        customer={null}
+        smsEnabled={false}
+        emailEnabled={false}
+        telegramEnabled={false}
+      />
+    )
+    expect(screen.getByLabelText('Link expires')).toHaveValue('2026-12-09')
+  })
+})

+ 55 - 0
src/__tests__/lib/workshop-today.test.ts

@@ -0,0 +1,55 @@
+/**
+ * "Today" on the workshop's calendar. At 16:00 UTC on 24 November it is
+ * already 05:00 on the 25th in Auckland, and at 06:00 UTC on the 25th it is
+ * still 22:00 on the 24th in Los Angeles. The UTC day is wrong in both.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { addDaysToDayKey, dayKeyToLocalDate, workshopTodayKey } from '@/lib/workshop-datetime'
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('workshopTodayKey', () => {
+  it('is the next day in Auckland while UTC is still on the 24th', () => {
+    vi.useFakeTimers({ toFake: ['Date'] })
+    vi.setSystemTime(new Date('2026-11-24T16:00:00Z'))
+    expect(workshopTodayKey('Pacific/Auckland')).toBe('2026-11-25')
+  })
+
+  it('is the day before in Los Angeles while UTC is already on the 25th', () => {
+    vi.useFakeTimers({ toFake: ['Date'] })
+    vi.setSystemTime(new Date('2026-11-25T06:00:00Z'))
+    expect(workshopTodayKey('America/Los_Angeles')).toBe('2026-11-24')
+  })
+
+  it('takes the instant it is given', () => {
+    expect(workshopTodayKey('Pacific/Auckland', new Date('2026-11-24T10:59:00Z'))).toBe(
+      '2026-11-24'
+    )
+    expect(workshopTodayKey('Pacific/Auckland', new Date('2026-11-24T11:00:00Z'))).toBe(
+      '2026-11-25'
+    )
+  })
+
+  it('falls back to UTC for a zone the runtime does not know', () => {
+    expect(workshopTodayKey('Mars/Olympus_Mons', new Date('2026-11-24T16:00:00Z'))).toBe(
+      '2026-11-24'
+    )
+  })
+})
+
+describe('addDaysToDayKey', () => {
+  it('counts calendar days across a month end and a DST change', () => {
+    expect(addDaysToDayKey('2026-11-25', 14)).toBe('2026-12-09')
+    expect(addDaysToDayKey('2026-03-25', 14)).toBe('2026-04-08')
+    expect(addDaysToDayKey('2026-01-01', -1)).toBe('2025-12-31')
+  })
+})
+
+describe('dayKeyToLocalDate', () => {
+  it('reads back as the same day through local getters', () => {
+    const d = dayKeyToLocalDate('2026-11-25')
+    expect([d.getFullYear(), d.getMonth() + 1, d.getDate()]).toEqual([2026, 11, 25])
+  })
+})

+ 12 - 6
src/app/(authenticated)/reports/reports-client.tsx

@@ -76,6 +76,8 @@ import {
   getTechnicianTimeReport,
 } from '@/features/reports/Actions/reportActions'
 import { useFormatCurrency } from '@/components/currency-settings-context'
+import { useDateSettings } from '@/components/date-settings-context'
+import { dayKeyToLocalDate, workshopTodayKey } from '@/lib/workshop-datetime'
 import type {
   RevenueReport,
   ServiceReport,
@@ -175,7 +177,11 @@ export default function ReportsClient({
   const searchParams = useSearchParams()
   const router = useRouter()
   const pathname = usePathname()
-  const currentYear = new Date().getFullYear()
+  // The workshop's day, not the viewer's: a London viewer of an Auckland
+  // workshop otherwise ends the range on a day the workshop has left behind.
+  const { timezone } = useDateSettings()
+  const workshopToday = dayKeyToLocalDate(workshopTodayKey(timezone))
+  const currentYear = workshopToday.getFullYear()
 
   const initialTab = (
     VALID_TABS.includes(searchParams.get('tab') as ReportTab)
@@ -213,7 +219,7 @@ export default function ReportsClient({
   )
   const [dateRange, setDateRange] = useState<DateRange>({
     from: new Date(currentYear, 0, 1),
-    to: new Date(),
+    to: workshopToday,
   })
   const [pendingDateRange, setPendingDateRange] = useState<DateRange>(dateRange)
   const [datePickerOpen, setDatePickerOpen] = useState(false)
@@ -721,7 +727,7 @@ export default function ReportsClient({
       const url = URL.createObjectURL(blob)
       const a = document.createElement('a')
       a.href = url
-      a.download = `${filename}-${format(new Date(), 'yyyy-MM-dd')}.pdf`
+      a.download = `${filename}-${workshopTodayKey(timezone)}.pdf`
       a.click()
       URL.revokeObjectURL(url)
     } catch (error) {
@@ -891,12 +897,12 @@ export default function ReportsClient({
                     // arrow click at a time is what people rage-clicked.
                     captionLayout="dropdown"
                     startMonth={new Date(2000, 0)}
-                    endMonth={new Date(currentYear, new Date().getMonth())}
+                    endMonth={new Date(currentYear, workshopToday.getMonth())}
                   />
                   <div className="border-l p-2 flex flex-col gap-0.5 min-w-[130px]">
                     {(() => {
-                      const now = new Date()
-                      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
+                      const now = workshopToday
+                      const today = workshopToday
                       const presets: { label: string; from: Date; to: Date }[] = [
                         { label: t('dateRange.presets.today'), from: today, to: today },
                         {

+ 4 - 2
src/components/ui/date-input.tsx

@@ -11,6 +11,7 @@ import { cn } from '@/lib/utils'
 import { useDateSettings } from '@/components/date-settings-context'
 import { formatDate as formatWithOrgPattern } from '@/lib/format'
 import { parseDateText, toISODate } from '@/lib/parse-date-text'
+import { dayKeyToLocalDate, workshopTodayKey } from '@/lib/workshop-datetime'
 
 /**
  * Typeable date field with a calendar picker (shadcn date picker "Input"
@@ -38,7 +39,7 @@ export function DateInput({
   /** The id of the message that explains why the value is refused. */
   'aria-describedby'?: string
 }) {
-  const { dateFormat } = useDateSettings()
+  const { dateFormat, timezone } = useDateSettings()
   const ta = useTranslations('common.a11y')
   const display = (d: Date | undefined) => (d ? formatWithOrgPattern(d, dateFormat) : '')
 
@@ -92,7 +93,8 @@ export function DateInput({
       <Input
         id={id}
         value={text}
-        placeholder={placeholder ?? display(new Date())}
+        // The workshop's today, the same on the server (UTC) and in the browser.
+        placeholder={placeholder ?? display(dayKeyToLocalDate(workshopTodayKey(timezone)))}
         onChange={(e) => handleTextChange(e.target.value)}
         onBlur={handleBlur}
         onKeyDown={(e) => {

+ 5 - 2
src/features/billing/Components/RecurringInvoicesClient.tsx

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { useState, useTransition } from 'react'
 import { useRouter } from 'next/navigation'
 import Link from 'next/link'
@@ -153,6 +155,7 @@ export default function RecurringInvoicesClient({
   const t = useTranslations('billing')
   const tcm = useTranslations('common.contextMenu')
   const { formatDate } = useFormatDate()
+  const { timezone } = useDateSettings()
   const [isPending, startTransition] = useTransition()
   const [showCreate, setShowCreate] = useState(false)
 
@@ -170,7 +173,7 @@ export default function RecurringInvoicesClient({
   const [frequency, setFrequency] = useState<
     'weekly' | 'biweekly' | 'monthly' | 'quarterly' | 'yearly'
   >('monthly')
-  const [nextRunDate, setNextRunDate] = useState(new Date().toISOString().split('T')[0])
+  const [nextRunDate, setNextRunDate] = useState(() => workshopTodayKey(timezone))
   const [endDate, setEndDate] = useState('')
   const [vehicleId, setVehicleId] = useState('')
   const [serviceType, setServiceType] = useState('maintenance')
@@ -185,7 +188,7 @@ export default function RecurringInvoicesClient({
     setTitle('')
     setDescription('')
     setFrequency('monthly')
-    setNextRunDate(new Date().toISOString().split('T')[0])
+    setNextRunDate(workshopTodayKey(timezone))
     setEndDate('')
     setVehicleId('')
     setServiceType('maintenance')

+ 29 - 17
src/features/scheduled-messages/Components/ScheduleMessageDialog.tsx

@@ -3,6 +3,9 @@
 import { useEffect, useMemo, useState } from 'react'
 import { useTranslations } from 'next-intl'
 import { toast } from 'sonner'
+import { useDateSettings } from '@/components/date-settings-context'
+import { zonedDateInput, zonedTimeInput } from '@/lib/timezone'
+import { parseWorkshopDateTime, workshopTodayKey } from '@/lib/workshop-datetime'
 import { Bell, Loader2, Mail, MessageCircle, MessageSquare, Send } from 'lucide-react'
 import { getWhatsappTemplateState } from '@/features/whatsapp/Actions/whatsappActions'
 import { Button } from '@/components/ui/button'
@@ -68,15 +71,13 @@ interface ScheduleMessageDialogProps {
   onSaved?: () => void
 }
 
-function toLocalDateStr(d: Date): string {
-  const y = d.getFullYear()
-  const m = String(d.getMonth() + 1).padStart(2, '0')
-  const day = String(d.getDate()).padStart(2, '0')
-  return `${y}-${m}-${day}`
-}
-
-function toTimeStr(d: Date): string {
-  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
+/** The instant a typed date and time stand for; the browser's clock when the workshop has no zone yet. */
+function sendAtInstant(value: string, timeZone: string): number {
+  try {
+    return timeZone ? parseWorkshopDateTime(value, timeZone).getTime() : new Date(value).getTime()
+  } catch {
+    return Number.NaN
+  }
 }
 
 export function ScheduleMessageDialog({
@@ -92,6 +93,9 @@ export function ScheduleMessageDialog({
 }: ScheduleMessageDialogProps) {
   const t = useTranslations('scheduledMessages.dialog')
   const tc = useTranslations('common.buttons')
+  // The fields are the workshop's wall clock: the server reads them back in
+  // its zone, so filling them from the browser's clock moves the message.
+  const { timezone } = useDateSettings()
   const isEdit = !!message
 
   const [channel, setChannel] = useState<MessageChannel>(availableChannels[0] ?? 'email')
@@ -116,10 +120,10 @@ export function ScheduleMessageDialog({
       setRecipient(message.recipient ?? '')
       setSubject(message.subject ?? '')
       setBody(message.body)
-      setDate(toLocalDateStr(message.sendAt))
-      setTime(toTimeStr(message.sendAt))
+      setDate(zonedDateInput(message.sendAt, timezone))
+      setTime(zonedTimeInput(message.sendAt, timezone))
       setFrequency(message.frequency as MessageFrequency)
-      setEndDate(message.endDate ? toLocalDateStr(message.endDate) : '')
+      setEndDate(message.endDate ? zonedDateInput(message.endDate, timezone) : '')
     } else {
       // A draft handed over from the SMS composer stays an SMS when possible
       setChannel(
@@ -129,12 +133,21 @@ export function ScheduleMessageDialog({
       setRecipient('')
       setSubject('')
       setBody(defaultBody ?? '')
-      setDate(defaultDate ?? toLocalDateStr(new Date()))
+      setDate(defaultDate ?? workshopTodayKey(timezone))
       setTime(defaultTime ?? '09:00')
       setFrequency('once')
       setEndDate('')
     }
-  }, [open, message, defaultDate, defaultTime, defaultBody, defaultCustomer?.id, availableChannels])
+  }, [
+    open,
+    message,
+    defaultDate,
+    defaultTime,
+    defaultBody,
+    defaultCustomer?.id,
+    availableChannels,
+    timezone,
+  ])
 
   // A scheduled message fires later, when the customer's 24 hour window has
   // almost certainly closed, so it goes as a template or not at all.
@@ -163,9 +176,8 @@ export function ScheduleMessageDialog({
     (channel !== 'email' || !!subject.trim()) &&
     (!needsRecipient || !!recipient.trim())
 
-  // The browser's clock stands in for the workshop's here, as everywhere on
-  // the client; the server checks again in the workshop's zone.
-  const inPast = !!date && !!time && new Date(`${date}T${time}:00`).getTime() < Date.now()
+  // Read on the workshop's clock, as the server will; the server checks again.
+  const inPast = !!date && !!time && sendAtInstant(`${date}T${time}`, timezone) < Date.now()
 
   const handleSubmit = async (e: React.FormEvent) => {
     e.preventDefault()

+ 7 - 5
src/features/status-reports/Components/CreateStatusReportDialog.tsx

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { addDaysToDayKey, workshopTodayKey } from '@/lib/workshop-datetime'
 import { useState, useRef, useEffect } from 'react'
 import { useTranslations } from 'next-intl'
 import {
@@ -74,9 +76,9 @@ export function CreateStatusReportDialog({
   const [uploading, setUploading] = useState(false)
   const [uploadProgress, setUploadProgress] = useState(0)
   const [submitting, setSubmitting] = useState(false)
-  const [expiresAt, setExpiresAt] = useState(
-    new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
-  )
+  // Two weeks from the workshop's today; the link stays open to the end of that day.
+  const { timezone } = useDateSettings()
+  const [expiresAt, setExpiresAt] = useState(() => addDaysToDayKey(workshopTodayKey(timezone), 14))
 
   useEffect(() => {
     if (open) {
@@ -87,9 +89,9 @@ export function CreateStatusReportDialog({
       setUploading(false)
       setUploadProgress(0)
       setSubmitting(false)
-      setExpiresAt(new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0])
+      setExpiresAt(addDaysToDayKey(workshopTodayKey(timezone), 14))
     }
-  }, [open])
+  }, [open, timezone])
 
   async function handleFileUpload(file: File) {
     setUploading(true)

+ 5 - 2
src/features/tire-hotel/Components/NewTireJobDialog.tsx

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { useEffect, useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
@@ -79,6 +81,7 @@ export function NewTireJobDialog({
   canEditSettings?: boolean
 }) {
   const t = useTranslations('tireHotel')
+  const { timezone } = useDateSettings()
   const router = useRouter()
   const formatCurrency = useFormatCurrency()
   const { formatDate } = useFormatDate()
@@ -157,7 +160,7 @@ export function NewTireJobDialog({
       // blank on purpose: nobody knows when the customer will come back for
       // them, and a guessed date would print on the invoice as if they did.
       setStorageAmount(String(defaultStoragePrice || ''))
-      setStorageFrom(new Date().toISOString().slice(0, 10))
+      setStorageFrom(workshopTodayKey(timezone))
       setStorageTo('')
 
       const rows = jobs?.success && jobs.data ? jobs.data : []
@@ -167,7 +170,7 @@ export function NewTireJobDialog({
     return () => {
       cancelled = true
     }
-  }, [open, tireSetId, mode])
+  }, [open, tireSetId, mode, timezone])
 
   // Two characters is where a search stops meaning "most of the catalogue".
   const searchActive = query.trim().length >= 2

+ 4 - 1
src/features/vehicles/Components/ServiceForm.tsx

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { Button } from '@/components/ui/button'
@@ -37,7 +39,8 @@ export function ServiceForm({ vehicleId, open, onOpenChange }: ServiceFormProps)
   const modal = useGlassModal()
   const [loading, setLoading] = useState(false)
   const [type, setType] = useState('maintenance')
-  const [serviceDate, setServiceDate] = useState(new Date().toISOString().split('T')[0])
+  const { timezone } = useDateSettings()
+  const [serviceDate, setServiceDate] = useState(() => workshopTodayKey(timezone))
 
   const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
     e.preventDefault()

+ 6 - 1
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -18,6 +18,8 @@ import { Check, CreditCard, Loader2, Plus, Trash2, X } from 'lucide-react'
 import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import { useFormatDate } from '@/lib/use-format-date'
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { paymentStatusColors, paymentStatusLabels } from './types'
 import type { Payment } from './types'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
@@ -72,7 +74,10 @@ export function PaymentsSection({
   const modern = useModernWorkOrder()
   const [showForm, setShowForm] = useState(false)
   const [paymentMethod, setPaymentMethod] = useState('other')
-  const [paymentDate, setPaymentDate] = useState(new Date().toISOString().split('T')[0])
+  const { timezone } = useDateSettings()
+  // The workshop's day: in Auckland at 05:00 the UTC day is still yesterday,
+  // and Collected in reports counts a payment on the day it is dated.
+  const [paymentDate, setPaymentDate] = useState(() => workshopTodayKey(timezone))
   const { formatDate } = useFormatDate()
   const formRef = useRef<HTMLDivElement>(null)
   const sectionRef = useRef<HTMLDivElement>(null)

+ 4 - 1
src/features/vehicles/Components/service-edit/InvoiceDetailsSection.tsx

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { useEffect, useState } from 'react'
 import type { DesignAutoRule } from '@/features/invoice-designer/Lib/designRules'
 import { useTranslations } from 'next-intl'
@@ -76,6 +78,7 @@ export function InvoiceDetailsSection({
   part,
 }: InvoiceDetailsSectionProps) {
   const t = useTranslations('service.basicInfo')
+  const { timezone } = useDateSettings()
   const router = useRouter()
   // Saved on change rather than with the form: the choice is its own edit,
   // the way the schedule card's technician is, and must not wait for a save
@@ -158,7 +161,7 @@ export function InvoiceDetailsSection({
       <input
         type="hidden"
         name="serviceDate"
-        value={initialData.serviceDate || new Date().toISOString().split('T')[0]}
+        value={initialData.serviceDate || workshopTodayKey(timezone)}
       />
 
       <div

+ 15 - 9
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -75,6 +75,8 @@ import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './modern/details-props'
 import { lineTotal, resolvePartPrice } from '@/features/inventory/Lib/partPricing'
 import { vehicleName } from '@/lib/vehicle-name'
+import { useDateSettings } from '@/components/date-settings-context'
+import { addDaysToDayKey, dayKeyToLocalDate, workshopTodayKey } from '@/lib/workshop-datetime'
 
 export type { ServicePageClientProps, BoardTechnicianOption } from './service-page-types'
 
@@ -210,9 +212,13 @@ export function ServicePageClient({
   // Date check dialog state
   const [showDateCheck, setShowDateCheck] = useState(false)
   const dateCheckResolveRef = useRef<((proceed: boolean) => void) | null>(null)
-  const today = new Date(new Date().toISOString().split('T')[0])
+  // The workshop's day, not the UTC one: in Auckland at 05:00 the UTC day is
+  // still yesterday. The Dates are local midnights for the pickers.
+  const { timezone } = useDateSettings()
+  const todayKey = workshopTodayKey(timezone)
+  const today = dayKeyToLocalDate(todayKey)
   const suggestedDueDate =
-    defaultDueDays > 0 ? new Date(today.getTime() + defaultDueDays * 86400000) : today
+    defaultDueDays > 0 ? dayKeyToLocalDate(addDaysToDayKey(todayKey, defaultDueDays)) : today
   const [pendingInvoiceDate, setPendingInvoiceDate] = useState<Date>(today)
   const [pendingDueDate, setPendingDueDate] = useState<Date>(suggestedDueDate)
   const [updatingDates, setUpdatingDates] = useState(false)
@@ -226,11 +232,11 @@ export function ServicePageClient({
   const areDatesExpired = useMemo(() => {
     const invoiceDateStr = initialData.invoiceDate
     const dueDateStr = initialData.invoiceDueDate
-    const todayStr = new Date().toISOString().split('T')[0]
+    const todayStr = workshopTodayKey(timezone)
     const invoiceExpired = invoiceDateStr ? invoiceDateStr < todayStr : false
     const dueExpired = dueDateStr ? dueDateStr < todayStr : false
     return invoiceExpired || dueExpired
-  }, [initialData.invoiceDate, initialData.invoiceDueDate])
+  }, [initialData.invoiceDate, initialData.invoiceDueDate, timezone])
 
   const formState = useServiceFormState({
     vehicleId,
@@ -1015,11 +1021,11 @@ export function ServicePageClient({
                       disabled={updatingDates}
                       onClick={async () => {
                         if (updatingDates) return
-                        const now = new Date(new Date().toISOString().split('T')[0])
-                        const due =
-                          defaultDueDays > 0
-                            ? new Date(now.getTime() + defaultDueDays * 86400000)
-                            : new Date(now.getTime() + 14 * 86400000)
+                        const nowKey = workshopTodayKey(timezone)
+                        const now = dayKeyToLocalDate(nowKey)
+                        const due = dayKeyToLocalDate(
+                          addDaysToDayKey(nowKey, defaultDueDays > 0 ? defaultDueDays : 14)
+                        )
                         setPendingInvoiceDate(now)
                         setPendingDueDate(due)
                         setUpdatingDates(true)

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

@@ -1,5 +1,7 @@
 'use client'
 
+import { useDateSettings } from '@/components/date-settings-context'
+import { workshopTodayKey } from '@/lib/workshop-datetime'
 import {
   memo,
   useCallback,
@@ -173,6 +175,7 @@ export function ModernDetails(props: ModernDetailsProps) {
     notificationHistory = NO_NOTIFICATIONS,
   } = props
   const t = useTranslations('service')
+  const { timezone } = useDateSettings()
   const tClock = useTranslations('timeTracking.job')
   // What the labor guide matches a fluid against, priced the way a pick from stock is here.
   const { inventoryParts, defaultMarkupPercent, markupAppliesToInventory } = props
@@ -410,7 +413,7 @@ export function ModernDetails(props: ModernDetailsProps) {
             <input
               type="hidden"
               name="serviceDate"
-              value={formState.initialData.serviceDate || new Date().toISOString().split('T')[0]}
+              value={formState.initialData.serviceDate || workshopTodayKey(timezone)}
             />
             {/* Outside the lock: a locked invoice still moves along. */}
             <StatusStepper

+ 36 - 1
src/lib/workshop-datetime.ts

@@ -1,4 +1,11 @@
-import { addZonedDays, startOfZonedDay, zonedDate, zonedParts } from '@/lib/timezone'
+import {
+  addZonedDays,
+  safeTimeZone,
+  startOfZonedDay,
+  zonedDate,
+  zonedDateInput,
+  zonedParts,
+} from '@/lib/timezone'
 
 /**
  * A "YYYY-MM-DDTHH:MM" from the schedule dialog is the workshop's wall
@@ -102,3 +109,31 @@ export function workshopMonthKey(date: Date, timeZone: string): string {
   const p = zonedParts(date, timeZone)
   return `${p.year}-${String(p.month).padStart(2, '0')}`
 }
+
+/**
+ * Today in the workshop, as YYYY-MM-DD: the business day a payment, an
+ * invoice date or a report range means by "today". Not the UTC day
+ * (`toISOString().slice(0, 10)`), which is yesterday in Auckland every
+ * morning, and not the browser's day, which is wrong for a viewer abroad.
+ * An empty zone means the workshop has never chosen one, and then the
+ * runtime's own day is all there is.
+ */
+export function workshopTodayKey(timeZone: string, now: Date = new Date()): string {
+  return zonedDateInput(now, timeZone ? safeTimeZone(timeZone) : '')
+}
+
+/** The YYYY-MM-DD key `days` calendar days later (or earlier), with no clock involved. */
+export function addDaysToDayKey(key: string, days: number): string {
+  const [y, m, d] = key.split('-').map(Number)
+  return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10)
+}
+
+/**
+ * The runtime-local midnight of a YYYY-MM-DD key, for date pickers and
+ * date-fns, which read a Date by its local getters. Its wall clock is the
+ * day the key names; the instant itself means nothing and is never stored.
+ */
+export function dayKeyToLocalDate(key: string): Date {
+  const [y, m, d] = key.split('-').map(Number)
+  return new Date(y, m - 1, d)
+}