diff --git a/.gitignore b/.gitignore index c5169479..34b14f9a 100644 --- a/.gitignore +++ b/.gitignore @@ -262,3 +262,4 @@ __pycache__/ /ZRAdmin/Properties/launchSettings.json /ZRAdmin/Properties/PublishProfiles /ZR.Admin.WebApi/appsettings.Stage.json +/CodeGenerate diff --git a/Infrastructure/Extensions/AppServiceExtensions.cs b/Infrastructure/Extensions/AppServiceExtensions.cs index 98545c71..4f3f5e5b 100644 --- a/Infrastructure/Extensions/AppServiceExtensions.cs +++ b/Infrastructure/Extensions/AppServiceExtensions.cs @@ -59,7 +59,7 @@ namespace Infrastructure.Extensions services.AddTransient(serviceType, type); break; } - Console.WriteLine($"注册:{serviceType}"); + //Console.WriteLine($"注册:{serviceType}"); } else { diff --git a/ZR.Common/Extension/Extension.Convert.cs b/Infrastructure/Extensions/Extension.Convert.cs similarity index 99% rename from ZR.Common/Extension/Extension.Convert.cs rename to Infrastructure/Extensions/Extension.Convert.cs index febe6bb8..4710dfd0 100644 --- a/ZR.Common/Extension/Extension.Convert.cs +++ b/Infrastructure/Extensions/Extension.Convert.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ZR.Common.Extension +namespace Infrastructure.Extensions { public static partial class Extensions { diff --git a/ZR.Common/Extension/Extension.Enum.cs b/Infrastructure/Extensions/Extension.Enum.cs similarity index 98% rename from ZR.Common/Extension/Extension.Enum.cs rename to Infrastructure/Extensions/Extension.Enum.cs index d5be0200..72710ffa 100644 --- a/ZR.Common/Extension/Extension.Enum.cs +++ b/Infrastructure/Extensions/Extension.Enum.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading.Tasks; //using Newtonsoft.Json; -namespace ZR.Common.Extension +namespace Infrastructure.Extensions { public static partial class Extensions { diff --git a/ZR.Common/Extension/Extension.Exception.cs b/Infrastructure/Extensions/Extension.Exception.cs similarity index 91% rename from ZR.Common/Extension/Extension.Exception.cs rename to Infrastructure/Extensions/Extension.Exception.cs index f021439e..4af781d7 100644 --- a/ZR.Common/Extension/Extension.Exception.cs +++ b/Infrastructure/Extensions/Extension.Exception.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ZR.Common.Extension +namespace Infrastructure.Extensions { public static partial class Extensions { diff --git a/ZR.Common/Extension/Extension.Linq.cs b/Infrastructure/Extensions/Extension.Linq.cs similarity index 99% rename from ZR.Common/Extension/Extension.Linq.cs rename to Infrastructure/Extensions/Extension.Linq.cs index 45425ecb..0c23a710 100644 --- a/ZR.Common/Extension/Extension.Linq.cs +++ b/Infrastructure/Extensions/Extension.Linq.cs @@ -5,7 +5,7 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace ZR.Common.Extension +namespace Infrastructure.Extensions { public static class LinqExtensions { diff --git a/ZR.Common/Extension/Extension.Validate.cs b/Infrastructure/Extensions/Extension.Validate.cs similarity index 96% rename from ZR.Common/Extension/Extension.Validate.cs rename to Infrastructure/Extensions/Extension.Validate.cs index 379972b7..2d8c0833 100644 --- a/ZR.Common/Extension/Extension.Validate.cs +++ b/Infrastructure/Extensions/Extension.Validate.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ZR.Common.Extension +namespace Infrastructure.Extensions { public static partial class Extensions { diff --git a/ZR.Common/ComputerHelper.cs b/Infrastructure/Helper/ComputerHelper.cs similarity index 98% rename from ZR.Common/ComputerHelper.cs rename to Infrastructure/Helper/ComputerHelper.cs index 041022f9..b26e37bc 100644 --- a/ZR.Common/ComputerHelper.cs +++ b/Infrastructure/Helper/ComputerHelper.cs @@ -1,10 +1,10 @@ -using System; +using Infrastructure.Extensions; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; -using ZR.Common.Extension; -namespace ZR.Common +namespace Infrastructure { public class ComputerHelper { diff --git a/ZR.Common/DateTimeHelper.cs b/Infrastructure/Helper/DateTimeHelper.cs similarity index 99% rename from ZR.Common/DateTimeHelper.cs rename to Infrastructure/Helper/DateTimeHelper.cs index 2fb05d7a..a50008d2 100644 --- a/ZR.Common/DateTimeHelper.cs +++ b/Infrastructure/Helper/DateTimeHelper.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace ZR.Common +namespace Infrastructure { public class DateTimeHelper { diff --git a/ZR.Common/FileUtil.cs b/Infrastructure/Helper/FileUtil.cs similarity index 98% rename from ZR.Common/FileUtil.cs rename to Infrastructure/Helper/FileUtil.cs index ae0a079d..9d3b3aa9 100644 --- a/ZR.Common/FileUtil.cs +++ b/Infrastructure/Helper/FileUtil.cs @@ -4,7 +4,7 @@ using System.IO; using System.Security.Cryptography; using System.Text; -namespace ZR.Common +namespace Infrastructure { public class FileUtil { diff --git a/ZR.Common/HttpHelper.cs b/Infrastructure/Helper/HttpHelper.cs similarity index 99% rename from ZR.Common/HttpHelper.cs rename to Infrastructure/Helper/HttpHelper.cs index 403a916d..a42482b7 100644 --- a/ZR.Common/HttpHelper.cs +++ b/Infrastructure/Helper/HttpHelper.cs @@ -4,7 +4,7 @@ using System.Net.Http; using System.Text; using System.Threading.Tasks; -namespace ZR.Common +namespace Infrastructure { public class HttpHelper { diff --git a/ZR.Common/ShellHelper.cs b/Infrastructure/Helper/ShellHelper.cs similarity index 98% rename from ZR.Common/ShellHelper.cs rename to Infrastructure/Helper/ShellHelper.cs index c5f7ce38..4ca9e784 100644 --- a/ZR.Common/ShellHelper.cs +++ b/Infrastructure/Helper/ShellHelper.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Text; -namespace ZR.Common +namespace Infrastructure { public class ShellHelper { diff --git a/Infrastructure/OptionsSetting.cs b/Infrastructure/OptionsSetting.cs index 4aa2b2ec..6a876d14 100644 --- a/Infrastructure/OptionsSetting.cs +++ b/Infrastructure/OptionsSetting.cs @@ -6,20 +6,11 @@ namespace Infrastructure /// public class OptionsSetting { - public static string ConnAdmin = "Conn_admin"; - public static string DbType = "DbType"; + public static string ConnAdmin = "conn_zrAdmin"; + public static string ConnDbType = "conn_zrAdmin_Type"; public static string DbKey = "DbKey"; - public string Conn_Admin { get; set; } - - public string AppName { get; set; } - /// - /// 主库 - /// - public string Master { get; set; } - public string Redis { get; set; } - public string Database { get; set; } /// /// 是否演示模式 diff --git a/README.md b/README.md index dd5f2155..2f311b71 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,29 @@ ## 🍟概述 * 本项目适合有一定NetCore和 vue基础的开发人员 -* ZRAdmin.NET是基于.NET 5开发的权限管理及快速开发框架,整合最新技术包括Asp.NetCore WebApi、Sqlsugar、Swagger、Vue等,核心模块包括组织机构、角色用户、权限授权、定时任务、文章管理等。 -* 模块化架构设计,层次清晰,业务层推荐写到单独模块,框架升级不影响业务! -* 代码量少、通俗易懂、功能强大、易扩展,轻松开发从现在开始! +* 基于.NET 5实现的通用权限管理平台(RBAC模式)。整合最新技术高效快速开发,前后端分离模式,开箱即用。 +* 代码量少、学习简单、通俗易懂、功能强大、易扩展、轻量级,让web开发更快速、简单高效,解决70%的重复工作,专注您的业务,轻松开发从现在开始! * 前端采用Vue2.0、Element UI。 * 后端采用Net5、Sqlsugar、MySQL。 * 权限认证使用Jwt,支持多终端认证系统。 * 支持加载动态权限菜单,多方式轻松权限控制 -* 基于若依vue分离版本(java版本)修改 -~ 如果对您有帮助,您可以点右上角 “Star” 收藏一下 ,获取第一时间更新,谢谢!~ +``` +如果对您有帮助,您可以点右上角 “Star” 收藏一下 ,这样作者才有继续免费下去的动力,谢谢!~ +``` ## 🍿在线体验 -vue版本体验地址:http://www.izhaorui.cn:8080/ (用户名:admin,密码:123456) +- 体验地址:http://www.izhaorui.cn:8080/ +- 管理员:admin +- 密 码:123456 -**由于是个人项目,资金有限,体验服是低配,请大家爱惜,轻戳,不胜感激!!!** - -## 🥼前端技术 +``` +由于是个人项目,资金有限,体验服是低配,请大家爱惜,轻戳,不胜感激!!! +``` +## 🍁前端技术 Vue版前端技术栈 :基于vue、vuex、vue-router 、vue-cli 、axios 和 element-ui,前端采用vscode工具开发 -## 🥼后端技术 +## 🍀后端技术 核心框架:.Net5.0 + Web API + sqlsugar + swagger 定时计划任务:Quartz.Net组件 @@ -30,11 +33,11 @@ Vue版前端技术栈 :基于vue、vuex、vue-router 、vue-cli 、axios 和 e 日志管理:NLog、登录日志、操作日志 -工具类:验证码、丰富公共功能 +工具类:验证码、丰富公共功能、代码生成 ## 🍄快速启动 需要安装:VS2019(最新版)、npm或yarn(最新版) -准备工作:将document文件夹下面的admin.sql脚本导入到数据库中,修改ZRAdmin项目里面的Conn_Admin数据库连接字符串以及DbType选择对应的数据库类型,目前仅MySQL验证了 +准备工作:将document文件夹下面的admin.sql脚本导入到数据库中,修改appsettings.json配置文件里面中的conn_zrAdmin数据库连接字符串以及conn_zrAdmin_Type选择对应的数据库类型,目前仅支持MySQL、SQL server 启动后台:打开项目根目录的startup.bat即可启动(数据库默认MySQL) 启动前端:打开ZR.Vue文件夹,运行npm install命令,再运行npm run serve启动 浏览器访问:http://localhost:8887 (默认前端端口为:8887,后台端口为:8888) @@ -42,21 +45,47 @@ Vue版前端技术栈 :基于vue、vuex、vue-router 、vue-cli 、axios 和 e ## 🍖内置功能 -1. [X] 用户管理:用户是系统操作者,该功能主要完成系统用户配置。 -2. [X] 部门管理:配置系统组织机构(公司、部门、小组),树结构展现。 -3. [X] 岗位管理:配置系统用户所属担任职务。 -4. [X] 菜单管理:配置系统菜单,操作权限,按钮权限标识等。 -5. [X] 角色管理:角色菜单权限分配。 -6. [X] 字典管理:对系统中经常使用的一些较为固定的数据进行维护。 -7. [ ] 参数管理:对系统动态配置常用参数。 -8. [X] 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。 -9. [X] 登录日志:系统登录日志记录查询包含登录异常。 -10. [ ] 在线用户:当前系统中活跃用户状态监控。 -11. [X] 系统接口:使用swagger生成相关api接口文档。 -12. [X] 服务监控:监视当前系统CPU、内存、磁盘、堆栈等相关信息。 -13. [X] 在线构建器:拖动表单元素生成相应的VUE代码。 -14. [X] 任务系统:基于Quartz.NET定时任务执行。 -15. [X] 文章管理:可以写文章记录。 +1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。 +2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现。 +3. 岗位管理:配置系统用户所属担任职务。 +4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。 +5. 角色管理:角色菜单权限分配。 +6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。 +6. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。 +7. 登录日志:系统登录日志记录查询包含登录异常。 +8. 系统接口:使用swagger生成相关api接口文档。 +9. 服务监控:监视当前系统CPU、内存、磁盘、堆栈等相关信息。 +10. 在线构建器:拖动表单元素生成相应的VUE代码。 +11. 任务系统:基于Quartz.NET定时任务执行。 +12. 文章管理:可以写文章记录。 +13. 代码生成:可以一键生成前后端代码(.cs、.vue、.js),自定义配置前端展示控件、让开发更快捷高效。 + + +## 🍻项目结构 + +``` +- ZR.Service[服务层类库]:提供WebApi接口调用; +- ZR.Repository[仓库层类库]:方便提供有执行存储过程的操作; +- ZR.Model[实体层类库],提供项目中的数据库表、数据传输对象; +- ZR.Admin.WebApi[webapi接口]:为Vue版或其他三方系统提供接口服务。 +- ZR.Vue[前端UI]:vue版本UI层。 +- ZR.Tasks[定时任务类库]:提供项目定时任务实现功能; +- ZR.CodeGenerator[代码生成功能],包含代码生成的模板、方法、代码生成的下载。 +``` +## ⚡ 近期计划 + +- [ ] 参数管理 +- [ ] 在线用户 +- [ ] 文件管理 +- [ ] 邮件发送 +- [ ] 集成微信开发 + +## 📖 帮助文档 +👉快捷部署到Linux文档: +- [本地md文件](./document/nginx部署文档.md "代码生成") + +👉代码生成器使用教程: +- [本地md文件](./document/代码生成器使用.md "代码生成") ## 🍎演示图 @@ -80,7 +109,22 @@ Vue版前端技术栈 :基于vue、vuex、vue-router 、vue-cli 、axios 和 e - + + + + + + + + + + + + + + + + ## 🎉优势 @@ -89,16 +133,14 @@ Vue版前端技术栈 :基于vue、vuex、vue-router 、vue-cli 、axios 和 e 2. 后台系统无需任何二次开发,直接发布即可使用 3. 前台与后台系统分离,分别为不同的系统(域名可独立) 4. 全局异常统一处理 +5. 自定义的代码生成功能 ## 💐 特别鸣谢 - 👉Ruoyi.vue:[Ruoyi](http://www.ruoyi.vip/) -- 👉SqlSugar:https://gitee.com/dotnetchina/SqlSugar +- 👉SqlSugar:[SqlSugar](https://gitee.com/dotnetchina/SqlSugar) -## 🍻参与贡献 -- Fork 本项目 -- 新建 Feat_xxx 分支 -- 提交代码 -- 新建 Pull Request +## 😎联系作者 +QQ:599854767 ## 🎀捐赠 如果这个项目对您有所帮助,请扫下方二维码打赏一杯咖啡。 diff --git a/ZR.Admin.WebApi/Controllers/BaseController.cs b/ZR.Admin.WebApi/Controllers/BaseController.cs index 49413f1d..119d7c49 100644 --- a/ZR.Admin.WebApi/Controllers/BaseController.cs +++ b/ZR.Admin.WebApi/Controllers/BaseController.cs @@ -16,34 +16,36 @@ namespace ZR.Admin.WebApi.Controllers public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss"; public static string TIME_FORMAT_FULL_2 = "MM-dd HH:mm:ss"; - protected IActionResult SUCCESS(object data, string timeFormatStr = "MM-dd HH:mm:ss") + protected IActionResult SUCCESS(object data, string timeFormatStr = "yyyy-MM-dd HH:mm:ss") { string jsonStr = GetJsonStr(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.FAIL, data), timeFormatStr); return Content(jsonStr, "application/json"); } + protected IActionResult ToRespose(ResultCode resultCode, object data = null) + { + string jsonStr = GetJsonStr(GetApiResult(resultCode, data), ""); + return Content(jsonStr, "application/json"); + } + /// /// json输出带时间格式的 /// /// /// /// - protected IActionResult OutputJson(ApiResult apiResult, string timeFormatStr = "MM-dd HH:mm:ss") + protected IActionResult OutputJson(ApiResult apiResult, string timeFormatStr = "yyyy-MM-dd HH:mm:ss") { string jsonStr = GetJsonStr(apiResult, timeFormatStr); return Content(jsonStr, "application/json"); } - protected IActionResult OutputJson(long rows, string timeFormatStr = "MM-dd HH:mm:ss") + protected IActionResult OutputJson(long rows, string timeFormatStr = "yyyy-MM-dd HH:mm:ss") { string jsonStr = GetJsonStr(ToJson(rows), timeFormatStr); return Content(jsonStr, "application/json"); } - protected string SerializeObject(object obj) - { - return JsonConvert.SerializeObject(obj); - } /// /// 响应返回结果 diff --git a/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs b/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs new file mode 100644 index 00000000..d6a4f55b --- /dev/null +++ b/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs @@ -0,0 +1,249 @@ +using Infrastructure; +using Infrastructure.Attribute; +using Infrastructure.Enums; +using Mapster; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Hosting; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.IO; +using ZR.Admin.WebApi.Extensions; +using ZR.Admin.WebApi.Filters; +using ZR.CodeGenerator; +using ZR.CodeGenerator.Model; +using ZR.CodeGenerator.Service; +using ZR.Common; +using ZR.Model; +using ZR.Model.System.Dto; +using ZR.Model.System.Generate; +using ZR.Model.Vo; +using ZR.Service.System.IService; + +namespace ZR.Admin.WebApi.Controllers +{ + /// + /// 代码生成 + /// + [Route("tool/gen")] + public class CodeGeneratorController : BaseController + { + private CodeGeneraterService _CodeGeneraterService = new CodeGeneraterService(); + private IGenTableService GenTableService; + private IGenTableColumnService GenTableColumnService; + private IWebHostEnvironment WebHostEnvironment; + public CodeGeneratorController(IGenTableService genTableService, IGenTableColumnService genTableColumnService, IWebHostEnvironment webHostEnvironment) + { + GenTableService = genTableService; + GenTableColumnService = genTableColumnService; + WebHostEnvironment = webHostEnvironment; + } + + /// + /// 获取所有数据库的信息 + /// + /// + [HttpGet("getDbList")] + [ActionPermissionFilter(Permission = "tool:gen:list")] + public IActionResult GetListDataBase() + { + var dbList = _CodeGeneraterService.GetAllDataBases(); + var defaultDb = dbList.Count > 0 ? dbList[0] : null; + return SUCCESS(new { dbList, defaultDb }); + } + + /// + ///获取所有表根据数据名 + /// + /// 数据库名 + /// 表名 + /// 分页信息 + /// + [HttpGet("getTableList")] + [ActionPermissionFilter(Permission = "tool:gen:list")] + public IActionResult FindListTable(string dbName, string tableName, PagerInfo pager) + { + List list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager); + var vm = new VMPageResult(list, pager); + + return SUCCESS(vm); + } + + /// + /// 代码生成器 + /// + /// 数据传输对象 + /// + [HttpPost("genCode")] + [Log(Title = "代码生成", BusinessType = BusinessType.GENCODE)] + [ActionPermissionFilter(Permission = "tool:gen:code")] + public IActionResult Generate([FromBody] GenerateDto dto) + { + if (dto.TableId <= 0) + { + throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空"); + } + dto.ZipPath = Path.Combine(WebHostEnvironment.WebRootPath, "Generatecode"); + dto.GenCodePath = Path.Combine(dto.ZipPath, DateTime.Now.ToString("yyyyMMdd")); + + var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId); + genTableInfo.Columns = GenTableColumnService.GenTableColumns(dto.TableId); + + dto.GenTable = genTableInfo; + //生成代码 + CodeGeneratorTool.Generate(genTableInfo, dto); + //下载文件 + FileHelper.ZipGenCode(dto); + + //HttpContext.Response.Headers.Add("Content-disposition", $"attachment; filename={zipFileName}"); + return SUCCESS(new { zipPath = "/Generatecode/" + dto.ZipFileName, fileName = dto.ZipFileName }); + } + + /// + /// 获取代码生成表列表 + /// + /// 表名 + /// 分页信息 + /// + [HttpGet("listGenTable")] + public IActionResult GetGenTable(string tableName, PagerInfo pagerInfo) + { + //查询原表数据,部分字段映射到代码生成表字段 + var rows = GenTableService.GetGenTables(new GenTable() { TableName = tableName }, pagerInfo); + + return SUCCESS(rows); + } + + /// + /// 查询表字段列表 + /// + /// genTable表id + /// + [HttpGet("column/{tableId}")] + public IActionResult GetColumnList(long tableId) + { + var tableColumns = GenTableColumnService.GenTableColumns(tableId); + var tableInfo = GenTableService.GetGenTableInfo(tableId); + return SUCCESS(new { result = tableColumns, info = tableInfo }); + } + + /// + /// 删除代码生成 + /// + /// + /// + [Log(Title = "代码生成", BusinessType = BusinessType.DELETE)] + [HttpDelete("{tableIds}")] + [ActionPermissionFilter(Permission = "tool:gen:remove")] + public IActionResult Remove(string tableIds) + { + long[] tableId = Tools.SpitLongArrary(tableIds); + + int result = GenTableService.DeleteGenTableByIds(tableId); + return SUCCESS(result); + } + + /// + /// 导入表结构(保存) + /// + /// + /// + /// + [HttpPost("importTable")] + [Log(Title = "代码生成", BusinessType = BusinessType.IMPORT)] + [ActionPermissionFilter(Permission = "tool:gen:import")] + public IActionResult ImportTableSave(string tables, string dbName) + { + if (string.IsNullOrEmpty(tables)) + { + throw new CustomException("表不能为空"); + } + string[] tableNames = tables.Split(',', StringSplitOptions.RemoveEmptyEntries); + string userName = User.Identity.Name; + + foreach (var tableName in tableNames) + { + var tabInfo = _CodeGeneraterService.GetTableInfo(dbName, tableName); + if (tabInfo != null) + { + GenTable genTable = new() + { + BaseNameSpace = "ZR.",//导入默认命名空间前缀 + ModuleName = "business",//导入默认模块名 + ClassName = CodeGeneratorTool.GetClassName(tableName), + BusinessName = CodeGeneratorTool.GetClassName(tableName), + FunctionAuthor = ConfigUtils.Instance.GetConfig(GenConstants.Gen_author), + FunctionName = tabInfo.Description, + TableName = tableName, + TableComment = tabInfo.Description, + Create_by = userName, + }; + genTable.TableId = GenTableService.ImportGenTable(genTable); + + if (genTable.TableId > 0) + { + //保存列信息 + List dbColumnInfos = _CodeGeneraterService.GetColumnInfo(dbName, tableName); + List genTableColumns = CodeGeneratorTool.InitGenTableColumn(genTable, dbColumnInfos); + + GenTableColumnService.DeleteGenTableColumnByTableName(tableName); + GenTableColumnService.InsertGenTableColumn(genTableColumns); + genTable.Columns = genTableColumns; + + return SUCCESS(genTable); + } + } + } + + return ToRespose(ResultCode.FAIL); + } + + /// + /// 修改保存代码生成业务 + /// + /// + [HttpPut] + //[Log(Title = "代码生成", BusinessType = BusinessType.UPDATE)] + [ActionPermissionFilter(Permission = "tool:gen:edit")] + public IActionResult EditSave([FromBody] GenTableDto genTableDto) + { + if (genTableDto == null) throw new CustomException("请求参数错误"); + var genTable = genTableDto.Adapt().ToUpdate(HttpContext); + + int rows = GenTableService.UpdateGenTable(genTable); + if (rows > 0) + { + GenTableColumnService.UpdateGenTableColumn(genTable.Columns); + } + return SUCCESS(rows); + } + + /// + /// 预览代码 + /// + /// + /// + [HttpGet("preview/{tableId}")] + [ActionPermissionFilter(Permission = "tool:gen:preview")] + public IActionResult Preview(long tableId) + { + if (tableId <= 0) + { + throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空"); + } + var genTableInfo = GenTableService.GetGenTableInfo(tableId); + genTableInfo.Columns = GenTableColumnService.GenTableColumns(tableId); + GenerateDto dto = new(); + dto.GenTable = genTableInfo; + dto.ZipPath = Path.Combine(WebHostEnvironment.WebRootPath, "Generatecode"); + dto.GenCodePath = Path.Combine(dto.ZipPath, DateTime.Now.ToString("yyyyMMdd")); + dto.IsPreview = 1; + dto.GenCodeFiles = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; + //生成代码 + CodeGeneratorTool.Generate(genTableInfo, dto); + + return SUCCESS(dto.GenCodes); + } + } +} diff --git a/ZR.Admin.WebApi/Controllers/System/ArticleController.cs b/ZR.Admin.WebApi/Controllers/System/ArticleController.cs index 6f73f984..e175c265 100644 --- a/ZR.Admin.WebApi/Controllers/System/ArticleController.cs +++ b/ZR.Admin.WebApi/Controllers/System/ArticleController.cs @@ -1,22 +1,12 @@ - -//------------------------------------------------------------------------------ -// -// 此代码已从模板生成。 -// -// 手动更改此文件可能导致应用程序出现意外的行为。 -// 如果重新生成代码,将覆盖对此文件的手动更改。 -// -//------------------------------------------------------------------------------ - -using Infrastructure.Attribute; +using Infrastructure.Attribute; using Microsoft.AspNetCore.Mvc; using ZR.Admin.WebApi.Filters; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; using Infrastructure.Model; using SqlSugar; using Mapster; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using Infrastructure.Enums; using Infrastructure; using ZR.Admin.WebApi.Extensions; diff --git a/ZR.Admin.WebApi/Controllers/System/SysDeptController.cs b/ZR.Admin.WebApi/Controllers/System/SysDeptController.cs index 8dec679e..dc99ec23 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysDeptController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysDeptController.cs @@ -7,7 +7,7 @@ using ZR.Admin.WebApi.Filters; using ZR.Common; using ZR.Model.System; using ZR.Service; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysDictDataController.cs b/ZR.Admin.WebApi/Controllers/System/SysDictDataController.cs index d0968af5..c5fe2625 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysDictDataController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysDictDataController.cs @@ -7,7 +7,7 @@ using ZR.Admin.WebApi.Filters; using ZR.Model; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysDictTypeController.cs b/ZR.Admin.WebApi/Controllers/System/SysDictTypeController.cs index d9c12895..d61222ce 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysDictTypeController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysDictTypeController.cs @@ -8,7 +8,7 @@ using ZR.Common; using ZR.Model; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { @@ -36,8 +36,8 @@ namespace ZR.Admin.WebApi.Controllers.System [HttpGet("list")] public IActionResult List([FromQuery] SysDictType dict, [FromQuery] PagerInfo pagerInfo) { - var list = SysDictService.SelectDictTypeList(dict); - pagerInfo.TotalNum = list.Count; + var list = SysDictService.SelectDictTypeList(dict, pagerInfo); + var vm = new VMPageResult(list, pagerInfo); return SUCCESS(vm, TIME_FORMAT_FULL); } @@ -51,7 +51,7 @@ namespace ZR.Admin.WebApi.Controllers.System [ActionPermissionFilter(Permission = "system:dict:query")] public IActionResult GetInfo(long dictId = 0) { - return SUCCESS(SysDictService.SelectDictTypeById(dictId)); + return SUCCESS(SysDictService.GetFirst(f => f.DictId == dictId)); } /// diff --git a/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs b/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs index b363ab82..08afac81 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs @@ -11,8 +11,8 @@ using Infrastructure.Model; using Infrastructure; using Infrastructure.Attribute; using ZR.Model.System; -using ZR.Model.Dto.System; -using ZR.Service.IService; +using ZR.Model.System.Dto; +using ZR.Service.System.IService; using Hei.Captcha; using ZR.Common; diff --git a/ZR.Admin.WebApi/Controllers/System/SysMenuController.cs b/ZR.Admin.WebApi/Controllers/System/SysMenuController.cs index 27dd8467..aa05eaf8 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysMenuController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysMenuController.cs @@ -5,10 +5,10 @@ using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Filters; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Service; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysPostController.cs b/ZR.Admin.WebApi/Controllers/System/SysPostController.cs index 477ee607..ef3da923 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysPostController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysPostController.cs @@ -8,7 +8,7 @@ using Infrastructure.Extensions; using Infrastructure.Attribute; using Infrastructure.Enums; using Infrastructure; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysProfileController.cs b/ZR.Admin.WebApi/Controllers/System/SysProfileController.cs index d1e2172b..29890f1a 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysProfileController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysProfileController.cs @@ -12,9 +12,9 @@ using System.IO; using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Filters; using ZR.Common; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs b/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs index 1b92d244..7fa72fc8 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs @@ -8,7 +8,7 @@ using ZR.Admin.WebApi.Filters; using ZR.Model; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; using ZR.Admin.WebApi.Extensions; namespace ZR.Admin.WebApi.Controllers.System diff --git a/ZR.Admin.WebApi/Controllers/System/SysUserController.cs b/ZR.Admin.WebApi/Controllers/System/SysUserController.cs index 649738f6..e309a414 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysUserController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysUserController.cs @@ -10,7 +10,7 @@ using ZR.Admin.WebApi.Filters; using ZR.Model; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/SysUserRoleController.cs b/ZR.Admin.WebApi/Controllers/System/SysUserRoleController.cs index a801832b..b355f446 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysUserRoleController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysUserRoleController.cs @@ -5,9 +5,9 @@ using System; using System.Linq; using ZR.Admin.WebApi.Filters; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/TasksController.cs b/ZR.Admin.WebApi/Controllers/System/TasksController.cs index ad603855..541ad299 100644 --- a/ZR.Admin.WebApi/Controllers/System/TasksController.cs +++ b/ZR.Admin.WebApi/Controllers/System/TasksController.cs @@ -10,9 +10,9 @@ using System.Threading.Tasks; using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Filters; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; using ZR.Tasks; namespace ZR.Admin.WebApi.Controllers diff --git a/ZR.Admin.WebApi/Controllers/System/TasksLogController.cs b/ZR.Admin.WebApi/Controllers/System/TasksLogController.cs index ca842ca8..432aad4e 100644 --- a/ZR.Admin.WebApi/Controllers/System/TasksLogController.cs +++ b/ZR.Admin.WebApi/Controllers/System/TasksLogController.cs @@ -1,14 +1,15 @@ using Microsoft.AspNetCore.Mvc; using SqlSugar; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using Infrastructure.Extensions; using Infrastructure.Attribute; using ZR.Admin.WebApi.Filters; using ZR.Common; using Infrastructure.Enums; -using ZR.Service.IService; +using ZR.Service.System.IService; +using Infrastructure; namespace ZR.Admin.WebApi.Controllers.System { diff --git a/ZR.Admin.WebApi/Controllers/System/monitor/SysLogininforController.cs b/ZR.Admin.WebApi/Controllers/System/monitor/SysLogininforController.cs index 74a41394..686be342 100644 --- a/ZR.Admin.WebApi/Controllers/System/monitor/SysLogininforController.cs +++ b/ZR.Admin.WebApi/Controllers/System/monitor/SysLogininforController.cs @@ -5,7 +5,7 @@ using ZR.Common; using ZR.Model; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.monitor { diff --git a/ZR.Admin.WebApi/Controllers/System/monitor/SysOperlogController.cs b/ZR.Admin.WebApi/Controllers/System/monitor/SysOperlogController.cs index fd76f8f1..e2774b20 100644 --- a/ZR.Admin.WebApi/Controllers/System/monitor/SysOperlogController.cs +++ b/ZR.Admin.WebApi/Controllers/System/monitor/SysOperlogController.cs @@ -5,10 +5,10 @@ using Microsoft.AspNetCore.Mvc; using ZR.Admin.WebApi.Filters; using ZR.Common; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Model.Vo; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Controllers.monitor { diff --git a/ZR.Admin.WebApi/Extensions/EntityExtension.cs b/ZR.Admin.WebApi/Extensions/EntityExtension.cs index d5186561..879a2581 100644 --- a/ZR.Admin.WebApi/Extensions/EntityExtension.cs +++ b/ZR.Admin.WebApi/Extensions/EntityExtension.cs @@ -10,13 +10,13 @@ namespace ZR.Admin.WebApi.Extensions { var types = source.GetType(); - var worker = new IdWorker(1, 1); - if (types.GetProperty("ID") != null) - { - long id = worker.NextId(); + //var worker = new IdWorker(1, 1); + //if (types.GetProperty("ID") != null) + //{ + // long id = worker.NextId(); - types.GetProperty("ID").SetValue(source, id.ToString(), null); - } + // types.GetProperty("ID").SetValue(source, id.ToString(), null); + //} if (types.GetProperty("CreateTime") != null) { @@ -49,27 +49,34 @@ namespace ZR.Admin.WebApi.Extensions return source; } - //public static TSource ToUpdate(this TSource source, UserSessionVM userSession) - //{ - // var types = source.GetType(); + public static TSource ToUpdate(this TSource source, HttpContext context = null) + { + var types = source.GetType(); - // if (types.GetProperty("UpdateTime") != null) - // { - // types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null); - // } + if (types.GetProperty("UpdateTime") != null) + { + types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null); + } + if (types.GetProperty("Update_Time") != null) + { + types.GetProperty("Update_Time").SetValue(source, DateTime.Now, null); + } + //if (types.GetProperty("UpdateID") != null) + //{ + // types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null); + //} - // if (types.GetProperty("UpdateID") != null) - // { - // types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null); - // } + if (types.GetProperty("UpdateBy") != null) + { + types.GetProperty("UpdateBy").SetValue(source,context.GetName(), null); + } + if (types.GetProperty("Update_by") != null) + { + types.GetProperty("Update_by").SetValue(source, context.GetName(), null); + } - // if (types.GetProperty("UpdateName") != null) - // { - // types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null); - // } - - // return source; - //} + return source; + } } } diff --git a/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs b/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs index 0720d47a..d2cb61fd 100644 --- a/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs +++ b/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs @@ -71,7 +71,7 @@ namespace ZR.Admin.WebApi.Extensions } public static string GetName(this HttpContext context) { - var uid = context.User.Identity.Name; + var uid = context.User?.Identity?.Name; return uid; } diff --git a/ZR.Admin.WebApi/Extensions/TasksExtension.cs b/ZR.Admin.WebApi/Extensions/TasksExtension.cs index dda6ba7c..d125afaa 100644 --- a/ZR.Admin.WebApi/Extensions/TasksExtension.cs +++ b/ZR.Admin.WebApi/Extensions/TasksExtension.cs @@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Quartz.Spi; using System; -using ZR.Service.IService; +using ZR.Service.System.IService; using ZR.Tasks; namespace ZR.Admin.WebApi.Extensions diff --git a/ZR.Admin.WebApi/Filters/LogActionFilter.cs b/ZR.Admin.WebApi/Filters/LogActionFilter.cs index 0d9df95d..b116d74d 100644 --- a/ZR.Admin.WebApi/Filters/LogActionFilter.cs +++ b/ZR.Admin.WebApi/Filters/LogActionFilter.cs @@ -12,7 +12,7 @@ using System.Linq; using System.Text; using ZR.Admin.WebApi.Extensions; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Filters { diff --git a/ZR.Admin.WebApi/Framework/JwtUtil.cs b/ZR.Admin.WebApi/Framework/JwtUtil.cs index e75abff8..1f7f0738 100644 --- a/ZR.Admin.WebApi/Framework/JwtUtil.cs +++ b/ZR.Admin.WebApi/Framework/JwtUtil.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Http; +using Infrastructure; +using Microsoft.AspNetCore.Http; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using System; @@ -43,12 +44,13 @@ namespace ZR.Admin.WebApi.Framework { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(KEY); + var expires = ConfigUtils.Instance.GetAppConfig("sysConfig:tokenExpire", 10); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), //Issuer = "", //Audience = "", - Expires = DateTime.Now.AddDays(7), + Expires = DateTime.Now.AddMinutes(expires), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); diff --git a/ZR.Admin.WebApi/Middleware/GlobalExceptionMiddleware.cs b/ZR.Admin.WebApi/Middleware/GlobalExceptionMiddleware.cs index 4bbe2986..cca6d89b 100644 --- a/ZR.Admin.WebApi/Middleware/GlobalExceptionMiddleware.cs +++ b/ZR.Admin.WebApi/Middleware/GlobalExceptionMiddleware.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Filters; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Admin.WebApi.Middleware { diff --git a/ZR.Admin.WebApi/NLog.config b/ZR.Admin.WebApi/NLog.config index a9d67833..a6d075cc 100644 --- a/ZR.Admin.WebApi/NLog.config +++ b/ZR.Admin.WebApi/NLog.config @@ -23,7 +23,8 @@ -// 此代码已从模板生成。 -// -// 手动更改此文件可能导致应用程序出现意外的行为。 -// 如果重新生成代码,将覆盖对此文件的手动更改。 -// -//------------------------------------------------------------------------------ -using Infrastructure.Attribute; -using Microsoft.AspNetCore.Mvc; -using ZR.Admin.WebApi.Filters; -using ZR.Model.System; -using ZR.Service.IService; -using Infrastructure.Model; -using SqlSugar; -using Mapster; -using ZR.Model.Dto.System; -using Infrastructure.Enums; -using Infrastructure; -using ZR.Admin.WebApi.Extensions; - -namespace ZR.Admin.WebApi.Controllers -{ - /// - /// T4代码自动生成 - /// - - [Verify] - [Route("system/SysFile")] - public class SysFile1Controller: BaseController - { - /// - /// 文件管理接口 - /// - private readonly ISysFileService _SysFileService; - - public SysFile1Controller(ISysFileService SysFileService) - { - _SysFileService = SysFileService; - } - - /// - /// 查询文件管理列表 - /// - /// - [HttpGet("list")] - //[ActionPermissionFilter(Permission = "system:SysFile:list")] - public IActionResult Query([FromQuery] SysFileQueryDto parm) - { - //开始拼装查询条件 - var predicate = Expressionable.Create(); - - //TODO 搜索条件 - //predicate = predicate.And(m => m.Name.Contains(parm.Name)); - - var response = _SysFileService.GetPages(predicate.ToExpression(), parm); - - return SUCCESS(response); - } - - /// - /// 查询文件管理详情 - /// - /// - /// - [HttpGet("{id}")] - public IActionResult Get(string id) - { - var response = _SysFileService.GetId(id); - - return SUCCESS(response); - } - - /// - /// 添加文件管理 - /// - /// - [HttpPost] - //[ActionPermissionFilter(Permission = "system:SysFile:add")] - [Log(Title = "文件管理添加", BusinessType = BusinessType.INSERT)] - public IActionResult Create([FromBody] SysFile parm) - { - if (parm == null) - { - throw new CustomException("请求参数错误"); - } - //从 Dto 映射到 实体 - var addModel = parm.Adapt().ToCreate(); - //addModel.CreateID = User.Identity.Name; - - return SUCCESS(_SysFileService.Add(addModel)); - } - - /// - /// 更新文件管理 - /// - /// - [HttpPut("edit")] - //[ActionPermissionFilter(Permission = "system:SysFile:update")] - [Log(Title = "文件管理修改", BusinessType = BusinessType.UPDATE)] - public IActionResult Update([FromBody] SysFile parm) - { - //从 Dto 映射到 实体 - var addModel = parm.Adapt().ToCreate(); - //addModel.CreateID = User.Identity.Name; - //TODO 字段映射 - var response = _SysFileService.Update(addModel); - - return SUCCESS(response); - } - - /// - /// 删除文件管理 - /// - /// - [HttpDelete("{id}")] - //[ActionPermissionFilter(Permission = "system:SysFile:delete")] - [Log(Title = "文件管理删除", BusinessType = BusinessType.DELETE)] - public IActionResult Delete(int id = 0) - { - if (id <= 0) { return OutputJson(ApiResult.Error($"删除失败Id 不能为空")); } - - // 删除文件管理 - var response = _SysFileService.Delete(id); - - return SUCCESS(response); - } - } -} \ No newline at end of file diff --git a/ZR.Admin.WebApi/Template/Controller.tt b/ZR.Admin.WebApi/Template/Controller.tt deleted file mode 100644 index 3646cc69..00000000 --- a/ZR.Admin.WebApi/Template/Controller.tt +++ /dev/null @@ -1,145 +0,0 @@ -<#@ template debug="false" hostspecific="false" language="C#" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ output extension=".cs" #> - -<# -string ModelName="SysFile"; -string ControllerName="SysFile"; -string ServiceName="SysFileService"; -string FileName="文件管理"; -string ModelNameSpace="ZRAdmin.Controllers"; -#> -//------------------------------------------------------------------------------ -// -// 此代码已从模板生成。 -// -// 手动更改此文件可能导致应用程序出现意外的行为。 -// 如果重新生成代码,将覆盖对此文件的手动更改。 -// -//------------------------------------------------------------------------------ -using Infrastructure.Attribute; -using Microsoft.AspNetCore.Mvc; -using ZRAdmin.Filters; -using ZR.Model; -using ZR.Model.System; -using ZR.Model.Vo; -using ZR.Service.IService; -using Infrastructure.Model; -using SqlSugar; -using Mapster; -using ZR.Model.Dto.System; -using Infrastructure.Enums; -using Infrastructure; -using ZRAdmin.Extensions; - -namespace <#=ModelNameSpace#> -{ - /// - /// T4代码自动生成 - /// - - [Verify] - [Route("system/<#=ModelName#>")] - public class <#=ControllerName#>1Controller: BaseController - { - /// - /// <#=FileName#>接口 - /// - private readonly I<#=ServiceName#> _<#=ServiceName#>; - - public <#=ControllerName#>1Controller(I<#=ServiceName#> <#=ServiceName#>) - { - _<#=ServiceName#> = <#=ServiceName#>; - } - - /// - /// 查询<#=FileName#>列表 - /// - /// - [HttpGet("list")] - //[ActionPermissionFilter(Permission = "system:<#=ModelName#>:list")] - public IActionResult Query([FromQuery] <#=ModelName#>QueryDto parm) - { - //开始拼装查询条件 - var predicate = Expressionable.Create<<#=ModelName#>>(); - - //TODO 搜索条件 - //predicate = predicate.And(m => m.Name.Contains(parm.Name)); - - var response = _<#=ServiceName#>.GetPages(predicate.ToExpression(), parm); - - return SUCCESS(response); - } - - /// - /// 查询<#=FileName#>详情 - /// - /// - /// - [HttpGet("{id}")] - public IActionResult Get(string id) - { - var response = _<#=ServiceName#>.GetId(id); - - return SUCCESS(response); - } - - /// - /// 添加<#=FileName#> - /// - /// - [HttpPost] - //[ActionPermissionFilter(Permission = "system:<#=ModelName#>:add")] - [Log(Title = "<#=FileName#>添加", BusinessType = BusinessType.INSERT)] - public IActionResult Create([FromBody] <#=ModelName#> parm) - { - if (parm == null) - { - throw new CustomException("请求参数错误"); - } - //从 Dto 映射到 实体 - var addModel = parm.Adapt<<#=ModelName#>>().ToCreate(); - //addModel.CreateID = User.Identity.Name; - - return SUCCESS(_<#=ServiceName#>.Add(addModel)); - } - - /// - /// 更新<#=FileName#> - /// - /// - [HttpPut("edit")] - //[ActionPermissionFilter(Permission = "system:<#=ModelName#>:update")] - [Log(Title = "<#=FileName#>修改", BusinessType = BusinessType.UPDATE)] - public IActionResult Update([FromBody] <#=ModelName#> parm) - { - //从 Dto 映射到 实体 - var addModel = parm.Adapt<<#=ModelName#>>().ToCreate(); - //addModel.CreateID = User.Identity.Name; - //TODO 字段映射 - var response = _<#=ServiceName#>.Update(addModel); - - return SUCCESS(response); - } - - /// - /// 删除<#=FileName#> - /// - /// - [HttpDelete("{id}")] - //[ActionPermissionFilter(Permission = "system:<#=ModelName#>:delete")] - [Log(Title = "<#=FileName#>删除", BusinessType = BusinessType.DELETE)] - public IActionResult Delete(int id = 0) - { - if (id <= 0) { return OutputJson(ApiResult.Error($"删除失败Id 不能为空")); } - - // 删除<#=FileName#> - var response = _<#=ServiceName#>.Delete(id); - - return SUCCESS(response); - } - } -} \ No newline at end of file diff --git a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj index 9f82d370..7b527944 100644 --- a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj +++ b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj @@ -15,6 +15,11 @@ + + + + + @@ -32,6 +37,7 @@ + @@ -52,27 +58,49 @@ Always - - TextTemplatingFileGenerator - Controller.cs + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always - + + + + + + + Always + + + Always + - - - True - True - Controller.tt - - - diff --git a/ZR.Admin.WebApi/appsettings.Development.json b/ZR.Admin.WebApi/appsettings.Development.json deleted file mode 100644 index 8d64c6da..00000000 --- a/ZR.Admin.WebApi/appsettings.Development.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "appName": "ZR Admin System", - "ConnectionStrings": { - "Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc" - }, - "urls": "http://localhost:8888", //url - "sysConfig": { - "DBCommandTimeout": 10, - "cors": "http://localhost:8887" //ÿַ - }, - "DemoMode": false, //Ƿʾģʽ - "DbKey": "", - "DbType": 0, //MySql = 0, SqlServer = 1, Sqlite = 2, Oracle = 3, PostgreSQL = 4, - "Upload": { - "UploadDirectory": "/", - "UploadUrl": "http://localhost:8888" - }, - "ALYUN_OCS": { - "REGIONID": "cn-hangzhou", - "KEY": "XX", - "SECRET": "XX" - } -} diff --git a/ZR.Admin.WebApi/appsettings.Production.json b/ZR.Admin.WebApi/appsettings.Production.json deleted file mode 100644 index 68ffe8e7..00000000 --- a/ZR.Admin.WebApi/appsettings.Production.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "appName": "ZR Admin system", - "ConnectionStrings": { - "Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc" - }, - "urls": "http://localhost:8888", - "sysConfig": { - "DBCommandTimeout": 10, - "cors": "http://localhost:8887" - }, - "DemoMode": false, //Ƿʾģʽ - "DbKey": "", - "DbType": 0, //MySql = 0, SqlServer = 1, Sqlite = 2, Oracle = 3, PostgreSQL = 4, - "Upload": { - "UploadDirectory": "/", - "UploadUrl": "http://localhost:8888" - }, - "ALYUN_OCS": { - "REGIONID": "cn-hangzhou", - "KEY": "XX", - "SECRET": "XX" - } -} diff --git a/ZR.Admin.WebApi/appsettings.json b/ZR.Admin.WebApi/appsettings.json index 8983e0fc..44168670 100644 --- a/ZR.Admin.WebApi/appsettings.json +++ b/ZR.Admin.WebApi/appsettings.json @@ -5,5 +5,33 @@ "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } + }, + "ConnectionStrings": { + "conn_zrAdmin": "server=127.0.0.1;user=zr;pwd=abc;database=admin" + }, + "conn_zrAdmin_Type": 0, //MySql = 0, SqlServer = 1 + "urls": "http://localhost:8888", //Ŀurl + "sysConfig": { + "DBCommandTimeout": 10, + "tokenExpire": 1440,//Jwt tokenʱʱ䣨֣ + "cors": "http://localhost:8887" //ַ"," + }, + "DemoMode": false, //Ƿʾģʽ + "DbKey": "", //ݿkey + "Upload": { + "UploadDirectory": "/", + "UploadUrl": "http://localhost:8888" + }, + "ALYUN_OCS": { + "REGIONID": "cn-hangzhou", + "KEY": "XX", + "SECRET": "XX" + }, + "gen": { + "conn": "server=127.0.0.1;user=zr;pwd=abc;database={database}", + "dbType": 0, //MySql = 0, SqlServer = 1 + "autoPre": true, //Զȥǰ׺ + "author": "zr", + "tablePrefix": "live_,sys_" //"ǰ׺ǰ׺öŷָ", } } diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ControllersTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ControllersTemplate.txt new file mode 100644 index 00000000..24973cea --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ControllersTemplate.txt @@ -0,0 +1,137 @@ +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using SqlSugar; +using Infrastructure; +using Infrastructure.Attribute; +using Infrastructure.Enums; +using Infrastructure.Model; +using Mapster; +using {ModelsNamespace}.Dto; +using {ModelsNamespace}.Models; +using {ServicesNamespace}.Business; +using {ApiControllerNamespace}.Extensions; +using {ApiControllerNamespace}.Filters; +using ZR.Common; + +namespace {ApiControllerNamespace}.Controllers +{ + /// + /// {FunctionName}Controller + /// + /// @author {Author} + /// @date {DateTime} + /// + [Verify] + [Route("{ModuleName}/{ModelName}")] + public class {ModelName}Controller: BaseController + { + /// + /// {FunctionName}接口 + /// + private readonly I{ModelName}Service _{ModelName}Service; + + public {ModelName}Controller(I{ModelName}Service {ModelName}Service) + { + _{ModelName}Service = {ModelName}Service; + } + + /// + /// 查询{FunctionName}列表 + /// + /// + [HttpGet("list")] + [ActionPermissionFilter(Permission = "{Permission}:list")] + public IActionResult Query{ModelName}([FromQuery] {ModelName}QueryDto parm) + { + //开始拼装查询条件 + var predicate = Expressionable.Create<{ModelName}>(); + + //TODO 搜索条件 + //predicate = predicate.And(m => m.Name.Contains(parm.Name)); + + var response = _{ModelName}Service.GetPages(predicate.ToExpression(), parm); + + return SUCCESS(response); + } + + /// + /// 查询{FunctionName}详情 + /// + /// + /// + [HttpGet("{{PrimaryKey}}")] + [ActionPermissionFilter(Permission = "{Permission}:query")] + public IActionResult Get{ModelName}({PKCsharpType} {PrimaryKey}) + { + var response = _{ModelName}Service.GetId({PrimaryKey}); + + return SUCCESS(response); + } + + /// + /// 添加{FunctionName} + /// + /// + [HttpPost] + [ActionPermissionFilter(Permission = "{Permission}:add")] + [Log(Title = "{TableDesc}添加", BusinessType = BusinessType.INSERT)] + public IActionResult Add{ModelName}([FromBody] {ModelName}Dto parm) + { + if (parm == null) + { + throw new CustomException("请求参数错误"); + } + //从 Dto 映射到 实体 + var model = parm.Adapt<{ModelName}>().ToCreate(); + + return SUCCESS(_{ModelName}Service.Add(model, it => new + { + {InsertColumn} + })); + } + + /// + /// 更新{FunctionName} + /// + /// + [HttpPut] + [ActionPermissionFilter(Permission = "{Permission}:update")] + [Log(Title = "{TableDesc}修改", BusinessType = BusinessType.UPDATE)] + public IActionResult Update{ModelName}([FromBody] {ModelName}Dto parm) + { + if (parm == null) + { + throw new CustomException("请求实体不能为空"); + } + //从 Dto 映射到 实体 + var model = parm.Adapt<{ModelName}>().ToUpdate(); + + var response = _{ModelName}Service.Update(w => w.{PrimaryKey} == model.{PrimaryKey}, it => new {ModelName}() + { + //Update 字段映射 + {UpdateColumn} + }); + + return SUCCESS(response); + } + + /// + /// 删除{FunctionName} + /// + /// + [HttpDelete("{ids}")] + [ActionPermissionFilter(Permission = "{Permission}:delete")] + [Log(Title = "{TableDesc}删除", BusinessType = BusinessType.DELETE)] + public IActionResult Delete{ModelName}(string ids) + { + int[] idsArr = Tools.SpitIntArrary(ids); + if (idsArr.Length <= 0) { return OutputJson(ApiResult.Error($"删除失败Id 不能为空")); } + + var response = _{ModelName}Service.Delete(idsArr); + + return SUCCESS(response); + } + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/IServiceTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/IServiceTemplate.txt new file mode 100644 index 00000000..b64fd985 --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/IServiceTemplate.txt @@ -0,0 +1,15 @@ +using System; +using {ModelsNamespace}.Models; + +namespace {IServicsNamespace}.Business +{ + /// + /// {FunctionName}service接口 + /// + /// @author {Author} + /// @date {DateTime} + /// + public interface I{ModelTypeName}Service: IBaseService<{ModelTypeName}> + { + } +} diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/InputDtoTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/InputDtoTemplate.txt new file mode 100644 index 00000000..ded802d1 --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/InputDtoTemplate.txt @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using {ModelsNamespace}.Dto; +using {ModelsNamespace}.Models; + +namespace {DtosNamespace}.Dto +{ + /// + /// {FunctionName}输入对象模型 + /// + public class {ModelTypeName}Dto + { +{PropertyName} + } + + /// + /// {FunctionName}查询对象模型 + /// + public class {ModelTypeName}QueryDto: PagerInfo + { +{QueryProperty} + public DateTime? BeginTime { get; set; } + public DateTime? EndTime { get; set; } + } +} diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ModelTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ModelTemplate.txt new file mode 100644 index 00000000..66bbcce6 --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ModelTemplate.txt @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace {ModelsNamespace}.Models +{ + /// + /// {FunctionName},数据实体对象 + /// + /// @author {Author} + /// @date {DateTime} + /// + [SqlSugar.SugarTable("{TableName}")] + public class {ModelTypeName} + { +{PropertyName} + } +} diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/MySqlTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/MySqlTemplate.txt new file mode 100644 index 00000000..1c36b1ee --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/MySqlTemplate.txt @@ -0,0 +1,23 @@ +-- 菜单 +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('{FunctionName}', 0, 1, '/{ModuleName}/{ModelTypeName}', '{ModuleName}/{ViewsFileName}/index', 0, 0, 'C', '0', '0', '{Permission}:list', '#', '', sysdate(), '', NULL, '{ModelTypeDesc}菜单'); + +-- 按钮父菜单id +SELECT @menuId := LAST_INSERT_ID(); + + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('查询', @menuId, 1, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:query', '', '', sysdate(), '', NULL, ''); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('新增', @menuId, 1, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:add', '', '', sysdate(), '', NULL, NULL); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('删除', @menuId, 2, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:delete', '', '', sysdate(), '', NULL, NULL); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('修改', @menuId, 3, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:update', '', '', sysdate(), '', NULL, NULL); + + +SELECT * FROM sys_menu WHERE parentId = @menuId; +SELECT * FROM sys_menu WHERE menuId = @menuId; \ No newline at end of file diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/RepositoryTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/RepositoryTemplate.txt new file mode 100644 index 00000000..db312b9a --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/RepositoryTemplate.txt @@ -0,0 +1,20 @@ +using System; +using Infrastructure.Attribute; +using {RepositoriesNamespace}.System; +using {ModelsNamespace}.Models; + +namespace {RepositoriesNamespace} +{ + /// + /// {FunctionName}仓储接口的实现 + /// + /// @author {Author} + /// @date {DateTime} + /// + [AppService(ServiceLifetime = LifeTime.Transient)] + public class {ModelTypeName}Repository : BaseRepository + { + #region 业务逻辑代码 + #endregion + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ServiceTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ServiceTemplate.txt new file mode 100644 index 00000000..c42b2ebe --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/ServiceTemplate.txt @@ -0,0 +1,34 @@ +using Infrastructure; +using Infrastructure.Attribute; +using Infrastructure.Extensions; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using ZR.Common; +using {ModelsNamespace}.Models; +using {IRepositoriesNamespace}; + +namespace {ServicesNamespace}.Business +{ + /// + /// {FunctionName}Service业务层处理 + /// + /// @author {Author} + /// @date {DateTime} + /// + [AppService(ServiceType = typeof(I{ModelTypeName}Service), ServiceLifetime = LifeTime.Transient)] + public class {ModelTypeName}Service: BaseService<{ModelTypeName}>, I{ModelTypeName}Service + { + private readonly {ModelTypeName}Repository _repository; + public {ModelTypeName}Service({ModelTypeName}Repository repository) + { + _repository = repository; + } + + #region 业务逻辑代码 + + #endregion + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/SqlTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/SqlTemplate.txt new file mode 100644 index 00000000..3cd128cd --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/SqlTemplate.txt @@ -0,0 +1,23 @@ +-- 菜单 +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('{FunctionName}', 0, 1, '/{ModuleName}/{ModelTypeName}', '{ModuleName}/{ViewsFileName}/index', 0, 0, 'C', '0', '0', '{Permission}:list', '#', '', GETDATE(), '', NULL, '{ModelTypeDesc}'); + +-- 按钮父菜单id +declare @menuId int = @@identity + + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('查询', @menuId, 1, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:query', '', '', GETDATE(), '', NULL, ''); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('新增', @menuId, 1, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:add', '', '', GETDATE(), '', NULL, NULL); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('删除', @menuId, 2, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:delete', '', '', GETDATE(), '', NULL, NULL); + +INSERT INTO sys_menu(menuName, parentId, orderNum, path, component, isFrame, isCache, menuType, visible, status, perms, icon, create_by,create_time, update_by, update_time, remark) +VALUES ('修改', @menuId, 3, '#', NULL, 0, 0, 'F', '0', '0', '{Permission}:update', '', '', GETDATE(), '', NULL, NULL); + +GO +SELECT * FROM sys_menu WHERE parentId = @menuId; +SELECT * FROM sys_menu WHERE menuId = @menuId; \ No newline at end of file diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueJsTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueJsTemplate.txt new file mode 100644 index 00000000..3d37ec0a --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueJsTemplate.txt @@ -0,0 +1,59 @@ +import request from '@/utils/request' + +/** + * {FunctionName}分页查询 + * @param {查询条件} data + */ +export function list{ModelTypeName}(query) { + return request({ + url: '{ModuleName}/{ModelTypeName}/list', + method: 'get', + params: query, + }) +} + +/** + * 新增{FunctionName} + * @param data + */ +export function add{ModelTypeName}(data) { + return request({ + url: '{ModuleName}/{ModelTypeName}', + method: 'post', + data: data, + }) +} + +/** + * 修改{FunctionName} + * @param data + */ +export function update{ModelTypeName}(data) { + return request({ + url: '{ModuleName}/{ModelTypeName}', + method: 'PUT', + data: data, + }) +} + +/** + * 获取{FunctionName}详情 + * @param {Id} {ModelTypeDesc}Id + */ +export function get{ModelTypeName}(id) { + return request({ + url: '{ModuleName}/{ModelTypeName}/' + id, + method: 'get' + }) +} + +/** + * 删除 + * @param {主键} pid + */ +export function del{ModelTypeName}(pid) { + return request({ + url: '{ModuleName}/{ModelTypeName}/' + pid, + method: 'delete' + }) +} diff --git a/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueTemplate.txt b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueTemplate.txt new file mode 100644 index 00000000..432f3fb6 --- /dev/null +++ b/ZR.Admin.WebApi/wwwroot/CodeGenTemplate/VueTemplate.txt @@ -0,0 +1,210 @@ + + + diff --git a/ZR.CodeGenerator/CodeGenerateOption.cs b/ZR.CodeGenerator/CodeGenerateOption.cs new file mode 100644 index 00000000..a3bad7f5 --- /dev/null +++ b/ZR.CodeGenerator/CodeGenerateOption.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZR.CodeGenerator +{ + public class CodeGenerateOption + { + /// + /// 项目命名空间 + /// + public string BaseNamespace { get; set; } + /// + /// 数据实体命名空间 + /// + public string ModelsNamespace { get; set; } + /// + /// 输入输出数据实体名称空间 + /// + public string DtosNamespace { get; set; } + /// + /// 仓储接口命名空间 + /// + public string IRepositoriesNamespace { get; set; } + /// + /// 仓储实现名称空间 + /// + public string RepositoriesNamespace { get; set; } + /// + /// 服务接口命名空间 + /// + public string IServicsNamespace { get; set; } + /// + /// 服务接口实现命名空间 + /// + public string ServicesNamespace { get; set; } + + /// + /// Api控制器命名空间 + /// + public string ApiControllerNamespace { get; set; } + + /// + /// 去掉的表头字符 + /// + public string ReplaceTableNameStr { get; set; } + /// + /// 要生数据的表,用“,”分割 + /// + //public string TableList { get; set; } + } +} diff --git a/ZR.CodeGenerator/CodeGenerateTemplate.cs b/ZR.CodeGenerator/CodeGenerateTemplate.cs new file mode 100644 index 00000000..d0477198 --- /dev/null +++ b/ZR.CodeGenerator/CodeGenerateTemplate.cs @@ -0,0 +1,243 @@ +using System; +using System.Linq; +using System.Text; +using ZR.Model.System.Generate; + +namespace ZR.CodeGenerator +{ + /// + /// 代码生成模板 + /// + public class CodeGenerateTemplate + { + /// + /// 生成vuejs模板,目前只有上传文件方法 + /// + /// + /// + public static string GetVueJsMethod(GenTableColumn dbFieldInfo) + { + string columnName = dbFieldInfo.ColumnName; + var sb = new StringBuilder(); + + if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD)) + { + sb.AppendLine($" //文件上传成功方法"); + sb.AppendLine($" handleUpload{dbFieldInfo.CsharpField}Success(res, file) {{"); + sb.AppendLine($" this.form.{columnName} = URL.createObjectURL(file.raw);"); + sb.AppendLine($" // this.$refs.upload.clearFiles();"); + sb.AppendLine($" }},"); + } + //有下拉框选项初列表查询数据 + if ((dbFieldInfo.HtmlType == GenConstants.HTML_SELECT || dbFieldInfo.HtmlType == GenConstants.HTML_RADIO) && !string.IsNullOrEmpty(dbFieldInfo.DictType)) + { + sb.AppendLine(@$" // {dbFieldInfo.ColumnComment}字典翻译"); + sb.AppendLine($" {columnName}Format(row, column) {{"); + sb.AppendLine(@$" return this.selectDictLabel(this.{columnName}Options, row.{columnName});"); + sb.AppendLine(@" },"); + + } + return sb.ToString(); + } + + //rules + public static string GetFormRules(GenTableColumn dbFieldInfo) + { + StringBuilder sbRule = new StringBuilder(); + //Rule 规则验证 + if (!dbFieldInfo.IsPk && !dbFieldInfo.IsIncrement && dbFieldInfo.IsRequired) + { + sbRule.AppendLine($" {dbFieldInfo.ColumnName}: [{{ required: true, message: '请输入{dbFieldInfo.ColumnComment}', trigger: \"blur\"}}],"); + } + else if (CodeGeneratorTool.IsNumber(dbFieldInfo.ColumnType) && dbFieldInfo.IsRequired) + { + sbRule.AppendLine($" {dbFieldInfo.ColumnName}: [{{ type: 'number', message: '{dbFieldInfo.ColumnName}必须为数字值', trigger: \"blur\"}}],"); + } + return sbRule.ToString(); + } + + //model 属性 + public static string GetModelTemplate(GenTableColumn dbFieldInfo) + { + StringBuilder sbModel = new StringBuilder(); + sbModel.AppendLine(" /// "); + sbModel.AppendLine($" /// 描述 :{dbFieldInfo.ColumnComment}"); + sbModel.AppendLine($" /// 空值 :{!dbFieldInfo.IsRequired}"); + sbModel.AppendLine(" /// "); + if (dbFieldInfo.IsPk || dbFieldInfo.IsIncrement) + { + sbModel.AppendLine($" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPk.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIncrement.ToString().ToLower()})]"); + } + sbModel.AppendLine($" public {dbFieldInfo.CsharpType}{(GetModelRequired(dbFieldInfo))} {dbFieldInfo.CsharpField} {{ get; set; }}"); + return sbModel.ToString(); + } + public static string GetModelRequired(GenTableColumn dbFieldInfo) + { + string str = ""; + if (!dbFieldInfo.IsRequired && (CodeGeneratorTool.IsNumber(dbFieldInfo.ColumnType) || dbFieldInfo.CsharpType == "DateTime")) + { + str = "?"; + } + + return str; + } + //DTO model + public static string GetDtoProperty(GenTableColumn dbFieldInfo) + { + string InputDtoContent = ""; + if (GenConstants.inputDtoNoField.Any(f => f.Replace("_", "").ToLower().Contains(dbFieldInfo.CsharpField.ToLower().Replace("_", "")))) + { + return InputDtoContent; + } + else if (dbFieldInfo.IsInsert || dbFieldInfo.IsEdit || dbFieldInfo.IsPk || dbFieldInfo.IsIncrement) + { + InputDtoContent += $" public {dbFieldInfo.CsharpType}{GetModelRequired(dbFieldInfo)} {dbFieldInfo.CsharpField} {{ get; set; }}\r\n"; + } + + return InputDtoContent; + } + /// + /// 查询Dto属性 + /// + /// + /// + public static string GetQueryDtoProperty(GenTableColumn dbFieldInfo) + { + string QueryDtoContent = ""; + if (dbFieldInfo.IsQuery && !GenConstants.inputDtoNoField.Any(f => f.ToLower().Contains(dbFieldInfo.CsharpField.ToLower()))) + { + QueryDtoContent += $" public {dbFieldInfo.CsharpType} {dbFieldInfo.CsharpField} {{ get; set; }}\r\n"; + } + + return QueryDtoContent; + } + + //form-item + public static string GetVueViewFormContent(GenTableColumn dbFieldInfo) + { + string columnName = dbFieldInfo.ColumnName; + string labelName = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, columnName); + string labelDisabled = dbFieldInfo.IsPk ? ":disabled=\"true\"" : ""; + string placeHolder = dbFieldInfo.IsIncrement ? "" : $"请输入{labelName}"; + StringBuilder sb = new StringBuilder(); + if (GenConstants.inputDtoNoField.Any(f => f.ToLower().Contains(dbFieldInfo.CsharpField.ToLower()))) + { + return sb.ToString(); + } + if (!dbFieldInfo.IsInsert || !dbFieldInfo.IsEdit) + { + return sb.ToString(); + } + if (dbFieldInfo.HtmlType == GenConstants.HTML_DATETIME) + { + //时间 + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + } + else if (dbFieldInfo.HtmlType == GenConstants.HTML_IMAGE_UPLOAD) + { + //图片 + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + } + else if (dbFieldInfo.HtmlType == GenConstants.HTML_RADIO) + { + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + } + else if (dbFieldInfo.HtmlType == GenConstants.HTML_TEXTAREA) + { + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + } + else if (dbFieldInfo.HtmlType == GenConstants.HTML_SELECT && !string.IsNullOrEmpty(dbFieldInfo.DictType)) + { + string value = CodeGeneratorTool.IsNumber(dbFieldInfo.CsharpType) ? "parseInt(item.dictValue)" : "item.dictValue"; + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + } + else + { + string inputNumTxt = CodeGeneratorTool.IsNumber(dbFieldInfo.CsharpType) ? ".number" : ""; + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + } + + return sb.ToString(); + } + + /// + /// 查询表单 + /// + /// + /// + public static string GetQueryFormHtml(GenTableColumn dbFieldInfo) + { + StringBuilder sb = new(); + string labelName = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, dbFieldInfo.ColumnName); + if (!dbFieldInfo.IsQuery || dbFieldInfo.HtmlType == GenConstants.HTML_FILE_UPLOAD) return sb.ToString(); + if (dbFieldInfo.HtmlType == GenConstants.HTML_DATETIME) + { + sb.AppendLine(" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + } + else + { + string inputNumTxt = CodeGeneratorTool.IsNumber(dbFieldInfo.CsharpType) ? ".number" : ""; + sb.AppendLine($" "); + sb.AppendLine($" "); + sb.AppendLine(" "); + } + + return sb.ToString(); + } + + //table-column + public static string GetTableColumn(GenTableColumn dbFieldInfo) + { + string columnName = dbFieldInfo.ColumnName; + string label = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, columnName); + string showToolTip = dbFieldInfo.CsharpType == "string" ? ":show-overflow-tooltip=\"true\"" : ""; + string formatter = !string.IsNullOrEmpty(dbFieldInfo.DictType) ? $" :formatter=\"{columnName}Format\"" : ""; + StringBuilder sb = new StringBuilder(); + if (dbFieldInfo.IsList && dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD)) + { + sb.AppendLine($" "); + sb.AppendLine(" "); + sb.AppendLine(" "); + } + //else if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_RADIO)) + //{ + // vueViewListContent += $" \r\n"; + // vueViewListContent += " \r\n"; + // vueViewListContent += " \r\n"; + //} + else if (dbFieldInfo.IsList) + { + sb.AppendLine($" "); + } + return sb.ToString(); + } + } +} diff --git a/ZR.CodeGenerator/CodeGeneratorTool.cs b/ZR.CodeGenerator/CodeGeneratorTool.cs new file mode 100644 index 00000000..f39c2dd0 --- /dev/null +++ b/ZR.CodeGenerator/CodeGeneratorTool.cs @@ -0,0 +1,551 @@ +using Infrastructure; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using ZR.CodeGenerator.Model; +using ZR.Model.System.Generate; + +namespace ZR.CodeGenerator +{ + /// + /// 代码生成器。 + /// + /// + public class CodeGeneratorTool + { + /// + /// 代码生成器配置 + /// + private static CodeGenerateOption _option = new CodeGenerateOption(); + + /// + /// 代码生成器入口方法 + /// + /// + /// + public static void Generate(GenTable dbTableInfo, GenerateDto dto) + { + _option.BaseNamespace = dbTableInfo.BaseNameSpace; + _option.DtosNamespace = _option.BaseNamespace + "Model"; + _option.ModelsNamespace = _option.BaseNamespace + "Model"; + _option.RepositoriesNamespace = _option.BaseNamespace + "Repository"; + _option.IRepositoriesNamespace = _option.BaseNamespace + "Repository"; + _option.IServicsNamespace = _option.BaseNamespace + "Service"; + _option.ServicesNamespace = _option.BaseNamespace + "Service"; + _option.ApiControllerNamespace = _option.BaseNamespace + "Admin.WebApi"; + + GenerateSingle(dbTableInfo?.Columns, dbTableInfo, dto); + } + + /// + /// 单表生成代码 + /// + /// 表字段集合 + /// 表信息 + /// + public static void GenerateSingle(List listField, GenTable tableInfo, GenerateDto dto) + { + string PKName = "id"; + string PKType = "int"; + ReplaceDto replaceDto = new(); + replaceDto.ModelTypeName = tableInfo.ClassName;//表名对应C# 实体类名 + replaceDto.TableName = tableInfo.TableName;//表名 + replaceDto.TableDesc = tableInfo.TableComment;//表说明描述 + replaceDto.Permission = $"{tableInfo.ModuleName}:{tableInfo.ClassName.ToLower()}";//权限 + replaceDto.ViewsFileName = FirstLowerCase(replaceDto.ModelTypeName); + replaceDto.Author = tableInfo.FunctionAuthor; + + StringBuilder sb1 = new StringBuilder(); + StringBuilder sb2 = new StringBuilder(); + + //循环表字段信息 + foreach (GenTableColumn dbFieldInfo in listField) + { + string columnName = dbFieldInfo.ColumnName; + + if (dbFieldInfo.IsInsert || dbFieldInfo.IsEdit) + { + replaceDto.VueViewFormResetHtml += $" {columnName}: undefined,\r\n"; + } + if (dbFieldInfo.IsPk || dbFieldInfo.IsIncrement) + { + PKName = dbFieldInfo.CsharpField; + PKType = dbFieldInfo.CsharpType; + } + //编辑字段 + if (dbFieldInfo.IsEdit) + { + replaceDto.UpdateColumn += $"{dbFieldInfo.CsharpField} = model.{dbFieldInfo.CsharpField}, "; + } + //新增字段 + if (dbFieldInfo.IsInsert) + { + replaceDto.InsertColumn += $"it.{dbFieldInfo.CsharpField}, "; + } + //TODO 查询 + //if (dbFieldInfo.IsQuery) + //{ + // replaceDto.Querycondition += $"predicate = predicate.And(m => m.{dbFieldInfo.CsharpField}.Contains(parm.Name));"; + //} + + if ((dbFieldInfo.HtmlType == GenConstants.HTML_SELECT || dbFieldInfo.HtmlType == GenConstants.HTML_RADIO) && !string.IsNullOrEmpty(dbFieldInfo.DictType)) + { + sb1.AppendLine($" // {dbFieldInfo.ColumnComment}选项列表"); + sb1.AppendLine($" {FirstLowerCase(dbFieldInfo.CsharpField)}Options: [],"); + + sb2.AppendLine($" this.getDicts(\"{dbFieldInfo.DictType}\").then((response) => {{"); + sb2.AppendLine($" this.{FirstLowerCase(dbFieldInfo.CsharpField)}Options = response.data;"); + sb2.AppendLine(" })"); + } + + replaceDto.QueryProperty += CodeGenerateTemplate.GetQueryDtoProperty(dbFieldInfo); + replaceDto.ModelProperty += CodeGenerateTemplate.GetModelTemplate(dbFieldInfo); + replaceDto.VueViewFormHtml += CodeGenerateTemplate.GetVueViewFormContent(dbFieldInfo); + replaceDto.VueJsMethod += CodeGenerateTemplate.GetVueJsMethod(dbFieldInfo); + replaceDto.VueViewListHtml += CodeGenerateTemplate.GetTableColumn(dbFieldInfo); + replaceDto.VueViewEditFormRuleContent += CodeGenerateTemplate.GetFormRules(dbFieldInfo); + replaceDto.InputDtoProperty += CodeGenerateTemplate.GetDtoProperty(dbFieldInfo); + replaceDto.VueQueryFormHtml += CodeGenerateTemplate.GetQueryFormHtml(dbFieldInfo); + } + replaceDto.VueDataContent = sb1.ToString(); + replaceDto.MountedMethod = sb2.ToString(); + + replaceDto.PKName = PKName; + replaceDto.PKType = PKType; + + if (dto.GenCodeFiles.Contains(1)) + { + GenerateModels(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(2)) + { + GenerateInputDto(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(3)) + { + GenerateRepository(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(4)) + { + GenerateIService(replaceDto, dto); + GenerateService(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(5)) + { + GenerateControllers(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(6)) + { + GenerateVueViews(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(7)) + { + GenerateVueJs(replaceDto, dto); + } + if (dto.GenCodeFiles.Contains(8)) + { + GenerateSql(replaceDto, dto); + } + if (dto.IsPreview == 1) + { + return; + } + foreach (var item in dto.GenCodes) + { + FileHelper.WriteAndSave(item.Path, item.Content); + } + } + + #region 生成Model + + /// + /// 生成实体类Model + /// + /// + /// 替换实体 + private static void GenerateModels(ReplaceDto replaceDto, GenerateDto generateDto) + { + // ../ZR.Model/Models/User.cs + var fullPath = Path.Combine(generateDto.GenCodePath, _option.ModelsNamespace, "Models", replaceDto.ModelTypeName + ".cs"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("ModelTemplate.txt") + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{KeyTypeName}", replaceDto.PKName) + .Replace("{PropertyName}", replaceDto.ModelProperty) + .Replace("{TableName}", replaceDto.TableName) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(1, "实体类", fullPath, content)); + } + + /// + /// 生成表单提交输入参数Dto + /// + /// + /// 替换实体 + private static void GenerateInputDto(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, _option.ModelsNamespace, "Dto", $"{replaceDto.ModelTypeName}Dto.cs"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("InputDtoTemplate.txt") + .Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{PropertyName}", replaceDto.InputDtoProperty) + .Replace("{QueryProperty}", replaceDto.QueryProperty) + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(2, "数据传输实体类", fullPath, content)); + } + #endregion + + #region 生成Repository + + /// + /// 生成Repository层代码文件 + /// + /// + /// 替换实体 + private static void GenerateRepository(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, _option.RepositoriesNamespace, "Repositories", $"{replaceDto.ModelTypeName}Repository.cs"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("RepositoryTemplate.txt") + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{RepositoriesNamespace}", _option.RepositoriesNamespace) + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{TableName}", replaceDto.TableName) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(3, "仓储层", fullPath, content)); + } + + #endregion + + #region 生成Service + /// + /// 生成IService文件 + /// + /// + /// 替换实体 + private static void GenerateIService(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, _option.IServicsNamespace, "Business", "IBusService", $"I{replaceDto.ModelTypeName}Service.cs"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + var content = FileHelper.ReadTemplate("IServiceTemplate.txt") + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("{IServicsNamespace}", _option.IServicsNamespace) + .Replace("{RepositoriesNamespace}", _option.RepositoriesNamespace) + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(4, "接口层", fullPath, content)); + } + + /// + /// 生成Service文件 + /// + private static void GenerateService(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, _option.ServicesNamespace, "Business", $"{replaceDto.ModelTypeName}Service.cs"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("ServiceTemplate.txt") + .Replace("{IRepositoriesNamespace}", _option.IRepositoriesNamespace) + .Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("{IServicsNamespace}", _option.IServicsNamespace) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{ServicesNamespace}", _option.ServicesNamespace) + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(4, "服务层", fullPath, content)); + } + + #endregion + + #region 生成Controller + /// + /// 生成控制器ApiControllers文件 + /// + private static void GenerateControllers(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, _option.ApiControllerNamespace, "Controllers", generateDto.GenTable.ModuleName, $"{replaceDto.ModelTypeName}Controller.cs"); + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("ControllersTemplate.txt") + .Replace("{ApiControllerNamespace}", _option.ApiControllerNamespace) + .Replace("{ServicesNamespace}", _option.ServicesNamespace) + .Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{ModelName}", replaceDto.ModelTypeName) + .Replace("{Permission}", replaceDto.Permission) + .Replace("{PrimaryKey}", replaceDto.PKName) + .Replace("{UpdateColumn}", replaceDto.UpdateColumn) + .Replace("{InsertColumn}", replaceDto.InsertColumn) + .Replace("{ModuleName}", generateDto.GenTable.ModuleName) + .Replace("{PKCsharpType}", replaceDto.PKType) + .Replace("{Author}", replaceDto.Author) + .Replace("{DateTime}", replaceDto.AddTime); + + generateDto.GenCodes.Add(new GenCode(5, "控制器", fullPath, content)); + } + #endregion + + #region 生成Vue页面 & api + /// + /// 6、生成Vue页面 + private static void GenerateVueViews(ReplaceDto replaceDto, GenerateDto generateDto) + { + var fullPath = Path.Combine(generateDto.GenCodePath, "ZR.Vue", "src", "views", generateDto.GenTable.ModuleName, replaceDto.ViewsFileName, "index.vue"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("VueTemplate.txt") + .Replace("{fileClassName}", replaceDto.ViewsFileName) + .Replace("{VueViewListContent}", replaceDto.VueViewListHtml)//查询 table列 + .Replace("{VueViewFormContent}", replaceDto.VueViewFormHtml)//添加、修改表单 + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{Permission}", replaceDto.Permission) + .Replace("{VueViewFormResetHtml}", replaceDto.VueViewFormResetHtml) + .Replace("{vueJsMethod}", replaceDto.VueJsMethod) + .Replace("{vueQueryFormHtml}", replaceDto.VueQueryFormHtml) + .Replace("{VueDataContent}", replaceDto.VueDataContent) + .Replace("{PrimaryKey}", FirstLowerCase(replaceDto.PKName)) + .Replace("{MountedMethod}", replaceDto.MountedMethod) + .Replace("{VueViewEditFormRuleContent}", replaceDto.VueViewEditFormRuleContent);//添加、修改表单验证规则 + + generateDto.GenCodes.Add(new GenCode(6, "index.vue", fullPath, content)); + } + /// + /// 7、生成vue页面api + /// + /// + /// + /// + public static void GenerateVueJs(ReplaceDto replaceDto, GenerateDto generateDto) + { + string fullPath = Path.Combine(generateDto.GenCodePath, "ZR.Vue", "src", "api", replaceDto.ViewsFileName + ".js"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + + var content = FileHelper.ReadTemplate("VueJsTemplate.txt") + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName) + .Replace("{ModuleName}", generateDto.GenTable.ModuleName); + + generateDto.GenCodes.Add(new GenCode(7, "api.js", fullPath, content)); + } + + #endregion + + #region 8、生成SQL + + public static void GenerateSql(ReplaceDto replaceDto, GenerateDto generateDto) + { + string fullPath = Path.Combine(generateDto.GenCodePath, replaceDto.ViewsFileName + ".sql"); + + if (File.Exists(fullPath) && !generateDto.Coverd) + return; + var tempName = ""; + switch (generateDto.DbType) + { + case 0: + tempName = "MySqlTemplate"; + break; + case 1: + tempName = "SqlTemplate"; + break; + default: + break; + } + var content = FileHelper.ReadTemplate($"{tempName}.txt") + .Replace("{ModelTypeName}", replaceDto.ModelTypeName) + .Replace("{Permission}", replaceDto.Permission) + .Replace("{ModelTypeDesc}", replaceDto.TableDesc) + .Replace("{ModuleName}", generateDto.GenTable.ModuleName) + .Replace("{ViewsFileName}", replaceDto.ViewsFileName) + .Replace("{FunctionName}", generateDto.GenTable.FunctionName); + + generateDto.GenCodes.Add(new GenCode(8, "sql", fullPath, content)); + } + + #endregion + + #region 帮助方法 + + /// + /// 如果有前缀替换将前缀替换成空,替换下划线"_"为空再将首字母大写 + /// 表名转换成C#类名 + /// + /// + /// + public static string GetClassName(string tableName) + { + bool autoRemovePre = ConfigUtils.Instance.GetAppConfig(GenConstants.Gen_autoPre, false); + string tablePrefix = ConfigUtils.Instance.GetAppConfig(GenConstants.Gen_tablePrefix); + + if (!string.IsNullOrEmpty(tablePrefix) && autoRemovePre) + { + string[] searcList = tablePrefix.Split(",", StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < searcList.Length; i++) + { + if (!string.IsNullOrEmpty(searcList[i].ToString())) + { + tableName = tableName.Replace(searcList[i], ""); + } + } + } + return tableName.Substring(0, 1).ToUpper() + tableName[1..].Replace("_", ""); + } + + /// + /// 首字母转小写,输出前端 + /// + /// + /// + public static string FirstLowerCase(string str) + { + return string.IsNullOrEmpty(str) ? str : str.Substring(0, 1).ToLower() + str[1..]; + } + + /// + /// 获取前端标签名 + /// + /// + /// + /// + public static string GetLabelName(string columnDescription, string columnName) + { + return string.IsNullOrEmpty(columnDescription) ? columnName : columnDescription; + } + #endregion + + /// + /// 初始化列属性字段数据 + /// + /// + /// + public static List InitGenTableColumn(GenTable genTable, List dbColumnInfos) + { + List genTableColumns = new(); + foreach (var column in dbColumnInfos) + { + GenTableColumn genTableColumn = new() + { + ColumnName = FirstLowerCase(column.DbColumnName), + ColumnComment = column.ColumnDescription, + IsPk = column.IsPrimarykey, + ColumnType = column.DataType, + TableId = genTable.TableId, + TableName = genTable.TableName, + CsharpType = GetCSharpDatatype(column.DataType), + CsharpField = column.DbColumnName.Substring(0, 1).ToUpper() + column.DbColumnName[1..], + IsRequired = !column.IsNullable, + IsIncrement = column.IsIdentity, + Create_by = genTable.Create_by, + Create_time = DateTime.Now, + IsInsert = !column.IsIdentity,//非自增字段都需要插入 + IsQuery = false, + HtmlType = GenConstants.HTML_INPUT + }; + + if (GenConstants.imageFiled.Any(f => column.DbColumnName.ToLower().Contains(f.ToLower()))) + { + genTableColumn.HtmlType = GenConstants.HTML_IMAGE_UPLOAD; + } + else if (GenConstants.COLUMNTYPE_TIME.Any(f => genTableColumn.CsharpType.ToLower().Contains(f.ToLower()))) + { + genTableColumn.HtmlType = GenConstants.HTML_DATETIME; + } + else if (GenConstants.radioFiled.Any(f => column.DbColumnName.EndsWith(f, StringComparison.OrdinalIgnoreCase)) || + GenConstants.radioFiled.Any(f => column.DbColumnName.StartsWith(f, StringComparison.OrdinalIgnoreCase))) + { + genTableColumn.HtmlType = GenConstants.HTML_RADIO; + } + else if (GenConstants.selectFiled.Any(f => column.DbColumnName == f) || + GenConstants.selectFiled.Any(f => column.DbColumnName.EndsWith(f, StringComparison.OrdinalIgnoreCase))) + { + genTableColumn.HtmlType = GenConstants.HTML_SELECT; + } + else if (column.Length > 500) + { + genTableColumn.HtmlType = GenConstants.HTML_TEXTAREA; + } + //编辑字段 + if (GenConstants.COLUMNNAME_NOT_EDIT.Any(f => column.DbColumnName.Contains(f)) && !column.IsIdentity && !column.IsPrimarykey) + { + genTableColumn.IsEdit = true; + } + //列表字段 + if (!GenConstants.COLUMNNAME_NOT_LIST.Any(f => column.DbColumnName.Contains(f) && !column.IsPrimarykey)) + { + genTableColumn.IsList = true; + } + + genTableColumns.Add(genTableColumn); + } + return genTableColumns; + } + + /// + /// 获取C# 类型 + /// + /// + /// + public static string GetCSharpDatatype(string sDatatype) + { + sDatatype = sDatatype.ToLower(); + string sTempDatatype = sDatatype switch + { + "int" or "number" or "integer" or "smallint" => "int", + "bigint" => "long", + "tinyint" => "byte", + "numeric" or "real" or "float" => "float", + "decimal" or "numer(8,2)" => "decimal", + "bit" => "bool", + "date" or "datetime" or "datetime2" or "smalldatetime" => "DateTime", + "money" or "smallmoney" => "double", + _ => "string", + }; + return sTempDatatype; + } + + public static bool IsNumber(string tableDataType) + { + string[] arr = new string[] { "int", "long" }; + return arr.Any(f => f.Contains(GetCSharpDatatype(tableDataType))); + } + } +} diff --git a/ZR.CodeGenerator/DbProvider.cs b/ZR.CodeGenerator/DbProvider.cs new file mode 100644 index 00000000..71982e1f --- /dev/null +++ b/ZR.CodeGenerator/DbProvider.cs @@ -0,0 +1,47 @@ +using Infrastructure; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZR.CodeGenerator +{ + /// + /// 代码生成数据库连接 + /// + public class DbProvider + { + protected static SqlSugarScope CodeDb; + + /// + /// 获取动态连接字符串 + /// + /// 数据库名 + /// + public SqlSugarScope GetSugarDbContext(string dbName = "") + { + string connStr = ConfigUtils.Instance.GetConfig(GenConstants.Gen_conn); + int dbType = ConfigUtils.Instance.GetAppConfig(GenConstants.Gen_conn_dbType, 0); + connStr = connStr.Replace("{database}", dbName); + if (string.IsNullOrEmpty(dbName)) + { + connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin); + dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.ConnDbType); + } + var db = new SqlSugarScope(new List() + { + new ConnectionConfig(){ + ConnectionString = connStr, + DbType = (DbType)dbType, + IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样 + InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息 + }, + }); + + CodeDb = db; + return db; + } + } +} diff --git a/ZR.CodeGenerator/FileHelper.cs b/ZR.CodeGenerator/FileHelper.cs new file mode 100644 index 00000000..6d1e32d5 --- /dev/null +++ b/ZR.CodeGenerator/FileHelper.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using ZR.CodeGenerator.Model; + +namespace ZR.CodeGenerator +{ + public class FileHelper + { + /// + /// 创建文件夹 + /// + /// + /// + public static bool CreateDirectory(string path) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + path = path.Replace("\\", "/").Replace("//", "/"); + } + try + { + if (!Directory.Exists(path)) + { + DirectoryInfo info = Directory.CreateDirectory(path); + Console.WriteLine("不存在创建文件夹" + info); + } + } + catch (Exception ex) + { + Console.WriteLine($"创建文件夹出错了,{ex.Message}"); + return false; + } + return true; + } + + /// + /// 写文件 + /// + /// 完整路径带扩展名的 + /// + public static void WriteAndSave(string path, string content) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + path = path.Replace("\\", "/").Replace("//", "/"); + } + if (!Directory.Exists(Path.GetDirectoryName(path))) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + } + Console.WriteLine("写入文件:" + path); + try + { + //实例化一个文件流--->与写入文件相关联 + using var fs = new FileStream(path, FileMode.Create, FileAccess.Write); + //实例化一个StreamWriter-->与fs相关联 + using var sw = new StreamWriter(fs); + //开始写入 + sw.Write(content); + //清空缓冲区 + sw.Flush(); + //关闭流 + sw.Close(); + fs.Close(); + } + catch (Exception ex) + { + Console.WriteLine("写入文件出错了:" + ex.Message); + } + } + + + /// + /// 从代码模板中读取内容 + /// + /// 模板名称,应包括文件扩展名称。比如:template.txt + /// + public static string ReadTemplate(string templateName) + { + string path = Environment.CurrentDirectory; + string fullName = $"{path}/wwwroot/CodeGenTemplate/{templateName}"; + + Console.WriteLine("开始读取模板=" + fullName); + string temp = fullName; + string str = ""; + if (!File.Exists(temp)) + { + return str; + } + StreamReader sr = null; + try + { + sr = new StreamReader(temp); + str = sr.ReadToEnd(); // 读取文件 + } + catch (Exception ex) + { + Console.WriteLine($"读取模板出错了{ex.Message}"); + } + sr?.Close(); + sr?.Dispose(); + return str; + } + + + /// + /// 压缩代码 + /// + /// + /// + public static string ZipGenCode(GenerateDto dto) + { + try + { + //生成压缩包 + string zipReturnFileName = dto.GenTable.BaseNameSpace + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"; + + CreateDirectory(dto.GenCodePath); + string zipFileName = Path.Combine(dto.ZipPath, zipReturnFileName); + if (File.Exists(zipFileName)) + { + File.Delete(zipFileName); + } + + ZipFile.CreateFromDirectory(dto.GenCodePath, zipFileName); + DeleteDirectory(dto.GenCodePath); + dto.ZipFileName = zipReturnFileName; + return zipReturnFileName; + } + catch (Exception ex) + { + Console.WriteLine("压缩文件出错。" + ex.Message); + return ""; + } + } + + /// + /// 删除指定目录下的所有文件及文件夹(保留目录) + /// + /// 文件目录 + public static void DeleteDirectory(string file) + { + try + { + //判断文件夹是否还存在 + if (Directory.Exists(file)) + { + DirectoryInfo fileInfo = new DirectoryInfo(file); + //去除文件夹的只读属性 + fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory; + foreach (string f in Directory.GetFileSystemEntries(file)) + { + if (File.Exists(f)) + { + //去除文件的只读属性 + File.SetAttributes(file, FileAttributes.Normal); + //如果有子文件删除文件 + File.Delete(f); + } + else + { + //循环递归删除子文件夹 + DeleteDirectory(f); + } + } + //删除空文件夹 + Directory.Delete(file); + } + + } + catch (Exception ex) // 异常处理 + { + //Log4NetHelper.Error("代码生成异常", ex); + } + } + + } +} diff --git a/ZR.CodeGenerator/GenConstants.cs b/ZR.CodeGenerator/GenConstants.cs new file mode 100644 index 00000000..7c24f721 --- /dev/null +++ b/ZR.CodeGenerator/GenConstants.cs @@ -0,0 +1,136 @@ + + +namespace ZR.CodeGenerator +{ + /// + /// 代码生成常量 + /// + public class GenConstants + { + public static string Gen_conn = "gen:conn"; + public static string Gen_conn_dbType = "gen:dbType"; + public static string Gen_author = "gen:author"; + public static string Gen_autoPre = "gen:autoPre"; + public static string Gen_tablePrefix = "gen:tablePrefix"; + + /// + /// InputDto输入实体是不包含字段 + /// + public static readonly string[] inputDtoNoField = new string[] { "createTime", "updateTime", "addtime", "create_time", "update_time" }; + /// + /// 图片字段 + /// + public static readonly string[] imageFiled = new string[] { "icon", "img", "image", "url", "pic", "photo", "avatar" }; + /// + /// 下拉框字段 + /// + public static readonly string[] selectFiled = new string[] { "status", "type", "state", "sex", "gender" }; + /// + /// 单选按钮字段 + /// + public static readonly string[] radioFiled = new string[] { "status", "state", "is"}; + + + /** 单表(增删改查) */ + public static string TPL_CRUD = "crud"; + + /** 树表(增删改查) */ + public static string TPL_TREE = "tree"; + + /** 主子表(增删改查) */ + public static string TPL_SUB = "sub"; + + /** 树编码字段 */ + public static string TREE_CODE = "treeCode"; + + /** 树父编码字段 */ + public static string TREE_PARENT_CODE = "treeParentCode"; + + /** 树名称字段 */ + public static string TREE_NAME = "treeName"; + + /** 上级菜单ID字段 */ + public static string PARENT_MENU_ID = "parentMenuId"; + + /** 上级菜单名称字段 */ + public static string PARENT_MENU_NAME = "parentMenuName"; + + /** 数据库字符串类型 */ + public static string[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" }; + + /** 数据库文本类型 */ + public static string[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" }; + + /** 数据库时间类型 */ + public static string[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" }; + + /** 数据库数字类型 */ + public static string[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer", + "bit", "bigint", "float", "double", "decimal" }; + + /** 页面不需要编辑字段 */ + public static string[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "delFlag" }; + + /** 页面不需要显示的列表字段 */ + public static string[] COLUMNNAME_NOT_LIST = { "create_by", "create_time", "delFlag", "update_by", + "update_time" , "password"}; + + /** 页面不需要查询字段 */ + public static string[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "delFlag", "update_by", + "update_time", "remark" }; + + /** Entity基类字段 */ + public static string[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" }; + + /** Tree基类字段 */ + public static string[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors", "children" }; + + /** 文本框 */ + public static string HTML_INPUT = "input"; + + /** 文本域 */ + public static string HTML_TEXTAREA = "textarea"; + + /** 下拉框 */ + public static string HTML_SELECT = "select"; + + /** 单选框 */ + public static string HTML_RADIO = "radio"; + + /** 复选框 */ + public static string HTML_CHECKBOX = "checkbox"; + + /** 日期控件 */ + public static string HTML_DATETIME = "datetime"; + + /** 图片上传控件 */ + public static string HTML_IMAGE_UPLOAD = "imageUpload"; + + /** 文件上传控件 */ + public static string HTML_FILE_UPLOAD = "fileUpload"; + + /** 富文本控件 */ + public static string HTML_EDITOR = "editor"; + + /** 字符串类型 */ + public static string TYPE_STRING = "string"; + + /** 整型 */ + public static string TYPE_INT = "int"; + + /** 长整型 */ + public static string TYPE_LONG = "long"; + + /** 浮点型 */ + public static string TYPE_DOUBLE = "Double"; + + /** 时间类型 */ + public static string TYPE_DATE = "Date"; + + /** 模糊查询 */ + public static string QUERY_LIKE = "LIKE"; + + /** 需要 */ + public static string REQUIRE = "1"; + } +} \ No newline at end of file diff --git a/ZR.CodeGenerator/Model/GenerateDto.cs b/ZR.CodeGenerator/Model/GenerateDto.cs new file mode 100644 index 00000000..9ce7d077 --- /dev/null +++ b/ZR.CodeGenerator/Model/GenerateDto.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ZR.Model.System.Generate; + +namespace ZR.CodeGenerator.Model +{ + public class GenerateDto + { + public long TableId { get; set; } + //public string[] QueryColumn { get; set; } + /// + /// 是否预览代码 + /// + public int IsPreview { get; set; } + /// + /// 要生成的文件 + /// + public int[] GenCodeFiles { get; set; } + /// + /// 如果目标文件存在,是否覆盖。默认为false + /// + public bool Coverd { get; set; } = true; + /// + /// 生成代码的数据库类型 0、mysql 1、sqlserver + /// + public int DbType { get; set; } + public GenTable GenTable { get; set; } + #region 存储路径 + /// + /// 代码模板预览存储路径存放 + /// + public List GenCodes { get; set; } = new List(); + /// + /// 代码生成路径 + /// + public string GenCodePath { get; set; } + /// + /// 代码生成压缩包路径 + /// + public string ZipPath { get; set; } + /// + /// 代码生成压缩包名称 + /// + public string ZipFileName { get; set; } + #endregion + } + + public class GenCode + { + public int Type { get; set; } + public string Title { get; set; } + public string Path { get; set; } + public string Content { get; set; } + + public GenCode(int type, string title, string path, string content) + { + Type = type; + Title = title; + Path = path; + Content = content; + } + } +} diff --git a/ZR.CodeGenerator/Model/ReplaceDto.cs b/ZR.CodeGenerator/Model/ReplaceDto.cs new file mode 100644 index 00000000..425e63a5 --- /dev/null +++ b/ZR.CodeGenerator/Model/ReplaceDto.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZR.CodeGenerator.Model +{ + public class ReplaceDto + { + //public string ModelsNamespace { get; set; } + //public string DtosNamespace { get; set; } + //public string RepositoriesNamespace { get; set; } + //public string IRepositoriesNamespace { get; set; } + //public string IServicsNamespace { get; set; } + //public string ServicesNamespace { get; set; } + + /// + /// 主键字段 + /// + public string PKName { get; set; } + /// + /// 主键类型 + /// + public string PKType { get; set; } + /// + /// 控制器权限 + /// + public string Permission { get; set; } + /// + /// C#类名 + /// + public string ModelTypeName { get; set; } + /// + /// 数据库表名 + /// + public string TableName { get; set; } + /// + /// 表描述、说明 + /// + public string TableDesc { get; set; } + /// + /// 修改列 + /// + public string UpdateColumn { get; set; } + /// + /// 插入列 + /// + public string InsertColumn { get; set; } + + + /// + /// 实体属性模板 + /// + public string ModelProperty { get; set; } + /// + /// 输入Dto模板 + /// + public string InputDtoProperty { get; set; } + + //vue、api + public string VueViewFormResetHtml { get; set; } + /// + /// 前端列表查询html + /// + public string VueViewListHtml { get; set; } + /// + /// 前端添加、编辑表格html + /// + public string VueViewFormHtml { get; set; } + /// + /// 前端搜索表单html + /// + public string VueQueryFormHtml { get; set; } + /// + /// vue js方法 + /// + public string VueJsMethod { get; set; } + /// + /// vue 添加、编辑表单规则 + /// + public string VueViewEditFormRuleContent { get; set; } + /// + /// 查询条件 + /// + public string QueryCondition { get; set; } + /// + /// 查询属性 + /// + public string QueryProperty { get; set; } + /// + /// vue data内容 + /// + public string VueDataContent { get; set; } + /// + /// vue mounted 方法 + /// + public string MountedMethod { get; set; } + /// + /// views、js文件名 + /// + public string ViewsFileName { get; set; } + public string Author { get; set; } + public string AddTime { get; set; } = DateTime.Now.ToString("yyyy-MM-dd"); + } +} diff --git a/ZR.CodeGenerator/Service/CodeGeneraterService.cs b/ZR.CodeGenerator/Service/CodeGeneraterService.cs new file mode 100644 index 00000000..1e5612d9 --- /dev/null +++ b/ZR.CodeGenerator/Service/CodeGeneraterService.cs @@ -0,0 +1,69 @@ +using SqlSugar; +using System.Collections.Generic; +using System.Linq; +using ZR.Model; + +namespace ZR.CodeGenerator.Service +{ + public class CodeGeneraterService : DbProvider + { + /// + /// 获取所有数据库名 + /// + /// + public List GetAllDataBases() + { + var db = GetSugarDbContext(); + var templist = db.DbMaintenance.GetDataBaseList(db.ScopedContext); + + return templist; + } + + /// + /// 获取所有表 + /// + /// + /// + /// + /// + public List GetAllTables(string dbName, string tableName, PagerInfo pager) + { + var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); + if (!string.IsNullOrEmpty(tableName)) + { + tableList = tableList.Where(f => f.Name.ToLower().Contains(tableName.ToLower())).ToList(); + } + tableList = tableList.Where(f => !new string[] { "gen", "sys_" }.Contains(f.Name)).ToList(); + pager.TotalNum = tableList.Count; + return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList(); + } + + /// + /// 获取单表数据 + /// + /// + /// + /// + public DbTableInfo GetTableInfo(string dbName, string tableName) + { + var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); + if (!string.IsNullOrEmpty(tableName)) + { + return tableList.Where(f => f.Name.ToLower() == (tableName.ToLower())).FirstOrDefault(); + } + + return null; + } + /// + /// 获取列信息 + /// + /// + /// + /// + public List GetColumnInfo(string dbName, string tableName) + { + return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true); + } + + } +} diff --git a/ZR.CodeGenerator/TableMappingHelper.cs b/ZR.CodeGenerator/TableMappingHelper.cs deleted file mode 100644 index e0c9daa1..00000000 --- a/ZR.CodeGenerator/TableMappingHelper.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Infrastructure.Extensions; -using ZR.Common.Extension; - -namespace ZR.CodeGenerator.CodeGenerator -{ - public class TableMappingHelper - { - /// - /// UserService转成userService - /// - /// - /// - public static string FirstLetterLowercase(string instanceName) - { - instanceName = instanceName.ParseToString(); - if (!instanceName.IsEmpty()) - { - StringBuilder sb = new StringBuilder(); - sb.Append(instanceName[0].ToString().ToLower() + instanceName.Substring(1)); - return sb.ToString(); - } - else - { - return instanceName; - } - } - - /// - /// sys_menu_authorize变成MenuAuthorize - /// - public static string GetClassNamePrefix(string tableName) - { - string[] arr = tableName.Split('_'); - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < arr.Length; i++) - { - sb.Append(arr[i][0].ToString().ToUpper() + arr[i].Substring(1)); - } - return sb.ToString(); - } - - public static string GetPropertyDatatype(string sDatatype) - { - string sTempDatatype = string.Empty; - sDatatype = sDatatype.ToLower(); - switch (sDatatype) - { - case "int": - case "number": - case "integer": - case "smallint": - sTempDatatype = "int?"; - break; - - case "bigint": - sTempDatatype = "long?"; - break; - - case "tinyint": - sTempDatatype = "byte?"; - break; - - case "numeric": - case "real": - sTempDatatype = "Single?"; - break; - - case "float": - sTempDatatype = "float?"; - break; - - case "decimal": - case "numer(8,2)": - sTempDatatype = "decimal?"; - break; - - case "bit": - sTempDatatype = "bool?"; - break; - - case "date": - case "datetime": - case "datetime2": - case "smalldatetime": - sTempDatatype = "DateTime?"; - break; - - case "money": - case "smallmoney": - sTempDatatype = "double?"; - break; - - case "char": - case "varchar": - case "nvarchar2": - case "text": - case "nchar": - case "nvarchar": - case "ntext": - default: - sTempDatatype = "string"; - break; - } - return sTempDatatype; - } - } -} diff --git a/ZR.CodeGenerator/ZR.CodeGenerator.csproj b/ZR.CodeGenerator/ZR.CodeGenerator.csproj index 948f8053..cbcf9692 100644 --- a/ZR.CodeGenerator/ZR.CodeGenerator.csproj +++ b/ZR.CodeGenerator/ZR.CodeGenerator.csproj @@ -11,8 +11,13 @@ - - + + + + + + PreserveNewest + diff --git a/ZR.Model/Models/README.txt b/ZR.Model/Models/README.txt new file mode 100644 index 00000000..39e9872e --- /dev/null +++ b/ZR.Model/Models/README.txt @@ -0,0 +1 @@ +此文件夹用于存放业务代码数据库实体类 \ No newline at end of file diff --git a/ZR.Model/Dto/System/ArticleDto.cs b/ZR.Model/System/Dto/ArticleDto.cs similarity index 91% rename from ZR.Model/Dto/System/ArticleDto.cs rename to ZR.Model/System/Dto/ArticleDto.cs index ff5a3c0f..368b1ea2 100644 --- a/ZR.Model/Dto/System/ArticleDto.cs +++ b/ZR.Model/System/Dto/ArticleDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class ArticleQueryDto: PagerInfo { diff --git a/ZR.Model/System/Dto/GenTableDto.cs b/ZR.Model/System/Dto/GenTableDto.cs new file mode 100644 index 00000000..7820d7bc --- /dev/null +++ b/ZR.Model/System/Dto/GenTableDto.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Text; +using ZR.Model.System.Generate; + +namespace ZR.Model.System.Dto +{ + public class GenTableDto + { + public int TableId { get; set; } + public string TableName { get; set; } + public string TableComment { get; set; } + public string SubTableName { get; set; } + public string SubTableFkName { get; set; } + public string ClassName { get; set; } + public string TplCategory { get; set; } + public string BaseNameSpace { get; set; } + public string ModuleName { get; set; } + public string BusinessName { get; set; } + public string FunctionName { get; set; } + public string FunctionAuthor { get; set; } + public string GenType { get; set; } + public string Options { get; set; } + public List Columns { get; set; } + } + + public class GenTableColumnDto + { + public int ColumnId { get; set; } + public int TableId { get; set; } + public string ColumnComment { get; set; } + public string CsharpType { get; set; } + public string CsharpField { get; set; } + public bool IsInsert { get; set; } + public bool IsEdit { get; set; } + public bool IsList { get; set; } + public bool IsQuery { get; set; } + public bool IsRequired { get; set; } + /// + /// 显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件) + /// + public string HtmlType { get; set; } + /// + /// 查询类型(等于、不等于、大于、小于、范围) + /// + public string QueryType { get; set; } = "EQ"; + public int Sort { get; set; } + /// + /// 字典类型 + /// + public string DictType { get; set; } + } +} diff --git a/ZR.Model/Dto/System/LoginBodyDto.cs b/ZR.Model/System/Dto/LoginBodyDto.cs similarity index 95% rename from ZR.Model/Dto/System/LoginBodyDto.cs rename to ZR.Model/System/Dto/LoginBodyDto.cs index cf0fa0bd..6bb22461 100644 --- a/ZR.Model/Dto/System/LoginBodyDto.cs +++ b/ZR.Model/System/Dto/LoginBodyDto.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class LoginBodyDto { diff --git a/ZR.Model/Dto/System/MenuDto.cs b/ZR.Model/System/Dto/MenuDto.cs similarity index 96% rename from ZR.Model/Dto/System/MenuDto.cs rename to ZR.Model/System/Dto/MenuDto.cs index ac241f75..0fa56718 100644 --- a/ZR.Model/Dto/System/MenuDto.cs +++ b/ZR.Model/System/Dto/MenuDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class MenuDto { diff --git a/ZR.Model/Dto/System/RoleUsersCreateDto.cs b/ZR.Model/System/Dto/RoleUsersCreateDto.cs similarity index 95% rename from ZR.Model/Dto/System/RoleUsersCreateDto.cs rename to ZR.Model/System/Dto/RoleUsersCreateDto.cs index 2ba0cfb7..456621a2 100644 --- a/ZR.Model/Dto/System/RoleUsersCreateDto.cs +++ b/ZR.Model/System/Dto/RoleUsersCreateDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class RoleUsersCreateDto { diff --git a/ZR.Model/Dto/System/SysFileQueryDto.cs b/ZR.Model/System/Dto/SysFileQueryDto.cs similarity index 81% rename from ZR.Model/Dto/System/SysFileQueryDto.cs rename to ZR.Model/System/Dto/SysFileQueryDto.cs index 5c3d018c..868534d9 100644 --- a/ZR.Model/Dto/System/SysFileQueryDto.cs +++ b/ZR.Model/System/Dto/SysFileQueryDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class SysFileQueryDto : PagerInfo { diff --git a/ZR.Model/Dto/System/SysLogininfoDto.cs b/ZR.Model/System/Dto/SysLogininfoDto.cs similarity index 94% rename from ZR.Model/Dto/System/SysLogininfoDto.cs rename to ZR.Model/System/Dto/SysLogininfoDto.cs index 7d5bc43d..a125b9a6 100644 --- a/ZR.Model/Dto/System/SysLogininfoDto.cs +++ b/ZR.Model/System/Dto/SysLogininfoDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class SysLogininfoDto : SysBase { diff --git a/ZR.Model/Dto/System/SysOperLogDto.cs b/ZR.Model/System/Dto/SysOperLogDto.cs similarity index 96% rename from ZR.Model/Dto/System/SysOperLogDto.cs rename to ZR.Model/System/Dto/SysOperLogDto.cs index e686da1b..23bd3cb0 100644 --- a/ZR.Model/Dto/System/SysOperLogDto.cs +++ b/ZR.Model/System/Dto/SysOperLogDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class SysOperLogDto : SysBase { diff --git a/ZR.Model/Dto/System/SysRoleDto.cs b/ZR.Model/System/Dto/SysRoleDto.cs similarity index 94% rename from ZR.Model/Dto/System/SysRoleDto.cs rename to ZR.Model/System/Dto/SysRoleDto.cs index 7ba3d47c..5a291952 100644 --- a/ZR.Model/Dto/System/SysRoleDto.cs +++ b/ZR.Model/System/Dto/SysRoleDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class SysRoleDto: SysBase { diff --git a/ZR.Model/Dto/System/SysUserDto.cs b/ZR.Model/System/Dto/SysUserDto.cs similarity index 94% rename from ZR.Model/Dto/System/SysUserDto.cs rename to ZR.Model/System/Dto/SysUserDto.cs index ef7df57c..6841ef63 100644 --- a/ZR.Model/Dto/System/SysUserDto.cs +++ b/ZR.Model/System/Dto/SysUserDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class SysUserDto { diff --git a/ZR.Model/Dto/System/TasksDto.cs b/ZR.Model/System/Dto/TasksDto.cs similarity index 99% rename from ZR.Model/Dto/System/TasksDto.cs rename to ZR.Model/System/Dto/TasksDto.cs index bc190bc4..f41827f0 100644 --- a/ZR.Model/Dto/System/TasksDto.cs +++ b/ZR.Model/System/Dto/TasksDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class TasksQueryDto { diff --git a/ZR.Model/Dto/System/TasksLogDto.cs b/ZR.Model/System/Dto/TasksLogDto.cs similarity index 95% rename from ZR.Model/Dto/System/TasksLogDto.cs rename to ZR.Model/System/Dto/TasksLogDto.cs index 7c573e40..0284234e 100644 --- a/ZR.Model/Dto/System/TasksLogDto.cs +++ b/ZR.Model/System/Dto/TasksLogDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace ZR.Model.Dto.System +namespace ZR.Model.System.Dto { public class TasksLogQueryDto { diff --git a/ZR.Model/System/Generate/GenTable.cs b/ZR.Model/System/Generate/GenTable.cs new file mode 100644 index 00000000..0737c33a --- /dev/null +++ b/ZR.Model/System/Generate/GenTable.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ZR.Model.System.Generate +{ + /// + /// 代码生成表 + /// + [SqlSugar.SugarTable("gen_table")] + public class GenTable: SysBase + { + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int TableId { get; set; } + public string TableName { get; set; } + public string TableComment { get; set; } + public string SubTableName { get; set; } + public string SubTableFkName { get; set; } + public string ClassName { get; set; } + public string TplCategory { get; set; } + public string BaseNameSpace { get; set; } + public string ModuleName { get; set; } + public string BusinessName { get; set; } + public string FunctionName { get; set; } + public string FunctionAuthor { get; set; } + public string GenType { get; set; } + public string Options { get; set; } + + + /** 表列信息 */ + [SqlSugar.SugarColumn(IsIgnore = true)] + public List Columns { get; set; } + } +} diff --git a/ZR.Model/System/Generate/GenTableColumn.cs b/ZR.Model/System/Generate/GenTableColumn.cs new file mode 100644 index 00000000..e517540c --- /dev/null +++ b/ZR.Model/System/Generate/GenTableColumn.cs @@ -0,0 +1,66 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace ZR.Model.System.Generate +{ + /// + /// 代码生成表字段 + /// + [SqlSugar.SugarTable("gen_table_column")] + public class GenTableColumn: SysBase + { + [SqlSugar.SugarColumn(IsIdentity = true, IsPrimaryKey = true)] + public int ColumnId { get; set; } + public string ColumnName { get; set; } + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public int TableId { get; set; } + + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public string TableName { get; set; } + public string ColumnComment { get; set; } + + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public string ColumnType { get; set; } + public string CsharpType { get; set; } + public string CsharpField { get; set; } + /// + /// 是否主键(1是) + /// + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public bool IsPk { get; set; } + /// + /// 是否必填(1是) + /// + public bool IsRequired { get; set; } + [SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] + public bool IsIncrement { get; set; } + /// + /// 是否插入 + /// + public bool IsInsert { get; set; } + /// + /// 是否需要编辑 + /// + public bool IsEdit { get; set; } + /// + /// isList + /// + public bool IsList { get; set; } + public bool IsQuery { get; set; } + /// + /// 显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件) + /// + public string HtmlType { get; set; } + /// + /// 查询类型(等于、不等于、大于、小于、范围) + /// + public string QueryType { get; set; } = "EQ"; + public int Sort { get; set; } + /// + /// 字典类型 + /// + public string DictType { get; set; } + } +} diff --git a/ZR.Model/System/SysBase.cs b/ZR.Model/System/SysBase.cs index 07d07f7c..22faa649 100644 --- a/ZR.Model/System/SysBase.cs +++ b/ZR.Model/System/SysBase.cs @@ -22,10 +22,10 @@ namespace ZR.Model.System [SugarColumn(IsOnlyIgnoreInsert = true)] public string Update_by { get; set; } + //[JsonIgnore] [SugarColumn(IsOnlyIgnoreInsert = true)]//设置后插入数据不会有此字段 - [JsonIgnore] [JsonProperty(propertyName: "UpdateTime")] - public DateTime Update_time { get; set; } = DateTime.Now; + public DateTime? Update_time { get; set; } public string Remark { get; set; } @@ -39,7 +39,6 @@ namespace ZR.Model.System /// [Computed]计算属性,打上此标签,对象地insert,update等操作会忽略此列 /// [SugarColumn(IsIgnore = true)] - //[Computed] [JsonIgnore] public DateTime? BeginTime { get; set; } @@ -47,7 +46,6 @@ namespace ZR.Model.System /// 用于搜索使用 /// [SugarColumn(IsIgnore = true)] - //[Computed] [JsonIgnore] public DateTime? EndTime { get; set; } } diff --git a/ZR.Model/System/SysLogininfor.cs b/ZR.Model/System/SysLogininfor.cs index e1ea4724..4cd080d6 100644 --- a/ZR.Model/System/SysLogininfor.cs +++ b/ZR.Model/System/SysLogininfor.cs @@ -11,7 +11,7 @@ namespace ZR.Model.System public class SysLogininfor: SysBase { //[Key] - [SugarColumn(IsPrimaryKey = true)] + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public long infoId { get; set; } /// diff --git a/ZR.Model/System/SysMenu.cs b/ZR.Model/System/SysMenu.cs index 1af655ce..36f53f7a 100644 --- a/ZR.Model/System/SysMenu.cs +++ b/ZR.Model/System/SysMenu.cs @@ -13,7 +13,7 @@ namespace ZR.Model.System /// 菜单ID /// //[Key]//非自动增长主键时使用ExplicitKey - [SqlSugar.SugarColumn(IsPrimaryKey = true)] + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public long menuId { get; set; } /// /// 菜单名称 diff --git a/ZR.Model/System/SysOperLog.cs b/ZR.Model/System/SysOperLog.cs index 3a04de5e..93a88309 100644 --- a/ZR.Model/System/SysOperLog.cs +++ b/ZR.Model/System/SysOperLog.cs @@ -8,7 +8,7 @@ namespace ZR.Model.System [SqlSugar.SugarTable("sys_oper_log")] public class SysOperLog { - [SqlSugar.SugarColumn(IsPrimaryKey = true)] + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public long OperId { get; set; } /** 操作模块 */ //@Excel(name = "操作模块") diff --git a/ZR.Model/Vo/System/RouterVo.cs b/ZR.Model/System/Vo/RouterVo.cs similarity index 100% rename from ZR.Model/Vo/System/RouterVo.cs rename to ZR.Model/System/Vo/RouterVo.cs diff --git a/ZR.Model/Vo/System/TreeSelectVo.cs b/ZR.Model/System/Vo/TreeSelectVo.cs similarity index 100% rename from ZR.Model/Vo/System/TreeSelectVo.cs rename to ZR.Model/System/Vo/TreeSelectVo.cs diff --git a/ZR.Model/ZR.Model.csproj b/ZR.Model/ZR.Model.csproj index 975d7303..d5193787 100644 --- a/ZR.Model/ZR.Model.csproj +++ b/ZR.Model/ZR.Model.csproj @@ -17,6 +17,7 @@ + diff --git a/ZR.Repository/DbProvider/SugarDbContext.cs b/ZR.Repository/DbProvider/SugarDbContext.cs index 67ec6575..69fee4e4 100644 --- a/ZR.Repository/DbProvider/SugarDbContext.cs +++ b/ZR.Repository/DbProvider/SugarDbContext.cs @@ -22,11 +22,12 @@ namespace ZR.Repository.DbProvider { string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin); string dbKey = ConfigUtils.Instance.GetAppConfig(OptionsSetting.DbKey); - int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.DbType, 0); + int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.ConnDbType); if (!string.IsNullOrEmpty(dbKey)) { connStr = NETCore.Encrypt.EncryptProvider.DESDecrypt(connStr, dbKey); } + Db = new SqlSugarClient(new List() { new ConnectionConfig(){ @@ -41,6 +42,7 @@ namespace ZR.Repository.DbProvider //调式代码 用来打印SQL Db.Aop.OnLogExecuting = (sql, pars) => { + Console.BackgroundColor = ConsoleColor.Yellow; Console.WriteLine("【SQL语句】" + sql.ToLower() + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); }; //出错打印日志 diff --git a/ZR.Repository/System/ArticleRepository.cs b/ZR.Repository/System/ArticleRepository.cs index 5b0cd75b..57001a7a 100644 --- a/ZR.Repository/System/ArticleRepository.cs +++ b/ZR.Repository/System/ArticleRepository.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; namespace ZR.Repository.System diff --git a/ZR.Repository/System/SysDictDataRepository.cs b/ZR.Repository/System/SysDictDataRepository.cs index 43b24b64..6cdf0c66 100644 --- a/ZR.Repository/System/SysDictDataRepository.cs +++ b/ZR.Repository/System/SysDictDataRepository.cs @@ -37,16 +37,6 @@ namespace ZR.Repository.System .ToList(); } - /// - /// 根据DictCode查询 - /// - /// - /// - public SysDictData SelectDictDataById(long dictCode) - { - return Db.Queryable().Where(f => f.DictCode == dictCode).First(); - } - /// /// 新增保存字典数据信息 /// @@ -89,16 +79,6 @@ namespace ZR.Repository.System return Db.Deleteable().In(dictCodes).ExecuteCommand(); } - /// - /// 查询字典数据 - /// - /// - /// - public int CountDictDataByType(string dictType) - { - return Db.Queryable().Count(f => f.DictType == dictType); - } - /// /// 同步修改字典类型 /// diff --git a/ZR.Repository/System/SysDictRepository.cs b/ZR.Repository/System/SysDictRepository.cs index f30a142a..e01de1b9 100644 --- a/ZR.Repository/System/SysDictRepository.cs +++ b/ZR.Repository/System/SysDictRepository.cs @@ -17,43 +17,17 @@ namespace ZR.Repository.System /// /// 实体模型 /// - public List SelectDictTypeList(SysDictType dictType) + public List SelectDictTypeList(SysDictType dictType, Model.PagerInfo pager) { - return Db + var totalNum = 0; + var list = Db .Queryable() .WhereIF(!string.IsNullOrEmpty(dictType.DictName), it => it.DictName.Contains(dictType.DictName)) .WhereIF(!string.IsNullOrEmpty(dictType.Status), it => it.Status == dictType.Status) - .WhereIF(!string.IsNullOrEmpty(dictType.DictType), it => it.DictType == dictType.DictType).ToList(); - } - - /// - /// 根据Id查询 - /// - /// - /// - public SysDictType SelectDictTypeById(long id) - { - return Db.Queryable().First(it => it.DictId == id); - } - - /// - /// 检查字典类型唯一值 - /// - /// - /// - public SysDictType CheckDictTypeUnique(string dictType) - { - return Db.Queryable().First(it => it.DictType == dictType); - } - - /// - /// 删除一个 - /// - /// - /// - public int DeleteDictTypeById(long id) - { - return Db.Deleteable().In(id).ExecuteCommand(); + .WhereIF(!string.IsNullOrEmpty(dictType.DictType), it => it.DictType == dictType.DictType) + .ToPageList(pager.PageNum, pager.PageSize, ref totalNum); + pager.TotalNum = totalNum; + return list; } /// @@ -66,18 +40,6 @@ namespace ZR.Repository.System return Db.Deleteable().In(id).ExecuteCommand(); } - /// - /// 插入 - /// - /// - /// - public long InsertDictType(SysDictType sysDictType) - { - var result = Db.Insertable(sysDictType).IgnoreColumns(it => new { sysDictType.Update_by }) - .ExecuteReturnIdentity(); - return result; - } - /// /// 修改 /// diff --git a/ZR.Repository/System/SysLogininfoRepository.cs b/ZR.Repository/System/SysLogininfoRepository.cs index 1bdb9627..f91a88dc 100644 --- a/ZR.Repository/System/SysLogininfoRepository.cs +++ b/ZR.Repository/System/SysLogininfoRepository.cs @@ -2,7 +2,7 @@ using Infrastructure.Extensions; using System.Collections.Generic; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; namespace ZR.Repository.System diff --git a/ZR.Repository/System/SysMenuRepository.cs b/ZR.Repository/System/SysMenuRepository.cs index 0332b878..3fafa0b4 100644 --- a/ZR.Repository/System/SysMenuRepository.cs +++ b/ZR.Repository/System/SysMenuRepository.cs @@ -3,7 +3,7 @@ using SqlSugar; using System; using System.Collections.Generic; using System.Linq; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; namespace ZR.Repository.System diff --git a/ZR.Repository/System/SysOperLogRepository.cs b/ZR.Repository/System/SysOperLogRepository.cs index 840de437..9c47b116 100644 --- a/ZR.Repository/System/SysOperLogRepository.cs +++ b/ZR.Repository/System/SysOperLogRepository.cs @@ -2,7 +2,7 @@ using Infrastructure.Extensions; using System.Collections.Generic; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; namespace ZR.Repository.System diff --git a/ZR.Repository/System/SysUserRepository.cs b/ZR.Repository/System/SysUserRepository.cs index 03ab81cd..754edcd9 100644 --- a/ZR.Repository/System/SysUserRepository.cs +++ b/ZR.Repository/System/SysUserRepository.cs @@ -29,7 +29,7 @@ namespace ZR.Repository.System .WhereIF(!string.IsNullOrEmpty(user.UserName), it => it.UserName.Contains(user.UserName)) .WhereIF(!string.IsNullOrEmpty(user.Status), it => it.Status == user.Status) .WhereIF(user.BeginTime != DateTime.MinValue && user.BeginTime != null, it => it.Create_time >= user.BeginTime) - .WhereIF(user.EndTime != DateTime.MinValue && user.BeginTime != null, it => it.EndTime <= user.EndTime) + .WhereIF(user.EndTime != DateTime.MinValue && user.BeginTime != null, it => it.Create_time <= user.EndTime) .WhereIF(user.DeptId != 0, it => it.DeptId == user.DeptId) .OrderBy(it => it.UserId) .ToPageList(pager.PageNum, pager.PageSize, ref totalCount); diff --git a/ZR.Repository/System/SysUserRoleRepository.cs b/ZR.Repository/System/SysUserRoleRepository.cs index d64bb93e..f63d2960 100644 --- a/ZR.Repository/System/SysUserRoleRepository.cs +++ b/ZR.Repository/System/SysUserRoleRepository.cs @@ -67,10 +67,10 @@ namespace ZR.Repository.System /// public List GetSysUsersByRoleId(long roleId) { - return Db.Queryable((t1, user) => new JoinQueryInfos( - JoinType.Left, t1.UserId == user.UserId)) - .Where((t1, user) => t1.RoleId == roleId && user.DelFlag == "0") - .Select((t1, user) => user) + return Db.Queryable((t1, u) => new JoinQueryInfos( + JoinType.Left, t1.UserId == u.UserId)) + .Where((t1, u) => t1.RoleId == roleId && u.DelFlag == "0") + .Select((t1, u) => u) .ToList(); } } diff --git a/ZR.Repository/ZR.Repository.csproj b/ZR.Repository/ZR.Repository.csproj index c4175f53..dd8fc0ff 100644 --- a/ZR.Repository/ZR.Repository.csproj +++ b/ZR.Repository/ZR.Repository.csproj @@ -15,4 +15,8 @@ + + + + diff --git a/ZR.Service/BaseService.cs b/ZR.Service/BaseService.cs index f2d3830f..8eb83d00 100644 --- a/ZR.Service/BaseService.cs +++ b/ZR.Service/BaseService.cs @@ -54,6 +54,18 @@ namespace ZR.Service return Db.Insertable(parm).RemoveDataCache().ExecuteCommand(); } + /// + /// 添加 + /// + /// + /// 插入列 + /// 忽略null列 + /// + public int Add(T parm, Expression> iClumns = null, bool ignoreNull = true) + { + return Db.Insertable(parm).InsertColumns(iClumns).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand(); + } + /// /// 批量添加数据 /// @@ -65,7 +77,7 @@ namespace ZR.Service } /// - /// 添加或更新数据 + /// 添加或更新数据,不推荐使用了 /// /// List /// @@ -166,7 +178,7 @@ namespace ZR.Service /// 查询所有数据(无分页,请慎用) /// /// - public List GetAll(bool useCache = false, int cacheSecond = 3600) + public List GetAll(bool useCache = false, int cacheSecond = 3600) { return Db.Queryable().WithCacheIF(useCache, cacheSecond).ToList(); } diff --git a/ZR.Service/IBaseService.cs b/ZR.Service/IBaseService.cs index 72959f0e..38d20658 100644 --- a/ZR.Service/IBaseService.cs +++ b/ZR.Service/IBaseService.cs @@ -3,8 +3,6 @@ using SqlSugar; using System; using System.Collections.Generic; using System.Linq.Expressions; -using System.Threading.Tasks; -using ZR.Model; namespace ZR.Service { @@ -44,6 +42,8 @@ namespace ZR.Service /// int Add(T parm); + int Add(T parm, Expression> iClumns = null, bool ignoreNull = false); + /// /// 批量添加数据 /// @@ -138,7 +138,7 @@ namespace ZR.Service /// /// /// - PagedInfo GetPages(Expression> where, PagerInfo parm); + PagedInfo GetPages(Expression> where, Model.PagerInfo parm); /// /// 根据条件查询分页 @@ -148,7 +148,7 @@ namespace ZR.Service /// /// /// - PagedInfo GetPages(Expression> where, PagerInfo parm, Expression> order, string orderEnum = "Asc"); + PagedInfo GetPages(Expression> where, Model.PagerInfo parm, Expression> order, string orderEnum = "Asc"); /// /// 根据条件查询数据 diff --git a/ZR.Service/System/ArticleCategoryService.cs b/ZR.Service/System/ArticleCategoryService.cs index 9dd5a0a8..7ef4573e 100644 --- a/ZR.Service/System/ArticleCategoryService.cs +++ b/ZR.Service/System/ArticleCategoryService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Linq; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/ArticleService.cs b/ZR.Service/System/ArticleService.cs index fd7c06d6..863efa9c 100644 --- a/ZR.Service/System/ArticleService.cs +++ b/ZR.Service/System/ArticleService.cs @@ -1,6 +1,6 @@ using Infrastructure.Attribute; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/GenTableService.cs b/ZR.Service/System/GenTableService.cs new file mode 100644 index 00000000..782324e6 --- /dev/null +++ b/ZR.Service/System/GenTableService.cs @@ -0,0 +1,193 @@ +using Infrastructure.Attribute; +using Infrastructure.Extensions; +using Infrastructure.Model; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using ZR.Model.System.Generate; +using ZR.Service.System.IService; + +namespace ZR.Service.System +{ + /// + /// 代码生成表 + /// + [AppService(ServiceType = typeof(IGenTableService), ServiceLifetime = LifeTime.Transient)] + public class GenTableService : BaseService, IGenTableService + { + public IGenTableColumnService GenTableColumnService; + public GenTableService(IGenTableColumnService genTableColumnService) + { + GenTableColumnService = genTableColumnService; + } + + /// + /// 删除表 + /// + /// 需要删除的表id + /// + public int DeleteGenTableByIds(long[] tableIds) + { + Db.Deleteable().Where(f => tableIds.Contains(f.TableId)).ExecuteCommand(); + return GenTableColumnService.DeleteGenTableColumn(tableIds); + } + + /// + /// 删除表根据表名 + /// + /// + /// + public int DeleteGenTableByTbName(string tableName) + { + return Db.Deleteable().Where(f => f.TableName == tableName).ExecuteCommand(); + } + + /// + /// 获取表信息 + /// + /// + /// + public GenTable GetGenTableInfo(long tableId) + { + return GetId(tableId); + } + + /// + /// 查询代码生成表信息 + /// + /// + /// + /// + public PagedInfo GetGenTables(GenTable genTable, Model.PagerInfo pagerInfo) + { + var predicate = Expressionable.Create(); + predicate = predicate.AndIF(genTable.TableName.IfNotEmpty(), it => it.TableName.Contains(genTable.TableName)); + + return GetPages(predicate.ToExpression(), pagerInfo); + } + + /// + /// 插入代码生成表 + /// + /// + /// + public int ImportGenTable(GenTable table) + { + var db = Db; + table.Create_time = db.GetDate(); + //导入前删除现有表 + //DeleteGenTableByIds(new long[] { table.TableId }); + DeleteGenTableByTbName(table.TableName); + + return db.Insertable(table).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnIdentity(); + } + + /// + /// 获取表数据 + /// + /// + /// + public List SelectDbTableListByNamess(string[] tableNames) + { + throw new NotImplementedException(); + } + + public int UpdateGenTable(GenTable genTable) + { + var db = Db; + genTable.Update_time = db.GetDate(); + return db.Updateable(genTable).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); + } + } + + /// + /// 代码生成表列 + /// + [AppService(ServiceType = typeof(IGenTableColumnService), ServiceLifetime = LifeTime.Transient)] + public class GenTableColumnService : BaseService, IGenTableColumnService + { + /// + /// 删除表字段 + /// + /// + /// + public int DeleteGenTableColumn(long tableId) + { + return DeleteGenTableColumn(new long[] { tableId }); + } + /// + /// 根据表id批量删除表字段 + /// + /// + /// + public int DeleteGenTableColumn(long[] tableId) + { + return Db.Deleteable().Where(f => tableId.Contains(f.TableId)).ExecuteCommand(); + } + + /// + /// 根据表名删除字段 + /// + /// + /// + public int DeleteGenTableColumnByTableName(string tableName) + { + return Db.Deleteable().Where(f => f.TableName == tableName).ExecuteCommand(); + } + + /// + /// 获取表所有字段 + /// + /// + /// + public List GenTableColumns(long tableId) + { + return Db.Queryable().Where(f => f.TableId == tableId).OrderBy(x => x.Sort).ToList(); + } + + /// + /// 插入表字段 + /// + /// + /// + public int InsertGenTableColumn(List tableColumn) + { + return Db.Insertable(tableColumn).IgnoreColumns(x => new { x.Remark }).ExecuteCommand(); + } + + /// + /// 批量更新表字段 + /// + /// + /// + public int UpdateGenTableColumn(List tableColumn) + { + foreach (var item in tableColumn) + { + Db.Updateable() + .Where(f => f.TableId == item.TableId) + .SetColumns(it => new GenTableColumn() + { + ColumnComment = item.ColumnComment, + CsharpField = item.CsharpField, + CsharpType = item.CsharpType, + IsQuery = item.IsQuery, + IsEdit = item.IsEdit, + IsInsert = item.IsInsert, + IsList = item.IsList, + QueryType = item.QueryType, + HtmlType = item.HtmlType, + IsRequired = item.IsRequired, + Sort = item.Sort, + Update_time = DateTime.Now, + DictType = item.DictType + }) + .Where(f => f.ColumnId == item.ColumnId) + .ExecuteCommand(); + } + + return 1; + } + } +} diff --git a/ZR.Service/IService/IArticleCategoryService.cs b/ZR.Service/System/IService/IArticleCategoryService.cs similarity index 89% rename from ZR.Service/IService/IArticleCategoryService.cs rename to ZR.Service/System/IService/IArticleCategoryService.cs index 2db0a40e..602b2283 100644 --- a/ZR.Service/IService/IArticleCategoryService.cs +++ b/ZR.Service/System/IService/IArticleCategoryService.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading.Tasks; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface IArticleCategoryService : IBaseService { diff --git a/ZR.Service/IService/IArticleService.cs b/ZR.Service/System/IService/IArticleService.cs similarity index 77% rename from ZR.Service/IService/IArticleService.cs rename to ZR.Service/System/IService/IArticleService.cs index 9e9dcd77..0f4e7ded 100644 --- a/ZR.Service/IService/IArticleService.cs +++ b/ZR.Service/System/IService/IArticleService.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface IArticleService : IBaseService
{ diff --git a/ZR.Service/System/IService/IGenTableService.cs b/ZR.Service/System/IService/IGenTableService.cs new file mode 100644 index 00000000..7adc936c --- /dev/null +++ b/ZR.Service/System/IService/IGenTableService.cs @@ -0,0 +1,34 @@ +using Infrastructure.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ZR.Model.System.Generate; + +namespace ZR.Service.System.IService +{ + public interface IGenTableService + { + List SelectDbTableListByNamess(string[] tableNames); + + int ImportGenTable(GenTable tables); + + int DeleteGenTableByIds(long[] tableIds); + int DeleteGenTableByTbName(string tableName); + PagedInfo GetGenTables(GenTable genTable, Model.PagerInfo pagerInfo); + GenTable GetGenTableInfo(long tableId); + int UpdateGenTable(GenTable genTable); + } + + public interface IGenTableColumnService + { + int InsertGenTableColumn(List tableColumn); + + int DeleteGenTableColumn(long tableId); + int DeleteGenTableColumn(long[] tableIds); + int DeleteGenTableColumnByTableName(string tableName); + List GenTableColumns(long tableId); + int UpdateGenTableColumn(List tableColumn); + } +} diff --git a/ZR.Service/IService/ISysDeptService.cs b/ZR.Service/System/IService/ISysDeptService.cs similarity index 95% rename from ZR.Service/IService/ISysDeptService.cs rename to ZR.Service/System/IService/ISysDeptService.cs index 78bc4a0b..4e90491c 100644 --- a/ZR.Service/IService/ISysDeptService.cs +++ b/ZR.Service/System/IService/ISysDeptService.cs @@ -4,7 +4,7 @@ using System.Text; using ZR.Model.System; using ZR.Model.Vo.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysDeptService : IBaseService { diff --git a/ZR.Service/IService/ISysDictDataService.cs b/ZR.Service/System/IService/ISysDictDataService.cs similarity index 93% rename from ZR.Service/IService/ISysDictDataService.cs rename to ZR.Service/System/IService/ISysDictDataService.cs index 63b7d29c..d048b1a9 100644 --- a/ZR.Service/IService/ISysDictDataService.cs +++ b/ZR.Service/System/IService/ISysDictDataService.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysDictDataService : IBaseService { diff --git a/ZR.Service/IService/ISysDictService.cs b/ZR.Service/System/IService/ISysDictService.cs similarity index 73% rename from ZR.Service/IService/ISysDictService.cs rename to ZR.Service/System/IService/ISysDictService.cs index f2d0697d..6d99e7ac 100644 --- a/ZR.Service/IService/ISysDictService.cs +++ b/ZR.Service/System/IService/ISysDictService.cs @@ -3,21 +3,14 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { /// /// /// public interface ISysDictService: IBaseService { - public List SelectDictTypeList(SysDictType dictType); - - /// - /// 根据Id查询 - /// - /// - /// - public SysDictType SelectDictTypeById(long id); + public List SelectDictTypeList(SysDictType dictType, Model.PagerInfo pager); /// /// 校验字典类型称是否唯一 @@ -26,13 +19,6 @@ namespace ZR.Service.IService /// public string CheckDictTypeUnique(SysDictType dictType); - /// - /// 删除一个 - /// - /// - /// - public int DeleteDictTypeById(long id); - /// /// 批量删除字典数据信息 /// diff --git a/ZR.Service/IService/ISysFileService.cs b/ZR.Service/System/IService/ISysFileService.cs similarity index 78% rename from ZR.Service/IService/ISysFileService.cs rename to ZR.Service/System/IService/ISysFileService.cs index d1deeb48..f223bfff 100644 --- a/ZR.Service/IService/ISysFileService.cs +++ b/ZR.Service/System/IService/ISysFileService.cs @@ -1,7 +1,7 @@ using Infrastructure.Attribute; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysFileService : IBaseService { diff --git a/ZR.Service/IService/ISysLoginService.cs b/ZR.Service/System/IService/ISysLoginService.cs similarity index 94% rename from ZR.Service/IService/ISysLoginService.cs rename to ZR.Service/System/IService/ISysLoginService.cs index 22272e23..d80d99c0 100644 --- a/ZR.Service/IService/ISysLoginService.cs +++ b/ZR.Service/System/IService/ISysLoginService.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Text; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysLoginService { diff --git a/ZR.Service/IService/ISysMenuService.cs b/ZR.Service/System/IService/ISysMenuService.cs similarity index 94% rename from ZR.Service/IService/ISysMenuService.cs rename to ZR.Service/System/IService/ISysMenuService.cs index 04c90c4c..8928c4e5 100644 --- a/ZR.Service/IService/ISysMenuService.cs +++ b/ZR.Service/System/IService/ISysMenuService.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Model.System.Vo; using ZR.Model.Vo.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysMenuService: IBaseService { diff --git a/ZR.Service/IService/ISysOperLogService.cs b/ZR.Service/System/IService/ISysOperLogService.cs similarity index 94% rename from ZR.Service/IService/ISysOperLogService.cs rename to ZR.Service/System/IService/ISysOperLogService.cs index eef404ed..00299048 100644 --- a/ZR.Service/IService/ISysOperLogService.cs +++ b/ZR.Service/System/IService/ISysOperLogService.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Service.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysOperLogService : IBaseService { diff --git a/ZR.Service/IService/ISysPermissionService.cs b/ZR.Service/System/IService/ISysPermissionService.cs similarity index 89% rename from ZR.Service/IService/ISysPermissionService.cs rename to ZR.Service/System/IService/ISysPermissionService.cs index 68973964..f0ea8337 100644 --- a/ZR.Service/IService/ISysPermissionService.cs +++ b/ZR.Service/System/IService/ISysPermissionService.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading.Tasks; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysPermissionService { diff --git a/ZR.Service/IService/ISysPostService.cs b/ZR.Service/System/IService/ISysPostService.cs similarity index 88% rename from ZR.Service/IService/ISysPostService.cs rename to ZR.Service/System/IService/ISysPostService.cs index 1df4365c..9cd098b9 100644 --- a/ZR.Service/IService/ISysPostService.cs +++ b/ZR.Service/System/IService/ISysPostService.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysPostService: IBaseService { diff --git a/ZR.Service/IService/ISysRoleService.cs b/ZR.Service/System/IService/ISysRoleService.cs similarity index 99% rename from ZR.Service/IService/ISysRoleService.cs rename to ZR.Service/System/IService/ISysRoleService.cs index 3a343891..6f039fd4 100644 --- a/ZR.Service/IService/ISysRoleService.cs +++ b/ZR.Service/System/IService/ISysRoleService.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysRoleService: IBaseService { diff --git a/ZR.Service/IService/ISysTasksLogService.cs b/ZR.Service/System/IService/ISysTasksLogService.cs similarity index 90% rename from ZR.Service/IService/ISysTasksLogService.cs rename to ZR.Service/System/IService/ISysTasksLogService.cs index ef0bb096..48dbff47 100644 --- a/ZR.Service/IService/ISysTasksLogService.cs +++ b/ZR.Service/System/IService/ISysTasksLogService.cs @@ -1,6 +1,6 @@ using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysTasksLogService : IBaseService { diff --git a/ZR.Service/IService/ISysTasksQzService.cs b/ZR.Service/System/IService/ISysTasksQzService.cs similarity index 85% rename from ZR.Service/IService/ISysTasksQzService.cs rename to ZR.Service/System/IService/ISysTasksQzService.cs index a7c60c72..69931d0b 100644 --- a/ZR.Service/IService/ISysTasksQzService.cs +++ b/ZR.Service/System/IService/ISysTasksQzService.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading.Tasks; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysTasksQzService: IBaseService { diff --git a/ZR.Service/IService/ISysUserPostService.cs b/ZR.Service/System/IService/ISysUserPostService.cs similarity index 89% rename from ZR.Service/IService/ISysUserPostService.cs rename to ZR.Service/System/IService/ISysUserPostService.cs index 2335b17e..05140471 100644 --- a/ZR.Service/IService/ISysUserPostService.cs +++ b/ZR.Service/System/IService/ISysUserPostService.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysUserPostService: IBaseService { diff --git a/ZR.Service/IService/ISysUserRoleService.cs b/ZR.Service/System/IService/ISysUserRoleService.cs similarity index 95% rename from ZR.Service/IService/ISysUserRoleService.cs rename to ZR.Service/System/IService/ISysUserRoleService.cs index 55d4b014..6dc8125b 100644 --- a/ZR.Service/IService/ISysUserRoleService.cs +++ b/ZR.Service/System/IService/ISysUserRoleService.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysUserRoleService { diff --git a/ZR.Service/IService/ISysUserService.cs b/ZR.Service/System/IService/ISysUserService.cs similarity index 98% rename from ZR.Service/IService/ISysUserService.cs rename to ZR.Service/System/IService/ISysUserService.cs index ad65cb12..f49e9261 100644 --- a/ZR.Service/IService/ISysUserService.cs +++ b/ZR.Service/System/IService/ISysUserService.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using ZR.Model; using ZR.Model.System; -namespace ZR.Service.IService +namespace ZR.Service.System.IService { public interface ISysUserService : IBaseService { diff --git a/ZR.Service/System/SysDeptService.cs b/ZR.Service/System/SysDeptService.cs index f83b21ca..a99c5413 100644 --- a/ZR.Service/System/SysDeptService.cs +++ b/ZR.Service/System/SysDeptService.cs @@ -10,7 +10,7 @@ using ZR.Common; using ZR.Model.System; using ZR.Model.Vo.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { @@ -132,7 +132,8 @@ namespace ZR.Service.System if (child.DeptId.Equals(deptId)) { - DeptRepository.UdateDeptChildren(child); + Saveable(child, it => new { it.Ancestors }); + //DeptRepository.UdateDeptChildren(child); } } } diff --git a/ZR.Service/System/SysDictDataService.cs b/ZR.Service/System/SysDictDataService.cs index 9e650563..92c7a019 100644 --- a/ZR.Service/System/SysDictDataService.cs +++ b/ZR.Service/System/SysDictDataService.cs @@ -5,7 +5,7 @@ using System.Text; using ZR.Common; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { @@ -53,9 +53,9 @@ namespace ZR.Service.System public SysDictData SelectDictDataById(long dictCode) { string CK = $"SelectDictDataByCode_{dictCode}"; - if (!(CacheHelper.GetCache(CK) is SysDictData list)) + if (CacheHelper.GetCache(CK) is not SysDictData list) { - list = SysDictDataRepository.SelectDictDataById(dictCode); + list = GetFirst(f => f.DictCode == dictCode); CacheHelper.SetCache(CK, list, 5); } return list; diff --git a/ZR.Service/System/SysDictService.cs b/ZR.Service/System/SysDictService.cs index 3eef28ad..cf8c8490 100644 --- a/ZR.Service/System/SysDictService.cs +++ b/ZR.Service/System/SysDictService.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Text; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { @@ -14,7 +14,7 @@ namespace ZR.Service.System /// [AppService(ServiceType = typeof(ISysDictService), ServiceLifetime = LifeTime.Transient)] public class SysDictService : BaseService, ISysDictService - { + { private SysDictRepository sysDictRepository; private SysDictDataRepository DictDataRepository; @@ -29,19 +29,9 @@ namespace ZR.Service.System ///
/// 实体模型 /// - public List SelectDictTypeList(SysDictType dictType) + public List SelectDictTypeList(SysDictType dictType, Model.PagerInfo pager) { - return sysDictRepository.SelectDictTypeList(dictType); - } - - /// - /// 根据Id查询 - /// - /// - /// - public SysDictType SelectDictTypeById(long id) - { - return sysDictRepository.SelectDictTypeById(id); + return sysDictRepository.SelectDictTypeList(dictType, pager); } /// @@ -51,7 +41,7 @@ namespace ZR.Service.System /// public string CheckDictTypeUnique(SysDictType dictType) { - SysDictType sysDictType = sysDictRepository.CheckDictTypeUnique(dictType.DictType); + SysDictType sysDictType = GetFirst(f => f.DictType == dictType.DictType); if (sysDictType != null && sysDictType.DictId != dictType.DictId) { return UserConstants.NOT_UNIQUE; @@ -59,16 +49,6 @@ namespace ZR.Service.System return UserConstants.UNIQUE; } - /// - /// 删除一个 - /// - /// - /// - public int DeleteDictTypeById(long id) - { - return sysDictRepository.DeleteDictTypeById(id); - } - /// /// 批量删除字典数据信息 /// @@ -78,8 +58,8 @@ namespace ZR.Service.System { foreach (var dictId in dictIds) { - SysDictType dictType = SelectDictTypeById(dictId); - if (DictDataRepository.CountDictDataByType(dictType.DictType) > 0) + SysDictType dictType = GetFirst(x => x.DictId == dictId); + if (GetCount(f => f.DictType == dictType.DictType) > 0) { throw new CustomException($"{dictType.DictName}已分配,不能删除"); } @@ -99,7 +79,7 @@ namespace ZR.Service.System /// public long InsertDictType(SysDictType sysDictType) { - return sysDictRepository.InsertDictType(sysDictType); + return Saveable(sysDictType, iColumns: it => new { sysDictType.Update_by }).DictId; } /// @@ -109,7 +89,7 @@ namespace ZR.Service.System /// public int UpdateDictType(SysDictType sysDictType) { - SysDictType oldDict = sysDictRepository.SelectDictTypeById(sysDictType.DictId); + SysDictType oldDict = GetFirst(x => x.DictId == sysDictType.DictId); if (sysDictType.DictType != oldDict.DictType) { //同步修改 dict_data表里面的DictType值 diff --git a/ZR.Service/System/SysFileService.cs b/ZR.Service/System/SysFileService.cs index df1182d2..5098a885 100644 --- a/ZR.Service/System/SysFileService.cs +++ b/ZR.Service/System/SysFileService.cs @@ -1,6 +1,6 @@ using Infrastructure.Attribute; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysLoginService.cs b/ZR.Service/System/SysLoginService.cs index 8758e1b2..3a8056e4 100644 --- a/ZR.Service/System/SysLoginService.cs +++ b/ZR.Service/System/SysLoginService.cs @@ -4,10 +4,10 @@ using System; using System.Collections.Generic; using ZR.Common; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysMenuService.cs b/ZR.Service/System/SysMenuService.cs index c4d702e6..780a4688 100644 --- a/ZR.Service/System/SysMenuService.cs +++ b/ZR.Service/System/SysMenuService.cs @@ -1,13 +1,13 @@ using Infrastructure.Attribute; using System.Collections.Generic; using System.Linq; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Model.System.Vo; using ZR.Model.Vo; using ZR.Model.Vo.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service { diff --git a/ZR.Service/System/SysOperLogService.cs b/ZR.Service/System/SysOperLogService.cs index 668accd0..80a5f5fe 100644 --- a/ZR.Service/System/SysOperLogService.cs +++ b/ZR.Service/System/SysOperLogService.cs @@ -1,11 +1,11 @@ using Infrastructure.Attribute; using System.Collections.Generic; -using ZR.Common; using ZR.Model; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; +using Infrastructure; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysPermissionService.cs b/ZR.Service/System/SysPermissionService.cs index e946098e..607d3f9e 100644 --- a/ZR.Service/System/SysPermissionService.cs +++ b/ZR.Service/System/SysPermissionService.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; using System.Text; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysPostService.cs b/ZR.Service/System/SysPostService.cs index 56534c0b..39808a5b 100644 --- a/ZR.Service/System/SysPostService.cs +++ b/ZR.Service/System/SysPostService.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; using System.Text; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysRoleService.cs b/ZR.Service/System/SysRoleService.cs index 8591f928..c42b5fd2 100644 --- a/ZR.Service/System/SysRoleService.cs +++ b/ZR.Service/System/SysRoleService.cs @@ -7,8 +7,7 @@ using System.Linq; using System.Text; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; -using ZR.Service.System; +using ZR.Service.System.IService; namespace ZR.Service { diff --git a/ZR.Service/System/SysTasksLogService.cs b/ZR.Service/System/SysTasksLogService.cs index 4d832621..25f56e45 100644 --- a/ZR.Service/System/SysTasksLogService.cs +++ b/ZR.Service/System/SysTasksLogService.cs @@ -1,7 +1,7 @@ using Infrastructure.Attribute; using System; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysTasksQzService.cs b/ZR.Service/System/SysTasksQzService.cs index 1ecbc130..1569287e 100644 --- a/ZR.Service/System/SysTasksQzService.cs +++ b/ZR.Service/System/SysTasksQzService.cs @@ -1,6 +1,6 @@ using Infrastructure.Attribute; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysUserPostService.cs b/ZR.Service/System/SysUserPostService.cs index cf24642a..c312d318 100644 --- a/ZR.Service/System/SysUserPostService.cs +++ b/ZR.Service/System/SysUserPostService.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysUserRoleService.cs b/ZR.Service/System/SysUserRoleService.cs index a42cbf4d..94bdfc14 100644 --- a/ZR.Service/System/SysUserRoleService.cs +++ b/ZR.Service/System/SysUserRoleService.cs @@ -2,10 +2,10 @@ using System; using System.Collections.Generic; using System.Text; -using ZR.Model.Dto.System; +using ZR.Model.System.Dto; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service.System { diff --git a/ZR.Service/System/SysUserService.cs b/ZR.Service/System/SysUserService.cs index c3a0af0b..23b972e6 100644 --- a/ZR.Service/System/SysUserService.cs +++ b/ZR.Service/System/SysUserService.cs @@ -6,7 +6,7 @@ using System.Text; using ZR.Model; using ZR.Model.System; using ZR.Repository.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Service { diff --git a/ZR.Service/ZR.Service.csproj b/ZR.Service/ZR.Service.csproj index 6f3c4d02..a27cb439 100644 --- a/ZR.Service/ZR.Service.csproj +++ b/ZR.Service/ZR.Service.csproj @@ -9,4 +9,9 @@ + + + + + diff --git a/ZR.Tasks/TaskScheduler/JobBase.cs b/ZR.Tasks/TaskScheduler/JobBase.cs index 3d5b9cd5..5ed8fede 100644 --- a/ZR.Tasks/TaskScheduler/JobBase.cs +++ b/ZR.Tasks/TaskScheduler/JobBase.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using ZR.Model.System; -using ZR.Service.IService; +using ZR.Service.System.IService; namespace ZR.Tasks { diff --git a/ZR.Vue/document/t4.tt b/ZR.Vue/document/t4.tt deleted file mode 100644 index e69de29b..00000000 diff --git a/ZR.Vue/document/template.vue b/ZR.Vue/document/template.vue index 9a4ce728..74895c2c 100644 --- a/ZR.Vue/document/template.vue +++ b/ZR.Vue/document/template.vue @@ -2,9 +2,13 @@
- +<<<<<<< HEAD + +======= + +>>>>>>> db49575a0ded0eef5e8a68461da1448cdacb3d69 - + @@ -16,18 +20,18 @@ - + - + - 搜索 + 搜索 重置 @@ -44,13 +48,13 @@ 删除 - + + @@ -58,13 +62,9 @@ - + @@ -90,7 +90,7 @@ - + @@ -110,7 +110,7 @@ - {{dict.dictLabel}} + {{dict.dictLabel}} @@ -136,23 +136,23 @@ export default { name: "demo", data() { return { + labelWidth: "70px", // 遮罩层 loading: true, // 显示搜索条件 showSearch: true, // 查询参数 - queryParams: { - useridx: undefined, - name: undefined, - }, + queryParams: {}, // 弹出层标题 title: "", // 是否显示弹出层 open: false, // 表单参数 form: {}, + // 时间范围数组 + timeRange: [], // xxx下拉框 - options: [], + statusOptions: [], // 数据列表 dataList: [ { @@ -174,18 +174,30 @@ export default { // 表单校验 rules: { name: [{ required: true, message: "名称不能为空", trigger: "blur" }], - userId: [{ required: true, message: "id不能为空", trigger: "blur" }], + userId: [ + { + type: "number", + required: true, + message: "id不能为空,且不能为非数字", + trigger: "blur", + }, + ], }, }; }, mounted() { + // 列表数据查询 this.getList(); + // 下拉框绑定 + // this.getDicts("sys_normal_disable").then((response) => { + // this.statusOptions = response.data; + // }); }, methods: { // 查询数据 getList() { console.log(JSON.stringify(this.queryParams)); - // listXXXX().then(res => { + // listXXXX(this.addDateRange(this.queryParams, this.timeRange)).then(res => { // if (res.code == 200) { // this.dataList = res.data.result; // this.total = res.data.totalCount; @@ -199,7 +211,6 @@ export default { }, // 重置数据表单 reset() { - this.btnSubmitVisible = true; this.form = { Id: undefined, // TODO 其他列字段 @@ -208,7 +219,12 @@ export default { }, /** 重置查询操作 */ resetQuery() { + this.timeRange = []; this.resetForm("queryForm"); + this.queryParams = { + pageNum: 1, + //TODO 重置字段 + }; }, /** 搜索按钮操作 */ handleQuery() { @@ -224,11 +240,13 @@ export default { }, /** 删除按钮操作 */ handleDelete(row) { - // delXXX().then(function () { - - // }) - // .then(() => { + // delXXX().then((res) => { // this.msgSuccess("删除成功"); +<<<<<<< HEAD + +======= +>>>>>>> db49575a0ded0eef5e8a68461da1448cdacb3d69 + // this.handleQuery(); // }); }, /** 修改按钮操作 */ @@ -278,3 +296,8 @@ export default { }, }; + diff --git a/ZR.Vue/package.json b/ZR.Vue/package.json index 4b84f42a..fce507af 100644 --- a/ZR.Vue/package.json +++ b/ZR.Vue/package.json @@ -21,13 +21,14 @@ }, "dependencies": { "@riophae/vue-treeselect": "0.4.0", - "axios": "^0.21.1", + "axios": "^0.21.4", "clipboard": "2.0.4", "core-js": "3.6.5", "echarts": "^5.1.1", - "element-ui": "2.13.2", + "element-ui": "2.15.6", "file-saver": "2.0.1", "fuse.js": "3.4.4", + "highlight.js": "^11.2.0", "js-beautify": "1.10.2", "js-cookie": "2.2.0", "jsencrypt": "3.0.0-rc.1", diff --git a/ZR.Vue/public/index.html b/ZR.Vue/public/index.html index 6d64bf95..ad1a290d 100644 --- a/ZR.Vue/public/index.html +++ b/ZR.Vue/public/index.html @@ -1,13 +1,16 @@ - - - - - - - <%= webpackConfig.name %> - - - -
-
-
-
-
-
正在加载系统资源,请耐心等待
-
-
- + + + +
+
+
+ +
+

+
+ + diff --git a/ZR.Vue/src/api/monitor/operlog.js b/ZR.Vue/src/api/monitor/operlog.js index 07e27ab2..58def231 100644 --- a/ZR.Vue/src/api/monitor/operlog.js +++ b/ZR.Vue/src/api/monitor/operlog.js @@ -26,10 +26,10 @@ export function cleanOperlog() { } // 导出操作日志 -export function exportOperlog(query) { - return request({ - url: '/monitor/operlog/export', - method: 'get', - params: query - }) -} +// export function exportOperlog(query) { +// return request({ +// url: '/monitor/operlog/export', +// method: 'get', +// params: query +// }) +// } diff --git a/ZR.Vue/src/api/login.js b/ZR.Vue/src/api/system/login.js similarity index 100% rename from ZR.Vue/src/api/login.js rename to ZR.Vue/src/api/system/login.js diff --git a/ZR.Vue/src/api/tool/gen.js b/ZR.Vue/src/api/tool/gen.js index 45069278..ea4af5c4 100644 --- a/ZR.Vue/src/api/tool/gen.js +++ b/ZR.Vue/src/api/tool/gen.js @@ -1,39 +1,74 @@ import request from '@/utils/request' -// 查询生成表数据 -export function listTable(query) { +// 预览生成代码 +// export function previewTable(tableId) { +// return request({ +// url: '/tool/gen/preview/' + tableId, +// method: 'get' +// }) +// } + +/** + * 创建数据库连接 + */ +// export function createGetDBConn(data) { +// return request({ +// url: 'tool/gen/CreateDBConn', +// method: 'post', +// data: data, +// }) +// } +/** + * 获取数据库 + */ +export function codeGetDBList() { return request({ - url: '/tool/gen/list', + url: 'tool/gen/getDbList', method: 'get', - params: query }) } -// 查询db数据库列表 -export function listDbTable(query) { +/** + * 获取数据库表 + */ +export function listDbTable(data) { return request({ - url: '/tool/gen/db/list', + url: 'tool/gen/getTableList', method: 'get', - params: query + params: data, }) } +/** + * 生成代码 + */ +export async function codeGenerator(data) { + return await request({ + url: 'tool/gen/genCode', + method: 'post', + data: data, + }) +} + +/** + * 获取表格列信息 + * @param {*} data + * @returns + */ +export function queryColumnInfo(tableId) { + return request({ + url: 'tool/gen/Column/' + tableId, + method: 'GET', + }) +} + // 查询表详细信息 -export function getGenTable(tableId) { +export function getGenTable(params) { return request({ - url: '/tool/gen/' + tableId, - method: 'get' + url: 'tool/gen/listGenTable', + method: 'get', + params: params }) } - -// 修改代码生成信息 -export function updateGenTable(data) { - return request({ - url: '/tool/gen', - method: 'put', - data: data - }) -} - // 导入表 export function importTable(data) { return request({ @@ -42,6 +77,22 @@ export function importTable(data) { params: data }) } +// 删除表数据 +export function delTable(tableId) { + return request({ + url: '/tool/gen/' + tableId, + method: 'delete' + }) +} + +// 修改代码生成表信息 +export function updateGenTable(data) { + return request({ + url: '/tool/gen/', + method: 'put', + data: data + }) +} // 预览生成代码 export function previewTable(tableId) { @@ -51,26 +102,24 @@ export function previewTable(tableId) { }) } -// 删除表数据 -export function delTable(tableId) { - return request({ - url: '/tool/gen/' + tableId, - method: 'delete' - }) -} - -// 生成代码(自定义路径) -export function genCode(tableName) { - return request({ - url: '/tool/gen/genCode/' + tableName, - method: 'get' - }) -} - -// 同步数据库 -export function synchDb(tableName) { - return request({ - url: '/tool/gen/synchDb/' + tableName, - method: 'get' - }) -} +// /** +// * +// * 数据库解密 +// */ +// export function dbtoolsConnStrDecrypt(data) { +// return request({ +// url: 'DbTools/ConnStrDecrypt', +// method: 'post', +// params: data, +// }) +// } +// /** +// * 数据库加密 +// */ +// export function dbtoolsConnStrEncrypt(data) { +// return request({ +// url: 'DbTools/ConnStrEncrypt', +// method: 'post', +// params: data, +// }) +// } diff --git a/ZR.Vue/src/assets/styles/index.scss b/ZR.Vue/src/assets/styles/index.scss index 4133f953..7fbd419b 100644 --- a/ZR.Vue/src/assets/styles/index.scss +++ b/ZR.Vue/src/assets/styles/index.scss @@ -480,3 +480,17 @@ aside { position: relative; float: right; } +.icon { + width: 100px; +} +// 上传文件按钮样式 +.uploader-icon { + width: 50px; + height: 50px; + line-height: 50px; + border: 1px dashed #ccc; + margin-bottom: 10px; +} +.table-td-thumb { + width: 80px; +} diff --git a/ZR.Vue/src/components/SizeSelect/index.vue b/ZR.Vue/src/components/SizeSelect/index.vue index e88065b4..25698637 100644 --- a/ZR.Vue/src/components/SizeSelect/index.vue +++ b/ZR.Vue/src/components/SizeSelect/index.vue @@ -1,12 +1,11 @@ diff --git a/ZR.Vue/src/views/monitor/online/index.vue b/ZR.Vue/src/views/monitor/online/index.vue deleted file mode 100644 index a33614bd..00000000 --- a/ZR.Vue/src/views/monitor/online/index.vue +++ /dev/null @@ -1,128 +0,0 @@ - - - - diff --git a/ZR.Vue/src/views/monitor/operlog/index.vue b/ZR.Vue/src/views/monitor/operlog/index.vue index 081b7288..b4ba071f 100644 --- a/ZR.Vue/src/views/monitor/operlog/index.vue +++ b/ZR.Vue/src/views/monitor/operlog/index.vue @@ -38,7 +38,7 @@ - + @@ -121,11 +121,10 @@ import { cleanOperlog, exportOperlog, } from "@/api/monitor/operlog"; -import template from "../../../../document/template.vue"; import DateRangePicker from '@/components/DateRangePicker' export default { - components: { template ,DateRangePicker}, + components: { DateRangePicker}, name: "Operlog", data() { return { diff --git a/ZR.Vue/src/views/article/manager.vue b/ZR.Vue/src/views/system/article/manager.vue similarity index 99% rename from ZR.Vue/src/views/article/manager.vue rename to ZR.Vue/src/views/system/article/manager.vue index e8bc72df..0f4570d6 100644 --- a/ZR.Vue/src/views/article/manager.vue +++ b/ZR.Vue/src/views/system/article/manager.vue @@ -71,8 +71,6 @@ export default { showSearch: true, // 查询参数 queryParams: { - useridx: undefined, - name: undefined, }, // 弹出层标题 title: "", diff --git a/ZR.Vue/src/views/article/publish.vue b/ZR.Vue/src/views/system/article/publish.vue similarity index 100% rename from ZR.Vue/src/views/article/publish.vue rename to ZR.Vue/src/views/system/article/publish.vue diff --git a/ZR.Vue/src/views/system/menu/index.vue b/ZR.Vue/src/views/system/menu/index.vue index bd0cda25..dc1d0f29 100644 --- a/ZR.Vue/src/views/system/menu/index.vue +++ b/ZR.Vue/src/views/system/menu/index.vue @@ -48,7 +48,12 @@ - + + +