Quellcode durchsuchen

feat: 数据模型添加引入方法

liaojiaxing vor 3 Wochen
Ursprung
Commit
f0129bac5d

+ 1 - 0
.gitignore

@@ -11,6 +11,7 @@ node_modules
 .env.development.local
 .env.test.local
 .env.production.local
+.umi/
 
 # Testing
 coverage

+ 8 - 8
apps/er-designer/.umirc.ts

@@ -15,14 +15,14 @@ export default defineConfig({
   metas: [
     { name: 'viewport', content: 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' }
   ],
-  proxy: {
-    '/api': {
-      // 'target': 'http://ab.dev.jbpm.shalu.com/',
-      'target': 'https://edesign.shalu.com/',
-      'changeOrigin': true,
-      'pathRewrite': { '^/api' : '' },
-    },
-  },
+  // proxy: {
+  //   '/api': {
+  //     'target': 'http://ab.dev.jbpm.shalu.com/',
+  //     // 'target': 'https://edesign.shalu.com/',
+  //     'changeOrigin': true,
+  //     'pathRewrite': { '^/api' : '' },
+  //   },
+  // },
   scripts: [
     '//at.alicdn.com/t/c/font_4767192_5rinbe5e4f6.js'
   ],

+ 22 - 0
apps/er-designer/src/api/dataModel.ts

@@ -74,4 +74,26 @@ export const BatchAddAICreateResult = (data: any) => {
     method: "POST",
     data,
   });
+}
+
+/**
+ * 查询可以引入的表列表
+ * @param data 
+ */
+export const GetCanUseTableList = (data: any) => {
+  return request("/api/erDiagram/dataModel/unlinkedBusinessTables", {
+    method: "POST",
+    data
+  });
+}
+
+/**
+ * 导入引入的表
+ * @param data 
+ */
+export const ImportFromBusinessTables = (data: any) => {
+  return request("/api/erDiagram/dataModel/importFromBusinessTables", {
+    method: "POST",
+    data
+  });
 }

+ 1 - 1
apps/er-designer/src/app.ts

@@ -24,7 +24,7 @@ export const request: RequestConfig = {
       }
 
       return {
-        url: baseUrl + url,
+        url: 'http://ab.dev.jbpm.shalu.com' + url,
         options
       }
     }

+ 99 - 31
apps/er-designer/src/components/AddModel.tsx

@@ -1,23 +1,24 @@
-import React, { useRef } from "react";
-import { Modal, Input, Form, message, Select } from "antd";
-import { SaveDataModel } from "@/api";
+import React, { useRef, useMemo } from "react";
+import { Modal, Input, Form, message, TreeSelect } from "antd";
+import { SaveDataModel, GetCanUseTableList } from "@/api";
 import { TableType } from "@/enum";
-import { ProjectInfo } from "@/type";
+import { ProjectInfo, TableItemType } from "@/type";
 import { DEFAULT_SETTING } from "@/constants";
 import CustomColorPicker from "@/components/CustomColorPicker";
