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

Date an invoice the day it is issued, not the day the job was opened (#674)

* Date an invoice the day it is issued, not the day the job was opened

* Leave older sent invoices' dates alone and keep automatic due dates automatic

* Fit the due date placeholder on the invoice card
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
8ffd31d9c7

+ 4 - 0
messages/bg/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Номер на фактурата",
     "invoiceDate": "Дата на фактурата",
     "invoiceDueDate": "Падеж",
+    "invoiceDateOnIssuePlaceholder": "Изпращане",
+    "invoiceDueDateOnIssuePlaceholder": "По условия",
+    "invoiceDateOnIssueHint": "Ако остане празно, фактурата се датира с деня на изпращане, а падежът следва условията ви за плащане.",
+    "invoiceDueDateOnIssueHint": "Ако остане празно, падежът се определя по условията ви за плащане при изпращане на фактурата.",
     "typeOptions": {
       "maintenance": "Поддръжка",
       "repair": "Ремонт",

+ 4 - 0
messages/de/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Rechnungsnummer",
     "invoiceDate": "Rechnungsdatum",
     "invoiceDueDate": "Fälligkeitsdatum",
+    "invoiceDateOnIssuePlaceholder": "Versandtag",
+    "invoiceDueDateOnIssuePlaceholder": "Laut Frist",
+    "invoiceDateOnIssueHint": "Leer gelassen, erhält die Rechnung das Datum des Versandtags und wird nach Ihren Zahlungsbedingungen fällig.",
+    "invoiceDueDateOnIssueHint": "Leer gelassen, wird das Fälligkeitsdatum beim Versand der Rechnung aus Ihren Zahlungsbedingungen gesetzt.",
     "typeOptions": {
       "maintenance": "Wartung",
       "repair": "Reparatur",

+ 4 - 0
messages/en/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Invoice Number",
     "invoiceDate": "Invoice Date",
     "invoiceDueDate": "Due Date",
+    "invoiceDateOnIssuePlaceholder": "When sent",
+    "invoiceDueDateOnIssuePlaceholder": "From terms",
+    "invoiceDateOnIssueHint": "Left empty, the invoice is dated the day it is sent, and falls due by your payment terms.",
+    "invoiceDueDateOnIssueHint": "Left empty, the due date is set from your payment terms when the invoice is sent.",
     "typeOptions": {
       "maintenance": "Maintenance",
       "repair": "Repair",

+ 4 - 0
messages/es/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Número de Factura",
     "invoiceDate": "Fecha de factura",
     "invoiceDueDate": "Fecha de vencimiento",
+    "invoiceDateOnIssuePlaceholder": "Al enviarla",
+    "invoiceDueDateOnIssuePlaceholder": "Por plazo",
+    "invoiceDateOnIssueHint": "Si se deja vacío, la factura lleva la fecha del día en que se envía y vence según sus condiciones de pago.",
+    "invoiceDueDateOnIssueHint": "Si se deja vacío, la fecha de vencimiento se fija según sus condiciones de pago al enviar la factura.",
     "typeOptions": {
       "maintenance": "Mantenimiento",
       "repair": "Reparación",

+ 4 - 0
messages/fr/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Numéro de Facture",
     "invoiceDate": "Date de facture",
     "invoiceDueDate": "Date d'échéance",
+    "invoiceDateOnIssuePlaceholder": "À l'envoi",
+    "invoiceDueDateOnIssuePlaceholder": "Selon délai",
+    "invoiceDateOnIssueHint": "Laissée vide, la facture est datée du jour de son envoi et son échéance suit vos conditions de paiement.",
+    "invoiceDueDateOnIssueHint": "Laissée vide, l'échéance est fixée selon vos conditions de paiement à l'envoi de la facture.",
     "typeOptions": {
       "maintenance": "Maintenance",
       "repair": "Réparation",

+ 4 - 0
messages/it/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Numero Fattura",
     "invoiceDate": "Data fattura",
     "invoiceDueDate": "Data di scadenza",
+    "invoiceDateOnIssuePlaceholder": "All'invio",
+    "invoiceDueDateOnIssuePlaceholder": "Da termini",
+    "invoiceDateOnIssueHint": "Se lasciata vuota, la fattura è datata al giorno dell'invio e scade secondo i tuoi termini di pagamento.",
+    "invoiceDueDateOnIssueHint": "Se lasciata vuota, la scadenza viene fissata secondo i tuoi termini di pagamento all'invio della fattura.",
     "typeOptions": {
       "maintenance": "Manutenzione",
       "repair": "Riparazione",

+ 4 - 0
messages/lt/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Sąskaitos numeris",
     "invoiceDate": "Sąskaitos data",
     "invoiceDueDate": "Mokėjimo terminas",
+    "invoiceDateOnIssuePlaceholder": "Išsiuntus",
+    "invoiceDueDateOnIssuePlaceholder": "Iš sąlygų",
+    "invoiceDateOnIssueHint": "Palikus tuščią, sąskaita datuojama jos išsiuntimo diena, o apmokėjimo terminas skaičiuojamas pagal jūsų mokėjimo sąlygas.",
+    "invoiceDueDateOnIssueHint": "Palikus tuščią, apmokėjimo terminas nustatomas pagal jūsų mokėjimo sąlygas, kai sąskaita išsiunčiama.",
     "typeOptions": {
       "maintenance": "Priežiūra",
       "repair": "Remontas",

+ 4 - 0
messages/nb/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Fakturanummer",
     "invoiceDate": "Fakturadato",
     "invoiceDueDate": "Forfallsdato",
+    "invoiceDateOnIssuePlaceholder": "Ved sending",
+    "invoiceDueDateOnIssuePlaceholder": "Etter vilkår",
+    "invoiceDateOnIssueHint": "Står feltet tomt, dateres fakturaen den dagen den sendes, og forfaller etter betalingsbetingelsene dine.",
+    "invoiceDueDateOnIssueHint": "Står feltet tomt, settes forfallsdatoen etter betalingsbetingelsene dine når fakturaen sendes.",
     "typeOptions": {
       "maintenance": "Vedlikehold",
       "repair": "Reparasjon",

+ 4 - 0
messages/nl/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Factuurnummer",
     "invoiceDate": "Factuurdatum",
     "invoiceDueDate": "Vervaldatum",
+    "invoiceDateOnIssuePlaceholder": "Verzenddag",
+    "invoiceDueDateOnIssuePlaceholder": "Per termijn",
+    "invoiceDateOnIssueHint": "Leeg gelaten krijgt de factuur de datum van de dag waarop hij wordt verzonden, en vervalt hij volgens je betalingsvoorwaarden.",
+    "invoiceDueDateOnIssueHint": "Leeg gelaten wordt de vervaldatum bij het verzenden van de factuur bepaald volgens je betalingsvoorwaarden.",
     "typeOptions": {
       "maintenance": "Onderhoud",
       "repair": "Reparatie",

+ 4 - 0
messages/pl/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Numer Faktury",
     "invoiceDate": "Data faktury",
     "invoiceDueDate": "Termin płatności",
+    "invoiceDateOnIssuePlaceholder": "Po wysłaniu",
+    "invoiceDueDateOnIssuePlaceholder": "Wg terminu",
+    "invoiceDateOnIssueHint": "Jeśli pole pozostanie puste, faktura otrzyma datę dnia wysłania, a termin płatności wynika z Twoich warunków płatności.",
+    "invoiceDueDateOnIssueHint": "Jeśli pole pozostanie puste, termin płatności zostanie ustalony według Twoich warunków płatności przy wysyłce faktury.",
     "typeOptions": {
       "maintenance": "Konserwacja",
       "repair": "Naprawa",

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

@@ -86,6 +86,10 @@
     "invoiceNumber": "Número da Fatura",
     "invoiceDate": "Data da fatura",
     "invoiceDueDate": "Data de vencimento",
+    "invoiceDateOnIssuePlaceholder": "Ao enviar",
+    "invoiceDueDateOnIssuePlaceholder": "Pelo prazo",
+    "invoiceDateOnIssueHint": "Se ficar em branco, a fatura recebe a data do dia em que for enviada e vence conforme suas condições de pagamento.",
+    "invoiceDueDateOnIssueHint": "Se ficar em branco, o vencimento é definido pelas suas condições de pagamento quando a fatura for enviada.",
     "typeOptions": {
       "maintenance": "Manutenção",
       "repair": "Reparo",

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

@@ -86,6 +86,10 @@
     "invoiceNumber": "Número da fatura",
     "invoiceDate": "Data da fatura",
     "invoiceDueDate": "Data de vencimento",
+    "invoiceDateOnIssuePlaceholder": "Ao enviar",
+    "invoiceDueDateOnIssuePlaceholder": "Pelo prazo",
+    "invoiceDateOnIssueHint": "Se ficar em branco, a fatura fica com a data do dia em que for enviada e vence conforme as suas condições de pagamento.",
+    "invoiceDueDateOnIssueHint": "Se ficar em branco, o vencimento é definido pelas suas condições de pagamento quando a fatura for enviada.",
     "typeOptions": {
       "maintenance": "Manutenção",
       "repair": "Reparação",

+ 4 - 0
messages/ru/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Номер счёта",
     "invoiceDate": "Дата счёта",
     "invoiceDueDate": "Срок оплаты",
+    "invoiceDateOnIssuePlaceholder": "Отправка",
+    "invoiceDueDateOnIssuePlaceholder": "По сроку",
+    "invoiceDateOnIssueHint": "Если оставить пустым, счёт будет датирован днём отправки, а срок оплаты рассчитается по вашим условиям оплаты.",
+    "invoiceDueDateOnIssueHint": "Если оставить пустым, срок оплаты будет установлен по вашим условиям оплаты при отправке счёта.",
     "typeOptions": {
       "maintenance": "Техобслуживание",
       "repair": "Ремонт",

+ 4 - 0
messages/tr/service.json

@@ -86,6 +86,10 @@
     "invoiceNumber": "Fatura Numarası",
     "invoiceDate": "Fatura tarihi",
     "invoiceDueDate": "Vade tarihi",
+    "invoiceDateOnIssuePlaceholder": "Gönderince",
+    "invoiceDueDateOnIssuePlaceholder": "Vadeye göre",
+    "invoiceDateOnIssueHint": "Boş bırakılırsa fatura gönderildiği günün tarihini alır ve vadesi ödeme koşullarınıza göre belirlenir.",
+    "invoiceDueDateOnIssueHint": "Boş bırakılırsa vade tarihi, fatura gönderildiğinde ödeme koşullarınıza göre belirlenir.",
     "typeOptions": {
       "maintenance": "Bakım",
       "repair": "Onarım",

+ 141 - 0
src/__tests__/features/invoices/draft-invoice-print-date.test.ts

@@ -0,0 +1,141 @@
+// @vitest-environment node
+/**
+ * The date a draft invoice prints, in a workshop in Auckland.
+ *
+ * A draft is dated the day it is issued, so until then it prints the
+ * workshop's today: the date it would go out with. An invoice sent or paid
+ * before issuing tracked it is no draft and keeps printing the date it went
+ * out with, never today's.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const db = {
+  serviceRecord: { findUnique: vi.fn() },
+  appSetting: { findMany: vi.fn() },
+  organization: { findUnique: vi.fn() },
+  vehicleFinding: { findMany: vi.fn() },
+  documentDesign: { findFirst: vi.fn() },
+}
+// No meters in this workshop.
+vi.mock('@/features/meters/Lib/meters.server', () => ({
+  printableMeterReadings: async () => [],
+  activeMeterTypes: async () => [],
+}))
+// What is fitted to the vehicle; none here.
+vi.mock('@/features/equipment/Lib/equipmentPrint.server', () => ({
+  NO_EQUIPMENT: { job: [], vehicle: [] },
+  printableEquipment: async () => ({ job: [], vehicle: [] }),
+}))
+vi.mock('@/lib/db', () => ({ db }))
+vi.mock('@/features/custom-fields/Lib/getCustomFieldsForPrint', () => ({
+  getCustomFieldsForPrint: async () => [],
+  getRecordCustomFieldsForPrint: async () => [],
+}))
+vi.mock('@/features/invoice-designer/Lib/designRules.server', () => ({
+  designRuleSubjectOf: () => ({}),
+  findRuleDesign: async () => null,
+}))
+vi.mock('@/features/signatures/Lib/memberSignature.server', () => ({
+  memberSignatureDataUri: async () => undefined,
+}))
+vi.mock('@/features/condition-map/Lib/loadMarks.server', () => ({
+  loadVisitConditionMap: async () => null,
+  loadMarkTypeRows: async () => [],
+}))
+
+const { assembleInvoicePrint } = await import('@/features/invoices/Lib/assembleInvoicePrint')
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+const record = (over: Record<string, unknown> = {}): any => ({
+  id: 'rec-1',
+  organizationId: 'org-1',
+  vehicleId: 'veh-1',
+  inspectionId: null,
+  designId: null,
+  title: 'Service',
+  type: 'maintenance',
+  serviceDate: new Date('2026-09-24T09:00:00Z'),
+  invoiceNumber: '2026-0042',
+  mileage: 84120,
+  subtotal: 100,
+  taxRate: 0,
+  taxAmount: 0,
+  totalAmount: 100,
+  cost: 100,
+  discountValue: 0,
+  manuallyPaid: false,
+  conditionMapOnInvoice: null,
+  techName: null,
+  issuedAt: null,
+  issuedData: null,
+  editUnlockedAt: null,
+  partItems: [],
+  laborItems: [{ description: 'Oil change', hours: 1, rate: 100, total: 100 }],
+  attachments: [],
+  payments: [],
+  technician: null,
+  customer: { name: 'Alex Carter', invoiceDesignId: null },
+  vehicle: {
+    customerId: 'cust-1',
+    make: 'Volvo',
+    model: 'V60',
+    year: 2020,
+    vin: null,
+    licensePlate: 'AB 12345',
+    hsn: null,
+    tsn: null,
+    mileage: 84120,
+    customer: null,
+  },
+  issuedDesignSnapshot: null,
+  issuedLogoSnapshot: null,
+  issuedSignatureSnapshot: null,
+  createdBy: { id: 'user-1', name: 'Kari' },
+  ...over,
+})
+
+// 12:30 UTC on 17 November is 01:30 on 18 November in Auckland.
+const NOW = new Date('2026-11-17T12:30:00Z')
+const AUCKLAND_NOV_18 = new Date('2026-11-17T11:00:00Z')
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(NOW)
+  db.organization.findUnique.mockResolvedValue({ name: 'Shop', portalSlug: null })
+  db.vehicleFinding.findMany.mockResolvedValue([])
+  db.documentDesign.findFirst.mockResolvedValue(null)
+  db.appSetting.findMany.mockResolvedValue([
+    { key: 'workshop.timezone', value: 'Pacific/Auckland' },
+  ])
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('the date an invoice prints before it is issued', () => {
+  it("is the workshop's today on a draft", async () => {
+    db.serviceRecord.findUnique.mockResolvedValue(record())
+    const assembly = await assembleInvoicePrint('rec-1')
+    expect(assembly?.data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+  })
+
+  it('is a date somebody set on a draft', async () => {
+    const chosen = new Date('2026-10-31T11:00:00Z')
+    db.serviceRecord.findUnique.mockResolvedValue(record({ invoiceDate: chosen }))
+    const assembly = await assembleInvoicePrint('rec-1')
+    expect(assembly?.data.invoiceDate).toEqual(chosen)
+  })
+
+  it.each([
+    ['sent', { sentAt: new Date('2026-09-25T01:00:00Z') }],
+    ['marked paid', { manuallyPaid: true }],
+    ['paid', { payments: [{ amount: 100, date: new Date('2026-09-25T01:00:00Z') }] }],
+  ])('is never today on an invoice %s before issuing tracked it', async (_, over) => {
+    db.serviceRecord.findUnique.mockResolvedValue(record({ invoiceDate: null, ...over }))
+    const assembly = await assembleInvoicePrint('rec-1')
+    expect(assembly?.data.invoiceDate).toBeNull()
+  })
+})

+ 495 - 0
src/__tests__/features/invoices/invoice-date-on-issue.test.ts

@@ -0,0 +1,495 @@
+/**
+ * An invoice is dated the day it is issued, on the workshop's calendar.
+ *
+ * A job opened in September and invoiced in November is a November invoice:
+ * that is the date of issue VAT law asks for, and what a customer expects.
+ * A date somebody chose by hand is theirs and survives the issue, a sent
+ * invoice never changes its date on a re-send, and the deliberate update to
+ * today's details moves only a date the app wrote itself.
+ *
+ * The workshop is in Auckland, thirteen hours ahead of UTC in November, and
+ * "now" is a moment that is already the next day there: a stamp on the
+ * server's (UTC) calendar would be a day early.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const serviceRecord = { findFirst: vi.fn(), update: vi.fn() }
+vi.mock('@/lib/db', () => ({ db: { serviceRecord } }))
+
+const assembleInvoicePrint = vi.fn()
+vi.mock('@/features/invoices/Lib/assembleInvoicePrint', () => ({
+  assembleInvoicePrint: (...args: unknown[]) => assembleInvoicePrint(...args),
+}))
+vi.mock('@/features/invoice-designer/Lib/designSnapshots', () => ({
+  ensureDesignSnapshot: vi.fn().mockResolvedValue('design-snap'),
+  ensureAssetSnapshot: vi.fn().mockResolvedValue('asset-snap'),
+}))
+vi.mock('@/features/integrations/Lib/events', () => ({ notifyIntegrations: vi.fn() }))
+
+const { issueInvoice, reissueInvoice } = await import('@/features/invoices/Lib/issueInvoice')
+const { invoiceDateAtIssue } = await import('@/features/invoices/Lib/issuedInvoice')
+
+const assembly = {
+  settingsMap: { 'workshop.timezone': 'Pacific/Auckland' },
+  workshop: { name: 'Shop', address: '', phone: '', email: '' },
+  invoiceSettings: {},
+  serviceType: 'automotive',
+  taxLabel: 'GST',
+  designSource: { layout: {}, template: {} },
+  logoDataUri: undefined,
+  signer: { name: '', dataUri: undefined },
+  data: { customer: null, vehicle: null, findings: [], customFields: [] },
+}
+
+// 12:30 UTC on 17 November is 01:30 on 18 November in Auckland (UTC+13).
+const NOW = new Date('2026-11-17T12:30:00Z')
+// Midnight starting 18 November in Auckland.
+const AUCKLAND_NOV_18 = new Date('2026-11-17T11:00:00Z')
+// The day the job was opened, in September (Auckland is UTC+12 then).
+const SEPT_OPENED = new Date('2026-09-02T12:00:00Z')
+
+const updateData = () => serviceRecord.update.mock.calls[0]?.[0]?.data
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.useFakeTimers({ toFake: ['Date'] })
+  vi.setSystemTime(NOW)
+  serviceRecord.update.mockResolvedValue({})
+  assembleInvoicePrint.mockResolvedValue(assembly)
+})
+
+afterEach(() => {
+  vi.useRealTimers()
+})
+
+describe('the first issue', () => {
+  it('dates a job opened in September and sent in November to the November day', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: null,
+      serviceDate: SEPT_OPENED,
+      issuedData: null,
+    })
+
+    expect(await issueInvoice('rec-1', 'org-1', 'sent')).toBe(true)
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data.issuedData.autoInvoiceDate).toBe(AUCKLAND_NOV_18.toISOString())
+  })
+
+  it('dates the invoice the day a payment issues it', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: null,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'paid')
+
+    expect(updateData().invoiceDate).toEqual(AUCKLAND_NOV_18)
+  })
+
+  it('keeps a date somebody set by hand', async () => {
+    const chosen = new Date('2026-10-31T11:00:00Z')
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: chosen,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'sent')
+
+    const data = updateData()
+    expect(data).not.toHaveProperty('invoiceDate')
+    expect(data.issuedData.autoInvoiceDate).toBeNull()
+  })
+
+  it('leaves the date of an invoice the customer already held when freezing it later', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: new Date('2026-06-01T09:00:00Z'),
+      invoiceDate: null,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'backfill')
+
+    expect(updateData()).not.toHaveProperty('invoiceDate')
+  })
+})
+
+describe('an invoice already issued', () => {
+  it('is untouched when sent again', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      editUnlockedAt: null,
+      sentAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      issuedData: { version: 1, autoInvoiceDate: '2026-10-31T11:00:00.000Z' },
+    })
+
+    expect(await issueInvoice('rec-1', 'org-1', 'sent')).toBe(false)
+    expect(serviceRecord.update).not.toHaveBeenCalled()
+  })
+
+  it('keeps its date when an owner unlocks it and sends the corrected copy', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      editUnlockedAt: new Date('2026-11-10T01:00:00Z'),
+      sentAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      issuedData: { version: 1, autoInvoiceDate: '2026-10-31T11:00:00.000Z' },
+    })
+
+    expect(await issueInvoice('rec-1', 'org-1', 'sent')).toBe(true)
+
+    const data = updateData()
+    expect(data).not.toHaveProperty('invoiceDate')
+    // Still the app's date, so a later update to today's details may move it.
+    expect(data.issuedData.autoInvoiceDate).toBe('2026-10-31T11:00:00.000Z')
+  })
+})
+
+describe("updating to today's details", () => {
+  it('moves a date the last issue wrote to today', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      issuedData: { version: 1, autoInvoiceDate: '2026-10-31T11:00:00.000Z' },
+    })
+
+    expect(await reissueInvoice('rec-1', 'org-1')).toBe(true)
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data.issuedData.autoInvoiceDate).toBe(AUCKLAND_NOV_18.toISOString())
+  })
+
+  it('keeps a date somebody changed after the issue', async () => {
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-29T11:00:00Z'),
+      issuedData: { version: 1, autoInvoiceDate: '2026-10-31T11:00:00.000Z' },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    const data = updateData()
+    expect(data).not.toHaveProperty('invoiceDate')
+    expect(data.issuedData.autoInvoiceDate).toBeNull()
+  })
+
+  it('keeps the date of an invoice issued before issuing dated it', async () => {
+    // No record of the app having chosen the date: it may be a person's.
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-09-20T01:00:00Z'),
+      invoiceDate: SEPT_OPENED,
+      issuedData: { version: 1 },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    expect(updateData()).not.toHaveProperty('invoiceDate')
+  })
+})
+
+describe('the stored due date', () => {
+  // Midnight starting 2 December in Auckland: 18 November plus 14 days.
+  const AUCKLAND_DEC_2 = new Date('2026-12-01T11:00:00Z')
+  const withTerms = (dueDays: number) =>
+    assembleInvoicePrint.mockResolvedValue({ ...assembly, invoiceSettings: { dueDays } })
+
+  it('falls due by the terms from the November issue day of a September job', async () => {
+    withTerms(14)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: null,
+      invoiceDueDate: null,
+      serviceDate: SEPT_OPENED,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'sent')
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data.invoiceDueDate).toEqual(AUCKLAND_DEC_2)
+    expect(data.issuedData.autoInvoiceDueDate).toBe(AUCKLAND_DEC_2.toISOString())
+  })
+
+  it('keeps a due date somebody set', async () => {
+    withTerms(14)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: null,
+      invoiceDueDate: new Date('2026-11-30T11:00:00Z'),
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'sent')
+
+    const data = updateData()
+    expect(data).not.toHaveProperty('invoiceDueDate')
+    expect(data.issuedData.autoInvoiceDueDate).toBeNull()
+  })
+
+  it('writes no due date when the workshop has no payment terms', async () => {
+    withTerms(0)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: null,
+      invoiceDate: null,
+      invoiceDueDate: null,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'sent')
+
+    expect(updateData()).not.toHaveProperty('invoiceDueDate')
+  })
+
+  it('writes no due date on the freeze of an invoice the customer already held', async () => {
+    withTerms(14)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: null,
+      sentAt: new Date('2026-06-01T09:00:00Z'),
+      invoiceDate: new Date('2026-05-31T12:00:00Z'),
+      invoiceDueDate: null,
+      issuedData: null,
+    })
+
+    await issueInvoice('rec-1', 'org-1', 'backfill')
+
+    expect(updateData()).not.toHaveProperty('invoiceDueDate')
+  })
+
+  it("moves the app's due date on an update to today's details", async () => {
+    withTerms(14)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      invoiceDueDate: new Date('2026-11-14T11:00:00Z'),
+      issuedData: {
+        version: 1,
+        autoInvoiceDate: '2026-10-31T11:00:00.000Z',
+        autoInvoiceDueDate: '2026-11-14T11:00:00.000Z',
+      },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data.invoiceDueDate).toEqual(AUCKLAND_DEC_2)
+  })
+
+  it("keeps a hand-set due date on an update to today's details", async () => {
+    withTerms(14)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      invoiceDueDate: new Date('2026-12-24T11:00:00Z'),
+      issuedData: {
+        version: 1,
+        autoInvoiceDate: '2026-10-31T11:00:00.000Z',
+        autoInvoiceDueDate: '2026-11-14T11:00:00.000Z',
+      },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data).not.toHaveProperty('invoiceDueDate')
+    expect(data.issuedData.autoInvoiceDueDate).toBeNull()
+  })
+
+  it("clears the app's due date when the terms are now none", async () => {
+    withTerms(0)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      invoiceDueDate: new Date('2026-11-14T11:00:00Z'),
+      issuedData: {
+        version: 1,
+        autoInvoiceDate: '2026-10-31T11:00:00.000Z',
+        autoInvoiceDueDate: '2026-11-14T11:00:00.000Z',
+      },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    const data = updateData()
+    expect(data).toHaveProperty('invoiceDueDate', null)
+    expect(data.issuedData.autoInvoiceDueDate).toBeNull()
+  })
+
+  it('keeps a hand-set due date when the terms are now none', async () => {
+    withTerms(0)
+    serviceRecord.findFirst.mockResolvedValue({
+      id: 'rec-1',
+      issuedAt: new Date('2026-11-01T01:00:00Z'),
+      invoiceDate: new Date('2026-10-31T11:00:00Z'),
+      invoiceDueDate: new Date('2026-12-24T11:00:00Z'),
+      issuedData: {
+        version: 1,
+        autoInvoiceDate: '2026-10-31T11:00:00.000Z',
+        autoInvoiceDueDate: '2026-11-14T11:00:00.000Z',
+      },
+    })
+
+    await reissueInvoice('rec-1', 'org-1')
+
+    expect(updateData()).not.toHaveProperty('invoiceDueDate')
+  })
+})
+
+describe('an invoice sent or paid before issuing tracked it', () => {
+  // No issue stamp, no snapshot, no invoice date of its own: the customer
+  // holds a copy dated by the job, and a re-send must not redate it.
+  const legacy = (over: Record<string, unknown>) => ({
+    id: 'rec-1',
+    issuedAt: null,
+    editUnlockedAt: null,
+    sentAt: null,
+    manuallyPaid: false,
+    payments: [],
+    invoiceDate: null,
+    invoiceDueDate: null,
+    serviceDate: SEPT_OPENED,
+    issuedData: null,
+    ...over,
+  })
+
+  beforeEach(() => {
+    assembleInvoicePrint.mockResolvedValue({ ...assembly, invoiceSettings: { dueDays: 14 } })
+  })
+
+  it('is frozen with its dates left alone when sent again', async () => {
+    serviceRecord.findFirst.mockResolvedValue(legacy({ sentAt: new Date('2026-09-20T01:00:00Z') }))
+
+    expect(await issueInvoice('rec-1', 'org-1', 'sent')).toBe(true)
+
+    const data = updateData()
+    expect(data).not.toHaveProperty('invoiceDate')
+    expect(data).not.toHaveProperty('invoiceDueDate')
+    expect(data.issuedData.autoInvoiceDate).toBeNull()
+    expect(data.issuedData.autoInvoiceDueDate).toBeNull()
+  })
+
+  it('is left alone when marked paid before and sent now', async () => {
+    serviceRecord.findFirst.mockResolvedValue(legacy({ manuallyPaid: true }))
+
+    await issueInvoice('rec-1', 'org-1', 'sent')
+
+    expect(updateData()).not.toHaveProperty('invoiceDate')
+  })
+
+  it('is left alone when a second payment arrives', async () => {
+    serviceRecord.findFirst.mockResolvedValue(legacy({ payments: [{ id: 'p-1' }, { id: 'p-2' }] }))
+
+    await issueInvoice('rec-1', 'org-1', 'paid')
+
+    expect(updateData()).not.toHaveProperty('invoiceDate')
+  })
+
+  it('is not mistaken for the payment that issues a draft now', async () => {
+    // The payment is written before the issue it triggers.
+    serviceRecord.findFirst.mockResolvedValue(legacy({ payments: [{ id: 'p-1' }] }))
+
+    await issueInvoice('rec-1', 'org-1', 'paid')
+
+    const data = updateData()
+    expect(data.invoiceDate).toEqual(AUCKLAND_NOV_18)
+    expect(data.invoiceDueDate).toEqual(new Date('2026-12-01T11:00:00Z'))
+  })
+
+  it('is not mistaken for the paid mark that issues a draft now', async () => {
+    serviceRecord.findFirst.mockResolvedValue(legacy({ manuallyPaid: true }))
+
+    await issueInvoice('rec-1', 'org-1', 'paid')
+
+    expect(updateData().invoiceDate).toEqual(AUCKLAND_NOV_18)
+  })
+})
+
+describe('the due date', () => {
+  it('falls due by the payment terms counted from the issue day', async () => {
+    const { buildInvoicePrintSpec } = await import(
+      '@/features/invoice-designer/Pdf/buildInvoicePrint'
+    )
+    // Issued 18 November in Auckland with 14 days' terms and no due date of
+    // its own: due 2 December, not 14 days after the September opening.
+    const spec = buildInvoicePrintSpec({
+      data: {
+        id: 'rec-1',
+        title: 'Brakes',
+        description: null,
+        type: 'repair',
+        serviceDate: SEPT_OPENED,
+        startDateTime: SEPT_OPENED,
+        invoiceDate: AUCKLAND_NOV_18,
+        invoiceDueDate: null,
+        shopName: 'Shop',
+        techName: null,
+        mileage: null,
+        diagnosticNotes: null,
+        invoiceNotes: null,
+        subtotal: 100,
+        taxRate: 0,
+        taxAmount: 0,
+        totalAmount: 100,
+        cost: 100,
+        invoiceNumber: '2026-1001',
+        partItems: [],
+        laborItems: [{ description: 'Work', hours: 1, rate: 100, total: 100 }],
+        customer: null,
+        vehicle: null,
+      },
+      invoiceSettings: { currencyCode: 'NZD', dueDays: 14, timezone: 'Pacific/Auckland' },
+    })
+    const json = JSON.stringify(spec)
+    expect(json).toContain('Nov 18, 2026')
+    expect(json).toContain('Dec 2, 2026')
+  })
+})
+
+describe('invoiceDateAtIssue', () => {
+  const today = AUCKLAND_NOV_18
+
+  it('writes today when there is no date', () => {
+    expect(invoiceDateAtIssue({ current: null, previousAuto: null, today, redate: false })).toEqual(
+      { write: today, auto: today.toISOString() }
+    )
+  })
+
+  it('never writes over a date that is not the app’s, even on a redate', () => {
+    const chosen = new Date('2026-10-01T11:00:00Z')
+    expect(
+      invoiceDateAtIssue({ current: chosen, previousAuto: null, today, redate: true })
+    ).toEqual({ auto: null })
+  })
+})

+ 87 - 0
src/__tests__/features/vehicles/invoice-date-fields.test.ts

@@ -0,0 +1,87 @@
+/**
+ * The work order's invoice date fields, in a workshop in Auckland.
+ *
+ * A draft shows only the dates somebody set, so a save of the form can never
+ * store a date the issue would then take for a person's choice. An issued
+ * invoice, and one sent or paid before issuing tracked it, shows the dates
+ * it went out with.
+ */
+import { describe, expect, it } from 'vitest'
+import { invoiceDateFields } from '@/features/vehicles/Lib/invoiceDateFields'
+
+const opts = { timeZone: 'Pacific/Auckland', dueDays: 14 }
+// 2 September in Auckland (UTC+12).
+const OPENED = new Date('2026-09-02T00:30:00Z')
+
+const job = (over: Record<string, unknown> = {}) => ({
+  issuedAt: null,
+  sentAt: null,
+  manuallyPaid: false,
+  payments: [],
+  invoiceDate: null,
+  invoiceDueDate: null,
+  startDateTime: OPENED,
+  serviceDate: OPENED,
+  ...over,
+})
+
+describe('a draft', () => {
+  it('leaves both dates for the issue', () => {
+    expect(invoiceDateFields(job(), opts)).toEqual({
+      invoiceDate: '',
+      invoiceDueDate: '',
+      invoiceDatedOnIssue: true,
+      invoiceDueDatedOnIssue: true,
+    })
+  })
+
+  it('leaves the due date for the issue even with a typed invoice date', () => {
+    const fields = invoiceDateFields(job({ invoiceDate: new Date('2026-11-09T11:00:00Z') }), opts)
+    expect(fields.invoiceDate).toBe('2026-11-10')
+    expect(fields.invoiceDueDate).toBe('')
+    expect(fields.invoiceDatedOnIssue).toBe(false)
+    expect(fields.invoiceDueDatedOnIssue).toBe(true)
+  })
+
+  it('shows a due date somebody set', () => {
+    const fields = invoiceDateFields(
+      job({ invoiceDueDate: new Date('2026-12-24T11:00:00Z') }),
+      opts
+    )
+    expect(fields.invoiceDueDate).toBe('2026-12-25')
+  })
+})
+
+describe('an invoice sent or paid before issuing tracked it', () => {
+  it.each([
+    ['sent', { sentAt: new Date('2026-09-05T01:00:00Z') }],
+    ['marked paid', { manuallyPaid: true }],
+    ['paid', { payments: [{ amount: 100 }] }],
+  ])('shows the dates it went out with when %s', (_, over) => {
+    expect(invoiceDateFields(job(over), opts)).toEqual({
+      invoiceDate: '2026-09-02',
+      invoiceDueDate: '2026-09-16',
+      invoiceDatedOnIssue: false,
+      invoiceDueDatedOnIssue: false,
+    })
+  })
+})
+
+describe('an issued invoice', () => {
+  it('shows its stored dates', () => {
+    const fields = invoiceDateFields(
+      job({
+        issuedAt: new Date('2026-11-17T12:30:00Z'),
+        invoiceDate: new Date('2026-11-17T11:00:00Z'),
+        invoiceDueDate: new Date('2026-12-01T11:00:00Z'),
+      }),
+      opts
+    )
+    expect(fields).toEqual({
+      invoiceDate: '2026-11-18',
+      invoiceDueDate: '2026-12-02',
+      invoiceDatedOnIssue: false,
+      invoiceDueDatedOnIssue: false,
+    })
+  })
+})

+ 59 - 0
src/__tests__/features/workorders/create-workorder.test.ts

@@ -1215,3 +1215,62 @@ describe('createDraftServiceRecord — shop fee', () => {
     expect(data.laborItems).toBeUndefined()
   })
 })
+
+// ---------------------------------------------------------------------------
+// Invoice date: a job opened today is not an invoice dated today. The invoice
+// is dated the day it is issued, so a new job carries no invoice date unless
+// somebody gave it one.
+// ---------------------------------------------------------------------------
+
+describe('new work orders and the invoice date', () => {
+  function transactionWith(mockCreate: ReturnType<typeof vi.fn>) {
+    vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
+      fn({
+        serviceRecord: { create: mockCreate },
+        servicePart: { createMany: vi.fn() },
+        serviceLabor: { createMany: vi.fn() },
+        serviceAttachment: { createMany: vi.fn() },
+        inventoryPart: { findFirst: vi.fn(), update: vi.fn() },
+      })
+    )
+  }
+
+  it('leaves the invoice date empty on a job opened without one', async () => {
+    setupAuth()
+    setupCommonMocks()
+    const mockCreate = vi.fn().mockResolvedValue({ id: 'sr-1' })
+    transactionWith(mockCreate)
+
+    await createServiceRecord({ vehicleId: VEHICLE_ID, title: 'Brakes', serviceDate: '2026-09-03' })
+
+    expect(mockCreate.mock.calls[0][0].data.invoiceDate).toBeNull()
+  })
+
+  it('keeps an invoice date the caller chose', async () => {
+    setupAuth()
+    setupCommonMocks()
+    const mockCreate = vi.fn().mockResolvedValue({ id: 'sr-1' })
+    transactionWith(mockCreate)
+
+    await createServiceRecord({
+      vehicleId: VEHICLE_ID,
+      title: 'Brakes',
+      serviceDate: '2026-09-03',
+      invoiceDate: '2026-09-10',
+    })
+
+    expect(mockCreate.mock.calls[0][0].data.invoiceDate).toEqual(new Date('2026-09-10T00:00:00Z'))
+  })
+
+  it('opens a draft from the board without an invoice date', async () => {
+    setupAuth()
+    setupCommonMocks()
+    vi.mocked(db.serviceRecord.create).mockResolvedValue({ id: 'sr-draft' } as any)
+
+    await createDraftServiceRecord(VEHICLE_ID)
+
+    const data = vi.mocked(db.serviceRecord.create).mock.calls[0][0].data as any
+    expect(data.invoiceDate).toBeUndefined()
+    expect(data.serviceDate).toBeInstanceOf(Date)
+  })
+})

+ 17 - 0
src/features/invoices/Lib/assembleInvoicePrint.ts

@@ -25,6 +25,7 @@ import { findingLine } from '@/features/fault-codes/Lib/codes'
 import { resolveCurrencyCode, resolveCurrencyFormat } from '@/lib/currencies'
 import { readFile } from 'fs/promises'
 import { db } from '@/lib/db'
+import { resolveWorkshopTimeZone, startOfZonedDay } from '@/lib/timezone'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { resolveUploadPath } from '@/lib/resolve-upload-path'
 import { isOwnUploadUrl } from '@/lib/upload-url'
@@ -75,6 +76,7 @@ import {
   thawInspectionResults,
   type InvoiceConditionMap,
   type IssuedInvoiceData,
+  wasIssuedBeforeTracking,
 } from './issuedInvoice'
 import { gateTypeKey, typeKeyEnabledIn } from '@/features/vehicles/Lib/typeKeySetting'
 import {
@@ -558,6 +560,21 @@ async function assembleLive(
 
   const data: InvoiceData = {
     ...record,
+    // A draft is dated the day it is issued (invoiceDateAtIssue), so until
+    // then it prints the workshop's today: the date it would go out with.
+    // An invoice sent or paid before issuing tracked it is no draft: it
+    // keeps printing the date it went out with.
+    invoiceDate:
+      record.invoiceDate ??
+      (record.issuedAt || wasIssuedBeforeTracking(record)
+        ? null
+        : startOfZonedDay(
+            new Date(),
+            resolveWorkshopTimeZone(
+              settingsMap[SETTING_KEYS.TIMEZONE],
+              settingsMap[SETTING_KEYS.TIMEZONE_DETECTED]
+            )
+          )),
     customer: partyOf(record.customer),
     vehicle: record.vehicle
       ? {

+ 86 - 9
src/features/invoices/Lib/issueInvoice.ts

@@ -1,4 +1,6 @@
 import { db } from '@/lib/db'
+import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
+import { resolveWorkshopTimeZone, startOfZonedDay } from '@/lib/timezone'
 import type { Prisma } from '@/generated/prisma/client'
 import {
   ensureAssetSnapshot,
@@ -10,8 +12,12 @@ import {
   freezeConditionMap,
   freezeEquipment,
   freezeInspectionResults,
+  dueDateAtIssue,
+  invoiceDateAtIssue,
   ISSUED_INVOICE_VERSION,
+  readIssuedInvoiceData,
   shouldIssue,
+  wentOutBeforeIssue,
   type IssueReason,
   type IssuedInvoiceData,
 } from './issuedInvoice'
@@ -87,6 +93,14 @@ export function buildIssuedInvoiceData(a: InvoicePrintAssembly): IssuedInvoiceDa
   }
 }
 
+/**
+ * How an issue treats the invoice date. `ifUnset` dates an invoice that has
+ * no date yet to the workshop's today; `redate` also moves a date the last
+ * issue wrote; `keep` never touches it (the backfill of invoices the
+ * customer already holds, dated as they were sent).
+ */
+type InvoiceDating = 'ifUnset' | 'redate' | 'keep'
+
 /**
  * Captures the invoice as it prints right now and dates the issue. What
  * decides whether this moment calls for a capture lives with the callers;
@@ -94,10 +108,17 @@ export function buildIssuedInvoiceData(a: InvoicePrintAssembly): IssuedInvoiceDa
  * deliberate refresh of one already issued.
  */
 async function captureIssue(
-  recordId: string,
+  record: {
+    id: string
+    invoiceDate?: Date | null
+    invoiceDueDate?: Date | null
+    issuedData?: unknown
+  },
   organizationId: string,
-  issuedAt: Date
+  issuedAt: Date,
+  dating: InvoiceDating
 ): Promise<boolean> {
+  const recordId = record.id
   // The inspection's rows are frozen, never its photographs, so they are not
   // decoded here only to be thrown away.
   // The photo is kept for good, so issuing waits longer for it than a
@@ -130,15 +151,51 @@ async function captureIssue(
       : Promise.resolve(null),
   ])
 
+  // Dated the day it is issued, on the workshop's calendar, unless somebody
+  // chose the date (invoiceDateAtIssue).
+  const timeZone = resolveWorkshopTimeZone(
+    assembly.settingsMap?.[SETTING_KEYS.TIMEZONE],
+    assembly.settingsMap?.[SETTING_KEYS.TIMEZONE_DETECTED]
+  )
+  const previous = readIssuedInvoiceData(record.issuedData)
+  const dated: ReturnType<typeof invoiceDateAtIssue> =
+    dating === 'keep'
+      ? { auto: null }
+      : invoiceDateAtIssue({
+          current: record.invoiceDate,
+          previousAuto: previous?.autoInvoiceDate,
+          today: startOfZonedDay(new Date(), timeZone),
+          redate: dating === 'redate',
+        })
+  // And falls due by the payment terms from that date, stored, because the
+  // past-due report, the portal and the books read the row, not the sheet.
+  const due: ReturnType<typeof dueDateAtIssue> =
+    dating === 'keep'
+      ? { auto: null }
+      : dueDateAtIssue({
+          current: record.invoiceDueDate,
+          previousAuto: previous?.autoInvoiceDueDate,
+          invoiceDate: dated.write ?? record.invoiceDate,
+          dueDays: Number(assembly.invoiceSettings?.dueDays) || 0,
+          timeZone,
+          redate: dating === 'redate',
+        })
+
   await db.serviceRecord.update({
     where: { id: recordId },
     data: {
       issuedAt,
+      ...(dated.write ? { invoiceDate: dated.write } : {}),
+      ...(due.write !== undefined ? { invoiceDueDate: due.write } : {}),
       issuedDesignSnapshotId,
       issuedLogoSnapshotId,
       issuedSignatureSnapshotId,
       issuedVehiclePhotoSnapshotId,
-      issuedData: buildIssuedInvoiceData(assembly) as unknown as Prisma.InputJsonValue,
+      issuedData: {
+        ...buildIssuedInvoiceData(assembly),
+        autoInvoiceDate: dated.auto,
+        autoInvoiceDueDate: due.auto,
+      } as unknown as Prisma.InputJsonValue,
     },
   })
   // Issuing is the moment an accounting connector wants the invoice, and
@@ -175,15 +232,28 @@ export async function issueInvoice(
 ): Promise<boolean> {
   const record = await db.serviceRecord.findFirst({
     where: { id: recordId, organizationId },
-    select: { id: true, issuedAt: true, editUnlockedAt: true, sentAt: true },
+    select: {
+      id: true,
+      issuedAt: true,
+      editUnlockedAt: true,
+      sentAt: true,
+      invoiceDate: true,
+      invoiceDueDate: true,
+      issuedData: true,
+      manuallyPaid: true,
+      payments: { select: { id: true } },
+    },
   })
   if (!record) return false
   if (!shouldIssue(record, reason)) return false
 
   // A backfilled invoice is dated to when it was sent, which is the
-  // nearest thing to when it was issued that the record knows.
+  // nearest thing to when it was issued that the record knows. Its dates
+  // are the ones the customer already holds, and stay; so do those of any
+  // invoice sent or paid before issuing tracked it.
   const issuedAt = reason === 'backfill' ? (record.sentAt ?? new Date()) : new Date()
-  return captureIssue(recordId, organizationId, issuedAt)
+  const dating = reason === 'backfill' || wentOutBeforeIssue(record, reason) ? 'keep' : 'ifUnset'
+  return captureIssue(record, organizationId, issuedAt, dating)
 }
 
 /**
@@ -196,14 +266,21 @@ export async function issueInvoice(
  * workshop, customer, vehicle, terms and design are read again as they are
  * now and the invoice is locked to them, dated to this moment. The lines
  * and totals are the record's own and were never frozen, so they are not
- * touched. Refused for an invoice that was never issued: a draft prints
+ * touched. The invoice date moves to today too when the last issue wrote it
+ * and nobody has changed it since; a date somebody chose stays. Refused for an invoice that was never issued: a draft prints
  * live already. Returns whether a capture was taken.
  */
 export async function reissueInvoice(recordId: string, organizationId: string): Promise<boolean> {
   const record = await db.serviceRecord.findFirst({
     where: { id: recordId, organizationId },
-    select: { id: true, issuedAt: true },
+    select: {
+      id: true,
+      issuedAt: true,
+      invoiceDate: true,
+      invoiceDueDate: true,
+      issuedData: true,
+    },
   })
   if (!record?.issuedAt) return false
-  return captureIssue(recordId, organizationId, new Date())
+  return captureIssue(record, organizationId, new Date(), 'redate')
 }

+ 110 - 0
src/features/invoices/Lib/issuedInvoice.ts

@@ -1,4 +1,5 @@
 import { z } from 'zod'
+import { addZonedDays } from '@/lib/timezone'
 import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
 import type { MarkTypeRow } from '@/features/condition-map/Lib/markTypes'
 import type { InspectionResults } from '@/features/inspections/Lib/inspectionResults'
@@ -247,6 +248,19 @@ export const issuedInvoiceDataSchema = z
       .nullable()
       .optional()
       .catch(null),
+    /**
+     * The invoice date this issue wrote, as an ISO instant, when the date was
+     * the app's and not somebody's choice. A later update to today's details
+     * moves a date that still matches it and keeps one edited since. Null or
+     * absent when the date was set by hand, or on invoices issued before
+     * issuing dated them.
+     */
+    autoInvoiceDate: z.string().nullable().optional().catch(null),
+    /**
+     * The due date this issue wrote from the payment terms, the same way:
+     * null or absent when somebody set it, or the terms gave none.
+     */
+    autoInvoiceDueDate: z.string().nullable().optional().catch(null),
   })
   .passthrough()
 
@@ -564,3 +578,99 @@ export function wasIssuedBeforeTracking(record: {
   if (record.issuedAt) return false
   return Boolean(record.sentAt || record.manuallyPaid || (record.payments?.length ?? 0) > 0)
 }
+
+/**
+ * The invoice date an issue writes, and what it records as the app's own.
+ *
+ * An invoice is dated the day it is issued, not the day the job was opened:
+ * that is the date of issue VAT law asks for, and what a customer expects on
+ * a job opened in one month and invoiced in the next. So a draft carries no
+ * invoice date of its own until it is issued, and the first issue writes the
+ * workshop's day. A date somebody typed is theirs and is kept.
+ *
+ * `redate` is the deliberate update to today's details: it moves a date the
+ * previous issue wrote and nobody has touched since, and still keeps one set
+ * by hand. A re-send after an owner's unlock does not redate: the corrected
+ * copy goes out as the same invoice, under the same date.
+ *
+ * `write` is undefined when the row's date stays as it is. `auto` is what
+ * the snapshot records: the app's date, or null when the date is a person's.
+ */
+export function invoiceDateAtIssue(opts: {
+  current: Date | null | undefined
+  previousAuto: string | null | undefined
+  today: Date
+  redate: boolean
+}): { write?: Date; auto: string | null } {
+  const { current, previousAuto, today, redate } = opts
+  if (!current) return { write: today, auto: today.toISOString() }
+  const untouched =
+    !!previousAuto && new Date(previousAuto).getTime() === new Date(current).getTime()
+  if (!untouched) return { auto: null }
+  if (redate) return { write: today, auto: today.toISOString() }
+  return { auto: previousAuto }
+}
+
+/**
+ * The due date an issue writes, and what it records as the app's own.
+ *
+ * Reports, the portal, reminders and the books read the stored due date, so
+ * an issued invoice carries one: the invoice date it ends up with plus the
+ * payment terms, on the workshop's calendar. The same rules as the invoice
+ * date: a due date somebody set is kept, and the update to today's details
+ * moves only one the app wrote and nobody has changed since, and clears it
+ * when the terms are now none. No terms at the first issue, no due date.
+ * `write` undefined leaves the row's due date as it is; null clears it.
+ */
+export function dueDateAtIssue(opts: {
+  current: Date | null | undefined
+  previousAuto: string | null | undefined
+  /** The invoice date after this issue; null when it has none. */
+  invoiceDate: Date | null | undefined
+  dueDays: number
+  timeZone: string
+  redate: boolean
+}): { write?: Date | null; auto: string | null } {
+  const { current, previousAuto, invoiceDate, dueDays, timeZone, redate } = opts
+  const fromTerms = () =>
+    invoiceDate && dueDays > 0 ? addZonedDays(new Date(invoiceDate), dueDays, timeZone) : null
+  if (!current) {
+    const due = fromTerms()
+    return due ? { write: due, auto: due.toISOString() } : { auto: null }
+  }
+  const untouched =
+    !!previousAuto && new Date(previousAuto).getTime() === new Date(current).getTime()
+  if (!untouched) return { auto: null }
+  if (!redate) return { auto: previousAuto }
+  // The app's due date follows the terms as they are now; terms since set
+  // to none take it away rather than leave a date nobody chose.
+  const due = fromTerms()
+  return due ? { write: due, auto: due.toISOString() } : { write: null, auto: null }
+}
+
+/**
+ * Whether an invoice being issued now had already gone out before issuing
+ * tracked it: sent, or paid, on a date the customer already holds. Such an
+ * invoice is frozen as it is and its dates are left alone; only one that is
+ * issued for the first time on this occasion is dated by it.
+ *
+ * Differs from wasIssuedBeforeTracking only in what this occasion did itself:
+ * a payment issues the invoice after it is written, so the payment (or the
+ * paid mark) that triggered this issue is not evidence of an earlier one.
+ * Sending issues before it stamps, so a sentAt is always an earlier send.
+ */
+export function wentOutBeforeIssue(
+  record: {
+    issuedAt: Date | null
+    sentAt: Date | null
+    manuallyPaid: boolean
+    payments?: { id?: string }[]
+  },
+  reason: IssueReason
+): boolean {
+  if (record.issuedAt) return false
+  if (record.sentAt) return true
+  const payments = record.payments?.length ?? 0
+  if (reason === 'paid') return payments > 1 || (payments > 0 && record.manuallyPaid)
+  return record.manuallyPaid || payments > 0
+}

+ 4 - 4
src/features/vehicles/Actions/serviceActions.ts

@@ -562,10 +562,10 @@ export async function createServiceRecord(input: unknown) {
             // Reports and the calendar find a job by when it started; a job
             // without a start is in none of them.
             startDateTime: startsAt,
-            invoiceDate:
-              toSafeWorkshopDate(invoiceDate, timeZone) ??
-              toSafeWorkshopDate(serviceDate, timeZone) ??
-              new Date(),
+            // Only a date somebody chose. Without one the invoice is dated
+            // the day it is issued (invoiceDateAtIssue), not the day the job
+            // was opened.
+            invoiceDate: toSafeWorkshopDate(invoiceDate, timeZone) ?? null,
             invoiceDueDate: toSafeWorkshopDate(invoiceDueDate, timeZone),
             ...warranty,
             warrantyExpiresAt: warrantyExpiryFor(warranty, warrantyStartsOn, timeZone),

+ 16 - 0
src/features/vehicles/Components/service-edit/InvoiceDetailsSection.tsx

@@ -112,6 +112,13 @@ export function InvoiceDetailsSection({
     setInvoiceDueDate(initialData.invoiceDueDate || '')
   }, [initialData.invoiceDueDate])
 
+  // A draft's empty invoice date is filled the day it is sent; the hint says
+  // so while nobody has typed a date of their own.
+  const datedOnIssue = Boolean(initialData.invoiceDatedOnIssue) && !invoiceDate
+  // Likewise its empty due date, set from the payment terms at the issue.
+  const dueOnIssue = Boolean(initialData.invoiceDueDatedOnIssue) && !invoiceDueDate
+  const hintId = datedOnIssue || dueOnIssue ? 'invoiceDateOnIssueHint' : undefined
+
   // On the overhauled page the status is the stepper under the title, so the
   // select is not drawn a second time.
   const statusField = part ? null : (
@@ -205,6 +212,8 @@ export function InvoiceDetailsSection({
               setInvoiceDate(v)
               onDirty?.()
             }}
+            placeholder={datedOnIssue ? t('invoiceDateOnIssuePlaceholder') : undefined}
+            aria-describedby={datedOnIssue ? hintId : undefined}
             className="h-9 text-sm"
           />
         </div>
@@ -220,10 +229,17 @@ export function InvoiceDetailsSection({
               setInvoiceDueDate(v)
               onDirty?.()
             }}
+            placeholder={dueOnIssue ? t('invoiceDueDateOnIssuePlaceholder') : undefined}
+            aria-describedby={dueOnIssue ? hintId : undefined}
             className="h-9 text-sm"
           />
         </div>
       </div>
+      {hintId && (
+        <p id={hintId} className="text-xs text-muted-foreground">
+          {datedOnIssue ? t('invoiceDateOnIssueHint') : t('invoiceDueDateOnIssueHint')}
+        </p>
+      )}
 
       {designOptions.length > 0 && (
         <div className="space-y-1">

+ 4 - 0
src/features/vehicles/Components/service-edit/form-types.ts

@@ -48,6 +48,10 @@ export interface InitialData {
   invoiceNumber?: string
   invoiceDate: string
   invoiceDueDate: string
+  /** A draft with no invoice date of its own: it is dated the day it is issued. */
+  invoiceDatedOnIssue?: boolean
+  /** A draft: an empty due date is set from the payment terms when it is issued. */
+  invoiceDueDatedOnIssue?: boolean
   concerns: ConcernRow[]
   partItems: ServicePartInput[]
   laborItems: ServiceLaborInput[]

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

@@ -53,12 +53,13 @@ import { canTakePayments } from '@/lib/billing-access'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
 import { listDesignOptions } from '@/features/invoice-designer/Actions/documentDesignActions'
 import { rendersFromIssue } from '@/features/invoices/Lib/issuedInvoice'
+import { invoiceDateFields } from '@/features/vehicles/Lib/invoiceDateFields'
 import { offeredPaymentProviders } from '@/features/integrations/Lib/payments'
 import { listWorkOrderStatuses } from '@/features/work-order-statuses/Actions/workOrderStatusActions'
 import { PageHeader } from '@/components/page-header'
 import { getLocale, getTranslations } from 'next-intl/server'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
-import { addZonedDays, zonedDayKey } from '@/lib/timezone'
+import { zonedDayKey } from '@/lib/timezone'
 
 /**
  * Shared server component behind both service-record routes:
@@ -253,8 +254,6 @@ export async function ServiceRecordPage({
   // fallback date, not crash the page on toISOString().
   const isRenderable = (d: Date | null | undefined): d is Date =>
     !!d && !isNaN(new Date(d).getTime())
-  const effectiveInvoiceDate =
-    [record.invoiceDate, record.startDateTime, record.serviceDate].find(isRenderable) ?? new Date()
   // The date inputs show the workshop's calendar day, not the server's.
   const timeZone = organizationId ? await workshopTimeZone(organizationId) : 'UTC'
 
@@ -312,12 +311,8 @@ export async function ServiceRecordPage({
     diagnosticNotes: record.diagnosticNotes || '',
     invoiceNotes: record.invoiceNotes || '',
     invoiceNumber: record.invoiceNumber || '',
-    invoiceDate: zonedDayKey(effectiveInvoiceDate, timeZone),
-    invoiceDueDate: isRenderable(record.invoiceDueDate)
-      ? zonedDayKey(record.invoiceDueDate, timeZone)
-      : defaultDueDays > 0
-        ? zonedDayKey(addZonedDays(effectiveInvoiceDate, defaultDueDays, timeZone), timeZone)
-        : '',
+    // A draft shows only the dates somebody set; see invoiceDateFields.
+    ...invoiceDateFields(record, { timeZone, dueDays: defaultDueDays }),
     concerns: record.concerns.map((c) => ({
       id: c.id,
       description: c.description,

+ 2 - 1
src/features/vehicles/Lib/createDraftRecord.ts

@@ -282,7 +282,8 @@ export async function createDraftRecord(
       ...warranty,
       warrantyExpiresAt: warrantyExpiryFor(warranty, serviceDate, timeZone),
       serviceDate,
-      invoiceDate: serviceDate,
+      // No invoice date: the invoice is dated the day it is issued
+      // (invoiceDateAtIssue), not the day the job was opened.
       startDateTime: defaultStart,
       endDateTime: defaultEnd ?? new Date(defaultStart.getTime() + 3600000),
     },

+ 57 - 0
src/features/vehicles/Lib/invoiceDateFields.ts

@@ -0,0 +1,57 @@
+import { wasIssuedBeforeTracking } from '@/features/invoices/Lib/issuedInvoice'
+import { addZonedDays, zonedDayKey } from '@/lib/timezone'
+
+/**
+ * What the work order's invoice date fields show, as YYYY-MM-DD on the
+ * workshop's calendar, and whether each is left for the issue to fill.
+ *
+ * A draft is dated, and falls due by the payment terms, the day it is issued
+ * (invoiceDateAtIssue, dueDateAtIssue). So a draft shows only the dates
+ * somebody set: a date shown here would be saved with the form as if it had
+ * been chosen, and the issue would then keep it. That holds for the due date
+ * even when the invoice date was typed.
+ *
+ * An issued invoice shows the dates it went out with, the due date counted
+ * from the terms when it has none stored. So does an invoice sent or paid
+ * before issuing tracked it, with no issue stamp: it is no draft, and the
+ * print reads it the same way (assembleInvoicePrint).
+ */
+export function invoiceDateFields(
+  record: {
+    issuedAt: Date | null
+    sentAt: Date | null
+    manuallyPaid: boolean
+    payments?: { amount: number }[]
+    invoiceDate: Date | null
+    invoiceDueDate: Date | null
+    startDateTime: Date | null
+    serviceDate: Date
+  },
+  opts: { timeZone: string; dueDays: number }
+): {
+  invoiceDate: string
+  invoiceDueDate: string
+  invoiceDatedOnIssue: boolean
+  invoiceDueDatedOnIssue: boolean
+} {
+  const { timeZone, dueDays } = opts
+  // A timestamp outside JS date range (bad legacy data) must degrade to a
+  // fallback date, not crash the page.
+  const renderable = (d: Date | null | undefined): d is Date =>
+    !!d && !Number.isNaN(new Date(d).getTime())
+  const effective =
+    [record.invoiceDate, record.startDateTime, record.serviceDate].find(renderable) ?? new Date()
+  const isDraft = !record.issuedAt && !wasIssuedBeforeTracking(record)
+  const datedOnIssue = isDraft && !renderable(record.invoiceDate)
+
+  return {
+    invoiceDate: datedOnIssue ? '' : zonedDayKey(effective, timeZone),
+    invoiceDueDate: renderable(record.invoiceDueDate)
+      ? zonedDayKey(record.invoiceDueDate, timeZone)
+      : !isDraft && dueDays > 0
+        ? zonedDayKey(addZonedDays(effective, dueDays, timeZone), timeZone)
+        : '',
+    invoiceDatedOnIssue: datedOnIssue,
+    invoiceDueDatedOnIssue: isDraft,
+  }
+}