index-failed.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useReducer } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import useSWR from 'swr'
  6. import StatusWithAction from './status-with-action'
  7. import { getErrorDocs, retryErrorDocs } from '@/service/datasets'
  8. import type { IndexingStatusResponse } from '@/models/datasets'
  9. type Props = {
  10. datasetId: string
  11. }
  12. type IIndexState = {
  13. value: string
  14. }
  15. type ActionType = 'retry' | 'success' | 'error'
  16. type IAction = {
  17. type: ActionType
  18. }
  19. const indexStateReducer = (state: IIndexState, action: IAction) => {
  20. const actionMap = {
  21. retry: 'retry',
  22. success: 'success',
  23. error: 'error',
  24. }
  25. return {
  26. ...state,
  27. value: actionMap[action.type] || state.value,
  28. }
  29. }
  30. const RetryButton: FC<Props> = ({ datasetId }) => {
  31. const { t } = useTranslation()
  32. const [indexState, dispatch] = useReducer(indexStateReducer, { value: 'success' })
  33. const { data: errorDocs, isLoading } = useSWR({ datasetId }, getErrorDocs)
  34. const onRetryErrorDocs = async () => {
  35. dispatch({ type: 'retry' })
  36. const document_ids = errorDocs?.data.map((doc: IndexingStatusResponse) => doc.id) || []
  37. const res = await retryErrorDocs({ datasetId, document_ids })
  38. if (res.result === 'success')
  39. dispatch({ type: 'success' })
  40. else
  41. dispatch({ type: 'error' })
  42. }
  43. useEffect(() => {
  44. if (errorDocs?.total === 0)
  45. dispatch({ type: 'success' })
  46. else
  47. dispatch({ type: 'error' })
  48. }, [errorDocs?.total])
  49. if (isLoading || indexState.value === 'success')
  50. return null
  51. return (
  52. <StatusWithAction
  53. type='warning'
  54. description={`${errorDocs?.total} ${t('dataset.docsFailedNotice')}`}
  55. actionText={t('dataset.retry')}
  56. disabled={indexState.value === 'retry'}
  57. onAction={indexState.value === 'error' ? onRetryErrorDocs : () => { }}
  58. />
  59. )
  60. }
  61. export default RetryButton