// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using OfficeOpenXml;
using System.IO.Compression;
namespace Admin.NET.Core.Service;
///
/// 系统代码生成器服务 🧩
///
[ApiDescriptionSettings(Order = 270)]
public class SysCodeGenService : IDynamicApiController, ITransient
{
private readonly ISqlSugarClient _db;
private readonly SysCodeGenConfigService _codeGenConfigService;
private readonly SysEnumService _sysEnumService;
private readonly IViewEngine _viewEngine;
private readonly CodeGenOptions _codeGenOptions;
public SysCodeGenService(ISqlSugarClient db,
SysCodeGenConfigService codeGenConfigService,
IViewEngine viewEngine,
SysEnumService sysEnumService,
IOptions codeGenOptions)
{
_db = db;
_codeGenConfigService = codeGenConfigService;
_sysEnumService = sysEnumService;
_viewEngine = viewEngine;
_codeGenOptions = codeGenOptions.Value;
}
///
/// 获取代码生成分页列表 🔖
///
///
///
[DisplayName("获取代码生成分页列表")]
public async Task> Page(CodeGenInput input)
{
var ret = await _db.Queryable()
.WhereIF(!string.IsNullOrWhiteSpace(input.TableName), u => u.TableName.Contains(input.TableName.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(input.BusName), u => u.BusName.Contains(input.BusName.Trim()))
.Select()
.OrderByDescending(x => x.UpdateTime)
.ToPagedListAsync(input.Page, input.PageSize);
foreach (var item in ret.Items)
{
//单独处理按钮 【Editby shaocx,2024-05-27】
if (!string.IsNullOrEmpty(item.Buttons))
{
item.ButtonsList = item.Buttons.Split(",").ToList();
}
}
return ret;
}
///
/// 增加代码生成 🔖
///
///
///
[ApiDescriptionSettings(Name = "Add"), HttpPost]
[DisplayName("增加代码生成")]
public async Task AddCodeGen(AddCodeGenInput input)
{
var isExist = await _db.Queryable().Where(u => u.TableName == input.TableName).AnyAsync();
if (isExist)
throw Oops.Oh(ErrorCodeEnum.D1400);
var codeGen = input.Adapt();
//单独处理按钮 【Editby shaocx,2024-05-27】
codeGen.Buttons = string.Join(",", input.ButtonsList);
var newCodeGen = await _db.Insertable(codeGen).ExecuteReturnEntityAsync();
// 加入配置表中
_codeGenConfigService.AddList(GetColumnList(input), newCodeGen);
}
///
/// 更新代码生成 🔖
///
///
///
[ApiDescriptionSettings(Name = "Update"), HttpPost]
[DisplayName("更新代码生成")]
public async Task UpdateCodeGen(UpdateCodeGenInput input)
{
var isExist = await _db.Queryable().AnyAsync(u => u.TableName == input.TableName && u.Id != input.Id);
if (isExist)
throw Oops.Oh(ErrorCodeEnum.D1400);
var isExistObj = await _db.Queryable().FirstAsync(u => u.Id == input.Id);
if (isExistObj == null)
throw Oops.Oh(ErrorCodeEnum.D1002);
//判断如果生成表变化了,就需要重置配置表 【Editby shaocx,2024-04-13】
var isChangeTableName = false;
if (input.TableName != isExistObj.TableName)
{
isChangeTableName = true;
}
var codeGen = input.Adapt();
if (input.ButtonsList?.Count > 0)
{
//单独处理按钮 【Editby shaocx,2024-05-27】
codeGen.Buttons = string.Join(",", input.ButtonsList);
}
await _db.Updateable(codeGen).ExecuteCommandAsync();
if (isChangeTableName)
{
// 刷新配置表
await Refresh(input.Id);
}
}
///
/// 删除代码生成 🔖
///
///
///
[ApiDescriptionSettings(Name = "Delete"), HttpPost]
[DisplayName("删除代码生成")]
public async Task DeleteCodeGen(List inputs)
{
if (inputs == null || inputs.Count < 1) return;
int flag = inputs.First().DelFlag;
if (flag == 2)
{//重置配置
await Refresh(inputs.First().Id);
}
else
{//删除
var codeGenConfigTaskList = new List();
inputs.ForEach(u =>
{
_db.Deleteable().In(u.Id).ExecuteCommand();
// 删除配置表中
codeGenConfigTaskList.Add(_codeGenConfigService.DeleteCodeGenConfig(u.Id));
});
await Task.WhenAll(codeGenConfigTaskList);
}
}
///
/// 刷新配置表
///
///
[HttpGet("refresh/{id}")]
[DisplayName("刷新配置表")]
public async Task Refresh(long id)
{
var item = await _db.Queryable().Where(u => u.Id == id).FirstAsync();
// 删除配置表中
await _codeGenConfigService.DeleteCodeGenConfig(id);
// 加入配置表中
_codeGenConfigService.AddList(GetColumnList(item.Adapt()), item);
}
///
/// 获取代码生成详情 🔖
///
///
///
[DisplayName("获取代码生成详情")]
public async Task GetDetail([FromQuery] QueryCodeGenInput input)
{
return await _db.Queryable().SingleAsync(u => u.Id == input.Id);
}
///
/// 获取数据库库集合 🔖
///
///
[DisplayName("获取数据库库集合")]
public async Task> GetDatabaseList()
{
var dbConfigs = App.GetOptions().ConnectionConfigs;
return await Task.FromResult(dbConfigs.Adapt>());
}
///
/// 获取数据库表(实体)集合 🔖
///
///
[DisplayName("获取数据库表(实体)集合")]
public async Task> GetTableList(string configId = SqlSugarConst.MainConfigId)
{
var provider = _db.AsTenant().GetConnectionScope(configId);
var dbTableInfos = provider.DbMaintenance.GetTableInfoList(false); // 不能走缓存,否则切库不起作用
var dbViewInfos = provider.DbMaintenance.GetViewInfoList(false);// 不能走缓存,否则切库不起作用,增加视图 【Editby shaocx,2024-05-15】
var config = App.GetOptions().ConnectionConfigs.FirstOrDefault(u => configId.Equals(u.ConfigId));
var dbTableNames = dbTableInfos.Select(u => u.Name.ToLower()).ToList();
IEnumerable entityInfos = await GetEntityInfos();
var tableOutputList = new List();
foreach (var item in entityInfos)
{
var table = dbTableInfos.FirstOrDefault(u => u.Name.ToLower() == (config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(item.DbTableName) : item.DbTableName).ToLower());
if (table != null)
{
tableOutputList.Add(new TableOutput
{
ConfigId = configId,
EntityName = item.EntityName,
TableName = table.Name,
TableComment = item.TableDescription
});
}
else
{//增加视图 【Editby shaocx,2024-05-15】
var view = dbViewInfos.FirstOrDefault(u => u.Name.ToLower() == (config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(item.DbTableName) : item.DbTableName).ToLower());
if (view != null)
{
tableOutputList.Add(new TableOutput
{
ConfigId = configId,
EntityName = item.EntityName,
TableName = view.Name,
TableComment = item.TableDescription
});
}
}
}
return tableOutputList;
}
///
/// 根据表名获取列集合 🔖
///
///
[DisplayName("根据表名获取列集合")]
public List GetColumnListByTableName([Required] string tableName, string configId = SqlSugarConst.MainConfigId)
{
// 切库---多库代码生成用
var provider = _db.AsTenant().GetConnectionScope(configId);
var config = App.GetOptions().ConnectionConfigs.FirstOrDefault(u => u.ConfigId.ToString() == configId);
// 获取实体类型属性
var entityType = provider.DbMaintenance.GetTableInfoList(false).FirstOrDefault(u => u.Name == tableName);
if (entityType == null) return null;
var entityBasePropertyNames = _codeGenOptions.EntityBaseColumn[nameof(EntityTenant)];
// 按原始类型的顺序获取所有实体类型属性(不包含导航属性,会返回null)
return provider.DbMaintenance.GetColumnInfosByTableName(entityType.Name).Select(u => new ColumnOuput
{
ColumnName = config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(u.DbColumnName, entityBasePropertyNames) : u.DbColumnName,
ColumnKey = u.IsPrimarykey.ToString(),
DataType = u.DataType.ToString(),
NetType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
ColumnComment = u.ColumnDescription
}).ToList();
}
///
/// 获取数据表列(实体属性)集合
///
///
private List GetColumnList([FromQuery] AddCodeGenInput input)
{
var entityType = GetEntityInfos().GetAwaiter().GetResult().FirstOrDefault(u => u.EntityName == input.TableName);
if (entityType == null)
return null;
var config = App.GetOptions().ConnectionConfigs.FirstOrDefault(u => u.ConfigId.ToString() == input.ConfigId);
var dbTableName = config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(entityType.DbTableName) : entityType.DbTableName;
// 切库---多库代码生成用
var provider = _db.AsTenant().GetConnectionScope(!string.IsNullOrEmpty(input.ConfigId) ? input.ConfigId : SqlSugarConst.MainConfigId);
var entityBasePropertyNames = _codeGenOptions.EntityBaseColumn[nameof(EntityTenant)];
var columnInfos = provider.DbMaintenance.GetColumnInfosByTableName(dbTableName, false);
var result = columnInfos.Select(u => new ColumnOuput
{
// 转下划线后的列名需要再转回来(暂时不转)
//ColumnName = config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(u.DbColumnName, entityBasePropertyNames) : u.DbColumnName,
ColumnName = u.DbColumnName,
ColumnLength = u.Length,
IsPrimarykey = u.IsPrimarykey,
IsNullable = u.IsNullable,
ColumnKey = u.IsPrimarykey.ToString(),
NetType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
DataType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
ColumnComment = string.IsNullOrWhiteSpace(u.ColumnDescription) ? u.DbColumnName : u.ColumnDescription
}).ToList();
// 获取实体的属性信息,赋值给PropertyName属性(CodeFirst模式应以PropertyName为实际使用名称)
var entityProperties = entityType.Type.GetProperties();
for (int i = result.Count - 1; i >= 0; i--)
{
var columnOutput = result[i];
// 先找自定义字段名的,如果找不到就再找自动生成字段名的(并且过滤掉没有SugarColumn的属性)
var propertyInfo = entityProperties.FirstOrDefault(p => (p.GetCustomAttribute()?.ColumnName ?? "").ToLower() == columnOutput.ColumnName.ToLower()) ??
entityProperties.FirstOrDefault(p => p.GetCustomAttribute() != null && p.Name.ToLower() == (config.DbSettings.EnableUnderLine
? CodeGenUtil.CamelColumnName(columnOutput.ColumnName, entityBasePropertyNames).ToLower()
: columnOutput.ColumnName.ToLower()));
if (propertyInfo != null)
{
columnOutput.PropertyName = propertyInfo.Name;
columnOutput.ColumnComment = propertyInfo.GetCustomAttribute().ColumnDescription;
//修改赋值类型 【Editby shaocx,2024-05-10】
columnOutput.NetType = propertyInfo.PropertyType.ToString();
//判断是否是枚举类型 【Editby shaocx,2024-05-10】
if (propertyInfo.PropertyType.IsEnum || propertyInfo.PropertyType.FullName.IndexOf("Enum") > -1)
{
columnOutput.IsEnum = true;
}
}
else
{
result.RemoveAt(i); // 移除没有定义此属性的字段
}
}
return result;
}
///
/// 获取库表信息
///
///
private async Task> GetEntityInfos()
{
var entityInfos = new List();
var type = typeof(SugarTable);
var type_view = typeof(MySugarTableViewAttribute);//增加视图 【Editby shaocx,2024-05-15】
var types = new List();
if (_codeGenOptions.EntityAssemblyNames != null)
{
foreach (var assemblyName in _codeGenOptions.EntityAssemblyNames)
{
Assembly asm = Assembly.Load(assemblyName);
types.AddRange(asm.GetExportedTypes().ToList());
}
}
bool IsMyAttribute(Attribute[] o)
{
foreach (Attribute a in o)
{
if (a.GetType() == type || a.GetType() == type_view)
return true;
}
return false;
}
Type[] cosType = types.Where(o =>
{
return IsMyAttribute(Attribute.GetCustomAttributes(o, true));
}
).ToArray();
var _TableName = "";
var _TableDescription = "";
foreach (var c in cosType)
{
var sugarAttribute = c.GetCustomAttributes(type, true)?.FirstOrDefault();
if (sugarAttribute == null)
{//增加视图 【Editby shaocx,2024-05-15】
sugarAttribute = c.GetCustomAttributes(type_view, true)?.FirstOrDefault();
_TableName = ((MySugarTableViewAttribute)sugarAttribute).TableName;
_TableDescription = ((MySugarTableViewAttribute)sugarAttribute).TableDescription;
}
else
{
_TableName = ((SugarTable)sugarAttribute).TableName;
_TableDescription = ((SugarTable)sugarAttribute).TableDescription;
}
var des = c.GetCustomAttributes(typeof(DescriptionAttribute), true);
var description = "";
if (des.Length > 0)
{
description = ((DescriptionAttribute)des[0]).Description;
}
entityInfos.Add(new EntityInfo()
{
EntityName = c.Name,
DbTableName = sugarAttribute == null ? c.Name : _TableName,
TableDescription = sugarAttribute == null ? description : _TableDescription,
Type = c
});
}
return await Task.FromResult(entityInfos);
}
///
/// 获取程序保存位置 🔖
///
///
[DisplayName("获取程序保存位置")]
public List GetApplicationNamespaces()
{
return _codeGenOptions.BackendApplicationNamespaces;
}
///
/// 代码生成到本地 🔖
///
///
[DisplayName("代码生成到本地")]
public async Task RunLocal(SysCodeGen input)
{
if (string.IsNullOrEmpty(input.GenerateType))
input.GenerateType = "200";
// 先删除该表已生成的菜单列表
var templatePathList = GetTemplatePathList(input);
List targetPathList;
var zipPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
if (input.GenerateType.StartsWith('1'))
{
targetPathList = GetZipPathList(input);
if (Directory.Exists(zipPath))
Directory.Delete(zipPath, true);
}
else
targetPathList = GetTargetPathList(input);
var tableFieldList = await _codeGenConfigService.GetList(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
var queryWhetherList = tableFieldList.Where(u => u.QueryWhether == YesNoEnum.Y.ToString()).ToList(); // 前端查询集合
var joinTableList = tableFieldList.Where(u => u.EffectType == "Upload" || u.EffectType == "fk" || u.EffectType == "ApiTreeSelect").ToList(); // 需要连表查询的字段
(string joinTableNames, string lowerJoinTableNames) = GetJoinTableStr(joinTableList); // 获取连表的实体名和别名
if (input.GenerateType.StartsWith('2'))
{
CodeGenUtil.ValidateCodeGenConfig(tableFieldList);
}
//处理可空类型 【Editby shaocx,2024-04-07】
tableFieldList.ForEach(u =>
{
u.NetTypeIsNullLableForQueryInput = "?";
u.NetTypeIsNullLableForAddEditOutParam = "";
switch (u.NetType.ToLower())
{
case "int":
case "int32":
case "long":
case "guid":
case "decimal":
case "datetime":
case "datetimeoffset":
case "bool": //增加布尔类型的条件 【Editby shaocx,2024-04-07】
u.NetTypeIsNullLable = "?";
if (u.WhetherRequired != "Y")
{
u.NetTypeIsNullLableForAddEditOutParam = "?";
}
break;
case "string":
u.NetTypeIsNullLableForQueryInput = "";
break;
default://其他,比如枚举 【Editby shaocx,2024-04-07】
if (u.WhetherRequired != "Y")
{
u.NetTypeIsNullLableForAddEditOutParam = "?";
}
break;
}
//u.OriginalColumnName = u.ColumnName;
});
//获取导入功能自定义模板代码
StringBuilder templateContent = null;
templateContent = CreateImportExcelTemplteCode(input, tableFieldList);
var data = new CustomViewEngine(_db)
{
ConfigId = input.ConfigId,
AuthorName = input.AuthorName,
BusName = input.BusName,
NameSpace = input.NameSpace,
ClassName = input.TableName,
ModuleName = input.ModuleName,
Buttons = input.Buttons,
ImportExcelCustomizationContent = templateContent.ToString(),
ProjectLastName = input.NameSpace.Split('.').Last(),
QueryWhetherList = queryWhetherList,
TableField = tableFieldList,
IsJoinTable = joinTableList.Count > 0,
IsUpload = joinTableList.Where(u => u.EffectType == "Upload").Any(),
PrintType = input.PrintType,
PrintName = input.PrintName,
TableType = input.TableType,
KeyQueryStr = string.Join(",", tableFieldList.Where(x => x.WhetherKeyQuery == "Y").Select(x => x.ColumnComment).ToList())
};
for (var i = 0; i < templatePathList.Count; i++)
{
if (data.TableType == "视图" && templatePathList[i].IndexOf("editDialog.vue.vm") > -1) continue;
if (!File.Exists(templatePathList[i])) continue;
var tContent = File.ReadAllText(templatePathList[i]);
var tResult = await _viewEngine.RunCompileFromCachedAsync(tContent, data, builderAction: builder =>
{
builder.AddAssemblyReferenceByName("System.Linq");
builder.AddAssemblyReferenceByName("System.Collections");
builder.AddUsing("System.Collections.Generic");
builder.AddUsing("System.Linq");
});
var dirPath = new DirectoryInfo(targetPathList[i]).Parent.FullName;
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
File.WriteAllText(targetPathList[i], tResult, Encoding.UTF8);
}
if (!string.IsNullOrEmpty(input.Buttons))
{//如果没有任何按钮,就不生成菜单 【Editby shaocx,2024-07-31】
await AddMenu(input, input.TableName, input.BusName, input.MenuPid, tableFieldList, input.ModuleName);
}
if (input.Buttons.Contains("导入"))
{
//创建导入模版
await CreateImportTemplte(input);
}
// 非ZIP压缩返回空
if (!input.GenerateType.StartsWith('1'))
return null;
else
{
string downloadPath = zipPath + ".zip";
// 判断是否存在同名称文件
if (File.Exists(downloadPath))
File.Delete(downloadPath);
ZipFile.CreateFromDirectory(zipPath, downloadPath);
return new { url = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}/CodeGen/{input.TableName}.zip" };
}
}
///
/// 获取连表的实体名和别名
///
///
///
private static (string, string) GetJoinTableStr(List configs)
{
var uploads = configs.Where(u => u.EffectType == "Upload").ToList();
var fks = configs.Where(u => u.EffectType == "fk").ToList();
string str = ""; //
string lowerStr = ""; // (o, i, c)
foreach (var item in uploads)
{
lowerStr += "sysFile_FK_" + item.LowerPropertyName + ",";
str += "SysFile,";
}
foreach (var item in fks)
{
lowerStr += item.LowerFkEntityName + "_FK_" + item.LowerFkColumnName + ",";
str += item.FkEntityName + ",";
}
return (str.TrimEnd(','), lowerStr.TrimEnd(','));
}
///
/// 增加菜单
///
///
///
///
///
///
///
///
private async Task AddMenu(SysCodeGen input, string className, string busName, long pid, List tableFieldList, string moduleName)
{
var pPath = string.Empty;
// 若 pid=0 为顶级则创建菜单目录
if (pid == 0)
{
// 目录
var menuType0 = new SysMenu
{
Pid = 0,
Title = busName,
Type = MenuTypeEnum.Dir,
Icon = "robot",
Path = "/" + className.ToLower(),
Component = "Layout",
};
// 若先前存在则删除本级和下级
var menuList0 = await _db.Queryable().Where(u => u.Title == menuType0.Title && u.Type == menuType0.Type).ToListAsync();
if (menuList0.Count > 0)
{
var listIds = menuList0.Select(u => u.Id).ToList();
var childlistIds = new List();
foreach (var item in listIds)
{
var childlist = await _db.Queryable().ToChildListAsync(u => u.Pid, item);
childlistIds.AddRange(childlist.Select(u => u.Id).ToList());
}
listIds.AddRange(childlistIds);
await _db.Deleteable().Where(u => listIds.Contains(u.Id)).ExecuteCommandAsync();
await _db.Deleteable().Where(u => listIds.Contains(u.MenuId)).ExecuteCommandAsync();
}
pid = (await _db.Insertable(menuType0).ExecuteReturnEntityAsync()).Id;
}
else
{
var pMenu = await _db.Queryable().FirstAsync(u => u.Id == pid) ?? throw Oops.Oh(ErrorCodeEnum.D1505);
pPath = pMenu.Path;
}
// 菜单
var menuType1 = new SysMenu
{
Pid = pid,
Title = busName,
Name = className[..1].ToLower() + className[1..],
Type = MenuTypeEnum.Menu,
Path = pPath + "/" + className.ToLower(),
Component = "/main/" + moduleName + @"/" + className[..1].ToLower() + className[1..] + "/index",
};
// 若先前存在则删除本级和下级
var menuList1 = await _db.Queryable().Where(u => u.Title == menuType1.Title && u.Type == menuType1.Type).ToListAsync();
if (menuList1.Count > 0)
{
var listIds = menuList1.Select(u => u.Id).ToList();
var childlistIds = new List();
foreach (var item in listIds)
{
var childlist = await _db.Queryable().ToChildListAsync(u => u.Pid, item);
childlistIds.AddRange(childlist.Select(u => u.Id).ToList());
}
listIds.AddRange(childlistIds);
await _db.Deleteable().Where(u => listIds.Contains(u.Id)).ExecuteCommandAsync();
await _db.Deleteable().Where(u => listIds.Contains(u.MenuId)).ExecuteCommandAsync();
}
var pid1 = (await _db.Insertable(menuType1).ExecuteReturnEntityAsync()).Id;
int menuOrder = 100;
var menuList = new List();
if (input.Buttons.Contains("查询"))
{
// 按钮-page
var menuType2 = new SysMenu
{
Pid = pid1,
Title = "查询",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":page",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2);
}
if (input.Buttons.Contains("详情"))
{
// 按钮-detail
var menuType2_1 = new SysMenu
{
Pid = pid1,
Title = "详情",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":detail",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_1);
}
if (input.Buttons.Contains("新增"))
{
// 按钮-add
var menuType2_2 = new SysMenu
{
Pid = pid1,
Title = "新增",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":add",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_2);
}
if (input.Buttons.Contains("删除"))
{
// 按钮-delete
var menuType2_3 = new SysMenu
{
Pid = pid1,
Title = "删除",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":delete",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_3);
}
if (input.Buttons.Contains("编辑"))
{
// 按钮-update
var menuType2_4 = new SysMenu
{
Pid = pid1,
Title = "编辑",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":update",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_4);
}
if (input.Buttons.Contains("导入"))
{
// 按钮-import 【Editby shaocx,2024-05-27】
var menuType2_5 = new SysMenu
{
Pid = pid1,
Title = "导入",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":importExcel",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_5);
}
if (input.Buttons.Contains("导出"))
{
// 按钮-import 【Editby shaocx,2024-05-27】
var menuType2_6 = new SysMenu
{
Pid = pid1,
Title = "导出",
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":exportExcel",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType2_6);
}
// 加入fk、Upload、ApiTreeSelect 等接口的权限
// 在生成表格时,有些字段只是查询时显示,不需要填写(WhetherAddUpdate),所以这些字段没必要生成相应接口
var fkTableList = tableFieldList.Where(u => u.EffectType == "fk" && (u.WhetherAddUpdate == "Y" || u.QueryWhether == "Y")).ToList();
foreach (var @column in fkTableList)
{
var menuType = new SysMenu
{
Pid = pid1,
Title = "外键" + @column.ColumnName,
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":" + column.FkEntityName + column.ColumnName + "Dropdown",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType);
}
var treeSelectTableList = tableFieldList.Where(u => u.EffectType == "ApiTreeSelect").ToList();
foreach (var @column in treeSelectTableList)
{
var menuType = new SysMenu
{
Pid = pid1,
Title = "树型" + @column.ColumnName,
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":" + column.FkEntityName + "Tree",
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType);
}
var uploadTableList = tableFieldList.Where(u => u.EffectType == "Upload").ToList();
foreach (var @column in uploadTableList)
{
var menuType = new SysMenu
{
Pid = pid1,
Title = "上传" + @column.ColumnName,
Type = MenuTypeEnum.Btn,
Permission = className[..1].ToLower() + className[1..] + ":Upload" + column.ColumnName,
OrderNo = menuOrder
};
menuOrder += 10;
menuList.Add(menuType);
}
await _db.Insertable(menuList).ExecuteCommandAsync();
}
///
/// 获取模板文件路径集合
///
///
private static List GetTemplatePathList(SysCodeGen input)
{
var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
if (input.GenerateType.Substring(1, 1).Contains('1'))
{
return new List()
{
Path.Combine(templatePath , "index.vue.vm"),
Path.Combine(templatePath , "editDialog.vue.vm"),
Path.Combine(templatePath , "manage.js.vm"),
};
}
else if (input.GenerateType.Substring(1, 1).Contains('2'))
{
return new List()
{
Path.Combine(templatePath , "Service.cs.vm"),
Path.Combine(templatePath , "Input.cs.vm"),
Path.Combine(templatePath , "Output.cs.vm"),
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//Path.Combine(templatePath , "Dto.cs.vm"),
};
}
else
{
return new List()
{
Path.Combine(templatePath , "Service.cs.vm"),
Path.Combine(templatePath , "Input.cs.vm"),
Path.Combine(templatePath , "Output.cs.vm"),
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//Path.Combine(templatePath , "Dto.cs.vm"),
Path.Combine(templatePath , "index.vue.vm"),
Path.Combine(templatePath , "editDialog.vue.vm"),
Path.Combine(templatePath , "manage.js.vm"),
};
}
}
///
/// 获取模板文件路径集合
///
///
private static List GetTemplatePathList()
{
var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
return new List()
{
Path.Combine(templatePath , "Service.cs.vm"),
Path.Combine(templatePath , "Input.cs.vm"),
Path.Combine(templatePath , "Output.cs.vm"),
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//Path.Combine(templatePath , "Dto.cs.vm"),
Path.Combine(templatePath , "index.vue.vm"),
Path.Combine(templatePath , "editDialog.vue.vm"),
Path.Combine(templatePath , "manage.js.vm"),
};
}
///
/// 设置生成文件路径
///
///
///
private List GetTargetPathList(SysCodeGen input)
{
//var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, _codeGenOptions.BackendApplicationNamespace, "Service", input.TableName);
var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, input.NameSpace, "Service", input.ModuleName, input.TableName);
var servicePath = Path.Combine(backendPath, input.TableName + "Service.cs");
var inputPath = Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
var outputPath = Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//var viewPath = Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
var frontendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName, _codeGenOptions.FrontRootPath, "src", "views", "main", input.ModuleName);
var indexPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "index.vue");//
var formModalPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "component", "editDialog.vue");
var apiJsPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName, _codeGenOptions.FrontRootPath, "src", "api", "main", input.ModuleName, input.TableName[..1].ToLower() + input.TableName[1..] + ".ts");
if (input.GenerateType.Substring(1, 1).Contains('1'))
{
// 生成到本项目(前端)
return new List()
{
indexPath,
formModalPath,
apiJsPath
};
}
else if (input.GenerateType.Substring(1, 1).Contains('2'))
{
// 生成到本项目(后端)
return new List()
{
servicePath,
inputPath,
outputPath,
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//viewPath,
};
}
else
{
// 前后端同时生成到本项目
return new List()
{
servicePath,
inputPath,
outputPath,
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//viewPath,
indexPath,
formModalPath,
apiJsPath
};
}
}
///
/// 设置生成文件路径
///
///
///
private List GetZipPathList(SysCodeGen input)
{
var zipPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
//var backendPath = Path.Combine(zipPath, _codeGenOptions.BackendApplicationNamespace, "Service", input.TableName);
var backendPath = Path.Combine(zipPath, input.NameSpace, "Service", input.TableName);
var servicePath = Path.Combine(backendPath, input.TableName + "Service.cs");
var inputPath = Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
var outputPath = Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//var viewPath = Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
var frontendPath = Path.Combine(zipPath, _codeGenOptions.FrontRootPath, "src", "views", "main");
var indexPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "index.vue");
var formModalPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "component", "editDialog.vue");
var apiJsPath = Path.Combine(zipPath, _codeGenOptions.FrontRootPath, "src", "api", "main", input.TableName[..1].ToLower() + input.TableName[1..] + ".ts");
if (input.GenerateType.StartsWith("11"))
{
return new List()
{
indexPath,
formModalPath,
apiJsPath
};
}
else if (input.GenerateType.StartsWith("12"))
{
return new List()
{
servicePath,
inputPath,
outputPath,
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//viewPath
};
}
else
{
return new List()
{
servicePath,
inputPath,
outputPath,
//不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
//viewPath,
indexPath,
formModalPath,
apiJsPath
};
}
}
#region 导入相关
//update by liuwq 20240418
///
/// 创建导入功能自定义模板代码
///
///
///
///
private static StringBuilder CreateImportExcelTemplteCode(SysCodeGen input, List tableFieldList)
{
StringBuilder templateContent = new StringBuilder();
var whetherAddUpdate = tableFieldList.Where(u => u.WhetherAddUpdate == YesNoEnum.Y.ToString()).ToList(); // 前端查询增改集合
templateContent.AppendLine(" ");
templateContent.AppendLine($" var addItem = new {input.TableName}();");
//templateContent.AppendLine($" var addItem = new {input.TableName}()");
//templateContent.AppendLine(" {");
//templateContent.AppendLine(" CreatedTime = SysHelper.GetNowTime(),");
//templateContent.AppendLine(" CreatedUserId = SysHelper.GetUserId(),");
//templateContent.AppendLine(" CreatedUserName = SysHelper.GetUserName(),");
//templateContent.AppendLine(" UpdatedTime = SysHelper.GetNowTime(),");
//templateContent.AppendLine(" UpdatedUserId = SysHelper.GetUserId(),");
//templateContent.AppendLine(" UpdatedUserName = SysHelper.GetUserName()");
//templateContent.AppendLine(" };");
templateContent.AppendLine(" #region 定义变量");
foreach (var item in whetherAddUpdate)
{
templateContent.AppendLine($" var _{item.ColumnName} = \"\";//{item.ColumnComment}");
}
templateContent.AppendLine(" #endregion");
templateContent.AppendLine(" ");
templateContent.AppendLine(" ");
templateContent.AppendLine(" #region 取值");
foreach (var item in whetherAddUpdate)
{
templateContent.AppendLine($" _{item.ColumnName} = row[\"{item.ColumnComment}\"]?.ToString() ;");
}
templateContent.AppendLine(" #endregion");
templateContent.AppendLine(" ");
templateContent.AppendLine(" ");
templateContent.AppendLine(" #region 验证");
//数值类型验证
List numericalTypeList = new List()
{
"int",
"long",
"decimal"
};
foreach (var item in whetherAddUpdate)
{
//必填字段验证是否为空
if (item.WhetherRequired.Equals("Y"))
{
templateContent.AppendLine(" ");
templateContent.AppendLine($" if (string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}不能为空!\");");
templateContent.AppendLine(" }");
templateContent.AppendLine(" ");
}
//验证值是否有效
//验证bool值
if (item.NetType.Equals("bool"))
{
templateContent.AppendLine($" if(!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" if(!_{item.ColumnName}.Equals(\"是\") && !_{item.ColumnName}.Equals(\"否\"))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
templateContent.AppendLine(" }");
templateContent.AppendLine(" else");
templateContent.AppendLine(" {");
templateContent.AppendLine($" bool out{item.ColumnName} = _{item.ColumnName}.Equals(\"是\") ? true : false;");
templateContent.AppendLine($" addItem.{item.ColumnName} = out{item.ColumnName};");
templateContent.AppendLine(" }");
templateContent.AppendLine(" }");
templateContent.AppendLine(" ");
}
//验证枚举值是否有效
else if (!string.IsNullOrWhiteSpace(item.DictTypeCode))//字典code不为空 是使用枚举值
{
templateContent.AppendLine($" if(!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" {item.NetType} enum{item.ColumnName} = default({item.NetType});");
templateContent.AppendLine(" ");
templateContent.AppendLine($" if(!Enum.TryParse<{item.NetType}>(_{item.ColumnName}, out enum{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
templateContent.AppendLine(" }");
templateContent.AppendLine(" else");
templateContent.AppendLine(" {");
templateContent.AppendLine($" addItem.{item.ColumnName} = enum{item.ColumnName};");
templateContent.AppendLine(" }");
templateContent.AppendLine(" ");
templateContent.AppendLine(" }");
}//验证数值是否有效
else if (numericalTypeList.Any(a => a == item.NetType))
{
templateContent.AppendLine($" if(!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" if (!{item.NetType}.TryParse(_{item.ColumnName}, out {item.NetType} out{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
templateContent.AppendLine(" }");
templateContent.AppendLine($" if (out{item.ColumnName} <= 0&&!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
templateContent.AppendLine($" throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不能小于等于0!\");");
templateContent.AppendLine(" }");
templateContent.AppendLine(" else");
templateContent.AppendLine(" {");
templateContent.AppendLine($" addItem.{item.ColumnName} = out{item.ColumnName};");
templateContent.AppendLine(" }");
templateContent.AppendLine(" ");
templateContent.AppendLine(" }");
}
else
{
templateContent.AppendLine($" if(!string.IsNullOrEmpty(_{item.ColumnName}))");
templateContent.AppendLine(" {");
//日期控件
if (item.EffectType.ToLower() == "datepicker")
{
templateContent.AppendLine($" addItem.{item.ColumnName} = Convert.ToDateTime(Convert.ToDateTime(_{item.ColumnName}.Trim()).ToShortDateString());");
}//日期时间控件
else if (item.EffectType.ToLower() == "datetimepicker")
{
templateContent.AppendLine($" addItem.{item.ColumnName} = Convert.ToDateTime(_{item.ColumnName}.Trim());");
}
else
{
templateContent.AppendLine($" addItem.{item.ColumnName} = ({item.NetType})(_{item.ColumnName}.Trim());");
}
templateContent.AppendLine(" }");
}
}
templateContent.AppendLine(" #endregion");
templateContent.AppendLine(" ");
return templateContent;
}
///
/// 根据表名创建导入模版
///
///
private async Task CreateImportTemplte(SysCodeGen input)
{
string errMsg = string.Empty;
//业务名
string _busName = input.BusName;
var copayPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + "\\CommonTemplate.xlsx";
string newPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + $"\\{_busName}{TemplateConst.EXCEL_TEMPLATEFILE_导入模版名称后缀}.xlsx";
var tableFieldList = await _codeGenConfigService.GetList(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
CreatExcel(tableFieldList, copayPath, newPath);
}
///
/// 根据实体类名 生成导入excel模版
///
/// 代码生成选择配置表的字段
///
///
private void CreatExcel(List tableFieldList, string copayPath, string newPath)
{
string errMsg = string.Empty;
try
{
#region 验证原始导入模板文件是否存在
if (!File.Exists(copayPath))
{
errMsg = $"用来复制生成模版的EXCEL文件不存在";
throw Oops.Oh($"生成导入模版文件异常:{errMsg}");
}
#endregion
//获取模板文件
FileInfo copyFile = new FileInfo(copayPath);
// 检查新生成的导入模版文件是否存在,存在就删除,以避免可能的异常。
if (File.Exists(newPath))
{
File.Delete(newPath); // 删除文件
}
//复制原始导入模版,创建新的导入模版文件
copyFile.CopyTo(newPath, true);
FileInfo existingFile = new FileInfo(newPath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//获取模板内容
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];//获取第一个worksheet
//行和列都是从1开始,而不是从0开始!!!
int _remarkRowIndex = 1;//worksheet 行索引(说明) 注意:默认是第一行是导入模版的说明
int _mergeRowCount = _remarkRowIndex;//合并行 (必填字段数量) 默认是第一行合并
int _titleRowIndex = 2;//worksheet 行索引(标题)注意:默认是第一行是导入模版的标题
int _cellIndex = 1;//worksheet 列索引 注意:默认是第一列开始设置导入模版的标题
//模版第一列作为模版使用,所有新增的列样式报错一致
var templateCell = worksheet.Cells[_titleRowIndex, _cellIndex];
string _remark = string.Empty; //第一行添加说明,注意换行。
//获取要处理的代码生成配置的是增改的模版字段
var showCodeGenConfigs = tableFieldList.Where(w => w.WhetherAddUpdate.Equals("Y")).ToList();
showCodeGenConfigs = showCodeGenConfigs.Where(x => x.ColumnKey.ToLower() == "false").ToList();
int _mergeCellsCount = showCodeGenConfigs.Count();//合并列(模版赋值的标题列数)
//获取必填字段
//创建模版说明
StringBuilder _remarkContentBuilder = GetParseTemplateHint(showCodeGenConfigs);
string _remarkContent = _remarkContentBuilder.ToString();
#region 合并单元格
//合并单元格,合并行和列。默认是合并第一行的所有标题列
var cellRange = worksheet.Cells[1, 1, _mergeRowCount, _mergeCellsCount];
cellRange.Value = _remarkContent;//合并单元格后的内容赋值
var mergeCell = cellRange.Merge = true;//合并
int rowHeight = GetRowHeightBasedOnContent(showCodeGenConfigs.Count()); // 根据内容计算行高(这里需要你自己实现逻辑)
worksheet.Row(_remarkRowIndex).Height = rowHeight; // 设置行高,注意EPPlus的单位不同,需要转换
#endregion
//循环创建模版标题列
foreach (var item in showCodeGenConfigs)
{
var currentCell = worksheet.Cells[_titleRowIndex, _cellIndex];
//给新模版列标题赋值
currentCell.Value = item.ColumnComment;
//复制拷贝的excel模版列,给新模版列样式赋值
currentCell.StyleID = templateCell.StyleID;
// worksheet.Column(_cellIndex).AutoFit();//宽度自适应
_cellIndex++;
}
package.Save();//保存
}
}
catch (Exception ex)
{
throw Oops.Oh($"生成导入模版文件异常,请查看系统日志:" + ex.Message);
}
finally { }
}
// 这里是一个假设的方法,用于根据单元格内容计算行高。你需要根据实际情况来实现这个逻辑。
private static int GetRowHeightBasedOnContent(int lineCount)
{
// 这里只是一个示例逻辑,你可能需要更复杂的算法来决定合适的行高。
return (lineCount + 3) * 20; //
}
private StringBuilder GetParseTemplateHint(List requiredTableFieldList)
{
StringBuilder _remarkContentBuilder = new StringBuilder();
_remarkContentBuilder.AppendLine("");
_remarkContentBuilder.AppendLine("1.支持Excel2007及以上版本文件。");
_remarkContentBuilder.AppendLine("2.导入数据时不能超过5000行。");
_remarkContentBuilder.AppendLine("");
_remarkContentBuilder.AppendLine("");
Dictionary typeNameDict = new()
{
{ "string", "输入文本。"},
{ "int", "输入数字。"},
{ "long", "输入数字。"},
{ "decimal", "输入小数。"},
{ "bool", "是,否。"},
};
Dictionary effectTypeDict = new()
{
{ "datepicker", "日期。 示例: 2023/3/1。"},
{ "datetimepicker", "日期时间。示例: 2023/3/1 12:00:00。"},
};
requiredTableFieldList.ForEach(x =>
{
string text = "";
text += x.ColumnComment + "(" + (x.WhetherRequired.Equals("Y") ? "必填" : "非必填") + "): ";
var _dataType = x.DataType.Replace("?", "").ToLower();
if (effectTypeDict.ContainsKey(x.EffectType.ToLower()))
{
text += effectTypeDict[x.EffectType.ToLower()];
}
else if (x.EffectType.ToLower() == "enumselector")
{//注意:这个判断要放在判断_dataType前面,主要是考虑枚举和int类型的混淆
var queryValue = x.NetType.Split('.').Last();
var enumStr = _sysEnumService.GetEnumDataListStr(new EnumDataInput() { EnumName = queryValue });
text += enumStr + "。";
}
else if (typeNameDict.ContainsKey(_dataType))
{
text += typeNameDict[_dataType];
}
else
{
text += ("注意:类型未能识别出来,需要自己维护!!!。");
}
_remarkContentBuilder.AppendLine(text);
});
return _remarkContentBuilder;
}
///
/// 根据属性名称判断是否是枚举类型
///
///
///
///
///
public static bool IsEnumProperty(Type type, string propertyName)
{
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo == null)
{
throw new ArgumentException("Property not found", nameof(propertyName));
}
return propertyInfo.PropertyType.IsEnum;
}
#endregion
}