All files / web/src/hooks useAbacusPrintSettings.ts

0% Statements 0/71
0% Branches 0/1
0% Functions 0/1
0% Lines 0/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                                                                                                                                               
'use client'

import type { TicketStyle } from '@eink/print-dialog'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/lib/queryClient'
import { abacusPrintKeys } from '@/lib/queryKeys'

interface PrintSettingsResponse {
  style: TicketStyle | null
}

async function fetchPrintSettings(): Promise<TicketStyle | null> {
  const res = await api('abacus/print/settings')
  if (!res.ok) throw new Error('Failed to fetch print settings')
  const data: PrintSettingsResponse = await res.json()
  return data.style
}

async function savePrintSettings(style: TicketStyle): Promise<TicketStyle | null> {
  const res = await api('abacus/print/settings', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ style }),
  })
  if (!res.ok) throw new Error('Failed to save print settings')
  const data: PrintSettingsResponse = await res.json()
  return data.style
}

/**
 * Hook: the caller's saved print-settings overlay (TicketStyle), null when
 * they've never tuned one — the dialog then seeds from the printer's
 * capability doc as before.
 */
export function useAbacusPrintSettings(enabled = true) {
  return useQuery({
    queryKey: abacusPrintKeys.settings(),
    queryFn: fetchPrintSettings,
    enabled,
    // Changes only via the viewer's own saves (which set the cache directly)
    staleTime: 1000 * 60 * 30,
  })
}

/** Hook: save the print-settings overlay with optimistic update */
export function useSaveAbacusPrintSettings() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: savePrintSettings,
    onMutate: async (style) => {
      await queryClient.cancelQueries({ queryKey: abacusPrintKeys.settings() })

      const previous = queryClient.getQueryData<TicketStyle | null>(abacusPrintKeys.settings())

      queryClient.setQueryData(abacusPrintKeys.settings(), style)

      return { previous }
    },
    onError: (_err, _style, context) => {
      if (context?.previous !== undefined) {
        queryClient.setQueryData(abacusPrintKeys.settings(), context.previous)
      }
    },
    onSettled: (savedStyle) => {
      if (savedStyle) {
        queryClient.setQueryData(abacusPrintKeys.settings(), savedStyle)
      }
    },
  })
}