All files / src/hooks useDownloadInvoice.tsx

100% Statements 33/33
100% Branches 6/6
100% Functions 3/3
100% Lines 32/32

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                9x 9x 9x   9x   9x 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       9x    
import { useAuthStore } from '../stores/useAuthStore'
import { getUserInvoice } from '../services/billingService'
import { useState } from 'react'
import { useCustomSnackbar } from '../hooks/useCustomSnackbar'
import { useTranslation } from 'react-i18next'
import { logError } from '../utils/logger'
 
export function useDownloadInvoice() {
  const token = useAuthStore(s => s.authToken)
  const { t } = useTranslation('invoices')
  const { notify } = useCustomSnackbar()
 
  const [downloading, setDownloading] = useState(false)
 
  const download = async (invoice_link: string) => {
    if (!token) {
      notify(t('errors.not_authenticated'), 'warning')
      return
    }
    setDownloading(true)
 
    try {
      const blob = await getUserInvoice(invoice_link, token)
      // Créer un URL pour le blob et déclencher le téléchargement
      const blobUrl = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = blobUrl
      // Nom du fichier proposé : invoice_link ou autre nom
      a.download = invoice_link
      document.body.appendChild(a)
      a.click()
      a.remove()
      window.URL.revokeObjectURL(blobUrl)
      notify(t('card.download_success'), 'success')
    } catch (err: any) {
      logError('useDownloadInvoice', err)
      // On peut inspecter err.response?.status si c'est une erreur axios
      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 }
}