333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { IsNull, Not } from "typeorm";
import { default as BaseController } from "../baseController";
import * as fs from "fs";
import * as path from "path";
import { getManager } from "typeorm";
import { SysMvcTableInfo } from "../../entity/sys/core/sysMvcTableInfo";
import { SysMvcTableColumn } from "../../entity/sys/core/sysMvcTableColumn";
import { Post, Prefix } from "egg-shell-decorators";
import { SysMvcUserData } from "../../entity/sys/core/sysMvcUserData";
 
@Prefix("sysmvc")
export default class SysMvcController extends BaseController {
  //#region createModel
  /**
   * 创建model文件
   */
  @Post()
  public async createModel() {
    let { ctx } = this;
    let body = ctx.request.body;
    let changeDataType = (dataType, nullable?: number) => {
      let tsDatatype: string;
      dataType = ctx.helper.caseStyle(dataType);
      switch (dataType) {
        case "byte":
        case "tinyint":
        case "int":
        case "int32":
        case "int64":
        case "bigint":
        case "decimal":
        case "money":
          tsDatatype = "number";
          break;
        case "date":
        case "datetime":
        case "dateTime":
          tsDatatype = "Date";
          break;
        default:
          tsDatatype = "string";
          break;
      }
      tsDatatype = ": " + tsDatatype;
      if (nullable === 1) {
        tsDatatype = "?" + tsDatatype;
      }
 
      return tsDatatype;
    };
 
    try {
      //主数据
      let tableInfo = await getManager().getRepository(SysMvcTableInfo).findOne(body.table_Id);
 
      if (!tableInfo) {
        this.info.result = false;
        this.info.msg = "模块不存在";
        ctx.body = this.info;
        return;
      }
 
      let where = "";
      // StatData
      if (tableInfo.dataTableType === 5) {
        where = "table_Id = " + body.table_Id + " AND (isManagerDataSet>=1) And columnName<>'分割行'";
      } else {
        where = "table_Id = " + body.table_Id + " AND (isManagerDataSet>=1) And columnName<>'分割行'";
      }
      let colList = await getManager()
        .getRepository(SysMvcTableColumn)
        .find({
          select: ["columnName", "columnComment", "dataType", "groupBy", "isManagerDataSet", "fieldAttribute", "nullable", "isEditDataSet", "isSum"],
          where: where,
          order: { orderNo: "DESC", columnID: "ASC" }
        });
 
      let relation = "";
      let typeormList = "";
      let importList = "";
      let html = "";
 
      // 获得主表信息
      let whereStr = "detailName + ',' like '%' + :detailName + ',%'";
      if (tableInfo.tableView.indexOf(",") >= 0) {
        whereStr = "detailName=:detailName";
      }
      let _where = { detailName: tableInfo.tableView };
      let masterTableInfo = await this.dbRead.createQueryBuilder(SysMvcTableInfo, "t").where(whereStr, _where).getOne();
 
      for (let cInfo of colList) {
        if (cInfo.isEditDataSet == 3) continue; //3为分割行
        let dataType = changeDataType(cInfo.dataType, cInfo.nullable);
 
        let colProp = "@Column()";
        if (["decimal", "money"].indexOf(this.ctx.helper.caseStyle(cInfo.dataType)) >= 0) {
          colProp = `@Column({
    type: "decimal",
    precision: 14,
    scale: 4
  })`;
        }
        let keyIDs = [];
        if (tableInfo.keyIDs) {
          keyIDs = tableInfo.keyIDs.split(",");
        }
        let fieldAttribute = cInfo.fieldAttribute;
        if (fieldAttribute) {
          fieldAttribute = fieldAttribute.toLocaleLowerCase();
        }
        if (fieldAttribute == "key" || keyIDs.indexOf(cInfo.columnName) >= 0) {
          colProp = "@PrimaryGeneratedColumn()";
        } else if (cInfo.columnName == "CreateDate") {
          colProp = "@CreateDateColumn()";
          typeormList += ",\r\n  CreateDateColumn";
        } else if (cInfo.columnName == "ModifyDate") {
          colProp = "@UpdateDateColumn()";
          typeormList += ",\r\n  UpdateDateColumn";
        }
        // 子表信息,外键类型
        if (tableInfo && tableInfo.detailName && cInfo.fieldAttribute == "Key") {
          let tableView = tableInfo.tableView.replace(/_/gi, "");
          let _DetailName = tableInfo.detailName.replace(/_/gi, "");
          let DetailNames = _DetailName.split(",");
          let keyName = ctx.helper.caseStyle(tableView);
          switch (tableInfo.domainModelType) {
            case 2: // 一对多主
              let index = 0;
              let _relation = "";
              for (let DetailName of DetailNames) {
                let detailName = ctx.helper.caseStyle(DetailName);
                _relation += `
  /**
   * ${DetailName}明细表数据
   */
  @OneToMany(
    () => ${DetailName},
    t => t.${keyName}
  )
  ${detailName}: ${DetailName}[];\r\n\r\n`;
                if (index > 0) {
                  importList += "\r\n";
                }
                importList += "import { " + DetailName + ' } from "./' + detailName + '";';
                index++;
              }
              relation = _relation;
              if (index > 0) typeormList += ",\r\n  OneToMany";
              break;
          }
        }
 
        // 主表信息
        if (masterTableInfo != null) {
          if (masterTableInfo.keyIDs == cInfo.columnName) {
            let tableView = masterTableInfo.tableView.replace(/_/gi, "");
            let masterName = ctx.helper.caseStyle(tableView);
            let _currentTableView = ctx.helper.caseStyle(tableInfo.tableView.replace(/_/gi, ""));
            let keyName = ctx.helper.caseStyle(masterTableInfo.keyIDs);
            switch (tableInfo.domainModelType) {
              case 4: // 一对多从
                relation = `  /**
   * ${masterTableInfo.cnName}主表数据
   */
  @ManyToOne(
    () => ${tableView},
    t => t.${_currentTableView}
  )
  @JoinColumn({
    name: "${keyName}",
    referencedColumnName: "${keyName}"
  })
  ${masterName}: ${tableView};\r\n\r\n`;
                typeormList += ",\r\n  ManyToOne";
                typeormList += ",\r\n  JoinColumn";
                importList = "import { " + tableView + ' } from "./' + masterName + '";';
                break;
            }
          }
        }
        html += "  /**\r\n";
        html += "   * " + cInfo.columnComment + "\r\n";
        html += "   */\r\n";
        html += "  " + colProp + "\r\n";
        //分组特性
        let columnName = ctx.helper.caseStyle(cInfo.columnName);
        html += "  " + columnName + dataType + ";\r\n\r\n";
      }
      html = html.replace(/\s+$/, ""); // 移出结尾空白字符
      // 主外键关系
      html += relation;
 
      let tableView = tableInfo.tableView.replace(/_/gi, "");
 
      html = `import {
  Entity,
  PrimaryGeneratedColumn,
  Column${typeormList}
} from "typeorm";
${importList}
 
@Entity("${tableInfo.tableName}")
export class ${tableView} {
${html}
}
`;
 
      let _tableView = ctx.helper.caseStyle(tableView);
      let rootPath = path.resolve();
      let appPath = rootPath + `\\app\\entity\\`;
      let folderName = tableInfo.folderName.toLowerCase();
      let namespace = tableInfo.namespace.toLowerCase();
      let savePath = tableInfo.domainModelSavePath
        .replace(/\{namespace\}/gi, namespace)
        .replace(/\{folder\}/gi, folderName)
        .replace(/\{folderName\}/gi, folderName)
        .replace(/\{tableView\}/gi, tableInfo.tableView)
        .replace(/DomainModels\//gi, "")
        .replace(/SelectorModel\.cs/gi, ".ts")
        .replace(/Model\.cs/gi, ".ts")
        .replace(/..\/Rattan.Interface\./gi, appPath)
        .replace(/..\/Rattan.ERP\./gi, appPath)
        .replace(/..\/Rattan\./gi, appPath)
        .replace(tableInfo.tableView, tableView)
        // .replace("_", "")
        .replace(/\//gi, "\\");
 
      let regS = new RegExp(tableView, "gi");
      savePath = savePath.toLowerCase().replace(regS, _tableView);
 
      let pathToCreate = savePath.substring(0, savePath.lastIndexOf("\\"));
      ctx.helper.mkdir(pathToCreate);
 
      fs.writeFileSync(savePath, html);
      this.info.msg = "model文件保存成功";
      this.info.result = true;
    } catch (error) {
      console.log("生成model错误:" + error.message);
      this.info.msg = "生成model错误:" + error.mesage;
      this.info.result = false;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region createMenuTree
  /**
   * 生成菜单树
   */
  @Post()
  public async createMenuTree() {
    const { ctx } = this;
 
    let loadInfo = {
      folder: "sys/core",
      tableName: "Sys_Menu",
      tableView: "Sys_MenuVue",
      keyName: "menu_Id",
      nodeName: "menuName",
      parentName: "parentId",
      orderBy: { vueOrderNo: "DESC", menu_Id: "ASC" },
      where: { parentId: 0, vueEnable: 1, vueUrl: Not(IsNull()) },
      extendColumns: "vueUrl,vueFilePath,vueName,vueAuth,vueIcon"
    };
 
    try {
      let list = await this.ctx.service.common.getTreeDataAll(loadInfo, 0);
      let routers = await this.createMenuNode(list);
 
      routers = `/* eslint-disable */
export const asyncRouterMap = [${routers},
{
    path: '*',
    redirect: '/404',
    hidden: true
}]`;
 
      let rootPath = path.resolve();
      let appPath = rootPath + `\\..\\siemens2-site`;
      let baseVuePath = appPath + "\\src\\router\\modules\\router.js";
      let pathToCreate = baseVuePath.substring(0, baseVuePath.lastIndexOf("\\"));
      ctx.helper.mkdir(pathToCreate);
      fs.writeFileSync(baseVuePath, routers);
 
      this.info.result = true;
      this.info.msg = "生成成功!";
 
      ctx.body = this.info;
    } catch (ex) {
      let msg = "异常错误信息:" + ex.message;
      this.info.result = false;
      this.info.msg = msg;
    }
 
    return this.info;
  }
  //#endregion
 
  //#region createMenuNode
  private async createMenuNode(list: Array<Object>) {
    let routers = "";
    for (let item of list) {
      let node = "";
      let children = item["children"];
      if (children && children.length > 0) {
        node = `{
    path: '${item["vueUrl"]}',
    component: () => import('${item["vueFilePath"]}'),
    redirect: '/',
    name: '${item["vueName"]}',
    alwaysShow: true,
    meta: {
        title: '${item["vueName"]}',
        icon: '${item["vueIcon"] || ""}',
        menu_Id: ${item["menu_Id"]},
        menuName: '${item["menuName"]}'
    },
    children:[{children}]
}`;
        let childNode = await this.createMenuNode(children);
        node = node.replace("{children}", childNode);
      } else {
        node = `{
        path: '${item["vueUrl"]}',
        component: () => import('${item["vueFilePath"]}'),
        name: '${item["vueName"]}',
        meta: {
            title: '${item["vueName"]}',
            icon: '${item["vueIcon"] || ""}',
            menu_Id: ${item["menu_Id"]},
            menuName: '${item["menuName"]}'
        }
    }`;
      }
      if (routers) routers += ",";
      routers += node;
    }
 
    return routers;
  }
 
  //#endregion
 
  //#region 提取字段
  @Post()
  public async createField() {
    try {
      this.ctx.service.sys.sysMvc.params = Object.assign({}, this.body);
      this.info = await this.ctx.service.sys.sysMvc.generateTableColumns();
    } catch (error) {
      this.info.result = false;
      this.info.msg = error.message;
    }
 
    this.ctx.body = this.info;
  }
  //#endregion
 
  //#region 保存账套用户自定义
  @Post()
  public async saveUserJson() {
    try {
      let userInfo = await this.userInfo;
      let table_Id = this.body.table_Id;
      let userJson = JSON.stringify(this.body.userJson);
      let userData = await this.dbRead.findOne(SysMvcUserData, {
        userProduct_Id: userInfo.userProduct_Id,
        table_Id: table_Id
      });
      if (!userData) {
        userData = new SysMvcUserData();
      }
      await this.setAccountInfo(userData);
      userData.table_Id = this.body.table_Id;
      userData.tableView = this.body.tableView;
      userData.userJson = userJson;
      await this.dbWrite.save(userData);
 
      this.info.result = true;
      this.info.msg = "保存成功";
    } catch (error) {
      this.info.result = false;
      this.info.msg = error.message;
    }
 
    this.ctx.body = this.info;
  }
  //#endregion
 
  //#region 获取账套用户自定义
  @Post()
  public async getUserJson() {
    try {
      let userInfo = await this.userInfo;
      let table_Id = this.body.table_Id;
      let tableInfo = await this.dbRead.findOne(SysMvcUserData, {
        userProduct_Id: userInfo.userProduct_Id,
        table_Id: table_Id
      });
      if (!tableInfo) {
        this.info.result = false;
        this.ctx.body = this.info;
        return;
      }
      let userJson = tableInfo.userJson;
      if (userJson) {
        this.info.result = true;
        this.info.data = JSON.parse(userJson);
      } else {
        this.info.result = false;
      }
    } catch (error) {
      this.info.result = false;
      this.info.msg = error.message;
    }
 
    this.ctx.body = this.info;
  }
  //#endregion
}