平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BatchEditService.cs 7.8 KiB

4 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. 
  2. //
  3. namespace SafeCampus.System;
  4. /// <summary>
  5. /// <inheritdoc cref="IBatchEditService"/>
  6. /// </summary>
  7. public class BatchEditService : DbRepository<BatchEdit>, IBatchEditService
  8. {
  9. private readonly ILogger<BatchEditService> _logger;
  10. public BatchEditService(ILogger<BatchEditService> logger)
  11. {
  12. _logger = logger;
  13. }
  14. /// <inheritdoc/>
  15. public async Task<SqlSugarPagedList<BatchEdit>> Page(BatchEditPageInput input)
  16. {
  17. var query = Context.Queryable<BatchEdit>()
  18. .WhereIF(!string.IsNullOrWhiteSpace(input.ConfigId), it => it.ConfigId.Contains(input.ConfigId.Trim()))
  19. .WhereIF(!string.IsNullOrWhiteSpace(input.EntityName), it => it.EntityName.Contains(input.EntityName.Trim()))
  20. .WhereIF(!string.IsNullOrWhiteSpace(input.TableName), it => it.TableName.Contains(input.TableName.Trim()))
  21. //.WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Name.Contains(input.SearchKey))//根据关键字查询
  22. .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}");
  23. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  24. return pageInfo;
  25. }
  26. /// <inheritdoc />
  27. public async Task Add(BatchEditAddInput input)
  28. {
  29. var entity = input.Adapt<BatchEdit>();//实体转换
  30. await CheckInput(entity);//检查参数
  31. var tableColumns = SqlSugarUtils.GetTableColumns(input.ConfigId, input.TableName);//获取表的字段信息
  32. var batchEdiConfig = new List<BatchEditConfig>();//代码生成配置字段集合
  33. //遍历字段
  34. tableColumns.ForEach(it =>
  35. {
  36. //判断是否是主键或者通用字段
  37. var isPkOrCommon = it.IsPrimaryKey || SqlSugarUtils.IsCommonColumn(it.ColumnName);
  38. if (!isPkOrCommon)
  39. {
  40. //添加到字段集合
  41. batchEdiConfig.Add(GetUpdateBatchConfig(it));
  42. }
  43. });
  44. //事务
  45. var result = await Tenant.UseTranAsync(async () =>
  46. {
  47. entity = await InsertReturnEntityAsync(entity);//输入参数转实体并插入
  48. batchEdiConfig.ForEach(it => { it.UId = entity.Id; });//遍历字段赋值基础Id
  49. await Context.Insertable(batchEdiConfig).ExecuteCommandAsync();
  50. });
  51. if (!result.IsSuccess)//如果失败了
  52. {
  53. //写日志
  54. _logger.LogError(result.ErrorMessage, result.ErrorException);
  55. throw Oops.Oh(ErrorCodeEnum.A0003);
  56. }
  57. }
  58. /// <inheritdoc />
  59. public async Task Config(List<BatchEditConfigInput> input)
  60. {
  61. var updateBatch = input.Adapt<List<BatchEditConfig>>();//实体转换
  62. var configRep = ChangeRepository<DbRepository<BatchEditConfig>>();
  63. var ids = input.Select(it => it.Id).ToList();//获取当前配置Id
  64. if (ids.Any())
  65. {
  66. await configRep.DeleteAsync(it => !ids.Contains(it.Id) && it.UId == input.First().UId);//删除没有的
  67. await Context.Updateable(updateBatch).ExecuteCommandAsync();//更新数据
  68. }
  69. }
  70. /// <inheritdoc />
  71. public async Task Delete(BaseIdListInput input)
  72. {
  73. //获取所有ID
  74. var ids = input.Ids;
  75. if (ids.Count > 0)
  76. {
  77. //事务
  78. var result = await Tenant.UseTranAsync(async () =>
  79. {
  80. await DeleteByIdsAsync(ids.Cast<object>().ToArray());//删除数据
  81. await Context.Deleteable<BatchEditConfig>().Where(it => ids.Contains(it.UId)).ExecuteCommandAsync();
  82. });
  83. if (!result.IsSuccess)//如果失败了
  84. {
  85. //写日志
  86. _logger.LogError(result.ErrorMessage, result.ErrorException);
  87. throw Oops.Oh(ErrorCodeEnum.A0003);
  88. }
  89. }
  90. }
  91. /// <inheritdoc />
  92. public async Task SyncColumns(BaseIdInput input)
  93. {
  94. var config = await GetFirstAsync(it => it.Id == input.Id);
  95. if (config != null)
  96. {
  97. var newColumns = new List<BatchEditConfig>();
  98. //获取表的字段信息
  99. var tableColumns = SqlSugarUtils.GetTableColumns(config.ConfigId, config.TableName);
  100. //找到当前配置字段列表
  101. var batchEdiConfig = await Context.Queryable<BatchEditConfig>().Where(it => it.UId == config.Id).ToListAsync();
  102. foreach (var tableColumn in tableColumns)
  103. {
  104. //判断是否是主键或者通用字段
  105. var isPkOrCommon = tableColumn.IsPrimaryKey || SqlSugarUtils.IsCommonColumn(tableColumn.ColumnName);
  106. if (!isPkOrCommon)
  107. {
  108. //如果当前配置没有
  109. if (!batchEdiConfig.Any(it => it.ColumnName == tableColumn.ColumnName))
  110. {
  111. var netType = SqlSugarUtils.ConvertDataType(tableColumn.DataType);
  112. //添加到字段集合
  113. newColumns.Add(GetUpdateBatchConfig(tableColumn));
  114. }
  115. }
  116. }
  117. if (newColumns.Count > 0)
  118. {
  119. newColumns.ForEach(it => it.UId = config.Id);
  120. await Context.Insertable(newColumns).ExecuteCommandAsync();//插入新的字段数据
  121. }
  122. }
  123. }
  124. /// <inheritdoc />
  125. public async Task<List<BatchEditConfig>> Columns(string code)
  126. {
  127. var batchEdiConfig = new List<BatchEditConfig>();
  128. var updateBatch = await GetFirstAsync(it => it.Code == code);//根据code获取配置
  129. if (updateBatch != null)
  130. {
  131. //找到对应字段
  132. batchEdiConfig = await Context.Queryable<BatchEditConfig>().Where(it => it.UId == updateBatch.Id && it.Status == CommonStatusConst.ENABLE)
  133. .ToListAsync();
  134. }
  135. return batchEdiConfig;
  136. }
  137. /// <inheritdoc/>
  138. public List<SqlSugarTableInfo> GetTables()
  139. {
  140. return SqlSugarUtils.GetTablesByAttribute<BatchEditAttribute>();
  141. }
  142. /// <inheritdoc/>
  143. public async Task<List<BatchEditConfig>> ConfigList(BaseIdInput input)
  144. {
  145. return await Context.Queryable<BatchEditConfig>().Where(u => u.UId == input.Id).OrderByDescending(it => it.Status).ToListAsync();
  146. }
  147. /// <inheritdoc/>
  148. public async Task<Dictionary<string, object>> GetUpdateBatchConfigDict(string code, List<BatchEditColumn> columns)
  149. {
  150. var dic = new Dictionary<string, object>();
  151. var configs = await Columns(code);
  152. foreach (var item in columns)
  153. {
  154. var config = configs.Where(it => it.ColumnName == item.TableColumn).FirstOrDefault();
  155. if (config == null) throw Oops.Bah("不存在的列");
  156. dic.Add(item.TableColumn, item.ColumnValue.ToString());
  157. }
  158. return dic;
  159. }
  160. #region 方法
  161. /// <summary>
  162. /// 获取配置
  163. /// </summary>
  164. /// <param name="columnInfo"></param>
  165. private BatchEditConfig GetUpdateBatchConfig(SqlSugarColumnInfo columnInfo)
  166. {
  167. var netType = SqlSugarUtils.ConvertDataType(columnInfo.DataType);
  168. return new BatchEditConfig
  169. {
  170. ColumnName = columnInfo.ColumnName,
  171. ColumnComment = string.IsNullOrWhiteSpace(columnInfo.ColumnDescription) ? columnInfo.ColumnName : columnInfo.ColumnDescription,
  172. NetType = netType,
  173. DataType = SqlSugarUtils.DataTypeToEff(netType),
  174. Status = CommonStatusConst.DISABLED
  175. };
  176. }
  177. /// <summary>
  178. /// 检查输入参数
  179. /// </summary>
  180. /// <param name="updateBatch"></param>
  181. private async Task CheckInput(BatchEdit updateBatch)
  182. {
  183. if (updateBatch.Id == 0)
  184. {
  185. var isExist = await IsAnyAsync(it => it.Code == updateBatch.Code);
  186. if (isExist) throw Oops.Bah("唯一编码不能重复");
  187. }
  188. }
  189. #endregion 方法
  190. }