list.tsx 33 KB

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