Răsfoiți Sursa

Add an Alt+L shortcut for a new appointment (#631)

* Add an Alt+L shortcut for a new appointment

* Keep a key someone chose when a later default lands on it
Bernt Christian Egeland 8 ore în urmă
părinte
comite
c7cb00d54a

+ 1 - 0
messages/de/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Speichern",
       "sidebar": "Seitenleiste ein- oder ausblenden",
       "help": "Tastenkürzel anzeigen",
+      "newAppointment": "Neuer Termin",
       "newInspection": "Neue Inspektion",
       "calendar_day": "Tagesansicht",
       "calendar_week": "Wochenansicht",

+ 1 - 0
messages/en/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Save",
       "sidebar": "Show or hide the sidebar",
       "help": "Show keyboard shortcuts",
+      "newAppointment": "New appointment",
       "newInspection": "New inspection",
       "calendar_day": "Day view",
       "calendar_week": "Week view",

+ 1 - 0
messages/es/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Guardar",
       "sidebar": "Mostrar u ocultar la barra lateral",
       "help": "Mostrar atajos de teclado",
+      "newAppointment": "Nueva cita",
       "newInspection": "Nueva inspección",
       "calendar_day": "Vista de día",
       "calendar_week": "Vista de semana",

+ 1 - 0
messages/fr/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Enregistrer",
       "sidebar": "Afficher ou masquer la barre latérale",
       "help": "Afficher les raccourcis clavier",
+      "newAppointment": "Nouveau rendez-vous",
       "newInspection": "Nouvelle inspection",
       "calendar_day": "Vue jour",
       "calendar_week": "Vue semaine",

+ 1 - 0
messages/it/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Salva",
       "sidebar": "Mostra o nascondi la barra laterale",
       "help": "Mostra le scorciatoie da tastiera",
+      "newAppointment": "Nuovo appuntamento",
       "newInspection": "Nuova ispezione",
       "calendar_day": "Vista giorno",
       "calendar_week": "Vista settimana",

+ 1 - 0
messages/lt/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Išsaugoti",
       "sidebar": "Rodyti arba slėpti šoninę juostą",
       "help": "Rodyti sparčiuosius klavišus",
+      "newAppointment": "Naujas vizitas",
       "newInspection": "Nauja apžiūra",
       "calendar_day": "Dienos rodinys",
       "calendar_week": "Savaitės rodinys",

+ 1 - 0
messages/nb/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Lagre",
       "sidebar": "Vis eller skjul sidemenyen",
       "help": "Vis hurtigtaster",
+      "newAppointment": "Ny timeavtale",
       "newInspection": "Ny inspeksjon",
       "calendar_day": "Dagsvisning",
       "calendar_week": "Ukevisning",

+ 1 - 0
messages/nl/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Opslaan",
       "sidebar": "Zijbalk tonen of verbergen",
       "help": "Sneltoetsen tonen",
+      "newAppointment": "Nieuwe afspraak",
       "newInspection": "Nieuwe inspectie",
       "calendar_day": "Dagweergave",
       "calendar_week": "Weekweergave",

+ 1 - 0
messages/pl/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Zapisz",
       "sidebar": "Pokaż lub ukryj pasek boczny",
       "help": "Pokaż skróty klawiszowe",
+      "newAppointment": "Nowa wizyta",
       "newInspection": "Nowa inspekcja",
       "calendar_day": "Widok dnia",
       "calendar_week": "Widok tygodnia",

+ 1 - 0
messages/pt-BR/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Salvar",
       "sidebar": "Mostrar ou ocultar a barra lateral",
       "help": "Mostrar atalhos de teclado",
+      "newAppointment": "Novo agendamento",
       "newInspection": "Nova inspeção",
       "calendar_day": "Visualização do dia",
       "calendar_week": "Visualização da semana",

+ 1 - 0
messages/pt-PT/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Guardar",
       "sidebar": "Mostrar ou ocultar a barra lateral",
       "help": "Mostrar atalhos de teclado",
+      "newAppointment": "Nova marcação",
       "newInspection": "Nova inspeção",
       "calendar_day": "Vista de dia",
       "calendar_week": "Vista de semana",

+ 1 - 0
messages/ru/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Сохранить",
       "sidebar": "Показать или скрыть боковую панель",
       "help": "Показать горячие клавиши",
+      "newAppointment": "Новая запись",
       "newInspection": "Новый осмотр",
       "calendar_day": "Просмотр дня",
       "calendar_week": "Просмотр недели",

+ 1 - 0
messages/tr/settings.json

@@ -1445,6 +1445,7 @@
       "save": "Kaydet",
       "sidebar": "Kenar çubuğunu göster veya gizle",
       "help": "Klavye kısayollarını göster",
+      "newAppointment": "Yeni randevu",
       "newInspection": "Yeni muayene",
       "calendar_day": "Gün görünümü",
       "calendar_week": "Hafta görünümü",

+ 57 - 7
src/__tests__/components/quick-create-menu.test.tsx

@@ -3,7 +3,7 @@
  * whoever may book, beside starting a work order.
  */
 
-import { fireEvent, render, screen } from '@testing-library/react'
+import { act, fireEvent, render, screen } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 const noop = () => undefined
@@ -49,13 +49,25 @@ vi.mock('@/features/shortcuts/Actions/saveKeyboardShortcuts', () => ({
 
 import { BOOKING_EVENT, BookingAccessProvider } from '@/components/booking-launcher'
 import { QuickCreateMenu } from '@/components/quick-create-menu'
+import { ShortcutsProvider } from '@/features/shortcuts/Components/ShortcutsProvider'
 
-function openMenu(canBook: boolean) {
+function renderMenu(canBook: boolean, prefs: unknown = null) {
   render(
-    <BookingAccessProvider value={{ canBook, canAddCustomer: true }}>
-      <QuickCreateMenu />
-    </BookingAccessProvider>
+    <ShortcutsProvider
+      initialPrefs={prefs}
+      commands={{ isAdminOrOwner: true }}
+      plateLookupAvailable={false}
+      bookingAvailable={canBook}
+    >
+      <BookingAccessProvider value={{ canBook, canAddCustomer: true }}>
+        <QuickCreateMenu />
+      </BookingAccessProvider>
+    </ShortcutsProvider>
   )
+}
+
+function openMenu(canBook: boolean, prefs: unknown = null) {
+  renderMenu(canBook, prefs)
   fireEvent.keyDown(screen.getByRole('button', { name: 'Quick Add' }), { key: 'Enter' })
 }
 
@@ -68,7 +80,7 @@ describe('QuickCreateMenu', () => {
     openMenu(true)
     const booked = vi.fn()
     document.addEventListener(BOOKING_EVENT, booked)
-    fireEvent.click(await screen.findByRole('menuitem', { name: 'Appointment' }))
+    fireEvent.click(await screen.findByRole('menuitem', { name: /Appointment/ }))
     document.removeEventListener(BOOKING_EVENT, booked)
     expect(booked).toHaveBeenCalledTimes(1)
     expect((booked.mock.calls[0][0] as CustomEvent).detail).toEqual({})
@@ -77,6 +89,44 @@ describe('QuickCreateMenu', () => {
   it('offers no appointment to someone who may not book', async () => {
     openMenu(false)
     expect(await screen.findByRole('menuitem', { name: /Work Order/ })).toBeInTheDocument()
-    expect(screen.queryByRole('menuitem', { name: 'Appointment' })).not.toBeInTheDocument()
+    expect(screen.queryByRole('menuitem', { name: /Appointment/ })).not.toBeInTheDocument()
+  })
+
+  it('shows Alt+L beside "Appointment", like the other rows show theirs', async () => {
+    openMenu(true)
+    const row = await screen.findByRole('menuitem', { name: /Appointment/ })
+    expect(row).toHaveTextContent('AltL')
+  })
+
+  it('shows the key a person chose instead', async () => {
+    openMenu(true, { overrides: { 'create.appointment': 'alt+z' } })
+    const row = await screen.findByRole('menuitem', { name: /Appointment/ })
+    expect(row).toHaveTextContent('AltZ')
+  })
+
+  it('opens a booking on Alt+L from anywhere, without opening the menu', () => {
+    renderMenu(true)
+    const booked = vi.fn()
+    document.addEventListener(BOOKING_EVENT, booked)
+    act(() => {
+      document.body.dispatchEvent(
+        new KeyboardEvent('keydown', { key: 'l', altKey: true, bubbles: true, cancelable: true })
+      )
+    })
+    document.removeEventListener(BOOKING_EVENT, booked)
+    expect(booked).toHaveBeenCalledTimes(1)
+  })
+
+  it('does not book on Alt+L for someone who may not book', () => {
+    renderMenu(false)
+    const booked = vi.fn()
+    document.addEventListener(BOOKING_EVENT, booked)
+    act(() => {
+      document.body.dispatchEvent(
+        new KeyboardEvent('keydown', { key: 'l', altKey: true, bubbles: true, cancelable: true })
+      )
+    })
+    document.removeEventListener(BOOKING_EVENT, booked)
+    expect(booked).not.toHaveBeenCalled()
   })
 })

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

@@ -98,6 +98,7 @@ function renderPage() {
       initialPrefs={null}
       commands={{ isAdminOrOwner: true }}
       plateLookupAvailable={false}
+      bookingAvailable
     >
       <QuotePage />
     </ShortcutsProvider>

+ 16 - 0
src/__tests__/features/shortcuts/preferences.test.ts

@@ -327,6 +327,22 @@ describe('changing a key', () => {
     expect(assignedKeys(def('calendar.next'), prefs)).toEqual(['n'])
   })
 
+  it('keeps a key someone chose before a later default claimed it', () => {
+    // Alt+L was free for anyone to take until New appointment shipped on it.
+    const prefs = normalizeShortcutPrefs({ overrides: { 'goTo.calendar': 'alt+l' } })
+    expect(match('alt+l', { prefs })).toBe('goTo.calendar')
+    expect(assignedKeys(def('create.appointment'), prefs)).toEqual([])
+    expect(findClash(def('create.quote'), 'alt+l', prefs)?.id).toBe('goTo.calendar')
+    // Everyone else still gets the new default.
+    expect(match('alt+l')).toBe('create.appointment')
+  })
+
+  it('gives the default back once the person moves their own key elsewhere', () => {
+    const chosen = normalizeShortcutPrefs({ overrides: { 'goTo.calendar': 'alt+l' } })
+    const moved = assignKey(def('goTo.calendar'), 'alt+z', chosen)
+    expect(match('alt+l', { prefs: moved })).toBe('create.appointment')
+  })
+
   it('goes back to the shipped key on reset', () => {
     const changed = assignKey(def('create.workOrder'), 'alt+n', DEFAULT_SHORTCUT_PREFS)
     const prefs = resetKey(def('create.workOrder'), changed)

+ 38 - 1
src/__tests__/features/shortcuts/shortcuts-provider.test.tsx

@@ -27,15 +27,22 @@ function Calendar({ onWeek }: { onWeek: () => void }) {
 function App({
   prefs = null,
   commands = everyone,
+  bookingAvailable = true,
   children,
 }: {
   prefs?: unknown
+  bookingAvailable?: boolean
   commands?: Parameters<typeof ShortcutsProvider>[0]['commands']
   children?: React.ReactNode
 }) {
   return (
     <ConfirmProvider>
-      <ShortcutsProvider initialPrefs={prefs} commands={commands} plateLookupAvailable={false}>
+      <ShortcutsProvider
+        initialPrefs={prefs}
+        commands={commands}
+        plateLookupAvailable={false}
+        bookingAvailable={bookingAvailable}
+      >
         {children}
       </ShortcutsProvider>
     </ConfirmProvider>
@@ -323,6 +330,36 @@ describe('the Keyboard shortcuts settings page', () => {
     }
   })
 
+  it('lists New appointment on Alt+L with the other things to create, and lets it be changed', async () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    expect(row('New appointment')).toHaveTextContent('AltL')
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New appointment' }))
+    const recorder = screen.getByRole('button', {
+      name: /Recording a new shortcut for New appointment/,
+    })
+    fireEvent.keyDown(recorder, { key: 'z', altKey: true })
+    expect(row('New appointment')).toHaveTextContent('AltZ')
+    await waitFor(() =>
+      expect(save).toHaveBeenCalledWith(
+        expect.objectContaining({ overrides: { 'create.appointment': 'alt+z' } })
+      )
+    )
+  })
+
+  it('lists no New appointment for someone who may not book', () => {
+    render(
+      <App bookingAvailable={false}>
+        <ShortcutsSettings />
+      </App>
+    )
+    expect(screen.getByText('New work order')).toBeInTheDocument()
+    expect(screen.queryByText('New appointment')).toBeNull()
+  })
+
   it('records a new key, shows it and saves it', async () => {
     render(
       <App>

+ 1 - 0
src/__tests__/features/shortcuts/typing-safety.test.tsx

@@ -100,6 +100,7 @@ function App({ children }: { children?: React.ReactNode }) {
       initialPrefs={{ goToSequences: true }}
       commands={{ isAdminOrOwner: true }}
       plateLookupAvailable={false}
+      bookingAvailable
     >
       <CalendarKeys />
       {children}

+ 1 - 0
src/app/(authenticated)/layout.tsx

@@ -370,6 +370,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
                 <ShortcutsProvider
                   initialPrefs={data.keyboardShortcuts}
                   plateLookupAvailable={plateLookupAvailable}
+                  bookingAvailable={canBook}
                   commands={{
                     visibleSubjects,
                     features,

+ 2 - 0
src/components/quick-create-menu.tsx

@@ -76,6 +76,7 @@ export function QuickCreateMenu() {
   // page, which the shortcut registry does on its own.
   useShortcut('create.workOrder', handleNewWorkOrder)
   useShortcut('create.inspection', () => void handleNewInspection())
+  useShortcut('create.appointment', () => openBooking(), canBook)
 
   return (
     <>
@@ -103,6 +104,7 @@ export function QuickCreateMenu() {
             <DropdownMenuItem onSelect={() => openBooking()}>
               <CalendarPlus className="h-4 w-4" />
               {t('quickCreate.appointment')}
+              <ShortcutKeys id="create.appointment" className="ml-auto" />
             </DropdownMenuItem>
           )}
           <DropdownMenuItem onSelect={() => go('/customers?create=true')}>

+ 5 - 1
src/features/shortcuts/Components/ShortcutsProvider.tsx

@@ -106,6 +106,7 @@ export function ShortcutsProvider({
   initialPrefs,
   commands,
   plateLookupAvailable,
+  bookingAvailable,
   children,
 }: {
   /** User.keyboardShortcuts as stored. */
@@ -113,6 +114,8 @@ export function ShortcutsProvider({
   /** What the search palette is told about this person, for the same reason. */
   commands: CommandContext
   plateLookupAvailable: boolean
+  /** May book an appointment: the + menu offers one, so the shortcut does too. */
+  bookingAvailable: boolean
   children: ReactNode
 }) {
   const go = useGuardedPush()
@@ -143,11 +146,12 @@ export function ShortcutsProvider({
   const isVisible = useCallback(
     (def: ShortcutDef) => {
       if (def.id === 'general.plateLookup') return plateLookupAvailable
+      if (def.id === 'create.appointment') return bookingAvailable
       if (def.command) return visibleCommands.has(def.command)
       if (def.subject) return canAccessSubject(commands, def.subject)
       return true
     },
-    [visibleCommands, commands, plateLookupAvailable]
+    [visibleCommands, commands, plateLookupAvailable, bookingAvailable]
   )
 
   const canCustomize = canAccessSubject(commands, 'settings')

+ 10 - 1
src/features/shortcuts/Lib/preferences.ts

@@ -103,10 +103,19 @@ export function isDefaultShortcutPrefs(prefs: ShortcutPrefs): boolean {
 /** The keys a person may change: their own, or the ones it shipped with. */
 export function assignedKeys(def: ShortcutDef, prefs: ShortcutPrefs): Combo[] {
   const override = prefs.overrides[def.id]
-  if (override === undefined) return def.defaultKeys
+  if (override === undefined) {
+    // A key someone gave to another shortcut themselves stays theirs. A
+    // default added in a later release (Alt+L for a new appointment) must not
+    // take it back from them.
+    return def.defaultKeys.filter((combo) => !isChosenElsewhere(def, combo, prefs))
+  }
   return override ? [override] : []
 }
 
+function isChosenElsewhere(def: ShortcutDef, combo: Combo, prefs: ShortcutPrefs): boolean {
+  return Object.entries(prefs.overrides).some(([id, key]) => id !== def.id && key === combo)
+}
+
 export function isChanged(def: ShortcutDef, prefs: ShortcutPrefs): boolean {
   return prefs.overrides[def.id] !== undefined
 }

+ 10 - 0
src/features/shortcuts/Lib/registry.ts

@@ -163,6 +163,16 @@ export const SHORTCUTS: readonly ShortcutDef[] = [
     href: '/inventory?create=true',
     command: 'action:new-part',
   },
+  // Not A: Windows 11 keeps Alt+A for suggested actions. L is the calendar's
+  // letter in the go-to set, where the booking lands. The + menu opens the
+  // booking dialog on it, and only for someone who may book.
+  {
+    id: 'create.appointment',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+l'],
+    label: { from: 'shortcuts', key: 'newAppointment' },
+  },
   {
     id: 'create.inspection',
     group: 'create',