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

Say a locked quote is locked when Save is pressed (#643)

The locked quote page turns its inputs off, so its form sends no title.
updateQuote parsed the input before it asked the lock, and Save answered
with a validation message. The lock is now asked first, in updateQuote
and updateServiceRecord alike.
Bernt Christian Egeland 1 неделя назад
Родитель
Сommit
f5c95cd720

+ 89 - 0
src/__tests__/features/quotes/locked-quote-save.test.ts

@@ -0,0 +1,89 @@
+/**
+ * Pressing Save on a locked quote says the quote is locked.
+ *
+ * Save stays on the locked page, as it does on a locked work order, and the
+ * server's refusal is shown in the page's error dialog. The locked page turns
+ * its inputs off, so the form it submits carries no title: the save must go
+ * out all the same and come back with the lock's own sentence, never with a
+ * field name and a parser's complaint.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+
+const modalOpen = vi.fn()
+
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: modalOpen }) }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn(async () => true) }))
+vi.mock('@/features/quotes/Actions/quoteActions', () => ({
+  updateQuote: vi.fn(),
+  deleteQuote: vi.fn(),
+  convertQuoteToServiceRecord: vi.fn(),
+}))
+vi.mock('@/features/quotes/Actions/quoteResponseActions', () => ({
+  acknowledgeQuoteResponse: vi.fn(),
+}))
+
+import { updateQuote } from '@/features/quotes/Actions/quoteActions'
+import { useQuoteFormState } from '@/features/quotes/Components/useQuoteFormState'
+
+const LOCK_SENTENCE = 'This document is locked because it has been sent.'
+
+const quote = {
+  id: 'quote-1',
+  status: 'sent',
+  customer: null,
+  vehicle: null,
+  partItems: [],
+  laborItems: [],
+  taxRate: 0,
+  taxInclusive: false,
+  discountType: 'none',
+  discountValue: 0,
+  description: '',
+  notes: '',
+  validUntil: null,
+} as any
+
+/** The quote form as the locked page renders it: every input turned off. */
+function lockedForm() {
+  const form = document.createElement('form')
+  form.innerHTML =
+    '<fieldset disabled><input name="title" value="ZZ Rear shock absorbers" />' +
+    '<input name="validUntil" value="" /></fieldset>'
+  return form
+}
+
+beforeEach(() => vi.clearAllMocks())
+
+describe('Save on a locked quote', () => {
+  it('shows the lock sentence in the error dialog', async () => {
+    vi.mocked(updateQuote).mockResolvedValue({ success: false, error: LOCK_SENTENCE } as any)
+    const { result } = renderHook(() =>
+      useQuoteFormState({
+        quote,
+        currencyCode: 'GBP',
+        defaultTaxRate: 0,
+        taxEnabled: true,
+        defaultLaborRate: 0,
+        locked: true,
+        t: (key: string) => key,
+      })
+    )
+
+    await act(async () => {
+      await result.current.handleSubmit({
+        preventDefault: vi.fn(),
+        currentTarget: lockedForm(),
+      } as any)
+    })
+
+    // The form with its inputs off has no title to send.
+    expect(vi.mocked(updateQuote).mock.calls[0][0]).toMatchObject({ id: 'quote-1', title: null })
+    expect(modalOpen).toHaveBeenCalledTimes(1)
+    expect(modalOpen).toHaveBeenCalledWith('error', 'Error', LOCK_SENTENCE)
+    expect(result.current.saving).toBe(false)
+  })
+})

+ 52 - 0
src/__tests__/features/workorders/document-lock-enforcement.test.ts

@@ -134,6 +134,16 @@ describe('a locked invoice refuses edits', () => {
     expect(db.serviceRecord.updateMany).not.toHaveBeenCalled()
     expect(db.serviceRecord.updateMany).not.toHaveBeenCalled()
   })
   })
 
 