+import { useRequest, useModel } from "umi";
+import { pick } from "lodash-es";
 
 export default React.forwardRef(function AddModel(
   props: { onChange?: (val: string | ProjectInfo) => void },
   ref
 ) {
   const [open, setOpen] = React.useState(false);
-  const [loading, setLoading] = React.useState(false);
   const [color, setColor] = React.useState<string>();
-  const [tableOptions, setTableOptions] = React.useState<any[]>([]);
   const [form] = Form.useForm();
   const type = React.useRef<TableType>();
   const editInfo = useRef<ProjectInfo>();
   const folderRef = useRef<string>();
+  const { project } = useModel("erModel");
   React.useImperativeHandle(ref, () => {
     return {
       open: (tableType: TableType, folder?: string) => {
@@ -26,6 +27,9 @@ export default React.forwardRef(function AddModel(
         type.current = tableType;
         setOpen(true);
         form.resetFields();
+        run({
+          type: tableType,
+        });
       },
       edit: (info: ProjectInfo) => {
         editInfo.current = info;
@@ -35,12 +39,77 @@ export default React.forwardRef(function AddModel(
     };
   });
 
+  const {
+    data,
+    loading: loadingOptions,
+    run,
+  } = useRequest(GetCanUseTableList, {
+    manual: true,
+  });
+
+  // 可引入表列表
+  const treeData = useMemo(() => {
+    const tableMap: Record<string, any> = {};
+    data?.result
+      ?.filter(
+        (item: any) =>
+          // 过滤当前数据表类型及存在相同schemaName、aliasName的表
+          item?.type == project?.type
+      )
+      ?.forEach((item: any) => {
+        const option = {
+          key: item.id,
+          title: `${item?.schemaName}(${item.name})`,
+          value: item?.id,
+          selectable: !item.parentBusinessTableId,
+        };
+        // 子表
+        if (item.parentBusinessTableId) {
+          if (tableMap[item.parentBusinessTableId]) {
+            tableMap[item.parentBusinessTableId].children.push(option);
+          } else {
+            tableMap[item.parentBusinessTableId] = {
+              children: [option],
+            };
+          }
+        } else {
+          // 主表
+          if (tableMap[item.id]) {
+            tableMap[item.id] = {
+              ...tableMap[item.parentBusinessTableId],
+              ...option,
+            };
+          } else {
+            tableMap[item.id] = {
+              ...option,
+              children: [],
+            };
+          }
+        }
+        return;
+      });
+    return Object.keys(tableMap).map((key) => tableMap[key]);
+  }, [data]);
+
   const handleSubmit = () => {
     form.validateFields().then(async (values) => {
       if (editInfo.current) {
+        const businessTables =
+          data?.result
+            ?.filter((item: any) => values.table.includes(item.id))
+            ?.map((item: any) => {
+              return pick(item, [
+                "aliasName",
+                "schemaName",
+                "id",
+                "parentBusinessTableId",
+              ]);
+            }) || [];
         const params = {
           ...editInfo.current,
           ...values,
+          businessTables,
+          color
         };
         // 编辑
         await SaveDataModel(params);
@@ -86,31 +155,30 @@ export default React.forwardRef(function AddModel(
         <Form.Item name="description" label="模型描述">
           <Input.TextArea placeholder="请输入模型描述" />
         </Form.Item>
-        <Form.Item
-            label="选择表"
-            name="table"
-          >
-            <Select
-              mode="multiple"
-              placeholder="请选择"
-              loading={loading}
-              options={tableOptions}
-            />
-          </Form.Item>
-          <Form.Item label="颜色" name="color">
-            <CustomColorPicker onChange={setColor}>
-              {color ? (
-                <div
-                  className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer shadow-inner"
-                  style={{ background: color || "#eee" }}
-                ></div>
-              ) : (
-                <span className="bg-#eee px-5px py-3px rounded-4px cursor-pointer text-12px text-#666">
-                  随机生成,点击可选择颜色
-                </span>
-              )}
-            </CustomColorPicker>
-          </Form.Item>
+        <Form.Item label="选择表" name="table">
+          <TreeSelect
+            multiple
+            treeCheckable
+            allowClear
+            placeholder="请选择"
+            loading={loadingOptions}
+            treeData={treeData}
+          />
+        </Form.Item>
+        <Form.Item label="颜色" name="color">
+          <CustomColorPicker onChange={setColor}>
+            {color ? (
+              <div
+                className="rounded-4px cus-btn w-32px h-32px bg-#eee flex-none cursor-pointer shadow-inner"
+                style={{ background: color || "#eee" }}
+              ></div>
+            ) : (
+              <span className="bg-#eee px-5px py-3px rounded-4px cursor-pointer text-12px text-#666">
+                随机生成,点击可选择颜色
+              </span>
+            )}
+          </CustomColorPicker>
+        </Form.Item>
       </Form>
     </Modal>
   );

+ 213 - 165
apps/er-designer/src/pages/detail/components/AddTable.tsx

@@ -15,6 +15,7 @@ import {
   Select,
   Tabs,
   TabsProps,
+  TreeSelect,
 } from "antd";
 import LangInput from "@/components/LangInput";
 import LangInputTextarea from "@/components/LangInputTextarea";
@@ -23,10 +24,12 @@ import { createColumn, createTable } from "@/utils";
 import { TableItemType } from "@/type";
 import { useModel, useRequest } from "umi";
 import {
-  GetAllDesignTables,
-  GetAllBusinessTableColumns,
-  GetBusinessTablesByTableId,
-  ListLangByKey,
+  // GetAllDesignTables,
+  // GetAllBusinessTableColumns,
+  // GetBusinessTablesByTableId,
+  // ListLangByKey,
+  GetCanUseTableList,
+  ImportFromBusinessTables,
 } from "@/api";
 import { validateTableCode, validateAliasName } from "@/utils/validator";
 import { pick } from "lodash-es";
@@ -58,7 +61,7 @@ export default forwardRef(function AddTable(
     },
     openImportMode: () => {
       setTabActiveKey("2");
-      run();
+      run({ type: project?.type });
       setHideAddTab(true);
       setOpen(true);
     },
@@ -67,38 +70,65 @@ export default forwardRef(function AddTable(
     },
   }));
 
-  const { data, loading, run } = useRequest(() => GetAllDesignTables(), {
+  const { data, loading, run } = useRequest(GetCanUseTableList, {
     manual: true,
   });
 
-  const tableOptions = useMemo(() => {
-    const options =
-      data?.result?.appBusinessTables
-        ?.filter(
-          (item: any) =>
-            // 过滤当前数据表类型及存在相同schemaName、aliasName的表
-            item?.type == project?.type
-          // && !project.tables.find(
-          //   (tableItem) =>
-          //     tableItem.table.schemaName === item.schemaName ||
-          //     tableItem.table.aliasName === item.aliasName
-          // )
-        )
-        ?.map((item: any) => {
-          // 判断是否存在已引入的表
-          const hasTable = project.tables.find(
-            (tableItem: TableItemType) =>
-              tableItem.table.schemaName === item.schemaName ||
-              tableItem.table.aliasName === item.aliasName
-          );
-          return {
-            label: `${item?.schemaName}(${item.name})`,
-            value: item?.id,
-            disabled: hasTable,
-          };
-        }) || [];
+  // 可引入表列表
+  const treeData = useMemo(() => {
+    const tableMap: Record<string, any> = {};
+    data?.result
+      ?.filter(
+        (item: any) =>
+          // 过滤当前数据表类型及存在相同schemaName、aliasName的表
+          item?.type == project?.type
+        // && !project.tables.find(
+        //   (tableItem) =>
+        //     tableItem.table.schemaName === item.schemaName ||
+        //     tableItem.table.aliasName === item.aliasName
+        // )
+      )
+      ?.forEach((item: any) => {
+        // 判断是否存在已引入的表
+        const hasTable = project.tables.find(
+          (tableItem: TableItemType) =>
+            tableItem.table.schemaName === item.schemaName ||
+            tableItem.table.aliasName === item.aliasName
+        );
 
-    return options;
+        const option = {
+          key: item.id,
+          title: `${item?.schemaName}(${item.name})`,
+          value: item?.id,
+          disabled: hasTable,
+          selectable: !item.parentBusinessTableId,
+        };
+        // 子表
+        if (item.parentBusinessTableId) {
+          if (tableMap[item.parentBusinessTableId]) {
+            tableMap[item.parentBusinessTableId].children.push(option);
+          } else {
+            tableMap[item.parentBusinessTableId] = {
+              children: [option],
+            };
+          }
+        } else {
+          // 主表
+          if (tableMap[item.id]) {
+            tableMap[item.id] = {
+              ...tableMap[item.parentBusinessTableId],
+              ...option,
+            };
+          } else {
+            tableMap[item.id] = {
+              ...option,
+              children: [],
+            };
+          }
+        }
+        return;
+      });
+    return Object.keys(tableMap).map((key) => tableMap[key]);
   }, [data]);
 
   const items: TabsProps["items"] = [
@@ -198,11 +228,13 @@ export default forwardRef(function AddTable(
               name="table"
               rules={[{ required: true, message: "请选择表" }]}
             >
-              <Select
-                mode="multiple"
+              <TreeSelect
+                multiple
+                treeCheckable
+                allowClear
                 placeholder="请选择"
                 loading={loading}
-                options={tableOptions}
+                treeData={treeData}
               />
             </Form.Item>
             <Form.Item label="颜色" name="color">
@@ -234,68 +266,68 @@ export default forwardRef(function AddTable(
   };
 
   // 获取引入的表转换成模型表
-  const getNewTableByTable = async (
-    tableData: any,
-    columns: any[],
-    tableOther: Record<string, any> = {}
-  ): Promise<TableItemType> => {
-    const newTable = createTable(project.type, project.id);
-    const langKeyList: string[] = [];
-    if (tableData.langName) {
-      langKeyList.push(tableData.langName);
-    }
-    if (tableData.langDescription) {
-      langKeyList.push(tableData.langDescription);
-    }
-    columns.forEach((item) => {
-      if (item.langName) {
-        langKeyList.push(item.langName);
-      }
-    });
+  // const getNewTableByTable = async (
+  //   tableData: any,
+  //   columns: any[],
+  //   tableOther: Record<string, any> = {}
+  // ): Promise<TableItemType> => {
+  //   const newTable = createTable(project.type, project.id);
+  //   const langKeyList: string[] = [];
+  //   if (tableData.langName) {
+  //     langKeyList.push(tableData.langName);
+  //   }
+  //   if (tableData.langDescription) {
+  //     langKeyList.push(tableData.langDescription);
+  //   }
+  //   columns.forEach((item) => {
+  //     if (item.langName) {
+  //       langKeyList.push(item.langName);
+  //     }
+  //   });
 
-    // 获取全部多语言数据
-    const langList = await Promise.all(
-      [...new Set(langKeyList)].map((key) =>
-        ListLangByKey({ key }).then((res) => res.result)
-      )
-    );
+  //   // 获取全部多语言数据
+  //   const langList = await Promise.all(
+  //     [...new Set(langKeyList)].map((key) =>
+  //       ListLangByKey({ key }).then((res) => res.result)
+  //     )
+  //   );
 
-    const langName = langList.find((item) => item.key === tableData.langName);
-    const descName = langList.find(
-      (item) => item.key === tableData.langDescription
-    );
-    return {
-      isTable: true,
-      // 表格数据
-      table: {
-        ...newTable.table,
-        ...pick(tableData, ["schemaName", "aliasName", "isDeleted"]),
-        langNameList: [
-          { name: "zh-CN", value: langName?.["zh-CN"] || "" },
-          { name: "en", value: langName?.["en"] || "" },
-        ],
-        langDescriptionList: [
-          { name: "zh-CN", value: descName?.["zh-CN"] || "" },
-          { name: "en", value: descName?.["en"] || "" },
-        ],
-        ...tableOther,
-      },
-      // 字段数据
-      tableColumnList: columns.map((item) => {
-        const column = createColumn(newTable.table.id);
-        const langName = langList.find((lang) => lang.key === item.langName);
+  //   const langName = langList.find((item) => item.key === tableData.langName);
+  //   const descName = langList.find(
+  //     (item) => item.key === tableData.langDescription
+  //   );
+  //   return {
+  //     isTable: true,
+  //     // 表格数据
+  //     table: {
+  //       ...newTable.table,
+  //       ...pick(tableData, ["schemaName", "aliasName", "isDeleted"]),
+  //       langNameList: [
+  //         { name: "zh-CN", value: langName?.["zh-CN"] || "" },
+  //         { name: "en", value: langName?.["en"] || "" },
+  //       ],
+  //       langDescriptionList: [
+  //         { name: "zh-CN", value: descName?.["zh-CN"] || "" },
+  //         { name: "en", value: descName?.["en"] || "" },
+  //       ],
+  //       ...tableOther,
+  //     },
+  //     // 字段数据
+  //     tableColumnList: columns.map((item) => {
+  //       const column = createColumn(newTable.table.id);
+  //       const langName = langList.find((lang) => lang.key === item.langName);
 
-        return {
-          ...column,
-          ...pick(item, Object.keys(column)),
-          langNameList: [
-            { name: "zh-CN", value: langName?.["zh-CN"] || "" },
-            { name: "en", value: langName?.["en"] || "" },
-          ],
-        };
-      }),
-    };
-  };
+  //       return {
+  //         ...column,
+  //         ...pick(item, Object.keys(column)),
+  //         langNameList: [
+  //           { name: "zh-CN", value: langName?.["zh-CN"] || "" },
+  //           { name: "en", value: langName?.["en"] || "" },
+  //         ],
+  //       };
+  //     }),
+  //   };
+  // };
 
   const [loadingColumns, setLoadingColumns] = useState(false);
   const handleOk = () => {
@@ -321,81 +353,97 @@ export default forwardRef(function AddTable(
         const values = form1.getFieldsValue();
         try {
           setLoadingColumns(true);
-          const requestList = values.table.map((tableId: string) => [
-            GetBusinessTablesByTableId(tableId),
-            GetAllBusinessTableColumns({
-              currentPage: 1,
-              pageSize: 2000,
-              orderByProperty: "isPreDefined DESC, DisplayOrder",
-              Ascending: true,
-              totalPage: 1,
-              totalCount: 1,
-              filters: [
-                {
-                  name: "BusinessTableId",
-                  value: tableId,
-                },
-              ],
-            }),
-          ]);
-          if (requestList.length === 0) {
+          // const requestList = values.table.map((tableId: string) => [
+          //   GetBusinessTablesByTableId(tableId),
+          //   GetAllBusinessTableColumns({
+          //     currentPage: 1,
+          //     pageSize: 2000,
+          //     orderByProperty: "isPreDefined DESC, DisplayOrder",
+          //     Ascending: true,
+          //     totalPage: 1,
+          //     totalCount: 1,
+          //     filters: [
+          //       {
+          //         name: "BusinessTableId",
+          //         value: tableId,
+          //       },
+          //     ],
+          //   }),
+          // ]);
+          if (values.table.length === 0) {
             message.error("请选择要引入的表");
             return;
           }
-          const resArr = await Promise.allSettled(
-            (requestList as Promise<any>[]).flat(1)
-          );
+          // const resArr = await Promise.allSettled(
+          //   (requestList as Promise<any>[]).flat(1)
+          // );
 
-          const tableMap: Record<string, any> = {};
-          resArr.forEach((res) => {
-            if (res.status === "fulfilled") {
-              const value = res.value?.result;
-              // 表格数据
-              if (Array.isArray(value) && value[0]) {
-                tableMap[value[0].id] = {
-                  table: value[0],
-                  tableColumnList: [],
-                };
-              } else {
-                // 字段数据
-                const model = res.value?.result?.model;
-                const tableId = model?.[0]?.businessTableId;
-                if (tableId) {
-                  if (tableMap[tableId]) {
-                    tableMap[tableId].tableColumnList = model;
-                  } else {
-                    tableMap[tableId] = {
-                      table: {},
-                      tableColumnList: model,
-                    };
-                  }
-                }
-              }
-            }
-          });
-
-          const rect = graph?.getAllCellsBBox();
-          // 计算起始位置 默认往最后加
-          const startY = (rect?.height || 0) + (rect?.y || 0) + 20;
-          const result = Object.keys(tableMap).map(async (key, index) => {
-            const table = await getNewTableByTable(
-              tableMap[key].table,
-              tableMap[key].tableColumnList
-            );
-            table.table.style.y = startY;
-            table.table.style.x =
-              100 + index * (project.setting.tableWidth + 20);
-            if (color) {
-              table.table.style.color = color;
-            }
-            return table;
-          });
+          // const tableMap: Record<string, any> = {};
+          // resArr.forEach((res) => {
+          //   if (res.status === "fulfilled") {
+          //     const value = res.value?.result;
+          //     // 表格数据
+          //     if (Array.isArray(value) && value[0]) {
+          //       tableMap[value[0].id] = {
+          //         table: value[0],
+          //         tableColumnList: [],
+          //       };
+          //     } else {
+          //       // 字段数据
+          //       const model = res.value?.result?.model;
+          //       const tableId = model?.[0]?.businessTableId;
+          //       if (tableId) {
+          //         if (tableMap[tableId]) {
+          //           tableMap[tableId].tableColumnList = model;
+          //         } else {
+          //           tableMap[tableId] = {
+          //             table: {},
+          //             tableColumnList: model,
+          //           };
+          //         }
+          //       }
+          //     }
+          //   }
+          // });
 
-          const newTables = await Promise.all(result);
+          // const rect = graph?.getAllCellsBBox();
+          // // 计算起始位置 默认往最后加
+          // const startY = (rect?.height || 0) + (rect?.y || 0) + 20;
+          // const result = Object.keys(tableMap).map(async (key, index) => {
+          //   const table = await getNewTableByTable(
+          //     tableMap[key].table,
+          //     tableMap[key].tableColumnList
+          //   );
+          //   table.table.style.y = startY;
+          //   table.table.style.x =
+          //     100 + index * (project.setting.tableWidth + 20);
+          //   if (color) {
+          //     table.table.style.color = color;
+          //   }
+          //   return table;
+          // });
 
-          props.onChange(newTables);
-          form1.resetFields();
-          setOpen(false);
+          // const newTables = await Promise.all(result);
+          const businessTables =
+            data?.result
+              ?.filter((item: any) => values.table.includes(item.id))
+              ?.map((item: any) => {
+                return pick(item, [
+                  "aliasName",
+                  "schemaName",
+                  "id",
+                  "parentBusinessTableId",
+                ]);
+              }) || [];
+          const res = await ImportFromBusinessTables({
+            dataModelId: project.id,
+            color,
+            businessTables,
+          });
+          console.log("导入结果:", res);
+          // props.onChange(res.result);
+          // form1.resetFields();
+          // setOpen(false);
         } catch (err) {
           console.error(err);
           message.warning("引入失败");
@@ -409,7 +457,7 @@ export default forwardRef(function AddTable(
   const handleChangeTableActiveKey = (key: string) => {
     setTabActiveKey(key);
     if (key === "2") {
-      run();
+      run({ type: project.type });
     }
   };
 

+ 1 - 1
apps/er-designer/src/pages/detail/index.tsx

@@ -15,7 +15,7 @@ import type { DescriptionsProps, MenuProps } from "antd";
 import { DownOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
 import TableEdit from "@/components/TableEdit";
 import ER from "./components/ER";
-import AddTable from "./components/AddTable";
+import AddTable from "@/components/AddTable";
 import { useModel, useRequest, useParams } from "umi";
 import { GetDataModelDetail } from "@/api";
 import NoData from "@/assets/no-data.png";

+ 1 - 1
apps/er-designer/src/pages/er/components/TablePanel.tsx

@@ -11,7 +11,7 @@ import { useModel } from "umi";
 import noData from "@/assets/no-data.png";
 import TableEdit from "@/components/TableEdit";
 import { ColumnItem, TableItemType } from "@/type";
-import AddTable from "@/pages/detail/components/AddTable";
+import AddTable from "@/components/AddTable";
 export default function TablePanel() {
   const {
     project,