WeeklyFridayJob.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using Quartz;
  2. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  3. using OASystem.Domain.ViewModels.QiYeWeChat;
  4. namespace OASystem.API.OAMethodLib.Quartz.Jobs
  5. {
  6. /// <summary>
  7. /// 每周五下午4点执行的定时任务
  8. /// </summary>
  9. public class WeeklyFridayJob : IJob
  10. {
  11. private readonly ILogger<WeeklyFridayJob> _logger;
  12. private readonly SqlSugarClient _sqlSugar;
  13. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  14. private readonly HttpClient _httpClient;
  15. public WeeklyFridayJob(ILogger<WeeklyFridayJob> logger, SqlSugarClient sqlSugar
  16. , IHttpClientFactory httpClientFactory, IQiYeWeChatApiService qiYeWeChatApiService)
  17. {
  18. _logger = logger;
  19. _sqlSugar = sqlSugar;
  20. _httpClient = httpClientFactory.CreateClient();
  21. _qiYeWeChatApiService = qiYeWeChatApiService;
  22. }
  23. public async Task Execute(IJobExecutionContext context)
  24. {
  25. var jobName = context.JobDetail.Key.Name;
  26. _logger.LogInformation($"开始执行任务 {jobName},时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
  27. try
  28. {
  29. var startDate = DateTime.Today.AddDays(-4);
  30. var endDate = DateTime.Today.AddDays(1);
  31. string baseUrl = "http://132.232.92.186:8888";//"http://localhost:5256";
  32. var createUserId = 4;
  33. var sqSetting = _sqlSugar.Queryable<Sys_SetData>().First(x => x.Id == 1417);
  34. if (sqSetting != null)
  35. {
  36. Dictionary<int, List<int>> result = JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(sqSetting.Remark);
  37. result.Add(235, new List<int> { 258 });
  38. foreach (var item in result.Keys)
  39. {
  40. var keyUser = await _sqlSugar.Queryable<Sys_Users>()
  41. .FirstAsync(x => x.Id == item);
  42. var users = await _sqlSugar.Queryable<Sys_Users>()
  43. .LeftJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  44. .LeftJoin<Sys_JobPost>((u, d, jp) => u.JobPostId == jp.Id)
  45. .Where((u, d, jp) => u.IsDel == 0 && result[item].Contains(u.Id) && u.Id != item)
  46. .Select((u, d, jp) => new { u.Id, u.CnName, DepName = d.DepName ?? "", JobName = jp.JobName ?? "" })
  47. .ToListAsync();
  48. foreach (var user in users)
  49. {
  50. // 构建API URL
  51. string apiUrl = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_AllDepartment";
  52. // 构建查询参数
  53. var queryParams = new Dictionary<string, string>
  54. {
  55. { "userId", user.Id.ToString() },
  56. { "start", startDate.ToString("yyyy-MM-dd HH:mm:ss") },
  57. { "end", endDate.ToString("yyyy-MM-dd HH:mm:ss") },
  58. { "createUserId", createUserId.ToString() },
  59. { "isMonthData", "true" }
  60. };
  61. // 构建完整URL
  62. var queryString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));
  63. string fullUrl = $"{apiUrl}?{queryString}";
  64. _logger.LogInformation($"正在为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据...");
  65. _logger.LogInformation($"API URL: {fullUrl}");
  66. // 发送HTTP GET请求
  67. var response = await _httpClient.GetAsync(fullUrl);
  68. var responseContent = await response.Content.ReadAsStringAsync();
  69. if (response.IsSuccessStatusCode)
  70. {
  71. // 尝试解析响应结果
  72. try
  73. {
  74. var resultJson = JsonConvert.DeserializeObject<JsonView>(responseContent);
  75. if (resultJson != null && resultJson.Code == 200)
  76. {
  77. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成成功");
  78. //生成PDF
  79. var url = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_JobMarketingFileDown";
  80. //构建PDF查询参数
  81. var queryParamsPdf = new Dictionary<string, string>
  82. {
  83. { "userId", user.Id.ToString() },
  84. { "start", startDate.ToString("yyyy-MM-dd") },
  85. { "end", endDate.ToString("yyyy-MM-dd") },
  86. };
  87. var queryStringPdf = string.Join("&", queryParamsPdf.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));
  88. url = $"{url}?{queryStringPdf}";
  89. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 开始生成PDF:{url}");
  90. var pdfUrl = await _httpClient.PostAsync(url, new StringContent(queryStringPdf));
  91. if (pdfUrl.IsSuccessStatusCode)
  92. {
  93. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 开始生成PDF:{pdfUrl.StatusCode}");
  94. var pdfContent = await pdfUrl.Content.ReadAsStringAsync();
  95. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成PDF成功:{pdfContent}");
  96. var pdfContentJson = JObject.Parse(pdfContent);
  97. var pdfUrlString = pdfContentJson["data"]["url"].ToString();
  98. var pdfUrlSeed = new Uri(pdfUrlString);
  99. var pdfBytes = await _httpClient.GetByteArrayAsync(pdfUrlSeed);
  100. var fileName = pdfUrlString.Split('/').Last();
  101. var pdfFile = new FormFile(new MemoryStream(pdfBytes), 0, pdfBytes.Length, fileName, fileName);
  102. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName})文件大小:{pdfFile.Length}");
  103. var resultEmail = await _qiYeWeChatApiService.EmailSendAsync(new EmailRequestDto
  104. {
  105. ToEmails = new List<string> { keyUser.Email },
  106. Subject = $"用户 {user.CnName}(部门:{user.DepName} 日期区间:{startDate.ToString("yyyy-MM-dd")} 至 {endDate.ToString("yyyy-MM-dd")}) 绩效数据",
  107. Body = "员工绩效推送,请查看附件。",
  108. Files = new[] { pdfFile }
  109. });
  110. _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 发送邮件成功:{resultEmail.errcode}, {resultEmail.errmsg}");
  111. }
  112. else
  113. {
  114. _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成PDF失败:{pdfUrl.StatusCode}");
  115. _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成PDF失败:{pdfUrl.Content.ReadAsStringAsync()}");
  116. }
  117. }
  118. else
  119. {
  120. _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成失败:{resultJson?.Msg ?? "未知错误"}");
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. _logger.LogError(ex, $"解析用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 的API响应失败");
  126. }
  127. }
  128. else
  129. {
  130. _logger.LogError($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成API调用失败,状态码: {response.StatusCode}, 响应内容: {responseContent}");
  131. }
  132. // 添加延迟,避免请求过于频繁
  133. await Task.Delay(3000); // 延迟3秒
  134. }
  135. }
  136. }
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.LogError(ex, $"任务 {jobName} 执行失败");
  141. }
  142. }
  143. }
  144. }