+  it('says the invoice is locked even when the form sent with it does not parse', async () => {
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(PAID_INVOICE as any)
+
+    const result = await updateServiceRecord({ id: 'rec-1', title: null })
+
+    expect(result.success).toBe(false)
+    expect(result.error).toBe('This document is locked because it has been paid.')
+    expect(db.serviceRecord.update).not.toHaveBeenCalled()
+  })
+
   it('refuses deleteServiceRecord', async () => {
   it('refuses deleteServiceRecord', async () => {
     vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(PAID_INVOICE as any)
     vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(PAID_INVOICE as any)
 
 
@@ -237,6 +247,48 @@ describe('a locked quote refuses edits', () => {
     expect(db.quote.update).not.toHaveBeenCalled()
     expect(db.quote.update).not.toHaveBeenCalled()
   })
   })
 
 
+  it('says the quote is locked when Save is pressed on the locked page', async () => {
+    // The locked page turns its inputs off, so the form reads no title and
+    // sends null. Whoever pressed Save is told about the lock, not handed
+    // "title: Invalid input: expected string, received null".
+    lockSettings({
+      [SETTING_KEYS.QUOTE_LOCK_ENABLED]: 'true',
+      [SETTING_KEYS.QUOTE_LOCK_TRIGGER]: 'sent',
+    })
+    vi.mocked(db.quote.findFirst).mockResolvedValue({
+      status: 'sent',
+      sentAt: new Date('2026-11-19T10:00:00Z'),
+      editUnlockedAt: null,
+    } as any)
+
+    const result = await updateQuote({
+      id: 'quote-1',
+      title: null,
+      description: '',
+      status: 'sent',
+      validUntil: '',
+      partItems: [],
+      laborItems: [],
+    })
+
+    expect(result.success).toBe(false)
+    expect(result.error).toBe('This document is locked because it has been sent.')
+    expect(db.quote.update).not.toHaveBeenCalled()
+  })
+
+  it('still names the field when a quote that is not locked is sent without a title', async () => {
+    vi.mocked(db.quote.findFirst).mockResolvedValue({
+      status: 'draft',
+      editUnlockedAt: null,
+    } as any)
+
+    const result = await updateQuote({ id: 'quote-1', title: null })
+
+    expect(result.success).toBe(false)
+    expect(result.error).toMatch(/^title:/)
+    expect(db.quote.update).not.toHaveBeenCalled()
+  })
+
   it('refuses deleteQuote', async () => {
   it('refuses deleteQuote', async () => {
     vi.mocked(db.quote.findFirst).mockResolvedValue({
     vi.mocked(db.quote.findFirst).mockResolvedValue({
       status: 'converted',
       status: 'converted',

+ 6 - 2
src/features/quotes/Actions/quoteActions.ts

@@ -17,7 +17,7 @@ import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { savedDocumentTax, taxComponentsForCopy } from '@/features/settings/Lib/workshopTax'
 import { savedDocumentTax, taxComponentsForCopy } from '@/features/settings/Lib/workshopTax'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
 import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
-import { parseSentFields } from '@/lib/parse-sent-fields'
+import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
 import {
 import {
   isShopFeeLine,
   isShopFeeLine,
   newShopFeeLine,
   newShopFeeLine,
@@ -253,9 +253,13 @@ export async function createQuote(input: unknown) {
 export async function updateQuote(input: unknown) {
 export async function updateQuote(input: unknown) {
   return withAuth(
   return withAuth(
     async ({ userId, organizationId }) => {
     async ({ userId, organizationId }) => {
+      // The lock answers before the input is read: a locked page sends a form
+      // with its inputs off, and the person saving it is told about the lock,
+      // not about a field that did not arrive.
+      const quoteId = sentId(input)
+      if (quoteId) await assertQuoteEditable(quoteId, organizationId)
       // Only what was sent: see parseSentFields for what the defaults did.
       // Only what was sent: see parseSentFields for what the defaults did.
       const data = parseSentFields(updateQuoteSchema, input)
       const data = parseSentFields(updateQuoteSchema, input)
-      await assertQuoteEditable(data.id, organizationId)
       const existing = await db.quote.findFirst({
       const existing = await db.quote.findFirst({
         where: { id: data.id, organizationId },
         where: { id: data.id, organizationId },
       })
       })

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

@@ -20,7 +20,7 @@ import { EMPTY_WARRANTY, normalizeWarranty } from '@/lib/warranty'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { issueInvoice } from '@/features/invoices/Lib/issueInvoice'
 import { issueInvoice } from '@/features/invoices/Lib/issueInvoice'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
-import { parseSentFields } from '@/lib/parse-sent-fields'
+import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
 import { createServiceSchema, updateServiceSchema } from '../Schema/serviceSchema'
 import { createServiceSchema, updateServiceSchema } from '../Schema/serviceSchema'
 import { revalidatePath } from 'next/cache'
 import { revalidatePath } from 'next/cache'
 import { isSystemStatus, statusColumns } from '@/features/work-order-statuses/Lib/stages'
 import { isSystemStatus, statusColumns } from '@/features/work-order-statuses/Lib/stages'
@@ -646,11 +646,13 @@ export async function createServiceRecord(input: unknown) {
 export async function updateServiceRecord(input: unknown) {
 export async function updateServiceRecord(input: unknown) {
   return withAuth(
   return withAuth(
     async ({ userId, organizationId }) => {
     async ({ userId, organizationId }) => {
+      // Refused before anything is read or written: this is the main way the
+      // money on an invoice changes. Before the input is parsed too, so a
+      // locked invoice says it is locked whatever the form sent with it.
+      const recordId = sentId(input)
+      if (recordId) await assertInvoiceEditable(recordId, organizationId)
       // Only what was sent: see parseSentFields for what the defaults did.
       // Only what was sent: see parseSentFields for what the defaults did.
       const data = parseSentFields(updateServiceSchema, input)
       const data = parseSentFields(updateServiceSchema, input)
-      // Refused before anything is read or written: this is the main way the
-      // money on an invoice changes.
-      await assertInvoiceEditable(data.id, organizationId)
       const timeZone = await workshopTimeZone(organizationId)
       const timeZone = await workshopTimeZone(organizationId)
       const existing = await db.serviceRecord.findFirst({
       const existing = await db.serviceRecord.findFirst({
         where: { id: data.id, organizationId },
         where: { id: data.id, organizationId },

+ 16 - 0
src/lib/parse-sent-fields.ts

@@ -24,3 +24,19 @@ export function parseSentFields<T extends z.ZodType>(schema: T, input: unknown):
   }
   }
   return parsed as z.infer<T>
   return parsed as z.infer<T>
 }
 }
+
+/**
+ * The id an update was sent with, read before the rest of the input is
+ * parsed, or null when there is none to read.
+ *
+ * An update of a locked document is refused whatever else it carries, so the
+ * lock is asked first. The page of a locked document turns its inputs off,
+ * and a form with its inputs off sends them as null: parsed first, pressing
+ * Save answered "title: Invalid input: expected string, received null" where
+ * the person needed to hear that the document is locked.
+ */
+export function sentId(input: unknown): string | null {
+  if (!input || typeof input !== 'object') return null
+  const id = (input as Record<string, unknown>).id
+  return typeof id === 'string' && id ? id : null
+}