EnumToDictJob.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using System.Security.Cryptography;
  7. namespace Admin.NET.Core;
  8. /// <summary>
  9. /// 枚举转字典
  10. /// </summary>
  11. [JobDetail("job_EnumToDictJob", Description = "枚举转字典", GroupName = "default", Concurrent = false)]
  12. [PeriodSeconds(1, TriggerId = "trigger_EnumToDictJob", Description = "枚举转字典", MaxNumberOfRuns = 1, RunOnStart = true)]
  13. public class EnumToDictJob : IJob
  14. {
  15. private readonly IServiceScopeFactory _scopeFactory;
  16. private const string DefaultTagType = null;
  17. private const int OrderOffset = 10;
  18. public EnumToDictJob(IServiceScopeFactory scopeFactory)
  19. {
  20. _scopeFactory = scopeFactory;
  21. }
  22. public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
  23. {
  24. var originColor = Console.ForegroundColor;
  25. Console.ForegroundColor = ConsoleColor.Yellow;
  26. Console.WriteLine($"【{DateTime.Now}】系统枚举转换字典");
  27. using var serviceScope = _scopeFactory.CreateScope();
  28. var db = serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>().CopyNew();
  29. var sysEnumService = serviceScope.ServiceProvider.GetRequiredService<SysEnumService>();
  30. var sysDictTypeList = GetDictByEnumType(sysEnumService.GetEnumTypeList());
  31. // 校验枚举类命名规范,字典相关功能中需要通过后缀判断是否为枚举类型
  32. Console.ForegroundColor = ConsoleColor.Red;
  33. foreach (var dictType in sysDictTypeList.Where(x => !x.Code.EndsWith("Enum")))
  34. Console.WriteLine($"【{DateTime.Now}】系统枚举转换字典的枚举类名称必须以Enum结尾: {dictType.Code} ({dictType.Name})");
  35. sysDictTypeList = sysDictTypeList.Where(x => x.Code.EndsWith("Enum")).ToList();
  36. await SyncEnumToDictInfoAsync(db, sysDictTypeList);
  37. Console.ForegroundColor = ConsoleColor.Yellow;
  38. try
  39. {
  40. await db.BeginTranAsync();
  41. var storageable1 = await db.Storageable(sysDictTypeList)
  42. .WhereColumns(it => new { it.Code })
  43. .SplitInsert(it => !it.Any())
  44. .SplitUpdate(it => it.Any())
  45. .ToStorageAsync();
  46. await storageable1.BulkCopyAsync();
  47. await storageable1.BulkUpdateAsync();
  48. Console.WriteLine($"【{DateTime.Now}】系统枚举类转字典类型数据: 插入{storageable1.InsertList.Count}条, 更新{storageable1.UpdateList.Count}条, 共{storageable1.TotalList.Count}条。");
  49. var storageable2 = await db.Storageable(sysDictTypeList.SelectMany(x => x.Children).ToList())
  50. .WhereColumns(it => new { it.DictTypeId, it.Code })
  51. .SplitInsert(it => !it.Any())
  52. .SplitUpdate(it => it.Any())
  53. .ToStorageAsync();
  54. await storageable2.BulkCopyAsync();
  55. await storageable2.BulkUpdateAsync();
  56. Console.WriteLine($"【{DateTime.Now}】系统枚举项转字典值数据: 插入{storageable2.InsertList.Count}条, 更新{storageable2.UpdateList.Count}条, 共{storageable2.TotalList.Count}条。");
  57. await db.CommitTranAsync();
  58. }
  59. catch (Exception error)
  60. {
  61. await db.RollbackTranAsync();
  62. Log.Error($"系统枚举转换字典操作错误:{error.Message}\n堆栈跟踪:{error.StackTrace}", error);
  63. throw;
  64. }
  65. finally
  66. {
  67. Console.ForegroundColor = originColor;
  68. }
  69. }
  70. /// <summary>
  71. /// 用于同步枚举转字典旧数据, 后期可删除
  72. /// </summary>
  73. /// <param name="db"></param>
  74. /// <param name="list"></param>
  75. [Obsolete]
  76. private async Task SyncEnumToDictInfoAsync(SqlSugarClient db, List<SysDictType> list)
  77. {
  78. var codeList = list.Select(x => x.Code).ToList();
  79. foreach (var dbDictType in await db.Queryable<SysDictType>().Where(x => codeList.Contains(x.Code)).ToListAsync() ?? new())
  80. {
  81. var enumDictType = list.First(x => x.Code == dbDictType.Code);
  82. enumDictType.Children?.ForEach(e => e.DictTypeId = dbDictType.Id);
  83. // 数据不一致则删除
  84. if (enumDictType.Id != dbDictType.Id)
  85. {
  86. _ = db.Deleteable<SysDictData>().Where(x => x.DictTypeId == dbDictType.Id).ExecuteCommandAsync();
  87. _ = db.Deleteable<SysDictType>().Where(x => x.Id == dbDictType.Id).ExecuteCommandAsync();
  88. }
  89. enumDictType.Id = dbDictType.Id;
  90. }
  91. }
  92. /// <summary>
  93. /// 枚举信息转字典
  94. /// </summary>
  95. /// <param name="enumTypeList"></param>
  96. /// <returns></returns>
  97. private List<SysDictType> GetDictByEnumType(List<EnumTypeOutput> enumTypeList)
  98. {
  99. var orderNo = 1;
  100. var list = new List<SysDictType>();
  101. foreach (var type in enumTypeList)
  102. {
  103. var dictType = new SysDictType
  104. {
  105. Id = 900000000000 + CommonUtil.GetFixedHashCode(type.TypeName),
  106. Code = type.TypeName,
  107. Name = type.TypeDescribe,
  108. Remark = type.TypeRemark
  109. };
  110. dictType.Children = type.EnumEntities.Select(x => new SysDictData
  111. {
  112. Id = dictType.Id + orderNo++,
  113. DictTypeId = dictType.Id,
  114. Name = x.Name,
  115. Value = x.Describe,
  116. Code = x.Value.ToString(),
  117. OrderNo = x.Value + OrderOffset,
  118. TagType = x.Theme != "" ? x.Theme : DefaultTagType,
  119. }).ToList();
  120. list.Add(dictType);
  121. }
  122. return list;
  123. }
  124. }