database.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import { apiInterceptors, getDbList, getDbSupportType, postDbDelete } from '@/client/api';
  2. import GPTCard from '@/components/common/gpt-card';
  3. import MuiLoading from '@/components/common/loading';
  4. import FormDialog from '@/components/database/form-dialog';
  5. import ConstructLayout from '@/new-components/layout/Construct';
  6. import { DBOption, DBType, DbListResponse, DbSupportTypeResponse } from '@/types/db';
  7. import { dbMapper } from '@/utils';
  8. import { DeleteFilled, EditFilled, PlusOutlined } from '@ant-design/icons';
  9. import { useAsyncEffect } from 'ahooks';
  10. import { Badge, Button, Card, Drawer, Empty, Modal, message } from 'antd';
  11. import { useMemo, useState } from 'react';
  12. import { useTranslation } from 'react-i18next';
  13. type DBItem = DbListResponse[0];
  14. export function isFileDb(dbTypeList: DBOption[], dbType: DBType) {
  15. return dbTypeList.find(item => item.value === dbType)?.isFileDb;
  16. }
  17. function Database() {
  18. // const { setCurrentDialogInfo } = useContext(ChatContext); // unused
  19. // const router = useRouter(); // unused
  20. const { t } = useTranslation();
  21. const [dbList, setDbList] = useState<DbListResponse>([]);
  22. const [dbSupportList, setDbSupportList] = useState<DbSupportTypeResponse>([]);
  23. const [loading, setLoading] = useState(false);
  24. const [modal, setModal] = useState<{
  25. open: boolean;
  26. info?: DBItem;
  27. dbType?: DBType;
  28. }>({ open: false });
  29. const [draw, setDraw] = useState<{
  30. open: boolean;
  31. dbList?: DbListResponse;
  32. name?: string;
  33. type?: DBType;
  34. }>({ open: false });
  35. const getDbSupportList = async () => {
  36. const [, data] = await apiInterceptors(getDbSupportType());
  37. setDbSupportList(data ?? []);
  38. };
  39. const refreshDbList = async () => {
  40. setLoading(true);
  41. const [, data] = await apiInterceptors(getDbList());
  42. setDbList(data ?? []);
  43. setLoading(false);
  44. };
  45. const dbTypeList = useMemo(() => {
  46. const supportDbList = dbSupportList.map(item => {
  47. const { db_type, is_file_db } = item;
  48. return { ...dbMapper[db_type], value: db_type, isFileDb: is_file_db };
  49. }) as DBOption[];
  50. const unSupportDbList = Object.keys(dbMapper)
  51. .filter(item => !supportDbList.some(db => db.value === item))
  52. .map(item => ({
  53. ...dbMapper[item],
  54. value: dbMapper[item].label,
  55. disabled: true,
  56. })) as DBOption[];
  57. return [...supportDbList, ...unSupportDbList];
  58. }, [dbSupportList]);
  59. const onModify = (item: DBItem) => {
  60. setModal({ open: true, info: item });
  61. };
  62. const onDelete = (item: DBItem) => {
  63. Modal.confirm({
  64. title: 'Tips',
  65. content: `Do you Want to delete the ${item.db_name}?`,
  66. onOk() {
  67. return new Promise<void>((resolve, reject) => {
  68. handleDelete(item.db_name, resolve, reject);
  69. });
  70. },
  71. });
  72. };
  73. const handleDelete = async (dbName: string, resolve: () => void, reject: () => void) => {
  74. try {
  75. const [err] = await apiInterceptors(postDbDelete(dbName));
  76. if (err) {
  77. message.error(err.message);
  78. reject();
  79. return;
  80. }
  81. message.success('success');
  82. refreshDbList();
  83. resolve();
  84. } catch {
  85. reject();
  86. }
  87. };
  88. const dbListByType = useMemo(() => {
  89. const mapper = dbTypeList.reduce(
  90. (acc, item) => {
  91. acc[item.value] = dbList.filter(dbConn => dbConn.db_type === item.value);
  92. return acc;
  93. },
  94. {} as Record<DBType, DbListResponse>,
  95. );
  96. return mapper;
  97. }, [dbList, dbTypeList]);
  98. useAsyncEffect(async () => {
  99. await refreshDbList();
  100. await getDbSupportList();
  101. }, []);
  102. const handleDbTypeClick = (info: DBOption) => {
  103. const dbItems = dbList.filter(item => item.db_type === info.value);
  104. setDraw({
  105. open: true,
  106. dbList: dbItems,
  107. name: info.label,
  108. type: info.value,
  109. });
  110. };
  111. // TODO: unused function call
  112. // const handleChat = async (item: IChatDbSchema) => {
  113. // const [, data] = await apiInterceptors(
  114. // newDialogue({
  115. // chat_mode: 'chat_with_db_execute',
  116. // }),
  117. // );
  118. // // 知识库对话都默认私有知识库应用下
  119. // if (data?.conv_uid) {
  120. // setCurrentDialogInfo?.({
  121. // chat_scene: data.chat_mode,
  122. // app_code: data.chat_mode,
  123. // });
  124. // localStorage.setItem(
  125. // 'cur_dialog_info',
  126. // JSON.stringify({
  127. // chat_scene: data.chat_mode,
  128. // app_code: data.chat_mode,
  129. // }),
  130. // );
  131. // router.push(`/chat?scene=chat_with_db_execute&id=${data?.conv_uid}&db_name=${item.db_name}`);
  132. // }
  133. // };
  134. return (
  135. <ConstructLayout>
  136. <div className='relative min-h-full overflow-y-auto px-6 max-h-[90vh]'>
  137. <MuiLoading visible={loading} />
  138. <div className='flex justify-between items-center mb-6'>
  139. <div className='flex items-center gap-4'>
  140. {/* <Input
  141. variant="filled"
  142. prefix={<SearchOutlined />}
  143. placeholder={t('please_enter_the_keywords')}
  144. // onChange={onSearch}
  145. // onPressEnter={onSearch}
  146. allowClear
  147. className="w-[230px] h-[40px] border-1 border-white backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60"
  148. /> */}
  149. </div>
  150. <div className='flex items-center gap-4'>
  151. <Button
  152. className='border-none text-white bg-button-gradient'
  153. icon={<PlusOutlined />}
  154. onClick={() => {
  155. setModal({ open: true });
  156. }}
  157. >
  158. {t('Add_Datasource')}
  159. </Button>
  160. </div>
  161. </div>
  162. <div className='flex flex-wrap mx-[-8px] gap-2 md:gap-4'>
  163. {dbTypeList.map(item => {
  164. return (
  165. <Badge key={item.value} count={dbListByType[item.value]?.length} className='min-h-fit'>
  166. <GPTCard
  167. className='h-full'
  168. title={item.label}
  169. desc={item.desc ?? ''}
  170. disabled={item.disabled}
  171. icon={item.icon}
  172. onClick={() => {
  173. if (item.disabled) return;
  174. handleDbTypeClick(item);
  175. }}
  176. />
  177. </Badge>
  178. // <BlurredCard
  179. // description={item.db_path ?? ''}
  180. // name={item.db_name}
  181. // key={item.db_name}
  182. // logo={targetDBType?.icon}
  183. // RightTop={
  184. // <InnerDropdown
  185. // menu={{
  186. // items: [
  187. // {
  188. // key: 'del',
  189. // label: (
  190. // <span
  191. // className="text-red-400"
  192. // onClick={() => {
  193. // onDelete(item);
  194. // }}
  195. // >
  196. // {t('Delete_Btn')}
  197. // </span>
  198. // ),
  199. // },
  200. // ],
  201. // }}
  202. // />
  203. // }
  204. // rightTopHover={false}
  205. // Tags={
  206. // <div>
  207. // <Tag>{item.db_type}</Tag>
  208. // </div>
  209. // }
  210. // RightBottom={
  211. // <ChatButton
  212. // text={t('start_chat')}
  213. // onClick={() => {
  214. // handleChat(item);
  215. // }}
  216. // />
  217. // }
  218. // onClick={() => {
  219. // // if (targetDBType?.disabled) return;
  220. // // handleDbTypeClick(targetDBType);
  221. // onModify(item);
  222. // }}
  223. // />
  224. );
  225. })}
  226. </div>
  227. <FormDialog
  228. open={modal.open}
  229. dbTypeList={dbTypeList}
  230. choiceDBType={modal.dbType}
  231. editValue={modal.info}
  232. dbNames={dbList.map(item => item.db_name)}
  233. onSuccess={() => {
  234. setModal({ open: false });
  235. refreshDbList();
  236. }}
  237. onClose={() => {
  238. setModal({ open: false });
  239. }}
  240. />
  241. <Drawer
  242. title={draw.name}
  243. placement='right'
  244. onClose={() => {
  245. setDraw({ open: false });
  246. }}
  247. open={draw.open}
  248. >
  249. {draw.type && dbListByType[draw.type] && dbListByType[draw.type].length ? (
  250. <>
  251. <Button
  252. type='primary'
  253. className='mb-4 flex items-center'
  254. icon={<PlusOutlined />}
  255. onClick={() => {
  256. setModal({ open: true, dbType: draw.type });
  257. }}
  258. >
  259. Create
  260. </Button>
  261. {dbListByType[draw.type].map(item => (
  262. <Card
  263. key={item.db_name}
  264. title={item.db_name}
  265. extra={
  266. <>
  267. <EditFilled
  268. className='mr-2'
  269. style={{ color: '#1b7eff' }}
  270. onClick={() => {
  271. onModify(item);
  272. }}
  273. />
  274. <DeleteFilled
  275. style={{ color: '#ff1b2e' }}
  276. onClick={() => {
  277. onDelete(item);
  278. }}
  279. />
  280. </>
  281. }
  282. className='mb-4'
  283. >
  284. {item.db_path ? (
  285. <p>path: {item.db_path}</p>
  286. ) : (
  287. <>
  288. <p>host: {item.db_host}</p>
  289. <p>username: {item.db_user}</p>
  290. <p>port: {item.db_port}</p>
  291. </>
  292. )}
  293. <p>remark: {item.comment}</p>
  294. </Card>
  295. ))}
  296. </>
  297. ) : (
  298. <Empty image={Empty.PRESENTED_IMAGE_DEFAULT}>
  299. <Button
  300. type='primary'
  301. className='flex items-center mx-auto'
  302. icon={<PlusOutlined />}
  303. onClick={() => {
  304. setModal({ open: true, dbType: draw.type });
  305. }}
  306. >
  307. Create Now
  308. </Button>
  309. </Empty>
  310. )}
  311. </Drawer>
  312. </div>
  313. </ConstructLayout>
  314. );
  315. }
  316. export default Database;