wwf
2025-05-20 938c3e5a587ce950a94964ea509b9e7f8834dfae
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
'use client'
import type { FC } from 'react'
import React, { useEffect, useReducer } from 'react'
import { useTranslation } from 'react-i18next'
import useSWR from 'swr'
import StatusWithAction from './status-with-action'
import { getErrorDocs, retryErrorDocs } from '@/service/datasets'
import type { IndexingStatusResponse } from '@/models/datasets'
import { noop } from 'lodash-es'
 
type Props = {
  datasetId: string
}
type IIndexState = {
  value: string
}
type ActionType = 'retry' | 'success' | 'error'
 
type IAction = {
  type: ActionType
}
const indexStateReducer = (state: IIndexState, action: IAction) => {
  const actionMap = {
    retry: 'retry',
    success: 'success',
    error: 'error',
  }
 
  return {
    ...state,
    value: actionMap[action.type] || state.value,
  }
}
 
const RetryButton: FC<Props> = ({ datasetId }) => {
  const { t } = useTranslation()
  const [indexState, dispatch] = useReducer(indexStateReducer, { value: 'success' })
  const { data: errorDocs, isLoading } = useSWR({ datasetId }, getErrorDocs)
 
  const onRetryErrorDocs = async () => {
    dispatch({ type: 'retry' })
    const document_ids = errorDocs?.data.map((doc: IndexingStatusResponse) => doc.id) || []
    const res = await retryErrorDocs({ datasetId, document_ids })
    if (res.result === 'success')
      dispatch({ type: 'success' })
    else
      dispatch({ type: 'error' })
  }
 
  useEffect(() => {
    if (errorDocs?.total === 0)
      dispatch({ type: 'success' })
    else
      dispatch({ type: 'error' })
  }, [errorDocs?.total])
 
  if (isLoading || indexState.value === 'success')
    return null
 
  return (
    <StatusWithAction
      type='warning'
      description={`${errorDocs?.total} ${t('dataset.docsFailedNotice')}`}
      actionText={t('dataset.retry')}
      disabled={indexState.value === 'retry'}
      onAction={indexState.value === 'error' ? onRetryErrorDocs : noop}
    />
  )
}
export default RetryButton