CodeGeneratorController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Extensions.Options;
  3. using SqlSugar;
  4. using ZR.CodeGenerator;
  5. using ZR.CodeGenerator.Model;
  6. using ZR.CodeGenerator.Service;
  7. using ZR.Model;
  8. using ZR.Model.System.Dto;
  9. using ZR.Model.System.Generate;
  10. namespace ZR.Admin.WebApi.Controllers
  11. {
  12. /// <summary>
  13. /// 代码生成
  14. /// </summary>
  15. [Route("tool/gen")]
  16. [ApiExplorerSettings(GroupName = "sys")]
  17. public class CodeGeneratorController : BaseController
  18. {
  19. private readonly CodeGeneraterService _CodeGeneraterService = new CodeGeneraterService();
  20. private readonly IGenTableService GenTableService;
  21. private readonly IGenTableColumnService GenTableColumnService;
  22. private readonly ISysMenuService SysMenuService;
  23. private readonly IWebHostEnvironment WebHostEnvironment;
  24. private readonly OptionsSetting OptionsSetting;
  25. public CodeGeneratorController(
  26. IGenTableService genTableService,
  27. IGenTableColumnService genTableColumnService,
  28. IWebHostEnvironment webHostEnvironment,
  29. IOptions<OptionsSetting> options,
  30. ISysMenuService sysMenuService)
  31. {
  32. GenTableService = genTableService;
  33. GenTableColumnService = genTableColumnService;
  34. WebHostEnvironment = webHostEnvironment;
  35. SysMenuService = sysMenuService;
  36. OptionsSetting = options.Value;
  37. }
  38. /// <summary>
  39. /// 获取所有数据库的信息
  40. /// </summary>
  41. /// <returns></returns>
  42. [HttpGet("getDbList")]
  43. [ActionPermissionFilter(Permission = "tool:gen:list")]
  44. public IActionResult GetListDataBase()
  45. {
  46. var dbList = _CodeGeneraterService.GetAllDataBases();
  47. var defaultDb = dbList?[0];
  48. return SUCCESS(new { dbList, defaultDb });
  49. }
  50. /// <summary>
  51. ///获取所有表根据数据库名
  52. /// </summary>
  53. /// <param name="dbName">数据库名</param>
  54. /// <param name="tableName">表名</param>
  55. /// <param name="pager">分页信息</param>
  56. /// <returns></returns>
  57. [HttpGet("getTableList")]
  58. [ActionPermissionFilter(Permission = "tool:gen:list")]
  59. public IActionResult FindListTable(string dbName, string? tableName, PagerInfo pager)
  60. {
  61. List<DbTableInfo> list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager);
  62. var page = new PagedInfo<DbTableInfo>
  63. {
  64. TotalNum = pager.TotalNum,
  65. PageSize = pager.PageSize,
  66. PageIndex = pager.PageNum,
  67. Result = list
  68. };
  69. return SUCCESS(page);
  70. }
  71. /// <summary>
  72. /// 查询生成表数据
  73. /// </summary>
  74. /// <param name="tableName">表名</param>
  75. /// <param name="pagerInfo">分页信息</param>
  76. /// <returns></returns>
  77. [HttpGet("list")]
  78. [ActionPermissionFilter(Permission = "tool:gen:list")]
  79. public IActionResult GetGenTable(string? tableName, PagerInfo pagerInfo)
  80. {
  81. //查询原表数据,部分字段映射到代码生成表字段
  82. var rows = GenTableService.GetGenTables(new GenTable() { TableName = tableName }, pagerInfo);
  83. return SUCCESS(rows, "MM月dd日 HH:mm");
  84. }
  85. /// <summary>
  86. /// 修改代码生成业务查询
  87. /// </summary>
  88. /// <param name="tableId">genTable表id</param>
  89. /// <returns></returns>
  90. [HttpGet("{tableId}")]
  91. [ActionPermissionFilter(Permission = "tool:gen:query")]
  92. public IActionResult GetColumnList(long tableId)
  93. {
  94. var tableInfo = GenTableService.GetGenTableInfo(tableId);
  95. var tables = GenTableService.GetGenTableAll();
  96. return SUCCESS(new { info = tableInfo, tables });
  97. }
  98. /// <summary>
  99. /// 根据表id查询表列
  100. /// </summary>
  101. /// <param name="tableId">genTable表id</param>
  102. /// <returns></returns>
  103. [HttpGet("column/{tableId}")]
  104. [ActionPermissionFilter(Permission = "tool:gen:query")]
  105. public IActionResult GetTableColumnList(long tableId)
  106. {
  107. var tableColumns = GenTableColumnService.GenTableColumns(tableId);
  108. return SUCCESS(new { columns = tableColumns });
  109. }
  110. /// <summary>
  111. /// 删除代码生成
  112. /// </summary>
  113. /// <param name="tableIds"></param>
  114. /// <returns></returns>
  115. [Log(Title = "代码生成", BusinessType = BusinessType.DELETE)]
  116. [HttpDelete("{tableIds}")]
  117. [ActionPermissionFilter(Permission = "tool:gen:remove")]
  118. public IActionResult Remove(string tableIds)
  119. {
  120. long[] tableId = Tools.SpitLongArrary(tableIds);
  121. int result = GenTableService.DeleteGenTableByIds(tableId);
  122. return SUCCESS(result);
  123. }
  124. /// <summary>
  125. /// 导入表结构(保存)
  126. /// </summary>
  127. /// <param name="dto"></param>
  128. /// <returns></returns>
  129. [HttpPost("importTable")]
  130. [Log(Title = "代码生成", BusinessType = BusinessType.IMPORT)]
  131. [ActionPermissionFilter(Permission = "tool:gen:import")]
  132. public IActionResult ImportTableSave([FromBody] ImportCodeGenTableDto dto)
  133. {
  134. if (string.IsNullOrEmpty(dto.DbName) || dto.Tables == null)
  135. {
  136. throw new CustomException("表或数据库不能为空");
  137. }
  138. int result = 0;
  139. foreach (var table in dto.Tables)
  140. {
  141. List<OracleSeq> seqs = new();
  142. InitTableDto initTableDto = new()
  143. {
  144. DbName = dto.DbName,
  145. UserName = HttpContext.GetName(),
  146. TableName = table.Name,
  147. Desc = table.Description,
  148. CodeGen = OptionsSetting.CodeGen,
  149. FrontTpl = dto.FrontTpl,
  150. };
  151. GenTable genTable = CodeGeneratorTool.InitTable(initTableDto);
  152. genTable.TableId = GenTableService.ImportGenTable(genTable);
  153. if (OptionsSetting.CodeGenDbConfig.DbType == 3)
  154. {
  155. seqs = _CodeGeneraterService.GetAllOracleSeqs(table.Name);
  156. }
  157. if (genTable.TableId > 0)
  158. {
  159. //保存列信息
  160. List<DbColumnInfo> dbColumnInfos = _CodeGeneraterService.GetColumnInfo(dto.DbName, table.Name);
  161. List<GenTableColumn> genTableColumns = CodeGeneratorTool.InitGenTableColumn(genTable, dbColumnInfos, seqs, OptionsSetting.CodeGen);
  162. GenTableColumnService.DeleteGenTableColumnByTableName(table.Name);
  163. GenTableColumnService.InsertGenTableColumn(genTableColumns);
  164. genTable.Columns = genTableColumns;
  165. result++;
  166. }
  167. }
  168. return ToResponse(result);
  169. }
  170. /// <summary>
  171. /// 修改保存代码生成业务
  172. /// </summary>
  173. /// <param name="genTableDto">请求参数实体</param>
  174. /// <returns></returns>
  175. [HttpPut]
  176. [Log(Title = "代码生成", BusinessType = BusinessType.GENCODE, IsSaveRequestData = false)]
  177. [ActionPermissionFilter(Permission = "tool:gen:edit")]
  178. public IActionResult EditSave([FromBody] GenTableDto genTableDto)
  179. {
  180. if (genTableDto == null) throw new CustomException("请求参数错误");
  181. if (genTableDto.BusinessName.Equals(genTableDto.ModuleName, StringComparison.OrdinalIgnoreCase))
  182. {
  183. return ToResponse(ResultCode.CUSTOM_ERROR, "模块名不能和业务名一样");
  184. }
  185. var genTable = genTableDto.Adapt<GenTable>().ToUpdate(HttpContext);
  186. //将前端额外参数转成字符串存入Options中
  187. genTable.Options = genTableDto.Params.Adapt<CodeOptions>();
  188. DbResult<bool> result = GenTableService.UseTran(() =>
  189. {
  190. int rows = GenTableService.UpdateGenTable(genTable);
  191. if (rows > 0)
  192. {
  193. GenTableColumnService.UpdateGenTableColumn(genTable.Columns);
  194. }
  195. });
  196. return SUCCESS(result.IsSuccess);
  197. }
  198. /// <summary>
  199. /// 预览代码
  200. /// </summary>
  201. /// <param name="dto"></param>
  202. /// <param name="tableId"></param>
  203. /// <returns></returns>
  204. [HttpPost("preview/{tableId}")]
  205. [ActionPermissionFilter(Permission = "tool:gen:preview")]
  206. public IActionResult Preview([FromQuery] GenerateDto dto, [FromRoute] int tableId = 0)
  207. {
  208. dto.TableId = tableId;
  209. if (dto == null || dto.TableId <= 0)
  210. {
  211. throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空");
  212. }
  213. var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId);
  214. dto.DbType = OptionsSetting.CodeGenDbConfig.DbType;
  215. dto.GenTable = genTableInfo;
  216. dto.IsPreview = true;
  217. CodeGeneratorTool.Generate(dto);
  218. return SUCCESS(dto.GenCodes);
  219. }
  220. /// <summary>
  221. /// 生成代码(下载方式)
  222. /// </summary>
  223. /// <param name="dto">数据传输对象</param>
  224. /// <returns></returns>
  225. [HttpPost("genCode")]
  226. [Log(Title = "代码生成", BusinessType = BusinessType.GENCODE)]
  227. [ActionPermissionFilter(Permission = "tool:gen:code")]
  228. public IActionResult CodeGenerate([FromBody] GenerateDto dto)
  229. {
  230. if (dto == null || dto.TableId <= 0)
  231. {
  232. throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空");
  233. }
  234. dto.DbType = OptionsSetting.CodeGenDbConfig.DbType;
  235. dto.GenTable = GenTableService.GetGenTableInfo(dto.TableId);
  236. //生成压缩包
  237. string zipReturnFileName = $"ZrAdmin.NET-{dto.GenTable.TableName}-{DateTime.Now:MMddHHmmss}.zip";
  238. //生成代码到指定文件夹
  239. CodeGeneratorTool.Generate(dto);
  240. if (dto.GenTable.Options.GenerateMenu)
  241. {
  242. SysMenuService.AddSysMenu(dto.GenTable, dto.ReplaceDto.PermissionPrefix, dto.ReplaceDto.ShowBtnEdit, dto.ReplaceDto.ShowBtnExport, dto.ReplaceDto.ShowBtnImport);
  243. }
  244. if (dto.GenTable.GenType == "1")//自定义路径
  245. {
  246. var genPath = dto.GenTable.GenPath;
  247. string parentPath;
  248. string tempPath = WebHostEnvironment.ContentRootPath;
  249. if (ComputerHelper.IsUnix())
  250. {
  251. parentPath = Path.Combine(WebHostEnvironment.WebRootPath, "Generatecode");
  252. }
  253. else
  254. {
  255. parentPath = tempPath[..tempPath.LastIndexOf(@"\")];
  256. }
  257. Console.WriteLine("代码生成路径" + parentPath);
  258. //代码生成文件夹路径
  259. dto.GenCodePath = (genPath.IsEmpty() || genPath.Equals("/")) ? parentPath : genPath;
  260. }
  261. else
  262. {
  263. dto.ZipPath = Path.Combine(WebHostEnvironment.WebRootPath, "Generatecode");
  264. dto.GenCodePath = Path.Combine(dto.ZipPath, DateTime.Now.ToString("yyyyMMdd"));
  265. }
  266. //写入文件
  267. foreach (var item in dto.GenCodes)
  268. {
  269. item.Path = Path.Combine(dto.GenCodePath, item.Path);
  270. FileUtil.WriteAndSave(item.Path, item.Content);
  271. }
  272. if (dto.GenTable.GenType != "1")
  273. {
  274. //压缩文件
  275. FileUtil.ZipGenCode(dto.ZipPath, dto.GenCodePath, zipReturnFileName);
  276. }
  277. return SUCCESS(new { path = "/Generatecode/" + zipReturnFileName, fileName = dto.ZipFileName });
  278. }
  279. /// <summary>
  280. /// 同步数据库
  281. /// </summary>
  282. /// <param name="tableId"></param>
  283. /// <param name="tableName"></param>
  284. /// <returns></returns>
  285. [ActionPermissionFilter(Permission = "tool:gen:edit")]
  286. [Log(Title = "代码生成", BusinessType = BusinessType.UPDATE)]
  287. [HttpGet("synchDb/{tableId}")]
  288. public IActionResult SynchDb(string tableName, long tableId = 0)
  289. {
  290. if (string.IsNullOrEmpty(tableName) || tableId <= 0) throw new CustomException("参数错误");
  291. GenTable table = GenTableService.GetGenTableInfo(tableId);
  292. if (table == null) { throw new CustomException("同步数据失败,原表结构不存在"); }
  293. table.Update_by = HttpContext.GetName();
  294. var codeGen = AppSettings.Get<CodeGen>("codeGen");
  295. List<DbColumnInfo> dbColumnInfos = _CodeGeneraterService.GetColumnInfo(table.DbName, tableName);
  296. List<GenTableColumn> dbTableColumns = CodeGeneratorTool.InitGenTableColumn(table, dbColumnInfos, codeGen: codeGen);
  297. bool result = GenTableService.SynchDb(tableId, table, dbTableColumns);
  298. return SUCCESS(result);
  299. }
  300. }
  301. }