PerformanceJob.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using OASystem.API.OAMethodLib;
  2. using OASystem.Domain.Entities.System;
  3. using OASystem.Domain.ViewModels;
  4. using OASystem.Infrastructure.Tools;
  5. using Quartz;
  6. using SqlSugar;
  7. using Newtonsoft.Json;
  8. namespace OASystem.API.OAMethodLib.Quartz.Jobs
  9. {
  10. /// <summary>
  11. /// 绩效生成定时任务
  12. /// 每月1号5点执行
  13. /// </summary>
  14. public class PerformanceJob : IJob
  15. {
  16. private readonly ILogger<PerformanceJob> _logger;
  17. private readonly IHttpClientFactory _httpClientFactory;
  18. public PerformanceJob(ILogger<PerformanceJob> logger, IHttpClientFactory httpClientFactory)
  19. {
  20. _logger = logger;
  21. _httpClientFactory = httpClientFactory;
  22. }
  23. /// <summary>
  24. /// 绩效生成
  25. /// </summary>
  26. /// <param name="context"></param>
  27. /// <returns></returns>
  28. public async Task Execute(IJobExecutionContext context)
  29. {
  30. _logger.LogInformation("调用绩效生成任务 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  31. try
  32. {
  33. string baseUrl = "http://132.232.92.186:8888/";
  34. baseUrl = baseUrl.TrimEnd('/');
  35. // 创建HttpClient
  36. var httpClient = _httpClientFactory.CreateClient();
  37. httpClient.Timeout = TimeSpan.FromMinutes(30); // 设置超时时间
  38. // 计算上个月的时间范围(因为每月1号执行,所以生成上个月的绩效)
  39. var now = DateTime.Now;
  40. var lastMonth = now.AddMonths(-1);
  41. var startDate = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  42. var endDate = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month), 23, 59, 59);
  43. _logger.LogInformation($"开始生成绩效数据,时间范围:{startDate:yyyy-MM-dd HH:mm:ss} 至 {endDate:yyyy-MM-dd HH:mm:ss}");
  44. // 获取需要生成绩效的用户列表(通过数据库查询)
  45. var sqlSugar = AutofacIocManager.Instance.GetService<SqlSugarClient>();
  46. if (sqlSugar == null)
  47. {
  48. _logger.LogError("无法获取数据库连接,绩效生成任务终止");
  49. return;
  50. }
  51. // 获取需要生成绩效的用户列表(排除已删除的用户,排除配置中指定的用户ID)
  52. var notidsJson = sqlSugar.Queryable<Sys_SetData>().First(x => x.Id == 1463 && x.IsDel == 0)?.Remark;
  53. var notids = new List<int>();
  54. if (!string.IsNullOrWhiteSpace(notidsJson))
  55. {
  56. try
  57. {
  58. notids = JsonConvert.DeserializeObject<List<int>>(notidsJson) ?? new List<int>();
  59. }
  60. catch
  61. {
  62. _logger.LogWarning("解析排除用户ID配置失败");
  63. }
  64. }
  65. var users = await sqlSugar.Queryable<Sys_Users>()
  66. .LeftJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  67. .LeftJoin<Sys_JobPost>((u, d, jp) => u.JobPostId == jp.Id)
  68. .Where((u, d, jp) => u.IsDel == 0 && !notids.Contains(u.Id))
  69. .Select((u, d, jp) => new { u.Id, u.CnName, DepName = d.DepName ?? "", JobName = jp.JobName ?? "" })
  70. .ToListAsync();
  71. if (users == null || users.Count == 0)
  72. {
  73. _logger.LogWarning("未找到需要生成绩效的用户");
  74. return;
  75. }
  76. _logger.LogInformation($"找到 {users.Count} 个用户需要生成绩效数据");
  77. // 系统管理员ID(用于createUserId参数)
  78. int createUserId = 4; // 管理员ID
  79. // 为每个用户调用绩效分析API
  80. int successCount = 0;
  81. int failCount = 0;
  82. //添加不同岗位的绩效分析API
  83. foreach (var user in users)
  84. {
  85. try
  86. {
  87. // 构建API URL
  88. string apiUrl = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_AllDepartment";
  89. // 构建查询参数
  90. var queryParams = new Dictionary<string, string>
  91. {
  92. { "userId", user.Id.ToString() },
  93. { "start", startDate.ToString("yyyy-MM-dd HH:mm:ss") },
  94. { "end", endDate.ToString("yyyy-MM-dd HH:mm:ss") },
  95. { "createUserId", createUserId.ToString() }
  96. };
  97. // 构建完整URL
  98. var queryString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));
  99. string fullUrl = $"{apiUrl}?{queryString}";
  100. _logger.LogInformation($"正在为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据...");
  101. _logger.LogInformation($"API URL: {fullUrl}");
  102. // 发送HTTP GET请求
  103. var response = await httpClient.GetAsync(fullUrl);
  104. var responseContent = await response.Content.ReadAsStringAsync();
  105. if (response.IsSuccessStatusCode)
  106. {
  107. // 尝试解析响应结果
  108. try
  109. {
  110. var result = JsonConvert.DeserializeObject<JsonView>(responseContent);
  111. if (result != null && result.Code == 200)
  112. {
  113. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成成功");
  114. successCount++;
  115. }
  116. else
  117. {
  118. _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成失败:{result?.Msg ?? "未知错误"}");
  119. failCount++;
  120. }
  121. }
  122. catch (Exception ex)
  123. {
  124. _logger.LogError(ex, $"解析用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 的API响应失败");
  125. failCount++;
  126. }
  127. }
  128. else
  129. {
  130. _logger.LogError($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成API调用失败,状态码: {response.StatusCode}, 响应内容: {responseContent}");
  131. failCount++;
  132. }
  133. // 添加延迟,避免请求过于频繁
  134. await Task.Delay(3000); // 延迟3秒
  135. }
  136. catch (Exception ex)
  137. {
  138. _logger.LogError(ex, $"为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据时发生异常");
  139. failCount++;
  140. }
  141. }
  142. _logger.LogInformation($"绩效生成任务完成!成功:{successCount},失败:{failCount},总计:{users.Count}");
  143. }
  144. catch (Exception ex)
  145. {
  146. _logger.LogError(ex, $"调用绩效生成任务失败 ErrorMsg:{ex.Message} " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  147. }
  148. await Task.CompletedTask;
  149. }
  150. }
  151. }