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

Save a work order or quote before any in-app navigation leaves it (#613)

* Save a work order or quote before any in-app navigation leaves it

* Keep an edit made during a save unsaved, and a held navigation on its own destination
Bernt Christian Egeland 1 день назад
Родитель
Сommit
73edc23e59

+ 258 - 0
src/__tests__/features/leaving/quote-saves-before-leaving.test.tsx

@@ -0,0 +1,258 @@
+/**
+ * Leaving the quote editor saves first.
+ *
+ * The quote autosaves five seconds after the last edit and only warned about
+ * closing the tab. An edit followed within those seconds by a click on the
+ * sidebar, a go-to shortcut or a row in the search palette was dropped
+ * without a word. Every one of those ways out now waits for the save, and
+ * only a save that fails holds the person on the page.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+const push = vi.fn()
+const modalOpen = vi.fn()
+const toastError = vi.fn()
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push }),
+  usePathname: () => '/quotes/quote-1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: (m: string) => toastError(m) } }))
+vi.mock('@/components/glass-modal', () => ({
+  useGlassModal: () => ({ open: (...args: unknown[]) => modalOpen(...args) }),
+}))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn(async () => true) }))
+const updateQuote = vi.fn()
+vi.mock('@/features/quotes/Actions/quoteActions', () => ({
+  updateQuote: (input: unknown) => updateQuote(input),
+  deleteQuote: vi.fn(),
+  convertQuoteToServiceRecord: vi.fn(),
+}))
+vi.mock('@/features/quotes/Actions/quoteResponseActions', () => ({
+  acknowledgeQuoteResponse: vi.fn(),
+}))
+vi.mock('@/features/shortcuts/Actions/saveKeyboardShortcuts', () => ({
+  saveKeyboardShortcuts: vi.fn(async (input: unknown) => ({ success: true, data: input })),
+}))
+
+import { useQuoteFormState } from '@/features/quotes/Components/useQuoteFormState'
+import { LeaveUnsavedDialog } from '@/features/vehicles/Components/service-page/LeaveUnsavedDialog'
+import { ShortcutsProvider } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { useGuardedPush } from '@/hooks/use-guarded-push'
+
+const quote = {
+  id: 'quote-1',
+  status: 'draft',
+  customer: null,
+  vehicle: null,
+  partItems: [],
+  laborItems: [],
+  taxRate: 0,
+  taxInclusive: false,
+  discountType: 'none',
+  discountValue: 0,
+  description: '',
+  notes: '',
+  validUntil: null,
+} as any
+
+/** The quote page as far as leaving goes: its form, a sidebar link, and a
+ *  row that opens a page the way the search palette and the Create dialogs do. */
+function QuotePage() {
+  const state = useQuoteFormState({
+    quote,
+    currencyCode: 'USD',
+    defaultTaxRate: 0,
+    taxEnabled: true,
+    defaultLaborRate: 0,
+    locked: false,
+    t: (key: string) => key,
+  })
+  const go = useGuardedPush()
+  return (
+    <>
+      <a href="/customers">Customers</a>
+      <button type="button" onClick={() => go('/vehicles/v-1/service/new')}>
+        Open from the palette
+      </button>
+      <form ref={state.formRef} onSubmit={state.handleSubmit}>
+        <input name="title" aria-label="Title" defaultValue="Brakes" onChange={state.markDirty} />
+      </form>
+      <LeaveUnsavedDialog
+        open={state.blockedLeave !== null}
+        reason={state.blockedLeave?.reason ?? null}
+        onStay={state.stayOnPage}
+        onLeave={state.leaveWithoutSaving}
+      />
+    </>
+  )
+}
+
+function renderPage() {
+  render(
+    <ShortcutsProvider
+      initialPrefs={null}
+      commands={{ isAdminOrOwner: true }}
+      plateLookupAvailable={false}
+    >
+      <QuotePage />
+    </ShortcutsProvider>
+  )
+  // jsdom cannot follow a link; record that the click got through instead.
+  const arrived = vi.fn((event: Event) => event.preventDefault())
+  const sidebar = screen.getByRole('link', { name: 'Customers' })
+  sidebar.addEventListener('click', arrived)
+  return { sidebar, arrived }
+}
+
+function retitle(title: string) {
+  fireEvent.change(screen.getByLabelText('Title'), { target: { value: title } })
+}
+
+function press(init: KeyboardEventInit) {
+  act(() => {
+    document.body.dispatchEvent(
+      new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+    )
+  })
+}
+
+/** A save the test answers when it chooses to. */
+function slowSave() {
+  let answer: (result: { success: boolean; error?: string }) => void = () => undefined
+  updateQuote.mockImplementationOnce(
+    () =>
+      new Promise((resolve) => {
+        answer = resolve
+      })
+  )
+  return (result: { success: boolean; error?: string }) => act(async () => answer(result))
+}
+
+beforeEach(() => {
+  push.mockClear()
+  modalOpen.mockClear()
+  toastError.mockClear()
+  updateQuote.mockReset()
+  updateQuote.mockResolvedValue({ success: true })
+})
+afterEach(() => {
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+describe('leaving a quote with an edit the autosave has not taken yet', () => {
+  it('saves the edit before a sidebar link is followed, and asks nothing', async () => {
+    const { sidebar, arrived } = renderPage()
+    const answer = slowSave()
+    retitle('Brakes, front and rear')
+
+    fireEvent.click(sidebar)
+    await waitFor(() => expect(updateQuote).toHaveBeenCalledOnce())
+    expect(updateQuote.mock.calls[0][0]).toMatchObject({ title: 'Brakes, front and rear' })
+    // Still on the page while the save is on its way.
+    expect(arrived).not.toHaveBeenCalled()
+
+    await answer({ success: true })
+    await waitFor(() => expect(arrived).toHaveBeenCalledOnce())
+    expect(screen.queryByRole('alertdialog')).toBeNull()
+  })
+
+  it('saves the edit before a go-to shortcut opens another page', async () => {
+    renderPage()
+    const answer = slowSave()
+    retitle('Brakes, rear only')
+
+    press({ key: 'g', altKey: true })
+    press({ key: 'w', altKey: true })
+    await waitFor(() => expect(updateQuote).toHaveBeenCalledOnce())
+    expect(push).not.toHaveBeenCalled()
+
+    await answer({ success: true })
+    await waitFor(() => expect(push).toHaveBeenCalledWith('/work-orders'))
+    expect(updateQuote.mock.calls[0][0]).toMatchObject({ title: 'Brakes, rear only' })
+  })
+
+  it('saves the edit before the palette or a Create dialog opens a page', async () => {
+    renderPage()
+    retitle('Timing belt')
+
+    fireEvent.click(screen.getByRole('button', { name: 'Open from the palette' }))
+    await waitFor(() => expect(push).toHaveBeenCalledWith('/vehicles/v-1/service/new'))
+    expect(updateQuote).toHaveBeenCalledOnce()
+    expect(updateQuote.mock.calls[0][0]).toMatchObject({ title: 'Timing belt' })
+  })
+
+  it('saves an edit made while an earlier save was still on its way', async () => {
+    const { sidebar, arrived } = renderPage()
+    const answerFirst = slowSave()
+    retitle('Brakes')
+    fireEvent.submit(screen.getByLabelText('Title').closest('form') as HTMLFormElement)
+    await waitFor(() => expect(updateQuote).toHaveBeenCalledOnce())
+
+    // The first save has left with "Brakes"; the title is changed again.
+    retitle('Brakes and discs')
+    fireEvent.click(sidebar)
+    await answerFirst({ success: true })
+
+    await waitFor(() => expect(arrived).toHaveBeenCalledOnce())
+    expect(updateQuote).toHaveBeenCalledTimes(2)
+    expect(updateQuote.mock.calls[1][0]).toMatchObject({ title: 'Brakes and discs' })
+  })
+
+  it('holds the person on the page when the save fails, and says why', async () => {
+    renderPage()
+    updateQuote.mockResolvedValue({ success: false, error: 'The quote could not be reached' })
+    retitle('Clutch')
+
+    press({ key: 'g', altKey: true })
+    press({ key: 'w', altKey: true })
+    const dialog = await screen.findByRole('alertdialog', { name: 'Your changes are not saved' })
+    expect(dialog).toHaveTextContent('The quote could not be reached')
+    expect(push).not.toHaveBeenCalled()
+    // One explanation, in the dialog: no error box behind it.
+    expect(modalOpen).not.toHaveBeenCalled()
+
+    fireEvent.click(screen.getByRole('button', { name: 'Stay and fix' }))
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())
+    expect(push).not.toHaveBeenCalled()
+    expect(screen.getByLabelText('Title')).toHaveValue('Clutch')
+  })
+
+  it('leaves without the edit only when the person says so', async () => {
+    renderPage()
+    updateQuote.mockResolvedValue({ success: false, error: 'The quote could not be reached' })
+    retitle('Clutch')
+
+    fireEvent.click(screen.getByRole('button', { name: 'Open from the palette' }))
+    await screen.findByRole('alertdialog')
+    fireEvent.click(screen.getByRole('button', { name: 'Leave without saving' }))
+    await waitFor(() => expect(push).toHaveBeenCalledWith('/vehicles/v-1/service/new'))
+    expect(updateQuote).toHaveBeenCalledOnce()
+  })
+
+  it('still shows a failed save in its own box when nobody is leaving', async () => {
+    renderPage()
+    updateQuote.mockResolvedValue({ success: false, error: 'The quote could not be reached' })
+    retitle('Clutch')
+
+    fireEvent.submit(screen.getByLabelText('Title').closest('form') as HTMLFormElement)
+    await waitFor(() =>
+      expect(modalOpen).toHaveBeenCalledWith('error', 'Error', 'The quote could not be reached')
+    )
+    expect(screen.queryByRole('alertdialog')).toBeNull()
+  })
+})
+
+describe('leaving a quote with nothing to save', () => {
+  it('goes at once, by a link and by a shortcut', async () => {
+    const { sidebar, arrived } = renderPage()
+
+    fireEvent.click(sidebar)
+    expect(arrived).toHaveBeenCalledOnce()
+    press({ key: 'g', altKey: true })
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenCalledWith('/work-orders')
+    expect(updateQuote).not.toHaveBeenCalled()
+  })
+})

+ 124 - 0
src/__tests__/features/leaving/work-order-saves-before-leaving.test.tsx

@@ -0,0 +1,124 @@
+/**
+ * A page opened without a click on a link waits for the work order's save.
+ *
+ * The work order has held link clicks back until its save ran for a while,
+ * but the Create dialogs (pick a vehicle, new inspection), the search palette,
+ * the plate lookup and a notification all opened their page with a straight
+ * router.push, which walked past that and dropped the unsaved edit. They now
+ * go through useGuardedPush, which is held exactly as a link is.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, renderHook } from '@testing-library/react'
+
+const push = vi.fn()
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push }) }))
+
+import { useServiceFormState } from '@/features/vehicles/Components/service-page/useServiceFormState'
+import { useGuardedPush } from '@/hooks/use-guarded-push'
+
+const initialData = {
+  id: 'rec-1',
+  title: 'Brake job',
+  description: '',
+  type: 'repair',
+  status: 'pending',
+  serviceDate: '2026-01-01',
+  partItems: [],
+  laborItems: [],
+  concerns: [],
+} as any
+
+const record = { id: 'rec-1', payments: [], manuallyPaid: false, attachments: [] } as any
+
+function renderWorkOrder() {
+  const form = renderHook(() =>
+    useServiceFormState({
+      vehicleId: null,
+      initialData,
+      defaultTaxRate: 0,
+      currentUserName: 'Tester',
+      record,
+      locked: false,
+    })
+  )
+  const go = renderHook(() => useGuardedPush()).result.current
+  const el = document.createElement('form')
+  document.body.appendChild(el)
+  form.result.current.formRef.current = el
+  return { result: form.result, el, go }
+}
+
+const settle = () =>
+  act(async () => {
+    await vi.advanceTimersByTimeAsync(200)
+  })
+
+beforeEach(() => {
+  vi.useFakeTimers()
+  push.mockClear()
+})
+afterEach(() => {
+  vi.useRealTimers()
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+describe('opening a page from a dialog, the palette or a shortcut over an unsaved work order', () => {
+  it('saves the work order first, then opens the page', async () => {
+    const { result, el, go } = renderWorkOrder()
+    act(() => result.current.markDirty())
+    // The page's own save: it went through, for the edit made just now.
+    const revision = result.current.editRevisionRef.current
+    const requestSubmit = vi.spyOn(el, 'requestSubmit').mockImplementation(() => {
+      result.current.markSaved(revision)
+    })
+
+    // Picking a vehicle in the "new work order" dialog ends here.
+    act(() => go('/vehicles/v-2/service/new'))
+    expect(push).not.toHaveBeenCalled()
+
+    await settle()
+    expect(requestSubmit).toHaveBeenCalledOnce()
+    expect(push).toHaveBeenCalledWith('/vehicles/v-2/service/new')
+    expect(result.current.blockedLeave).toBeNull()
+  })
+
+  it('goes where the first attempt pointed when a second one is made while it waits', async () => {
+    const { result, el, go } = renderWorkOrder()
+    act(() => result.current.markDirty())
+    const revision = result.current.editRevisionRef.current
+    vi.spyOn(el, 'requestSubmit').mockImplementation(() => {
+      result.current.markSaved(revision)
+    })
+
+    act(() => go('/work-orders'))
+    act(() => go('/customers'))
+    await settle()
+
+    expect(push).toHaveBeenCalledOnce()
+    expect(push).toHaveBeenCalledWith('/work-orders')
+    expect(document.querySelectorAll('a[data-guarded-link]')).toHaveLength(0)
+  })
+
+  it('stays when the save is refused, and goes only once the person chooses to', async () => {
+    const { result, el, go } = renderWorkOrder()
+    vi.spyOn(el, 'requestSubmit').mockImplementation(() => {
+      result.current.lastSaveErrorRef.current = 'Please fill in all required custom fields'
+    })
+    act(() => result.current.markDirty())
+
+    act(() => go('/inspections/i-9'))
+    await settle()
+    expect(push).not.toHaveBeenCalled()
+    expect(result.current.blockedLeave?.reason).toBe('Please fill in all required custom fields')
+
+    act(() => result.current.leaveWithoutSaving())
+    expect(push).toHaveBeenCalledWith('/inspections/i-9')
+  })
+
+  it('opens the page at once when the work order has nothing to save', () => {
+    const { go } = renderWorkOrder()
+    act(() => go('/customers?create=true'))
+    expect(push).toHaveBeenCalledWith('/customers?create=true')
+  })
+})

+ 3 - 1
src/components/app-sidebar.tsx

@@ -1,5 +1,6 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import * as React from 'react'
 import Link from 'next/link'
 import Image from 'next/image'
@@ -178,6 +179,7 @@ export function AppSidebar({
   const pathname = usePathname()
   const { openHelp: openShortcutsHelp } = useShortcuts()
   const router = useRouter()
+  const go = useGuardedPush()
   const { data: session } = useSession()
   const { theme, setTheme } = useTheme()
   const { setOpenMobile, isMobile } = useSidebar()
@@ -412,7 +414,7 @@ export function AppSidebar({
                   className="pointer-events-auto cursor-pointer"
                   onClick={() => {
                     closeMobileSidebar()
-                    router.push(item.url)
+                    go(item.url)
                   }}
                 >
                   {count > 99 ? '99+' : count}

+ 9 - 7
src/components/quick-create-menu.tsx

@@ -1,7 +1,7 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { useState } from 'react'
-import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { Button } from '@/components/ui/button'
 import {
@@ -37,7 +37,9 @@ interface TemplateOption {
 
 export function QuickCreateMenu() {
   const t = useTranslations('navigation')
-  const router = useRouter()
+  // Through the save guard: the menu is in the header of every page, an
+  // open work order or quote with unsaved edits included.
+  const go = useGuardedPush()
   const [vehicleDialogOpen, setVehicleDialogOpen] = useState(false)
   const [inspectionDialogOpen, setInspectionDialogOpen] = useState(false)
   const [loading, setLoading] = useState(false)
@@ -93,22 +95,22 @@ export function QuickCreateMenu() {
             {t('quickCreate.workOrder')}
             <ShortcutKeys id="create.workOrder" className="ml-auto" />
           </DropdownMenuItem>
-          <DropdownMenuItem onSelect={() => router.push('/customers?create=true')}>
+          <DropdownMenuItem onSelect={() => go('/customers?create=true')}>
             <Users className="h-4 w-4" />
             {t('quickCreate.customer')}
             <ShortcutKeys id="create.customer" className="ml-auto" />
           </DropdownMenuItem>
-          <DropdownMenuItem onSelect={() => router.push('/vehicles?create=true')}>
+          <DropdownMenuItem onSelect={() => go('/vehicles?create=true')}>
             <Car className="h-4 w-4" />
             {t('quickCreate.vehicle')}
             <ShortcutKeys id="create.vehicle" className="ml-auto" />
           </DropdownMenuItem>
-          <DropdownMenuItem onSelect={() => router.push('/quotes?create=true')}>
+          <DropdownMenuItem onSelect={() => go('/quotes?create=true')}>
             <FileText className="h-4 w-4" />
             {t('quickCreate.quote')}
             <ShortcutKeys id="create.quote" className="ml-auto" />
           </DropdownMenuItem>
-          <DropdownMenuItem onSelect={() => router.push('/inventory?create=true')}>
+          <DropdownMenuItem onSelect={() => go('/inventory?create=true')}>
             <Package className="h-4 w-4" />
             {t('quickCreate.part')}
             <ShortcutKeys id="create.part" className="ml-auto" />
@@ -124,7 +126,7 @@ export function QuickCreateMenu() {
               adding a mechanic is not the same errand as booking a car in. */}
           <DropdownMenuSeparator />
           <DropdownMenuLabel>{t('quickCreate.shopActions')}</DropdownMenuLabel>
-          <DropdownMenuItem onSelect={() => router.push('/settings/team?add=true')}>
+          <DropdownMenuItem onSelect={() => go('/settings/team?add=true')}>
             <UserPlus className="mr-2 h-4 w-4" />
             {t('quickCreate.person')}
           </DropdownMenuItem>

+ 4 - 4
src/components/vehicle-picker-dialog.tsx

@@ -1,7 +1,7 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { useState, useEffect, useRef, type KeyboardEvent } from 'react'
-import { useRouter } from 'next/navigation'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
@@ -55,7 +55,7 @@ export function VehiclePickerDialog({
   title,
   redirectQuery,
 }: VehiclePickerDialogProps) {
-  const router = useRouter()
+  const go = useGuardedPush()
   const t = useTranslations('workOrders.vehiclePicker')
   const tc = useTranslations('common.buttons')
   const isMarine = useServiceType() === 'marine'
@@ -184,7 +184,7 @@ export function VehiclePickerDialog({
 
       onOpenChange(false)
       resetState()
-      router.push(`/sales/${result.data.id}`)
+      go(`/sales/${result.data.id}`)
     } catch {
       toast.error(t('somethingWentWrong'))
       setCreating(false)
@@ -195,7 +195,7 @@ export function VehiclePickerDialog({
     onOpenChange(false)
     resetState()
     const qs = redirectQuery ? '?' + new URLSearchParams(redirectQuery).toString() : ''
-    router.push(`/vehicles/${vehicleId}/service/new${qs}`)
+    go(`/vehicles/${vehicleId}/service/new${qs}`)
   }
 
   const handleOpenChange = (nextOpen: boolean) => {

+ 3 - 3
src/features/inspections/Components/NewInspectionDialog.tsx

@@ -1,7 +1,7 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { useState, useEffect, useMemo, useTransition } from 'react'
-import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
 import { DocsLink } from '@/components/docs-link'
@@ -47,7 +47,7 @@ export function NewInspectionDialog({
   serviceRecordId?: string
 }) {
   const t = useTranslations('inspections.new')
-  const router = useRouter()
+  const go = useGuardedPush()
   const serviceType = useServiceType()
   const [isPending, startTransition] = useTransition()
   const [fetchedTemplates, setFetchedTemplates] = useState<TemplateOption[]>([])
@@ -103,7 +103,7 @@ export function NewInspectionDialog({
       if (result.success && result.data) {
         toast.success('Inspection created')
         onOpenChange(false)
-        router.push(`/inspections/${result.data.id}`)
+        go(`/inspections/${result.data.id}`)
       } else {
         toast.error(result.error || 'Failed to create inspection')
       }

+ 3 - 1
src/features/notifications/Components/NotificationPanel.tsx

@@ -1,5 +1,6 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { useRef, useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
@@ -50,6 +51,7 @@ export function NotificationBell() {
 export function NotificationPanel() {
   const t = useTranslations('notifications')
   const router = useRouter()
+  const go = useGuardedPush()
   const {
     notifications,
     unreadCount,
@@ -130,7 +132,7 @@ export function NotificationPanel() {
       // is about.
       const here = `${window.location.pathname}${window.location.search}`
       if (entityUrl === here) router.refresh()
-      else router.push(entityUrl)
+      else go(entityUrl)
     }, 300)
   }
 

+ 8 - 0
src/features/quotes/Components/QuotePageClient.tsx

@@ -49,6 +49,7 @@ import type { QuoteAttachment, QuoteRecord, TabType } from './quote-page-types'
 import { StatusBadge } from '@/components/status-badge'
 import { useQuoteFormState, type ConvertTarget } from './useQuoteFormState'
 import { useSaveShortcut } from '@/hooks/use-save-shortcut'
+import { LeaveUnsavedDialog } from '@/features/vehicles/Components/service-page/LeaveUnsavedDialog'
 import {
   LaborPresetPickerDialog,
   type LaborPresetOption,
@@ -726,6 +727,13 @@ export function QuotePageClient({
                 </div>
               </DialogContent>
             </Dialog>
+
+            <LeaveUnsavedDialog
+              open={state.blockedLeave !== null}
+              reason={state.blockedLeave?.reason ?? null}
+              onStay={state.stayOnPage}
+              onLeave={state.leaveWithoutSaving}
+            />
           </div>
         </WorkshopTaxOfferProvider>
       </LineTaxProvider>

+ 71 - 10
src/features/quotes/Components/useQuoteFormState.ts

@@ -4,6 +4,7 @@ import { Trash2 } from 'lucide-react'
 import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
 import { useRouter } from 'next/navigation'
 import { toast } from 'sonner'
+import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { useGlassModal } from '@/components/glass-modal'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useDateSettings } from '@/components/date-settings-context'
@@ -210,6 +211,19 @@ export function useQuoteFormState({
 
   // Unsaved changes tracking & autosave
   const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
+  // Read through a ref by code that awaits a save and must know its outcome.
+  const hasUnsavedChangesRef = useRef(hasUnsavedChanges)
+  hasUnsavedChangesRef.current = hasUnsavedChanges
+  /**
+   * Counts edits. A save clears the unsaved mark only when no edit was made
+   * while it ran: the fields stay editable during a save, and an edit the
+   * save did not carry must still be saved before the page is left.
+   */
+  const editRevisionRef = useRef(0)
+  /** Why the last save failed, for the dialog that holds a link back. */
+  const lastSaveErrorRef = useRef<string | null>(null)
+  /** True while a link waits on its save: a failure goes into that dialog. */
+  const leavingRef = useRef(false)
   const [showSaved, setShowSaved] = useState(false)
   const savedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
   const formRef = useRef<HTMLFormElement>(null)
@@ -227,6 +241,8 @@ export function useQuoteFormState({
     // A locked quote cannot be saved, so nothing may queue an autosave that
     // the server will only refuse five seconds later.
     if (locked) return
+    editRevisionRef.current += 1
+    hasUnsavedChangesRef.current = true
     setHasUnsavedChanges(true)
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     autosaveTimer.current = setTimeout(() => {
@@ -278,6 +294,7 @@ export function useQuoteFormState({
       clearTimeout(autosaveTimer.current)
       autosaveTimer.current = null
     }
+    hasUnsavedChangesRef.current = false
     setHasUnsavedChanges(false)
   }, [locked])
 
@@ -290,6 +307,9 @@ export function useQuoteFormState({
   useEffect(() => {
     if (!hasUnsavedChanges) return
     const handler = (e: BeforeUnloadEvent) => {
+      // Read live: "Leave without saving" drops the edits and goes in the
+      // same moment, before this listener is taken down.
+      if (!hasUnsavedChangesRef.current) return
       e.preventDefault()
     }
     window.addEventListener('beforeunload', handler)
@@ -468,26 +488,39 @@ export function useQuoteFormState({
     const form = e.currentTarget
     if (isSavingRef.current) return
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
+    // Saving from here on, the custom fields included: whoever waits for this
+    // save (a link held back, the PDF) must not take that first step for the end.
+    isSavingRef.current = true
+    // A save a link is waiting on says why it failed in the dialog that holds
+    // the link, not in a toast or an error box on top of it.
+    const failed = (message: string, show: () => void) => {
+      lastSaveErrorRef.current = message
+      if (!leavingRef.current) show()
+    }
 
     // Validate and save custom fields before saving; a locked quote saves nothing.
     if (!locked && customFieldsSaveRef.current) {
       try {
         const { valid } = await customFieldsSaveRef.current()
         if (!valid) {
-          toast.error(t('page.customFieldsInvalid'))
+          isSavingRef.current = false
+          const message = t('page.customFieldsInvalid')
+          failed(message, () => toast.error(message))
           return
         }
       } catch (err) {
         console.error('Custom fields save error:', err)
-        toast.error(t('page.customFieldsSaveFailed'))
+        isSavingRef.current = false
+        const message = t('page.customFieldsSaveFailed')
+        failed(message, () => toast.error(message))
         return
       }
     }
 
-    isSavingRef.current = true
     setSaving(true)
     try {
       const formData = new FormData(form)
+      const revision = editRevisionRef.current
       const result = await updateQuote({
         id: quote.id,
         title: formData.get('title') as string,
@@ -515,18 +548,25 @@ export function useQuoteFormState({
         warrantyMileage: warranty.warrantyMileage ?? 0,
         warrantyNotes: warranty.warrantyNotes ?? '',
       })
-      if (result.success) {
+      if (result.success && editRevisionRef.current !== revision) {
+        // Edited while this save ran: still unsaved, and the autosave that
+        // edit queued (or a link waiting to leave) saves it next.
+        router.refresh()
+      } else if (result.success) {
+        hasUnsavedChangesRef.current = false
         setHasUnsavedChanges(false)
         if (savedTimerRef.current) clearTimeout(savedTimerRef.current)
         setShowSaved(true)
         savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
         router.refresh()
       } else {
-        modal.open('error', 'Error', result.error || t('page.failedSave'))
+        const message = result.error || t('page.failedSave')
+        failed(message, () => modal.open('error', 'Error', message))
       }
     } catch (err) {
       console.error('Quote save error:', err)
-      modal.open('error', 'Error', t('page.failedSave'))
+      const message = t('page.failedSave')
+      failed(message, () => modal.open('error', 'Error', message))
     } finally {
       // Whatever happened, the save button must stop spinning.
       isSavingRef.current = false
@@ -552,10 +592,6 @@ export function useQuoteFormState({
     }
   }
 
-  // Read through a ref by code that awaits a save and must know its outcome.
-  const hasUnsavedChangesRef = useRef(hasUnsavedChanges)
-  hasUnsavedChangesRef.current = hasUnsavedChanges
-
   const saveNow = async () => {
     if (!formRef.current || isSavingRef.current) return
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
@@ -569,6 +605,28 @@ export function useQuoteFormState({
     })
   }
 
+  // Leaving by a link, a shortcut or the search palette saves first. The
+  // autosave waits five seconds after the last edit, and until this guard an
+  // edit made inside that window was dropped without a word when the page
+  // was left. A save that fails holds the link and asks: stay, or leave
+  // without the unsaved changes.
+  const { blockedLeave, stayOnPage, leaveWithoutSaving } = useSaveBeforeLeaving({
+    active: hasUnsavedChanges,
+    isDirty: () => hasUnsavedChangesRef.current,
+    isSaving: () => isSavingRef.current,
+    save: saveNow,
+    lastErrorRef: lastSaveErrorRef,
+    leavingRef,
+    discard: () => {
+      if (autosaveTimer.current) {
+        clearTimeout(autosaveTimer.current)
+        autosaveTimer.current = null
+      }
+      hasUnsavedChangesRef.current = false
+      setHasUnsavedChanges(false)
+    },
+  })
+
   const handleDownloadPDF = async () => {
     if (hasUnsavedChanges) await saveNow()
     setDownloading(true)
@@ -776,6 +834,9 @@ export function useQuoteFormState({
     handleConvert,
     handleResolveResponse,
     saveNow,
+    blockedLeave,
+    stayOnPage,
+    leaveWithoutSaving,
   }
 }
 

+ 6 - 6
src/features/search/Components/SearchCommand.tsx

@@ -1,8 +1,8 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslations } from 'next-intl'
-import { useRouter } from 'next/navigation'
 import {
   Bell,
   Car,
@@ -346,7 +346,7 @@ export function SearchCommand({
   connectors = [],
   faultCodesEnabled,
 }: SearchCommandProps) {
-  const router = useRouter()
+  const go = useGuardedPush()
   const t = useTranslations('search')
   const tNav = useTranslations('navigation.sidebar')
   const tSettings = useTranslations('settings')
@@ -658,19 +658,19 @@ export function SearchCommand({
         item.run()
         return
       }
-      router.push(item.href)
+      go(item.href)
       if (item.anchor) requestSpotlight(item.anchor)
     },
-    [close, router]
+    [close, go]
   )
 
   const pickRecord = useCallback(
     (href: string, title: string, subtitle?: string) => {
       close()
       pushRecent({ id: href, href, title, subtitle, kind: 'record' })
-      router.push(href)
+      go(href)
     },
-    [close, router]
+    [close, go]
   )
 
   const hasRecords =

+ 6 - 25
src/features/shortcuts/Components/ShortcutsProvider.tsx

@@ -1,5 +1,6 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import {
   createContext,
   useCallback,
@@ -10,7 +11,6 @@ import {
   useState,
   type ReactNode,
 } from 'react'
-import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { toast } from 'sonner'
 import { useServiceType } from '@/components/service-type-context'
@@ -115,7 +115,7 @@ export function ShortcutsProvider({
   plateLookupAvailable: boolean
   children: ReactNode
 }) {
-  const router = useRouter()
+  const go = useGuardedPush()
   const t = useTranslations('settings.shortcuts')
   const [prefs, setPrefs] = useState(() => normalizeShortcutPrefs(initialPrefs))
   const [platform, setPlatform] = useState<Platform>('other')
@@ -189,31 +189,14 @@ export function ShortcutsProvider({
   const openHelp = useCallback(() => setHelpOpen(true), [])
 
   useEffect(() => {
-    // Opening a page goes through a click on a real link, not straight to
-    // the router. The work order page holds an unsaved job back by catching
-    // link clicks (save first, then let the click through), and a shortcut
-    // must be held back the same way a click on the sidebar is. A page with
-    // no such guard treats the shortcut exactly as it treats that click.
-    const link = document.createElement('a')
-    link.hidden = true
-    link.tabIndex = -1
-    link.setAttribute('aria-hidden', 'true')
-    link.dataset.shortcutLink = ''
-    const follow = (event: MouseEvent) => {
-      event.preventDefault()
-      const href = link.getAttribute('href')
-      if (href) router.push(href)
-    }
-    link.addEventListener('click', follow)
-    document.body.appendChild(link)
-
     const run = (def: ShortcutDef) => {
       const handler = handlers.current.get(def.id)?.at(-1)
       if (handler) {
         handler()
       } else if (def.href) {
-        link.setAttribute('href', def.href)
-        link.click()
+        // Through the save guard, as a click on the sidebar is: an editor
+        // with unsaved changes saves before the page is left.
+        go(def.href)
       }
     }
     const forget = () => {
@@ -305,13 +288,11 @@ export function ShortcutsProvider({
     window.addEventListener('blur', forget)
     return () => {
       forget()
-      link.removeEventListener('click', follow)
-      link.remove()
       document.removeEventListener('keydown', onKey)
       document.removeEventListener('pointerdown', forget, true)
       window.removeEventListener('blur', forget)
     }
-  }, [isVisible, router])
+  }, [isVisible, go])
 
   const value = useMemo<ShortcutsContextValue>(
     () => ({

+ 3 - 3
src/features/vehicles/Components/PlateLookupCommand.tsx

@@ -1,7 +1,7 @@
 'use client'
 
+import { useGuardedPush } from '@/hooks/use-guarded-push'
 import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { useRouter } from 'next/navigation'
 import { useFormatter, useTranslations } from 'next-intl'
 import {
   ArrowRight,
@@ -73,7 +73,7 @@ export function PlateLookupCommand() {
   const t = useTranslations('vehicles.plateLookup')
   const tf = useTranslations('vehicles.form')
   const format = useFormatter()
-  const router = useRouter()
+  const go = useGuardedPush()
   const { available, canCreate, registryName } = usePlateLookupAccess()
 
   const [open, setOpen] = useState(false)
@@ -157,7 +157,7 @@ export function PlateLookupCommand() {
 
   const openVehicle = (id: string) => {
     handleOpenChange(false)
-    router.push(`/vehicles/${id}`)
+    go(`/vehicles/${id}`)
   }
 
   const addVehicle = async () => {

+ 21 - 96
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -9,6 +9,7 @@ import {
 } from '@/lib/taxable-lines'
 import { normalizeWarranty, type WarrantyFields } from '@/lib/warranty'
 import { useDeferredCommit } from '@/hooks/use-deferred-commit'
+import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { lineTotal, repricePartRow } from '@/features/inventory/Lib/partPricing'
 import { reconcileConcernRows } from '@/features/vehicles/Lib/concernStory'
 import { addedLaborLines } from '@/features/vehicles/Lib/laborLines'
@@ -248,23 +249,13 @@ export function useServiceFormState({
   }
 
   /**
-   * Leaving the page by a link saves first.
-   *
-   * The autosave waits five seconds after the last edit, and the beforeunload
-   * warning only covers leaving the site: a title retyped and then the back
-   * arrow pressed within those seconds went nowhere, and in-app navigation
-   * raised no warning about it. So a click on any link to another page of
-   * the app is held until the pending save has run, and the same click is
-   * then let through. A save the rules refuse holds the link and asks: stay
-   * and fix it, or leave without the unsaved changes (blockedLeave below).
+   * Leaving the page by a link saves first (useSaveBeforeLeaving). A save the
+   * rules refuse, such as a required custom field left empty, holds the link
+   * and asks: stay and fix it, or leave without the unsaved changes.
    */
-  const saveNowRef = useRef(saveNow)
-  saveNowRef.current = saveNow
-  const releasedLink = useRef<HTMLAnchorElement | null>(null)
-
   /**
-   * Why the latest save was refused, in words, so the way out can say it.
-   * Set by the save itself; cleared when a link starts a new attempt.
+   * Why the last save was refused, written by the save itself. The link
+   * guard reads it once the save has settled, and shows it in the dialog.
    */
   const lastSaveErrorRef = useRef<string | null>(null)
   /**
@@ -272,88 +263,22 @@ export function useServiceFormState({
    * dialog rather than a toast or an error box on top of it.
    */
   const leavingRef = useRef(false)
-  /**
-   * The link a refused save held back, and why it was refused.
-   *
-   * Holding the link used to be the end of it: a required custom field left
-   * empty refused every save, so a note typed on the job could neither be
-   * saved nor left behind, and every link on the page answered with the same
-   * error. The person now chooses: stay and fix it, or leave without the
-   * changes made since the last save.
-   */
-  const [blockedLeave, setBlockedLeave] = useState<{
-    anchor: HTMLAnchorElement
-    reason: string | null
-  } | null>(null)
-
-  const stayOnPage = useCallback(() => setBlockedLeave(null), [])
-
-  const leaveWithoutSaving = useCallback(() => {
-    if (!blockedLeave) return
-    if (autosaveTimer.current) {
-      clearTimeout(autosaveTimer.current)
-      autosaveTimer.current = null
-    }
-    hasUnsavedChangesRef.current = false
-    setHasUnsavedChanges(false)
-    setBlockedLeave(null)
-    const { anchor } = blockedLeave
-    if (!anchor.isConnected) {
-      // A link inside a menu that has since closed: go by its address.
-      window.location.assign(anchor.href)
-      return
-    }
-    releasedLink.current = anchor
-    anchor.click()
-  }, [blockedLeave])
-
-  useEffect(() => {
-    if (!hasUnsavedChanges) return
-    const handler = (event: MouseEvent) => {
-      if (event.defaultPrevented || event.button !== 0) return
-      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
-      const anchor = (event.target as Element | null)?.closest?.('a[href]')
-      if (!(anchor instanceof HTMLAnchorElement)) return
-      // The click this handler released after saving: let it through.
-      if (releasedLink.current === anchor) {
-        releasedLink.current = null
-        return
+  const { blockedLeave, stayOnPage, leaveWithoutSaving } = useSaveBeforeLeaving({
+    active: hasUnsavedChanges,
+    isDirty: () => hasUnsavedChangesRef.current,
+    isSaving: () => isSavingRef.current,
+    save: saveNow,
+    lastErrorRef: lastSaveErrorRef,
+    leavingRef,
+    discard: () => {
+      if (autosaveTimer.current) {
+        clearTimeout(autosaveTimer.current)
+        autosaveTimer.current = null
       }
-      if (anchor.target && anchor.target !== '_self') return
-      if (anchor.hasAttribute('download')) return
-      const destination = new URL(anchor.href, window.location.href)
-      if (destination.origin !== window.location.origin) return
-      const here = `${window.location.pathname}${window.location.search}`
-      if (`${destination.pathname}${destination.search}` === here) return
-
-      event.preventDefault()
-      event.stopPropagation()
-      // One way out at a time: a second link clicked while the first waits
-      // would start its own wait, and both would navigate once the save landed.
-      if (leavingRef.current) return
-      leavingRef.current = true
-      lastSaveErrorRef.current = null
-      // An autosave already under way answers first; a second save would be
-      // turned away while it runs and read as a refusal.
-      const settled = new Promise<void>((resolve) => {
-        const check = () => (isSavingRef.current ? setTimeout(check, 50) : resolve())
-        check()
-      })
-      void settled
-        .then(() => (hasUnsavedChangesRef.current ? saveNowRef.current() : undefined))
-        .then(() => {
-          leavingRef.current = false
-          if (hasUnsavedChangesRef.current) {
-            setBlockedLeave({ anchor, reason: lastSaveErrorRef.current })
-            return
-          }
-          releasedLink.current = anchor
-          anchor.click()
-        })
-    }
-    document.addEventListener('click', handler, true)
-    return () => document.removeEventListener('click', handler, true)
-  }, [hasUnsavedChanges])
+      hasUnsavedChangesRef.current = false
+      setHasUnsavedChanges(false)
+    },
+  })
 
   // Custom fields save callback ref
   const customFieldsSaveRef = useRef<(() => Promise<{ valid: boolean }>) | null>(null)

+ 44 - 0
src/hooks/use-guarded-push.ts

@@ -0,0 +1,44 @@
+'use client'
+
+import { useRouter } from 'next/navigation'
+import { useCallback } from 'react'
+
+const MARK = 'data-guarded-link'
+
+/**
+ * `router.push` for navigation that does not start with a click on a link:
+ * a keyboard shortcut, a row in the search palette, a dialog that opens what
+ * it just made.
+ *
+ * It goes through a click on a real link rather than straight to the router.
+ * An editor with unsaved changes holds link clicks back until its save has
+ * run (`useSaveBeforeLeaving`), and a straight `router.push` would walk past
+ * that and drop the edit. With nothing unsaved the click arrives at once and
+ * this is `router.push`.
+ */
+export function useGuardedPush(): (href: string) => void {
+  const router = useRouter()
+  return useCallback(
+    (href: string) => {
+      // A link of its own for every attempt. A held attempt keeps its link
+      // and its address until the save has answered; a second attempt made
+      // meanwhile is turned away by the editor and must not change where the
+      // first one is going.
+      const link = document.createElement('a')
+      link.hidden = true
+      link.tabIndex = -1
+      link.setAttribute('aria-hidden', 'true')
+      link.setAttribute(MARK, '')
+      link.setAttribute('href', href)
+      link.addEventListener('click', (event) => {
+        event.preventDefault()
+        // Followed: this one and any attempt that was turned away are done.
+        for (const stale of document.querySelectorAll(`a[${MARK}]`)) stale.remove()
+        router.push(href)
+      })
+      document.body.appendChild(link)
+      link.click()
+    },
+    [router]
+  )
+}

+ 114 - 0
src/hooks/use-save-before-leaving.ts

@@ -0,0 +1,114 @@
+'use client'
+
+import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'
+
+/** The link a refused save held back, and why it was refused. */
+export type BlockedLeave = { anchor: HTMLAnchorElement; reason: string | null }
+
+type Options = {
+  /** There are edits on the page that no save has taken yet. */
+  active: boolean
+  /** Read at the moment of asking: still unsaved after the save ran. */
+  isDirty: () => boolean
+  isSaving: () => boolean
+  save: () => Promise<unknown>
+  /** Why the last save was refused, as the save said it. */
+  lastErrorRef: MutableRefObject<string | null>
+  /**
+   * True while a link waits on its save. The page reads it to keep a refusal
+   * out of a toast or an error box: it goes into the leave dialog instead.
+   */
+  leavingRef: MutableRefObject<boolean>
+  /** Drop the unsaved edits: stop the autosave and clear the unsaved mark. */
+  discard: () => void
+}
+
+/**
+ * Leaving an editor by a link saves first.
+ *
+ * An autosave waits a few seconds after the last edit, and the beforeunload
+ * warning only covers leaving the site: an edit followed at once by a click
+ * on the sidebar went nowhere, and in-app navigation raised no warning about
+ * it. So a click on any link to another page of the app is held until the
+ * pending save has run, and the same click is then let through. A save that
+ * fails holds the link and asks: stay and fix it, or leave without the
+ * unsaved changes.
+ *
+ * Navigation that is not a click on a link (a shortcut, the search palette,
+ * a dialog that opens what it made) goes through `useGuardedPush`, which
+ * clicks a link for it, so it is held the same way.
+ */
+export function useSaveBeforeLeaving(options: Options) {
+  const latest = useRef(options)
+  latest.current = options
+  const releasedLink = useRef<HTMLAnchorElement | null>(null)
+  const [blockedLeave, setBlockedLeave] = useState<BlockedLeave | null>(null)
+
+  const stayOnPage = useCallback(() => setBlockedLeave(null), [])
+
+  const leaveWithoutSaving = useCallback(() => {
+    if (!blockedLeave) return
+    latest.current.discard()
+    setBlockedLeave(null)
+    const { anchor } = blockedLeave
+    if (!anchor.isConnected) {
+      // A link inside a menu that has since closed: go by its address.
+      window.location.assign(anchor.href)
+      return
+    }
+    releasedLink.current = anchor
+    anchor.click()
+  }, [blockedLeave])
+
+  const { active } = options
+  useEffect(() => {
+    if (!active) return
+    const handler = (event: MouseEvent) => {
+      if (event.defaultPrevented || event.button !== 0) return
+      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
+      const anchor = (event.target as Element | null)?.closest?.('a[href]')
+      if (!(anchor instanceof HTMLAnchorElement)) return
+      // The click this handler released after saving: let it through.
+      if (releasedLink.current === anchor) {
+        releasedLink.current = null
+        return
+      }
+      if (anchor.target && anchor.target !== '_self') return
+      if (anchor.hasAttribute('download')) return
+      const destination = new URL(anchor.href, window.location.href)
+      if (destination.origin !== window.location.origin) return
+      const here = `${window.location.pathname}${window.location.search}`
+      if (`${destination.pathname}${destination.search}` === here) return
+
+      event.preventDefault()
+      event.stopPropagation()
+      const { leavingRef, lastErrorRef } = latest.current
+      // One way out at a time: a second link clicked while the first waits
+      // would start its own wait, and both would navigate once the save landed.
+      if (leavingRef.current) return
+      leavingRef.current = true
+      lastErrorRef.current = null
+      // An autosave already under way answers first; a second save would be
+      // turned away while it runs and read as a refusal.
+      const settled = new Promise<void>((resolve) => {
+        const check = () => (latest.current.isSaving() ? setTimeout(check, 50) : resolve())
+        check()
+      })
+      void settled
+        .then(() => (latest.current.isDirty() ? latest.current.save() : undefined))
+        .then(() => {
+          leavingRef.current = false
+          if (latest.current.isDirty()) {
+            setBlockedLeave({ anchor, reason: lastErrorRef.current })
+            return
+          }
+          releasedLink.current = anchor
+          anchor.click()
+        })
+    }
+    document.addEventListener('click', handler, true)
+    return () => document.removeEventListener('click', handler, true)
+  }, [active])
+
+  return { blockedLeave, stayOnPage, leaveWithoutSaving }
+}