doc-panel.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import {
  2. apiInterceptors,
  3. delDocument,
  4. editChunk,
  5. getDocumentList,
  6. // getKnowledgeAdmins,
  7. searchDocumentList,
  8. syncDocument,
  9. } from '@/client/api';
  10. import { IDocument, ISpace } from '@/types/knowledge';
  11. import {
  12. DeleteOutlined,
  13. DeploymentUnitOutlined,
  14. EditOutlined,
  15. EllipsisOutlined,
  16. ExperimentOutlined,
  17. EyeOutlined,
  18. LoadingOutlined,
  19. MinusCircleOutlined,
  20. PlusOutlined,
  21. SearchOutlined,
  22. SyncOutlined,
  23. ToolFilled,
  24. WarningOutlined,
  25. } from '@ant-design/icons';
  26. import { useRequest } from 'ahooks';
  27. import { Button, Card, Divider, Dropdown, Empty, Form, Input, Modal, Space, Spin, Tag, Tooltip, message } from 'antd';
  28. import cls from 'classnames';
  29. import moment from 'moment';
  30. import { useRouter } from 'next/router';
  31. import React, { useEffect, useMemo, useRef, useState } from 'react';
  32. import { useTranslation } from 'react-i18next';
  33. import RecallTestModal from './RecallTestModal';
  34. import ArgumentsModal from './arguments-modal';
  35. import DocIcon from './doc-icon';
  36. interface IProps {
  37. space: ISpace;
  38. addStatus?: string;
  39. onAddDoc: (spaceName: string) => void;
  40. onDeleteDoc: () => void;
  41. }
  42. const { confirm } = Modal;
  43. const SyncContent: React.FC<{ name: string; id: number }> = ({ name, id }) => {
  44. const [syncLoading, setSyncLoading] = useState<boolean>(false);
  45. const { t } = useTranslation();
  46. const handleSync = async (spaceName: string, id: number) => {
  47. setSyncLoading(true);
  48. const res = await apiInterceptors(syncDocument(spaceName, { doc_ids: [id] }));
  49. setSyncLoading(false);
  50. if (res[2]?.success) {
  51. message.success(t('Synchronization_initiated'));
  52. }
  53. };
  54. if (syncLoading) {
  55. return <Spin indicator={<LoadingOutlined spin />} />;
  56. }
  57. return (
  58. <Space
  59. onClick={() => {
  60. handleSync(name, id);
  61. }}
  62. >
  63. <SyncOutlined />
  64. <span>{t('Sync')}</span>
  65. </Space>
  66. );
  67. };
  68. export default function DocPanel(props: IProps) {
  69. const [form] = Form.useForm();
  70. const { space, addStatus } = props;
  71. const { t } = useTranslation();
  72. const router = useRouter();
  73. const page_size = 18;
  74. // const [_, setAdmins] = useState<string[]>([]);
  75. const [documents, setDocuments] = useState<any>([]);
  76. const [searchDocuments, setSearchDocuments] = useState<any>([]);
  77. const [argumentsShow, setArgumentsShow] = useState<boolean>(false);
  78. const [total, setTotal] = useState<number>(0);
  79. const [editOpen, setEditOpen] = useState<boolean>(false);
  80. const [curDoc, setCurDoc] = useState<IDocument>();
  81. // 召回测试弹窗
  82. const [recallTestOpen, setRecallTestOpen] = useState<boolean>(false);
  83. const currentPageRef = useRef(1);
  84. const hasMore = useMemo(() => {
  85. return documents?.length < total;
  86. }, [documents, total]);
  87. const showDeleteConfirm = (row: any) => {
  88. confirm({
  89. title: t('Tips'),
  90. icon: <WarningOutlined />,
  91. content: `${t('Del_Document_Tips')}?`,
  92. okText: 'Yes',
  93. okType: 'danger',
  94. cancelText: 'No',
  95. async onOk() {
  96. await handleDelete(row);
  97. },
  98. });
  99. };
  100. const {
  101. run: fetchDocuments,
  102. refresh,
  103. loading: isLoading,
  104. } = useRequest(
  105. async () =>
  106. await apiInterceptors(
  107. getDocumentList(space.name, {
  108. page: currentPageRef.current,
  109. page_size,
  110. }),
  111. ),
  112. {
  113. manual: true,
  114. onSuccess: res => {
  115. const [, data] = res;
  116. setDocuments(data?.data);
  117. setSearchDocuments(data?.data);
  118. setTotal(data?.total || 0);
  119. },
  120. },
  121. );
  122. const loadMoreDocuments = async () => {
  123. if (!hasMore) {
  124. return;
  125. }
  126. currentPageRef.current += 1;
  127. const [_, data] = await apiInterceptors(
  128. getDocumentList(space.name, {
  129. page: currentPageRef.current,
  130. page_size,
  131. }),
  132. );
  133. setDocuments([...documents, ...data!.data]);
  134. setSearchDocuments([...documents, ...data!.data]);
  135. };
  136. const handleDelete = async (row: any) => {
  137. await apiInterceptors(delDocument(space.name, { doc_name: row.doc_name }));
  138. fetchDocuments();
  139. props.onDeleteDoc();
  140. };
  141. const handleAddDocument = () => {
  142. props.onAddDoc(space.name);
  143. };
  144. const handleArguments = () => {
  145. setArgumentsShow(true);
  146. };
  147. const openGraphVisualPage = () => {
  148. router.push(`/knowledge/graph/?spaceName=${space.name}`);
  149. };
  150. const renderResultTag = (status: string, result: string) => {
  151. let color;
  152. switch (status) {
  153. case 'TODO':
  154. color = 'gold';
  155. break;
  156. case 'RUNNING':
  157. color = '#2db7f5';
  158. break;
  159. case 'FINISHED':
  160. color = 'cyan';
  161. break;
  162. case 'FAILED':
  163. color = 'red';
  164. break;
  165. default:
  166. color = 'red';
  167. break;
  168. }
  169. return (
  170. <Tooltip title={result}>
  171. <Tag color={color}>{status}</Tag>
  172. </Tooltip>
  173. );
  174. };
  175. useEffect(() => {
  176. fetchDocuments();
  177. // getAdmins();
  178. // eslint-disable-next-line react-hooks/exhaustive-deps
  179. }, []);
  180. useEffect(() => {
  181. if (addStatus === 'finish') {
  182. fetchDocuments();
  183. }
  184. // eslint-disable-next-line react-hooks/exhaustive-deps
  185. }, [addStatus]);
  186. // const updateAdmins = useCallback(
  187. // async (options: string[]) => {
  188. // const { data } = await updateKnowledgeAdmins({
  189. // space_id: space.id as string,
  190. // user_nos: options as any,
  191. // });
  192. // if (!data.success) {
  193. // // getAdmins();
  194. // notification.error({ description: data.err_msg, message: 'Update Error' });
  195. // } else {
  196. // message.success(t('Edit_Success'));
  197. // }
  198. // },
  199. // // eslint-disable-next-line react-hooks/exhaustive-deps
  200. // [space.id],
  201. // );
  202. // const handleChange = (value: string[]) => {
  203. // updateAdmins(value);
  204. // setAdmins(value);
  205. // };
  206. const { run: search, loading: searchLoading } = useRequest(
  207. async (_, doc_name: string) => {
  208. const [, res] = await apiInterceptors(searchDocumentList(space.name, { doc_name }));
  209. return res;
  210. },
  211. {
  212. manual: true,
  213. debounceWait: 500,
  214. onSuccess: data => {
  215. setSearchDocuments(data?.data);
  216. },
  217. },
  218. );
  219. const { run: editChunkRun, loading: chunkLoading } = useRequest(
  220. async (values: any) => {
  221. return await editChunk(props.space.name, {
  222. questions: values.questions?.map((item: any) => item.question),
  223. doc_id: curDoc?.id || '',
  224. doc_name: values.doc_name,
  225. });
  226. },
  227. {
  228. manual: true,
  229. onSuccess: async res => {
  230. if (res.data.success) {
  231. message.success(t('Edit_Success'));
  232. await fetchDocuments();
  233. setEditOpen(false);
  234. } else {
  235. message.error(res.data.err_msg);
  236. }
  237. },
  238. },
  239. );
  240. const renderDocumentCard = () => {
  241. return (
  242. <div className='w-full h-full'>
  243. <div className='mb-4'>
  244. {/* <div className="mb-1">管理员(工号,去前缀0):</div> */}
  245. <div className='flex w-full justify-end'>
  246. {/* <Select
  247. mode="tags"
  248. value={admins}
  249. style={{ width: '50%' }}
  250. onChange={handleChange}
  251. tokenSeparators={[',']}
  252. options={admins.map((item: string) => ({ label: item, value: item }))}
  253. /> */}
  254. <Button
  255. type='primary'
  256. onClick={async () => {
  257. await refresh();
  258. }}
  259. loading={isLoading}
  260. >
  261. {t('Refresh_status')}
  262. </Button>
  263. </div>
  264. </div>
  265. <div className='flex flex-col h-full p-3 border rounded-md'>
  266. {documents?.length > 0 ? (
  267. <>
  268. <div className='flex flex-1 justify-between items-center'>
  269. <Input
  270. className='w-1/3'
  271. prefix={<SearchOutlined />}
  272. placeholder={t('please_enter_the_keywords')}
  273. onChange={async e => {
  274. await search(space.id, e.target.value);
  275. }}
  276. allowClear
  277. />
  278. </div>
  279. <Spin spinning={searchLoading}>
  280. <>
  281. {searchDocuments.length > 0 ? (
  282. <div className='h-96 mt-3 grid grid-cols-3 gap-x-6 gap-y-5 overflow-y-auto'>
  283. {searchDocuments.map((document: IDocument) => {
  284. return (
  285. <Card
  286. key={document.id}
  287. className=' dark:bg-[#484848] relative shrink-0 grow-0 cursor-pointer rounded-[10px] border border-gray-200 border-solid w-full max-h-64'
  288. title={
  289. <Tooltip title={document.doc_name}>
  290. <div className='truncate '>
  291. <DocIcon type={document.doc_type} />
  292. <span>{document.doc_name}</span>
  293. </div>
  294. </Tooltip>
  295. }
  296. extra={
  297. <Dropdown
  298. menu={{
  299. items: [
  300. {
  301. key: 'publish',
  302. label: (
  303. <Space
  304. onClick={() => {
  305. router.push(
  306. `/construct/knowledge/chunk/?spaceName=${space.name}&id=${document.id}`,
  307. );
  308. }}
  309. >
  310. <EyeOutlined />
  311. <span>{t('detail')}</span>
  312. </Space>
  313. ),
  314. },
  315. {
  316. key: `${t('Sync')}`,
  317. label: <SyncContent name={space.name} id={document.id} />,
  318. },
  319. {
  320. key: 'edit',
  321. label: (
  322. <Space
  323. onClick={() => {
  324. setEditOpen(true);
  325. setCurDoc(document);
  326. }}
  327. >
  328. <EditOutlined />
  329. <span>{t('Edit')}</span>
  330. </Space>
  331. ),
  332. },
  333. {
  334. key: 'del',
  335. label: (
  336. <Space
  337. onClick={() => {
  338. showDeleteConfirm(document);
  339. }}
  340. >
  341. <DeleteOutlined />
  342. <span>{t('Delete')}</span>
  343. </Space>
  344. ),
  345. },
  346. ],
  347. }}
  348. getPopupContainer={node => node.parentNode as HTMLElement}
  349. placement='bottomRight'
  350. autoAdjustOverflow={false}
  351. className='rounded-md'
  352. >
  353. <EllipsisOutlined className='p-2' />
  354. </Dropdown>
  355. }
  356. >
  357. <p className='mt-2 font-semibold '>{t('Size')}:</p>
  358. <p>{document.chunk_size} chunks</p>
  359. <p className='mt-2 font-semibold '>{t('Last_Sync')}:</p>
  360. <p>{moment(document.last_sync).format('YYYY-MM-DD HH:MM:SS')}</p>
  361. <p className='mt-2 mb-2'>{renderResultTag(document.status, document.result)}</p>
  362. </Card>
  363. );
  364. })}
  365. </div>
  366. ) : (
  367. <Empty
  368. className='flex flex-1 w-full py-10 flex-col items-center justify-center'
  369. image={Empty.PRESENTED_IMAGE_DEFAULT}
  370. />
  371. )}
  372. </>
  373. {hasMore && (
  374. <Divider>
  375. <span className='cursor-pointer' onClick={loadMoreDocuments}>
  376. {t('Load_more')}
  377. </span>
  378. </Divider>
  379. )}
  380. </Spin>
  381. </>
  382. ) : (
  383. <Empty image={Empty.PRESENTED_IMAGE_DEFAULT}>
  384. <Button
  385. type='primary'
  386. className='flex items-center mx-auto'
  387. icon={<PlusOutlined />}
  388. onClick={handleAddDocument}
  389. >
  390. Create Now
  391. </Button>
  392. </Empty>
  393. )}
  394. </div>
  395. </div>
  396. );
  397. };
  398. useEffect(() => {
  399. if (!curDoc) {
  400. return;
  401. }
  402. form.setFieldsValue({
  403. doc_name: curDoc.doc_name,
  404. questions: curDoc.questions?.map(ques => {
  405. return {
  406. question: ques,
  407. };
  408. }),
  409. });
  410. }, [curDoc, form]);
  411. return (
  412. <div className='px-4'>
  413. <Space>
  414. <Button
  415. size='middle'
  416. type='primary'
  417. className='flex items-center'
  418. icon={<PlusOutlined />}
  419. onClick={handleAddDocument}
  420. >
  421. {t('Add_Datasource')}
  422. </Button>
  423. <Button size='middle' className='flex items-center mx-2' icon={<ToolFilled />} onClick={handleArguments}>
  424. Arguments
  425. </Button>
  426. {space.vector_type === 'KnowledgeGraph' && (
  427. <Button
  428. size='middle'
  429. className='flex items-center mx-2'
  430. icon={<DeploymentUnitOutlined />}
  431. onClick={openGraphVisualPage}
  432. >
  433. {t('View_Graph')}
  434. </Button>
  435. )}
  436. <Button icon={<ExperimentOutlined />} onClick={() => setRecallTestOpen(true)}>
  437. {t('Recall_test')}
  438. </Button>
  439. </Space>
  440. <Divider />
  441. <Spin spinning={isLoading}>{renderDocumentCard()}</Spin>
  442. <ArgumentsModal space={space} argumentsShow={argumentsShow} setArgumentsShow={setArgumentsShow} />
  443. {/* 编辑弹窗 */}
  444. <Modal
  445. title={t('Edit_document')}
  446. open={editOpen}
  447. onCancel={() => setEditOpen(false)}
  448. destroyOnClose={true}
  449. footer={[
  450. <Button key='back' onClick={() => setEditOpen(false)}>
  451. {t('cancel')}
  452. </Button>,
  453. <Button
  454. key='submit'
  455. type='primary'
  456. loading={chunkLoading}
  457. onClick={async () => {
  458. const values = form.getFieldsValue();
  459. await editChunkRun(values);
  460. }}
  461. >
  462. {t('verify')}
  463. </Button>,
  464. ]}
  465. >
  466. <Form
  467. form={form}
  468. initialValues={{
  469. doc_name: curDoc?.doc_name,
  470. questions: curDoc?.questions?.map(ques => {
  471. return {
  472. question: ques,
  473. };
  474. }),
  475. }}
  476. >
  477. <Form.Item label={t('Document_name')} name='doc_name'>
  478. <Input />
  479. </Form.Item>
  480. <Form.Item label={t('Correlation_problem')}>
  481. <Form.List name='questions'>
  482. {(fields, { add, remove }) => (
  483. <>
  484. {fields.map(({ key, name }) => (
  485. <div key={key} className={cls('flex flex-1 items-center gap-8 mb-6')}>
  486. <Form.Item label='' name={[name, 'question']} className='grow'>
  487. <Input placeholder='请输入' />
  488. </Form.Item>
  489. <Form.Item>
  490. <MinusCircleOutlined
  491. onClick={() => {
  492. remove(name);
  493. }}
  494. />
  495. </Form.Item>
  496. </div>
  497. ))}
  498. <Form.Item>
  499. <Button
  500. type='dashed'
  501. onClick={() => {
  502. add({ question: '', valid: false });
  503. }}
  504. block
  505. icon={<PlusOutlined />}
  506. >
  507. {t('Add_problem')}
  508. </Button>
  509. </Form.Item>
  510. </>
  511. )}
  512. </Form.List>
  513. </Form.Item>
  514. </Form>
  515. </Modal>
  516. {/* 召回测试弹窗 */}
  517. <RecallTestModal open={recallTestOpen} setOpen={setRecallTestOpen} space={space} />
  518. </div>
  519. );
  520. }