list.tsx 32 KB

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