You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useMemo, useState } from 'react'
  4. import { createContext, useContext, useContextSelector } from 'use-context-selector'
  5. import { useTranslation } from 'react-i18next'
  6. import { useRouter } from 'next/navigation'
  7. import { RiArrowLeftLine, RiLayoutLeft2Line, RiLayoutRight2Line } from '@remixicon/react'
  8. import { OperationAction, StatusItem } from '../list'
  9. import DocumentPicker from '../../common/document-picker'
  10. import Completed from './completed'
  11. import Embedding from './embedding'
  12. import Metadata from '@/app/components/datasets/metadata/metadata-document'
  13. import SegmentAdd, { ProcessStatus } from './segment-add'
  14. import BatchModal from './batch-modal'
  15. import style from './style.module.css'
  16. import cn from '@/utils/classnames'
  17. import Divider from '@/app/components/base/divider'
  18. import Loading from '@/app/components/base/loading'
  19. import { ToastContext } from '@/app/components/base/toast'
  20. import type { ChunkingMode, ParentMode, ProcessMode } from '@/models/datasets'
  21. import { useDatasetDetailContext } from '@/context/dataset-detail'
  22. import FloatRightContainer from '@/app/components/base/float-right-container'
  23. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  24. import { useCheckSegmentBatchImportProgress, useChildSegmentListKey, useSegmentBatchImport, useSegmentListKey } from '@/service/knowledge/use-segment'
  25. import { useDocumentDetail, useDocumentMetadata, useInvalidDocumentList } from '@/service/knowledge/use-document'
  26. import { useInvalid } from '@/service/use-base'
  27. type DocumentContextValue = {
  28. datasetId?: string
  29. documentId?: string
  30. docForm: string
  31. mode?: ProcessMode
  32. parentMode?: ParentMode
  33. }
  34. export const DocumentContext = createContext<DocumentContextValue>({ docForm: '' })
  35. export const useDocumentContext = (selector: (value: DocumentContextValue) => any) => {
  36. return useContextSelector(DocumentContext, selector)
  37. }
  38. type DocumentTitleProps = {
  39. datasetId: string
  40. extension?: string
  41. name?: string
  42. processMode?: ProcessMode
  43. parent_mode?: ParentMode
  44. iconCls?: string
  45. textCls?: string
  46. wrapperCls?: string
  47. }
  48. export const DocumentTitle: FC<DocumentTitleProps> = ({ datasetId, extension, name, processMode, parent_mode, wrapperCls }) => {
  49. const router = useRouter()
  50. return (
  51. <div className={cn('flex flex-1 items-center justify-start', wrapperCls)}>
  52. <DocumentPicker
  53. datasetId={datasetId}
  54. value={{
  55. name,
  56. extension,
  57. processMode,
  58. parentMode: parent_mode,
  59. }}
  60. onChange={(doc) => {
  61. router.push(`/datasets/${datasetId}/documents/${doc.id}`)
  62. }}
  63. />
  64. </div>
  65. )
  66. }
  67. type Props = {
  68. datasetId: string
  69. documentId: string
  70. }
  71. const DocumentDetail: FC<Props> = ({ datasetId, documentId }) => {
  72. const router = useRouter()
  73. const { t } = useTranslation()
  74. const media = useBreakpoints()
  75. const isMobile = media === MediaType.mobile
  76. const { notify } = useContext(ToastContext)
  77. const { dataset } = useDatasetDetailContext()
  78. const embeddingAvailable = !!dataset?.embedding_available
  79. const [showMetadata, setShowMetadata] = useState(!isMobile)
  80. const [newSegmentModalVisible, setNewSegmentModalVisible] = useState(false)
  81. const [batchModalVisible, setBatchModalVisible] = useState(false)
  82. const [importStatus, setImportStatus] = useState<ProcessStatus | string>()
  83. const showNewSegmentModal = () => setNewSegmentModalVisible(true)
  84. const showBatchModal = () => setBatchModalVisible(true)
  85. const hideBatchModal = () => setBatchModalVisible(false)
  86. const resetProcessStatus = () => setImportStatus('')
  87. const { mutateAsync: checkSegmentBatchImportProgress } = useCheckSegmentBatchImportProgress()
  88. const checkProcess = async (jobID: string) => {
  89. await checkSegmentBatchImportProgress({ jobID }, {
  90. onSuccess: (res) => {
  91. setImportStatus(res.job_status)
  92. if (res.job_status === ProcessStatus.WAITING || res.job_status === ProcessStatus.PROCESSING)
  93. setTimeout(() => checkProcess(res.job_id), 2500)
  94. if (res.job_status === ProcessStatus.ERROR)
  95. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}` })
  96. },
  97. onError: (e) => {
  98. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}${'message' in e ? `: ${e.message}` : ''}` })
  99. },
  100. })
  101. }
  102. const { mutateAsync: segmentBatchImport } = useSegmentBatchImport()
  103. const runBatch = async (csv: File) => {
  104. const formData = new FormData()
  105. formData.append('file', csv)
  106. await segmentBatchImport({
  107. url: `/datasets/${datasetId}/documents/${documentId}/segments/batch_import`,
  108. body: formData,
  109. }, {
  110. onSuccess: (res) => {
  111. setImportStatus(res.job_status)
  112. checkProcess(res.job_id)
  113. },
  114. onError: (e) => {
  115. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}${'message' in e ? `: ${e.message}` : ''}` })
  116. },
  117. })
  118. }
  119. const { data: documentDetail, error, refetch: detailMutate } = useDocumentDetail({
  120. datasetId,
  121. documentId,
  122. params: { metadata: 'without' },
  123. })
  124. const { data: documentMetadata } = useDocumentMetadata({
  125. datasetId,
  126. documentId,
  127. params: { metadata: 'only' },
  128. })
  129. const backToPrev = () => {
  130. router.push(`/datasets/${datasetId}/documents`)
  131. }
  132. const isDetailLoading = !documentDetail && !error
  133. const embedding = ['queuing', 'indexing', 'paused'].includes((documentDetail?.display_status || '').toLowerCase())
  134. const invalidChunkList = useInvalid(useSegmentListKey)
  135. const invalidChildChunkList = useInvalid(useChildSegmentListKey)
  136. const invalidDocumentList = useInvalidDocumentList(datasetId)
  137. const handleOperate = (operateName?: string) => {
  138. invalidDocumentList()
  139. if (operateName === 'delete') {
  140. backToPrev()
  141. }
  142. else {
  143. detailMutate()
  144. // If operation is not rename, refresh the chunk list after 5 seconds
  145. if (operateName) {
  146. setTimeout(() => {
  147. invalidChunkList()
  148. invalidChildChunkList()
  149. }, 5000)
  150. }
  151. }
  152. }
  153. const mode = useMemo(() => {
  154. return documentDetail?.document_process_rule?.mode
  155. }, [documentDetail?.document_process_rule])
  156. const parentMode = useMemo(() => {
  157. return documentDetail?.document_process_rule?.rules?.parent_mode
  158. }, [documentDetail?.document_process_rule])
  159. const isFullDocMode = useMemo(() => {
  160. return mode === 'hierarchical' && parentMode === 'full-doc'
  161. }, [mode, parentMode])
  162. return (
  163. <DocumentContext.Provider value={{
  164. datasetId,
  165. documentId,
  166. docForm: documentDetail?.doc_form || '',
  167. mode,
  168. parentMode,
  169. }}>
  170. <div className='flex h-full flex-col bg-background-default'>
  171. <div className='flex min-h-16 flex-wrap items-center justify-between border-b border-b-divider-subtle py-2.5 pl-3 pr-4'>
  172. <div onClick={backToPrev} className={'flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-full hover:bg-components-button-tertiary-bg'}>
  173. <RiArrowLeftLine className='h-4 w-4 text-components-button-ghost-text hover:text-text-tertiary' />
  174. </div>
  175. <DocumentTitle
  176. datasetId={datasetId}
  177. extension={documentDetail?.data_source_info?.upload_file?.extension}
  178. name={documentDetail?.name}
  179. wrapperCls='mr-2'
  180. parent_mode={parentMode}
  181. processMode={mode}
  182. />
  183. <div className='flex flex-wrap items-center'>
  184. {embeddingAvailable && documentDetail && !documentDetail.archived && !isFullDocMode && (
  185. <>
  186. <SegmentAdd
  187. importStatus={importStatus}
  188. clearProcessStatus={resetProcessStatus}
  189. showNewSegmentModal={showNewSegmentModal}
  190. showBatchModal={showBatchModal}
  191. embedding={embedding}
  192. />
  193. <Divider type='vertical' className='!mx-3 !h-[14px] !bg-divider-regular' />
  194. </>
  195. )}
  196. <StatusItem
  197. status={documentDetail?.display_status || 'available'}
  198. scene='detail'
  199. errorMessage={documentDetail?.error || ''}
  200. textCls='font-semibold text-xs uppercase'
  201. detail={{
  202. enabled: documentDetail?.enabled || false,
  203. archived: documentDetail?.archived || false,
  204. id: documentId,
  205. }}
  206. datasetId={datasetId}
  207. onUpdate={handleOperate}
  208. />
  209. <OperationAction
  210. scene='detail'
  211. embeddingAvailable={embeddingAvailable}
  212. detail={{
  213. name: documentDetail?.name || '',
  214. enabled: documentDetail?.enabled || false,
  215. archived: documentDetail?.archived || false,
  216. id: documentId,
  217. data_source_type: documentDetail?.data_source_type || '',
  218. doc_form: documentDetail?.doc_form || '',
  219. }}
  220. datasetId={datasetId}
  221. onUpdate={handleOperate}
  222. className='!w-[200px]'
  223. />
  224. <button
  225. className={style.layoutRightIcon}
  226. onClick={() => setShowMetadata(!showMetadata)}
  227. >
  228. {
  229. showMetadata
  230. ? <RiLayoutLeft2Line className='h-4 w-4 text-components-button-secondary-text' />
  231. : <RiLayoutRight2Line className='h-4 w-4 text-components-button-secondary-text' />
  232. }
  233. </button>
  234. </div>
  235. </div>
  236. <div className='flex flex-1 flex-row' style={{ height: 'calc(100% - 4rem)' }}>
  237. {isDetailLoading
  238. ? <Loading type='app' />
  239. : <div className={cn('flex h-full min-w-0 grow flex-col',
  240. embedding ? '' : isFullDocMode ? 'relative pl-11 pr-11 pt-4' : 'relative pl-5 pr-11 pt-3',
  241. )}>
  242. {embedding
  243. ? <Embedding
  244. detailUpdate={detailMutate}
  245. indexingType={dataset?.indexing_technique}
  246. retrievalMethod={dataset?.retrieval_model_dict?.search_method}
  247. />
  248. : <Completed
  249. embeddingAvailable={embeddingAvailable}
  250. showNewSegmentModal={newSegmentModalVisible}
  251. onNewSegmentModalChange={setNewSegmentModalVisible}
  252. importStatus={importStatus}
  253. archived={documentDetail?.archived}
  254. />
  255. }
  256. </div>
  257. }
  258. <FloatRightContainer showClose isOpen={showMetadata} onClose={() => setShowMetadata(false)} isMobile={isMobile} panelClassName='!justify-start' footer={null}>
  259. <Metadata
  260. className='mr-2 mt-3'
  261. datasetId={datasetId}
  262. documentId={documentId}
  263. docDetail={{ ...documentDetail, ...documentMetadata, doc_type: documentMetadata?.doc_type === 'others' ? '' : documentMetadata?.doc_type } as any}
  264. />
  265. </FloatRightContainer>
  266. </div>
  267. <BatchModal
  268. isShow={batchModalVisible}
  269. onCancel={hideBatchModal}
  270. onConfirm={runBatch}
  271. docForm={documentDetail?.doc_form as ChunkingMode}
  272. />
  273. </div>
  274. </DocumentContext.Provider>
  275. )
  276. }
  277. export default DocumentDetail