list.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useCallback, useEffect, useMemo, useState } from 'react'
  4. import { useBoolean, useDebounceFn } from 'ahooks'
  5. import { ArrowDownIcon } from '@heroicons/react/24/outline'
  6. import { pick, uniq } from 'lodash-es'
  7. import {
  8. RiArchive2Line,
  9. RiDeleteBinLine,
  10. RiEditLine,
  11. RiEqualizer2Line,
  12. RiLoopLeftLine,
  13. RiMoreFill,
  14. } from '@remixicon/react'
  15. import { useContext } from 'use-context-selector'
  16. import { useRouter } from 'next/navigation'
  17. import { useTranslation } from 'react-i18next'
  18. import dayjs from 'dayjs'
  19. import { Globe01 } from '../../base/icons/src/vender/line/mapsAndTravel'
  20. import ChunkingModeLabel from '../common/chunking-mode-label'
  21. import FileTypeIcon from '../../base/file-uploader/file-type-icon'
  22. import s from './style.module.css'
  23. import RenameModal from './rename-modal'
  24. import BatchAction from './detail/completed/common/batch-action'
  25. import cn from '@/utils/classnames'
  26. import Switch from '@/app/components/base/switch'
  27. import Divider from '@/app/components/base/divider'
  28. import Popover from '@/app/components/base/popover'
  29. import Confirm from '@/app/components/base/confirm'
  30. import Tooltip from '@/app/components/base/tooltip'
  31. import Toast, { ToastContext } from '@/app/components/base/toast'
  32. import type { ColorMap, IndicatorProps } from '@/app/components/header/indicator'
  33. import Indicator from '@/app/components/header/indicator'
  34. import { asyncRunSafe } from '@/utils'
  35. import { formatNumber } from '@/utils/format'
  36. import NotionIcon from '@/app/components/base/notion-icon'
  37. import ProgressBar from '@/app/components/base/progress-bar'
  38. import { ChunkingMode, DataSourceType, DocumentActionType, type DocumentDisplayStatus, type SimpleDocumentDetail } from '@/models/datasets'
  39. import type { CommonResponse } from '@/models/common'
  40. import useTimestamp from '@/hooks/use-timestamp'
  41. import { useDatasetDetailContextWithSelector as useDatasetDetailContext } from '@/context/dataset-detail'
  42. import type { Props as PaginationProps } from '@/app/components/base/pagination'
  43. import Pagination from '@/app/components/base/pagination'
  44. import Checkbox from '@/app/components/base/checkbox'
  45. import {
  46. useDocumentArchive,
  47. useDocumentCheckFail,
  48. useDocumentDelete,
  49. useDocumentDisable,
  50. useDocumentEnable,
  51. useDocumentUnArchive,
  52. useSyncDocument,
  53. useSyncWebsite,
  54. } from '@/service/knowledge/use-document'
  55. import { extensionToFileType } from '@/app/components/datasets/hit-testing/utils/extension-to-file-type'
  56. import useBatchEditDocumentMetadata from '../metadata/hooks/use-batch-edit-document-metadata'
  57. import EditMetadataBatchModal from '@/app/components/datasets/metadata/edit-metadata-batch/modal'
  58. import { useAppContext } from '@/context/app-context'
  59. export const useIndexStatus = () => {
  60. const { t } = useTranslation()
  61. return {
  62. queuing: { color: 'orange', text: t('datasetDocuments.list.status.queuing') }, // waiting
  63. indexing: { color: 'blue', text: t('datasetDocuments.list.status.indexing') }, // indexing splitting parsing cleaning
  64. paused: { color: 'orange', text: t('datasetDocuments.list.status.paused') }, // paused
  65. error: { color: 'red', text: t('datasetDocuments.list.status.error') }, // error
  66. available: { color: 'green', text: t('datasetDocuments.list.status.available') }, // completed,archived = false,enabled = true
  67. enabled: { color: 'green', text: t('datasetDocuments.list.status.enabled') }, // completed,archived = false,enabled = true
  68. disabled: { color: 'gray', text: t('datasetDocuments.list.status.disabled') }, // completed,archived = false,enabled = false
  69. archived: { color: 'gray', text: t('datasetDocuments.list.status.archived') }, // completed,archived = true
  70. }
  71. }
  72. const STATUS_TEXT_COLOR_MAP: ColorMap = {
  73. green: 'text-util-colors-green-green-600',
  74. orange: 'text-util-colors-warning-warning-600',
  75. red: 'text-util-colors-red-red-600',
  76. blue: 'text-util-colors-blue-light-blue-light-600',
  77. yellow: 'text-util-colors-warning-warning-600',
  78. gray: 'text-text-tertiary',
  79. }
  80. // status item for list
  81. export const StatusItem: FC<{
  82. status: DocumentDisplayStatus
  83. reverse?: boolean
  84. scene?: 'list' | 'detail'
  85. textCls?: string
  86. errorMessage?: string
  87. detail?: {
  88. enabled: boolean
  89. archived: boolean
  90. id: string
  91. }
  92. datasetId?: string
  93. onUpdate?: (operationName?: string) => void
  94. }> = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage, datasetId = '', detail, onUpdate }) => {
  95. const DOC_INDEX_STATUS_MAP = useIndexStatus()
  96. const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP
  97. const { enabled = false, archived = false, id = '' } = detail || {}
  98. const { notify } = useContext(ToastContext)
  99. const { t } = useTranslation()
  100. const { mutateAsync: enableDocument } = useDocumentEnable()
  101. const { mutateAsync: disableDocument } = useDocumentDisable()
  102. const { mutateAsync: deleteDocument } = useDocumentDelete()
  103. const onOperate = async (operationName: OperationName) => {
  104. let opApi = deleteDocument
  105. switch (operationName) {
  106. case 'enable':
  107. opApi = enableDocument
  108. break
  109. case 'disable':
  110. opApi = disableDocument
  111. break
  112. }
  113. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
  114. if (!e) {
  115. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  116. onUpdate?.()
  117. // onUpdate?.(operationName)
  118. }
  119. else { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  120. }
  121. const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {
  122. if (operationName === 'enable' && enabled)
  123. return
  124. if (operationName === 'disable' && !enabled)
  125. return
  126. onOperate(operationName)
  127. }, { wait: 500 })
  128. const embedding = useMemo(() => {
  129. return ['queuing', 'indexing', 'paused'].includes(localStatus)
  130. }, [localStatus])
  131. return <div className={
  132. cn('flex items-center',
  133. reverse ? 'flex-row-reverse' : '',
  134. scene === 'detail' ? s.statusItemDetail : '')
  135. }>
  136. <Indicator color={DOC_INDEX_STATUS_MAP[localStatus]?.color as IndicatorProps['color']} className={reverse ? 'ml-2' : 'mr-2'} />
  137. <span className={cn(`${STATUS_TEXT_COLOR_MAP[DOC_INDEX_STATUS_MAP[localStatus].color as keyof typeof STATUS_TEXT_COLOR_MAP]} text-sm`, textCls)}>
  138. {DOC_INDEX_STATUS_MAP[localStatus]?.text}
  139. </span>
  140. {
  141. errorMessage && (
  142. <Tooltip
  143. popupContent={
  144. <div className='max-w-[260px] break-all'>{errorMessage}</div>
  145. }
  146. triggerClassName='ml-1 w-4 h-4'
  147. />
  148. )
  149. }
  150. {
  151. scene === 'detail' && (
  152. <div className='ml-1.5 flex items-center justify-between'>
  153. <Tooltip
  154. popupContent={t('datasetDocuments.list.action.enableWarning')}
  155. popupClassName='text-text-secondary system-xs-medium'
  156. needsDelay
  157. disabled={!archived}
  158. >
  159. <Switch
  160. defaultValue={archived ? false : enabled}
  161. onChange={v => !archived && handleSwitch(v ? 'enable' : 'disable')}
  162. disabled={embedding || archived}
  163. size='md'
  164. />
  165. </Tooltip>
  166. </div>
  167. )
  168. }
  169. </div>
  170. }
  171. type OperationName = 'delete' | 'archive' | 'enable' | 'disable' | 'sync' | 'un_archive' | 'check_fail'
  172. // operation action for list and detail
  173. export const OperationAction: FC<{
  174. embeddingAvailable: boolean
  175. detail: {
  176. name: string
  177. enabled: boolean
  178. archived: boolean
  179. id: string
  180. data_source_type: string
  181. doc_form: string
  182. check_status: number
  183. }
  184. datasetId: string
  185. onUpdate: (operationName?: string) => void
  186. scene?: 'list' | 'detail'
  187. className?: string
  188. }> = ({ embeddingAvailable, datasetId, detail, onUpdate, scene = 'list', className = '' }) => {
  189. const { id, enabled = false, archived = false, data_source_type } = detail || {}
  190. const [showModal, setShowModal] = useState(false)
  191. const [deleting, setDeleting] = useState(false)
  192. const { notify } = useContext(ToastContext)
  193. const { t } = useTranslation()
  194. const router = useRouter()
  195. const { mutateAsync: archiveDocument } = useDocumentArchive()
  196. const { mutateAsync: unArchiveDocument } = useDocumentUnArchive()
  197. const { mutateAsync: enableDocument } = useDocumentEnable()
  198. const { mutateAsync: disableDocument } = useDocumentDisable()
  199. const { mutateAsync: deleteDocument } = useDocumentDelete()
  200. const { mutateAsync: syncDocument } = useSyncDocument()
  201. const { mutateAsync: syncWebsite } = useSyncWebsite()
  202. const isListScene = scene === 'list'
  203. const onOperate = async (operationName: OperationName) => {
  204. let opApi = deleteDocument
  205. switch (operationName) {
  206. case 'archive':
  207. opApi = archiveDocument
  208. break
  209. case 'un_archive':
  210. opApi = unArchiveDocument
  211. break
  212. case 'enable':
  213. opApi = enableDocument
  214. break
  215. case 'disable':
  216. opApi = disableDocument
  217. break
  218. case 'sync':
  219. if (data_source_type === 'notion_import')
  220. opApi = syncDocument
  221. else
  222. opApi = syncWebsite
  223. break
  224. default:
  225. opApi = deleteDocument
  226. setDeleting(true)
  227. break
  228. }
  229. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
  230. if (!e) {
  231. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  232. onUpdate(operationName)
  233. }
  234. else { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  235. if (operationName === 'delete')
  236. setDeleting(false)
  237. }
  238. const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {
  239. if (operationName === 'enable' && enabled)
  240. return
  241. if (operationName === 'disable' && !enabled)
  242. return
  243. onOperate(operationName)
  244. }, { wait: 500 })
  245. const [currDocument, setCurrDocument] = useState<{
  246. id: string
  247. name: string
  248. } | null>(null)
  249. const [isShowRenameModal, {
  250. setTrue: setShowRenameModalTrue,
  251. setFalse: setShowRenameModalFalse,
  252. }] = useBoolean(false)
  253. const handleShowRenameModal = useCallback((doc: {
  254. id: string
  255. name: string
  256. }) => {
  257. setCurrDocument(doc)
  258. setShowRenameModalTrue()
  259. }, [setShowRenameModalTrue])
  260. const handleRenamed = useCallback(() => {
  261. onUpdate()
  262. }, [onUpdate])
  263. const [showNotDelModal, setShowNotDelModal] = useState(false)
  264. const [showNotSwitchModal, setShowNotSwitchModal] = useState(false)
  265. const beforeDel = () => {
  266. if (!detail.enabled)
  267. setShowModal(true)
  268. else
  269. setShowNotDelModal(true)
  270. }
  271. const [showApplyExamine, setShowApplyExamine] = useState<boolean>(false)
  272. const appContext = useAppContext()
  273. const beforeHandleSwitch = () => {
  274. if (detail.check_status === 1) { // 待审核
  275. setShowNotSwitchModal(true)
  276. return false
  277. }
  278. if (!['owner', 'admin'].includes(appContext.currentWorkspace.role)) { // 提交审批
  279. setShowApplyExamine(true)
  280. return false
  281. }
  282. return true
  283. }
  284. const onApplyExamine = () => {
  285. handleSwitch(enabled ? 'disable' : 'enable')
  286. }
  287. return <div className='flex items-center' onClick={e => e.stopPropagation()}>
  288. {isListScene && !embeddingAvailable && (
  289. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  290. )}
  291. {isListScene && embeddingAvailable && (
  292. <>
  293. {archived
  294. ? <Tooltip
  295. popupContent={t('datasetDocuments.list.action.enableWarning')}
  296. popupClassName='!font-semibold'
  297. needsDelay
  298. >
  299. <div>
  300. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  301. </div>
  302. </Tooltip>
  303. : <Switch defaultValue={enabled} beforeChange={beforeHandleSwitch} onChange={v => handleSwitch(v ? 'enable' : 'disable')} size='md' />
  304. }
  305. <Divider className='!ml-4 !mr-2 !h-3' type='vertical' />
  306. </>
  307. )}
  308. {embeddingAvailable && (
  309. <>
  310. <Tooltip
  311. popupContent={t('datasetDocuments.list.action.settings')}
  312. popupClassName='text-text-secondary system-xs-medium'
  313. >
  314. <button
  315. className={cn('mr-2 cursor-pointer rounded-lg',
  316. !isListScene
  317. ? 'border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg p-2 shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover'
  318. : 'p-0.5 hover:bg-state-base-hover')}
  319. onClick={() => router.push(`/datasets/${datasetId}/documents/${detail.id}/settings`)}>
  320. <RiEqualizer2Line className='h-4 w-4 text-components-button-secondary-text' />
  321. </button>
  322. </Tooltip>
  323. <Popover
  324. htmlContent={
  325. <div className='w-full py-1'>
  326. {!archived && (
  327. <>
  328. <div className={s.actionItem} onClick={() => {
  329. handleShowRenameModal({
  330. id: detail.id,
  331. name: detail.name,
  332. })
  333. }}>
  334. <RiEditLine className='h-4 w-4 text-text-tertiary' />
  335. <span className={s.actionName}>{t('datasetDocuments.list.table.rename')}</span>
  336. </div>
  337. {['notion_import', DataSourceType.WEB].includes(data_source_type) && (
  338. <div className={s.actionItem} onClick={() => onOperate('sync')}>
  339. <RiLoopLeftLine className='h-4 w-4 text-text-tertiary' />
  340. <span className={s.actionName}>{t('datasetDocuments.list.action.sync')}</span>
  341. </div>
  342. )}
  343. <Divider className='my-1' />
  344. </>
  345. )}
  346. {!archived && <div className={s.actionItem} onClick={() => onOperate('archive')}>
  347. <RiArchive2Line className='h-4 w-4 text-text-tertiary' />
  348. <span className={s.actionName}>{t('datasetDocuments.list.action.archive')}</span>
  349. </div>}
  350. {archived && (
  351. <div className={s.actionItem} onClick={() => onOperate('un_archive')}>
  352. <RiArchive2Line className='h-4 w-4 text-text-tertiary' />
  353. <span className={s.actionName}>{t('datasetDocuments.list.action.unarchive')}</span>
  354. </div>
  355. )}
  356. <div className={cn(s.actionItem, s.deleteActionItem, 'group')} onClick={() => beforeDel()}>
  357. <RiDeleteBinLine className={'h-4 w-4 text-text-tertiary group-hover:text-text-destructive'} />
  358. <span className={cn(s.actionName, 'group-hover:text-text-destructive')}>{t('datasetDocuments.list.action.delete')}</span>
  359. </div>
  360. </div>
  361. }
  362. trigger='click'
  363. position='br'
  364. btnElement={
  365. <div className={cn(s.commonIcon)}>
  366. <RiMoreFill className='h-4 w-4 text-components-button-secondary-text' />
  367. </div>
  368. }
  369. btnClassName={open => cn(isListScene ? s.actionIconWrapperList : s.actionIconWrapperDetail, open ? '!hover:bg-state-base-hover !shadow-none' : '!bg-transparent')}
  370. popupClassName='!w-full'
  371. className={`!z-20 flex h-fit !w-[200px] justify-end ${className}`}
  372. />
  373. </>
  374. )}
  375. {showModal
  376. && <Confirm
  377. isShow={showModal}
  378. isLoading={deleting}
  379. isDisabled={deleting}
  380. title={t('datasetDocuments.list.delete.title')}
  381. content={t('datasetDocuments.list.delete.content')}
  382. confirmText={t('common.operation.sure')}
  383. onConfirm={() => onOperate('delete')}
  384. onCancel={() => setShowModal(false)}
  385. />
  386. }
  387. {showNotDelModal
  388. && <Confirm
  389. isShow={showNotDelModal}
  390. title="操作失败"
  391. content="请将该知识停用后再删除!"
  392. onConfirm={() => setShowNotDelModal(false)}
  393. onCancel={() => setShowNotDelModal(false)}
  394. showCancel={false}
  395. confirmText="好的"
  396. />
  397. }
  398. {showNotSwitchModal
  399. && <Confirm
  400. isShow={showNotSwitchModal}
  401. title="操作失败"
  402. content="该知识有待审核的操作,无法再进行上下线操作!"
  403. onConfirm={() => setShowNotSwitchModal(false)}
  404. onCancel={() => setShowNotSwitchModal(false)}
  405. showCancel={false}
  406. confirmText="好的"
  407. />
  408. }
  409. {showApplyExamine
  410. && <Confirm
  411. isShow={showApplyExamine}
  412. title={`${enabled ? '下线' : '上线'}审核确认`}
  413. content="该操作需要提交管理员审核后生效,请确认是否提交?"
  414. onConfirm={onApplyExamine}
  415. onCancel={() => setShowApplyExamine(false)}
  416. />
  417. }
  418. {isShowRenameModal && currDocument && (
  419. <RenameModal
  420. datasetId={datasetId}
  421. documentId={currDocument.id}
  422. name={currDocument.name}
  423. onClose={setShowRenameModalFalse}
  424. onSaved={handleRenamed}
  425. />
  426. )}
  427. </div>
  428. }
  429. export const renderTdValue = (value: string | number | null, isEmptyStyle = false) => {
  430. return (
  431. <div className={cn(isEmptyStyle ? 'text-text-tertiary' : 'text-text-secondary', s.tdValue)}>
  432. {value ?? '-'}
  433. </div>
  434. )
  435. }
  436. const renderCount = (count: number | undefined) => {
  437. if (!count)
  438. return renderTdValue(0, true)
  439. if (count < 1000)
  440. return count
  441. return `${formatNumber((count / 1000).toFixed(1))}k`
  442. }
  443. type LocalDoc = SimpleDocumentDetail & { percent?: number }
  444. type IDocumentListProps = {
  445. embeddingAvailable: boolean
  446. documents: LocalDoc[]
  447. selectedIds: string[]
  448. onSelectedIdChange: (selectedIds: string[]) => void
  449. datasetId: string
  450. pagination: PaginationProps
  451. onUpdate: () => void
  452. onManageMetadata: () => void,
  453. optionsExamineStatus: any[]
  454. }
  455. /**
  456. * Document list component including basic information
  457. */
  458. const DocumentList: FC<IDocumentListProps> = ({
  459. embeddingAvailable,
  460. documents = [],
  461. selectedIds,
  462. onSelectedIdChange,
  463. datasetId,
  464. pagination,
  465. onUpdate,
  466. onManageMetadata,
  467. optionsExamineStatus,
  468. }) => {
  469. const { t } = useTranslation()
  470. const { formatTime } = useTimestamp()
  471. const router = useRouter()
  472. const [datasetConfig] = useDatasetDetailContext(s => [s.dataset])
  473. const chunkingMode = datasetConfig?.doc_form
  474. const isGeneralMode = chunkingMode !== ChunkingMode.parentChild
  475. const isQAMode = chunkingMode === ChunkingMode.qa
  476. const [localDocs, setLocalDocs] = useState<LocalDoc[]>(documents)
  477. const [enableSort, setEnableSort] = useState(true)
  478. const {
  479. isShowEditModal,
  480. showEditModal,
  481. hideEditModal,
  482. originalList,
  483. handleSave,
  484. } = useBatchEditDocumentMetadata({
  485. datasetId,
  486. docList: documents.filter(item => selectedIds.includes(item.id)),
  487. onUpdate,
  488. })
  489. useEffect(() => {
  490. setLocalDocs(documents)
  491. }, [documents])
  492. const onClickSort = () => {
  493. setEnableSort(!enableSort)
  494. if (enableSort) {
  495. const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1)
  496. setLocalDocs(sortedDocs)
  497. }
  498. else {
  499. setLocalDocs(documents)
  500. }
  501. }
  502. const [currDocument, setCurrDocument] = useState<LocalDoc | null>(null)
  503. const [isShowRenameModal, {
  504. setTrue: setShowRenameModalTrue,
  505. setFalse: setShowRenameModalFalse,
  506. }] = useBoolean(false)
  507. const handleShowRenameModal = useCallback((doc: LocalDoc) => {
  508. setCurrDocument(doc)
  509. setShowRenameModalTrue()
  510. }, [setShowRenameModalTrue])
  511. const handleRenamed = useCallback(() => {
  512. onUpdate()
  513. }, [onUpdate])
  514. const isAllSelected = useMemo(() => {
  515. return localDocs.length > 0 && localDocs.every(doc => selectedIds.includes(doc.id))
  516. }, [localDocs, selectedIds])
  517. const isSomeSelected = useMemo(() => {
  518. return localDocs.some(doc => selectedIds.includes(doc.id))
  519. }, [localDocs, selectedIds])
  520. const onSelectedAll = useCallback(() => {
  521. if (isAllSelected)
  522. onSelectedIdChange([])
  523. else
  524. onSelectedIdChange(uniq([...selectedIds, ...localDocs.map(doc => doc.id)]))
  525. }, [isAllSelected, localDocs, onSelectedIdChange, selectedIds])
  526. const { mutateAsync: archiveDocument } = useDocumentArchive()
  527. const { mutateAsync: enableDocument } = useDocumentEnable()
  528. const { mutateAsync: disableDocument } = useDocumentDisable()
  529. const { mutateAsync: deleteDocument } = useDocumentDelete()
  530. const { mutateAsync: checkFailDocument } = useDocumentCheckFail()
  531. const handleAction = (actionName: DocumentActionType) => {
  532. return async () => {
  533. let opApi = deleteDocument
  534. switch (actionName) {
  535. case DocumentActionType.archive:
  536. opApi = archiveDocument
  537. break
  538. case DocumentActionType.enable:
  539. opApi = enableDocument
  540. break
  541. case DocumentActionType.disable:
  542. opApi = disableDocument
  543. break
  544. default:
  545. opApi = deleteDocument
  546. break
  547. }
  548. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentIds: selectedIds }) as Promise<CommonResponse>)
  549. if (!e) {
  550. Toast.notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  551. onUpdate()
  552. }
  553. else { Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  554. }
  555. }
  556. const ExamineMap = {
  557. 1: '待审核',
  558. 2: '审核不通过',
  559. 3: '无',
  560. }
  561. const appContext = useAppContext()
  562. const [row, setRow] = useState<any>({})
  563. const [showConfirmExamineResult, setShowConfirmExamineResult] = useState(false)
  564. const [confirmExamineResultContent, setConfirmExamineResultContent] = useState('')
  565. const [showConfirmExamineHandle, setShowConfirmExamineHandle] = useState(false)
  566. const [confirmExamineHandleTitle, setConfirmExamineHandleTitle] = useState('')
  567. const [confirmExamineHandleContent, setConfirmExamineHandleContent] = useState('')
  568. const { notify } = useContext(ToastContext)
  569. const onOperate = async (operationName: OperationName) => {
  570. let opApi = checkFailDocument
  571. switch (operationName) {
  572. case 'check_fail':
  573. opApi = checkFailDocument
  574. break
  575. case 'enable':
  576. opApi = enableDocument
  577. break
  578. case 'disable':
  579. opApi = disableDocument
  580. break
  581. }
  582. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: row.id }) as Promise<CommonResponse>)
  583. if (!e) {
  584. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  585. onUpdate()
  586. }
  587. else { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  588. onUpdate()
  589. setShowConfirmExamineHandle(false)
  590. }
  591. const onHandleExamine = (flag: boolean) => {
  592. if (flag)
  593. onOperate(row.enabled ? 'disable' : 'enable')
  594. else
  595. onOperate('check_fail')
  596. }
  597. return (
  598. <div className='relative flex h-full w-full flex-col'>
  599. <div className='relative grow overflow-x-auto'>
  600. <table className={`mt-3 w-full min-w-[700px] max-w-full border-collapse border-0 text-sm ${s.documentTable}`}>
  601. <thead className="h-8 border-b border-divider-subtle text-xs font-medium uppercase leading-8 text-text-tertiary">
  602. <tr>
  603. <td className='w-12'>
  604. <div className='flex items-center' onClick={e => e.stopPropagation()}>
  605. {embeddingAvailable && (
  606. <Checkbox
  607. className='mr-2 shrink-0'
  608. checked={isAllSelected}
  609. mixed={!isAllSelected && isSomeSelected}
  610. onCheck={onSelectedAll}
  611. />
  612. )}
  613. #
  614. </div>
  615. </td>
  616. <td>
  617. <div className='flex'>
  618. {t('datasetDocuments.list.table.header.fileName')}
  619. </div>
  620. </td>
  621. <td className='w-[130px]'>{t('datasetDocuments.list.table.header.chunkingMode')}</td>
  622. <td className='w-24'>{t('datasetDocuments.list.table.header.words')}</td>
  623. <td className='w-44'>{t('datasetDocuments.list.table.header.hitCount')}</td>
  624. <td className='w-44'>
  625. <div className='flex items-center' onClick={onClickSort}>
  626. {t('datasetDocuments.list.table.header.uploadTime')}
  627. <ArrowDownIcon className={cn('ml-0.5 h-3 w-3 cursor-pointer stroke-current stroke-2', enableSort ? 'text-text-tertiary' : 'text-text-disabled')} />
  628. </div>
  629. </td>
  630. <td className='w-40'>{t('datasetDocuments.list.table.header.status')}</td>
  631. <td className='w-40'>审核状态</td>
  632. <td className='w-20'>{t('datasetDocuments.list.table.header.action')}</td>
  633. </tr>
  634. </thead>
  635. <tbody className="text-text-secondary">
  636. {localDocs.map((doc, index) => {
  637. const isFile = doc.data_source_type === DataSourceType.FILE
  638. const fileType = isFile ? doc.data_source_detail_dict?.upload_file?.extension : ''
  639. return <tr
  640. key={doc.id}
  641. className={'h-8 cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover'}
  642. onClick={() => {
  643. (doc.check_status === 2 || doc.check_status === 3) && router.push(`/datasets/${datasetId}/documents/${doc.id}`)
  644. }}>
  645. <td className='text-left align-middle text-xs text-text-tertiary'>
  646. <div className='flex items-center' onClick={e => e.stopPropagation()}>
  647. <Checkbox
  648. className='mr-2 shrink-0'
  649. checked={selectedIds.includes(doc.id)}
  650. onCheck={() => {
  651. onSelectedIdChange(
  652. selectedIds.includes(doc.id)
  653. ? selectedIds.filter(id => id !== doc.id)
  654. : [...selectedIds, doc.id],
  655. )
  656. }}
  657. />
  658. {/* {doc.position} */}
  659. {index + 1}
  660. </div>
  661. </td>
  662. <td>
  663. <div className={'group mr-6 flex max-w-[460px] items-center hover:mr-0'}>
  664. <div className='shrink-0'>
  665. {doc?.data_source_type === DataSourceType.NOTION && <NotionIcon className='mr-1.5 mt-[-3px] inline-flex align-middle' type='page' src={doc.data_source_info.notion_page_icon} />}
  666. {doc?.data_source_type === DataSourceType.FILE && <FileTypeIcon type={extensionToFileType(doc?.data_source_info?.upload_file?.extension ?? fileType)} className='mr-1.5' />}
  667. {doc?.data_source_type === DataSourceType.WEB && <Globe01 className='mr-1.5 mt-[-3px] inline-flex align-middle' />}
  668. </div>
  669. <span className='grow-1 truncate text-sm'>{doc.name}</span>
  670. <div className='hidden shrink-0 group-hover:ml-auto group-hover:flex'>
  671. <Tooltip
  672. popupContent={t('datasetDocuments.list.table.rename')}
  673. >
  674. <div
  675. className='cursor-pointer rounded-md p-1 hover:bg-state-base-hover'
  676. onClick={(e) => {
  677. e.stopPropagation()
  678. handleShowRenameModal(doc)
  679. }}
  680. >
  681. <RiEditLine className='h-4 w-4 text-text-tertiary' />
  682. </div>
  683. </Tooltip>
  684. </div>
  685. </div>
  686. </td>
  687. <td>
  688. <ChunkingModeLabel
  689. isGeneralMode={isGeneralMode}
  690. isQAMode={isQAMode}
  691. />
  692. </td>
  693. <td>{renderCount(doc.word_count)}</td>
  694. <td>{renderCount(doc.hit_count)}</td>
  695. <td className='text-[13px] text-text-secondary'>
  696. {formatTime(doc.created_at, t('datasetHitTesting.dateTimeFormat') as string)}
  697. </td>
  698. <td>
  699. {
  700. (['indexing', 'splitting', 'parsing', 'cleaning'].includes(doc.indexing_status) && doc?.data_source_type === DataSourceType.NOTION)
  701. ? <ProgressBar percent={doc.percent || 0} />
  702. : <StatusItem status={doc.display_status} />
  703. }
  704. </td>
  705. <td>
  706. {
  707. doc.check_status === 1 && (
  708. ['owner', 'admin'].includes(appContext.currentWorkspace.role)
  709. ? <div className="cursor-pointer text-[#155aef]" onClick={(e) => {
  710. e.stopPropagation()
  711. setRow(doc)
  712. setConfirmExamineHandleTitle(`${doc.enabled ? '下线' : '上线'}审核`)
  713. setConfirmExamineHandleContent(`用户“${doc.enable_application}”申请将该知识${doc.enabled ? '下线' : '上线'},请审核!`)
  714. setShowConfirmExamineHandle(true)
  715. }}>{ExamineMap[doc.check_status]}</div>
  716. : <div>{ExamineMap[doc.check_status]}</div>
  717. )
  718. }
  719. {
  720. doc.check_status === 2 && (
  721. <div className="cursor text-[#155aef]" onClick={(e) => {
  722. e.stopPropagation()
  723. setConfirmExamineResultContent(`用户“${doc.check_by}”不同意将该知识上线!`)
  724. setShowConfirmExamineResult(true)
  725. }}>{ExamineMap[doc.check_status]}</div>
  726. )
  727. }
  728. {
  729. doc.check_status === 3 && (
  730. <div>{ExamineMap[doc.check_status]}</div>
  731. )
  732. }
  733. </td>
  734. <td>
  735. {
  736. (doc.check_status === 2 || doc.check_status === 3) && (<OperationAction
  737. embeddingAvailable={embeddingAvailable}
  738. datasetId={datasetId}
  739. detail={pick(doc, ['name', 'enabled', 'archived', 'id', 'data_source_type', 'doc_form', 'check_status'])}
  740. onUpdate={onUpdate}
  741. />)
  742. }
  743. </td>
  744. </tr>
  745. })}
  746. </tbody>
  747. </table>
  748. </div>
  749. {(selectedIds.length > 0) && (
  750. <BatchAction
  751. className='absolute bottom-16 left-0 z-20'
  752. selectedIds={selectedIds}
  753. onArchive={handleAction(DocumentActionType.archive)}
  754. onBatchEnable={handleAction(DocumentActionType.enable)}
  755. onBatchDisable={handleAction(DocumentActionType.disable)}
  756. onBatchDelete={handleAction(DocumentActionType.delete)}
  757. onEditMetadata={showEditModal}
  758. onCancel={() => {
  759. onSelectedIdChange([])
  760. }}
  761. />
  762. )}
  763. {/* Show Pagination only if the total is more than the limit */}
  764. {pagination.total && (
  765. <Pagination
  766. {...pagination}
  767. className='w-full shrink-0 px-0 pb-0'
  768. />
  769. )}
  770. {isShowRenameModal && currDocument && (
  771. <RenameModal
  772. datasetId={datasetId}
  773. documentId={currDocument.id}
  774. name={currDocument.name}
  775. onClose={setShowRenameModalFalse}
  776. onSaved={handleRenamed}
  777. />
  778. )}
  779. {isShowEditModal && (
  780. <EditMetadataBatchModal
  781. datasetId={datasetId}
  782. documentNum={selectedIds.length}
  783. list={originalList}
  784. onSave={handleSave}
  785. onHide={hideEditModal}
  786. onShowManage={() => {
  787. hideEditModal()
  788. onManageMetadata()
  789. }}
  790. />
  791. )}
  792. {showConfirmExamineResult && (
  793. <Confirm
  794. title="审核结果"
  795. content={confirmExamineResultContent}
  796. isShow={showConfirmExamineResult}
  797. onConfirm={() => setShowConfirmExamineResult(false)}
  798. onCancel={() => setShowConfirmExamineResult(false)}
  799. showCancel={false}
  800. confirmText="好的"
  801. />
  802. )}
  803. {showConfirmExamineHandle && (
  804. <Confirm
  805. title={confirmExamineHandleTitle}
  806. content={confirmExamineHandleContent}
  807. isShow={showConfirmExamineHandle}
  808. onConfirm={() => onHandleExamine(true)}
  809. onCancel={() => onHandleExamine(false)}
  810. confirmText="同意"
  811. cancelText="不同意"
  812. maskClosable={false}
  813. />
  814. )}
  815. </div>
  816. )
  817. }
  818. export default DocumentList