All files / src/hooks useDownloadTicket.ts

100% Statements 37/37
100% Branches 8/8
100% Functions 3/3
100% Lines 36/36

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                10x 10x 10x 10x   10x 6x 1x 1x   5x 5x 1x 1x   4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x   3x 3x 3x 3x 1x 1x 2x 1x 1x   3x   4x       10x    
import { useAuthStore } from '../stores/useAuthStore'
import { getUserTicketPdf } from '../services/billingService'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useCustomSnackbar } from '../hooks/useCustomSnackbar'
import { logError } from '../utils/logger'
 
export function useDownloadTicket() {
  const token = useAuthStore(s => s.authToken)
  const { t } = useTranslation('tickets')
  const { notify } = useCustomSnackbar()
  const [downloading, setDownloading] = useState(false)
 
  const download = async (rawPdfFilename: string) => {
    if (!token) {
      notify(t('errors.not_authenticated'), 'warning')
      return
    }
    const filename = rawPdfFilename.replace(/^.*[\\/]/, '')
    if (!filename) {
      notify(t('errors.download_failed'), 'error')
      return
    }
    setDownloading(true)
    try {
      const blob = await getUserTicketPdf(filename, token)
      const blobUrl = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = blobUrl
      a.download = filename
      document.body.appendChild(a)
      a.click()
      a.remove()
      window.URL.revokeObjectURL(blobUrl)
      notify(t('tickets.download_success'), 'success')
    } catch (err: any) {
      logError('useDownloadTicket', err)
      let msg = t('errors.download_failed')
      let severity: 'error' | 'warning' = 'error'
      if (err.response?.status === 404) {
        msg = t('errors.not_found')
        severity = 'warning'
      } else if (err.response?.status === 401) {
        msg = t('errors.unauthorized')
        severity = 'warning'
      }
      notify(msg, severity)
    } finally {
      setDownloading(false)
    }
  }
 
  return { download, downloading }
}