Просмотр исходного кода

添加绩效生成定时任务

yuanrf дней назад: 2
Родитель
Сommit
34da42f342

+ 66 - 1
OASystem/OASystem.Api/Controllers/PersonnelModuleController.cs

@@ -1110,7 +1110,7 @@ namespace OASystem.API.Controllers
                 .ToPageListAsync(dto.PageIndex, dto.PageSize, total);
 
             int index = 1;
-            var taskCompletedPerm = _sqlSugar.Queryable<Pm_TaskJobRelevancy>().Where(x => x.IsDel == 0 && x.PrimaryUserId == dto.UserId).Any(); 
+            var taskCompletedPerm = _sqlSugar.Queryable<Pm_TaskJobRelevancy>().Where(x => x.IsDel == 0 && x.PrimaryUserId == dto.UserId).Any();
             foreach (var item in view)
             {
                 item.RowNumber = index;
@@ -2840,6 +2840,71 @@ OPTION (MAXRECURSION 0); -- 允许无限递归      ";
             public string KaoqinAnswer { get; set; }
         }
 
+        /// <summary>
+        /// 全部门生成通用方法
+        /// </summary>
+        /// <param name="userId"></param>
+        /// <param name="start"></param>
+        /// <param name="end"></param>
+        /// <param name="createUserId"></param>
+        /// <returns></returns>
+        [HttpGet]
+        public async Task<IActionResult> AiPerformanceAnalysis_AllDepartmentAsync(int userId, DateTime start, DateTime end, int createUserId)
+        {
+            var jw = JsonView(false, "该员工暂无生成逻辑!");
+            var user = await _sqlSugar.Queryable<Sys_Users>()
+                               .LeftJoin<Sys_Department>((u, d) => u.DepId == d.Id)
+                               .LeftJoin<Sys_JobPost>((u, d, jp) => u.JobPostId == jp.Id)
+                               .Where((u, d, jp) => u.IsDel == 0 && u.Id == userId)
+                               .Select((u, d, jp) => new { u.Id, u.CnName, DepName = d.DepName ?? "", JobName = jp.JobName ?? "" })
+                               .FirstAsync();
+
+            var jobHandlers = new Dictionary<string, Func<Task<IActionResult>>>
+            {
+                { "机票", async () => { return await this.AiPerformanceAnalysis_AirTicketAsync(userId, start, end, createUserId);}},
+                { "酒店", async () => { return await this.AiPerformanceAnalysis_HotelAsync(userId, start, end, createUserId);}},
+                { "签证", async () => { return await this.AiPerformanceAnalysis_VisaAsync(userId, start, end, createUserId);}},
+                { "OP",   async () => { return await this.AiPerformanceAnalysis_OPAsync(userId, start, end, createUserId);}},
+                { "商邀", async () => { return await this.AiPerformanceAnalysis_BusinessInvitationAsync(userId, start, end, createUserId);}},
+            };
+
+            var DepartmentHandlers = new Dictionary<string, Func<Task<IActionResult>>>
+            {
+                { "信息部", async () => { return await this.AiPerformanceAnalysis_InformationDepartmentAsync(userId, start, end, createUserId);}},
+                { "策划部", async () => { return await this.AiPerformanceAnalysis_PlanningDepartmentAsync(userId, start, end, createUserId);}},
+                { "人事部",  async () => { return await this.AiPerformanceAnalysis_HumanResourceDepartmentAsync(userId, start, end, createUserId);}},
+                { "市场部",  async () => { return await this.AiPerformanceAnalysis_JobMarketingAsync(userId, start, end, createUserId);}},
+            };
+
+            var idHandlers = new Dictionary<int, Func<Task<IActionResult>>>
+            {
+                //曾
+                { 187, async () => { return await this.AiPerformanceAnalysis_FinancialDepartmentAsync(userId, start, end, createUserId);}},
+                 //伏
+                { 281, async () => { return await this.AiPerformanceAnalysis_Financial_Fu_DepartmentAsync(userId, start, end, createUserId);}},
+            };
+
+            //id
+            if (idHandlers.Keys.Contains(user.Id))
+            {
+                return await idHandlers[user.Id]();
+            }
+
+            //职位
+            if (jobHandlers.Keys.Contains(user.JobName))
+            {
+                return await jobHandlers[user.JobName]();
+            }
+
+            //部门
+            if (DepartmentHandlers.Keys.Contains(user.DepName))
+            {
+                return await DepartmentHandlers[user.DepName]();
+            }
+
+            return Ok(jw);
+        }
+
         /// <summary>
         /// 市场部员工分析
         /// </summary>

+ 181 - 0
OASystem/OASystem.Api/OAMethodLib/Quartz/Jobs/PerformanceJob.cs

@@ -0,0 +1,181 @@
+using OASystem.API.OAMethodLib;
+using OASystem.Domain.Entities.System;
+using OASystem.Domain.ViewModels;
+using OASystem.Infrastructure.Tools;
+using Quartz;
+using SqlSugar;
+using Newtonsoft.Json;
+
+namespace OASystem.API.OAMethodLib.Quartz.Jobs
+{
+    /// <summary>
+    /// 绩效生成定时任务
+    /// 每月1号5点执行
+    /// </summary>
+    public class PerformanceJob : IJob
+    {
+        private readonly ILogger<PerformanceJob> _logger;
+        private readonly IHttpClientFactory _httpClientFactory;
+
+        public PerformanceJob(ILogger<PerformanceJob> logger, IHttpClientFactory httpClientFactory)
+        {
+            _logger = logger;
+            _httpClientFactory = httpClientFactory;
+        }
+
+        /// <summary>
+        /// 绩效生成
+        /// </summary>
+        /// <param name="context"></param>
+        /// <returns></returns>
+        public async Task Execute(IJobExecutionContext context)
+        {
+            _logger.LogInformation("调用绩效生成任务 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
+
+            try
+            {
+                string baseUrl = "http://132.232.92.186:8888/";
+                if (!baseUrl.EndsWith("/"))
+                {
+                    baseUrl = baseUrl.TrimEnd('/');
+                }
+
+                // 创建HttpClient
+                var httpClient = _httpClientFactory.CreateClient();
+                httpClient.Timeout = TimeSpan.FromMinutes(30); // 设置超时时间
+
+                // 计算上个月的时间范围(因为每月1号执行,所以生成上个月的绩效)
+                var now = DateTime.Now;
+                var lastMonth = now.AddMonths(-1);
+                var startDate = new DateTime(lastMonth.Year, lastMonth.Month, 1);
+                var endDate = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month), 23, 59, 59);
+
+                _logger.LogInformation($"开始生成绩效数据,时间范围:{startDate:yyyy-MM-dd HH:mm:ss} 至 {endDate:yyyy-MM-dd HH:mm:ss}");
+
+                // 获取需要生成绩效的用户列表(通过数据库查询)
+                var sqlSugar = AutofacIocManager.Instance.GetService<SqlSugarClient>();
+                if (sqlSugar == null)
+                {
+                    _logger.LogError("无法获取数据库连接,绩效生成任务终止");
+                    return;
+                }
+
+                // 获取需要生成绩效的用户列表(排除已删除的用户,排除配置中指定的用户ID)
+                var notidsJson = sqlSugar.Queryable<Sys_SetData>().First(x => x.Id == 1463 && x.IsDel == 0)?.Remark;
+                var notids = new List<int>();
+                if (!string.IsNullOrWhiteSpace(notidsJson))
+                {
+                    try
+                    {
+                        notids = JsonConvert.DeserializeObject<List<int>>(notidsJson) ?? new List<int>();
+                    }
+                    catch
+                    {
+                        _logger.LogWarning("解析排除用户ID配置失败");
+                    }
+                }
+
+                var users = await sqlSugar.Queryable<Sys_Users>()
+                    .LeftJoin<Sys_Department>((u, d) => u.DepId == d.Id)
+                    .LeftJoin<Sys_JobPost>((u, d, jp) => u.JobPostId == jp.Id)
+                    .Where((u, d, jp) => u.IsDel == 0 && !notids.Contains(u.Id))
+                    .Select((u, d, jp) => new { u.Id, u.CnName, DepName = d.DepName ?? "", JobName = jp.JobName ?? "" })
+                    .ToListAsync();
+
+                if (users == null || users.Count == 0)
+                {
+                    _logger.LogWarning("未找到需要生成绩效的用户");
+                    return;
+                }
+
+                _logger.LogInformation($"找到 {users.Count} 个用户需要生成绩效数据");
+
+                // 系统管理员ID(用于createUserId参数)
+                int createUserId = 4; // 管理员ID
+
+                // 为每个用户调用绩效分析API
+                int successCount = 0;
+                int failCount = 0;
+
+                //添加不同岗位的绩效分析API
+
+                foreach (var user in users)
+                {
+                    try
+                    {
+                        // 构建API URL
+                        string apiUrl = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_AllDepartmentAsync";
+
+                        // 构建查询参数
+                        var queryParams = new Dictionary<string, string>
+                        {
+                            { "userId", user.Id.ToString() },
+                            { "start", startDate.ToString("yyyy-MM-dd HH:mm:ss") },
+                            { "end", endDate.ToString("yyyy-MM-dd HH:mm:ss") },
+                            { "createUserId", createUserId.ToString() }
+                        };
+
+                        // 构建完整URL
+                        var queryString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));
+                        string fullUrl = $"{apiUrl}?{queryString}";
+                        //url编码
+                        fullUrl = Uri.EscapeDataString(fullUrl);
+
+                        _logger.LogInformation($"正在为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据...");
+                        _logger.LogInformation($"API URL: {fullUrl}");
+
+                        // 发送HTTP GET请求
+                        var response = await httpClient.GetAsync(fullUrl);
+                        var responseContent = await response.Content.ReadAsStringAsync();
+
+                        if (response.IsSuccessStatusCode)
+                        {
+                            // 尝试解析响应结果
+                            try
+                            {
+                                var result = JsonConvert.DeserializeObject<JsonView>(responseContent);
+                                if (result != null && result.Code == 200)
+                                {
+                                    _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成成功");
+                                    successCount++;
+                                }
+                                else
+                                {
+                                    _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成失败:{result?.Msg ?? "未知错误"}");
+                                    failCount++;
+                                }
+                            }
+                            catch (Exception ex)
+                            {
+                                _logger.LogError(ex, $"解析用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 的API响应失败");
+                                failCount++;
+                            }
+                        }
+                        else
+                        {
+                            _logger.LogError($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成API调用失败,状态码: {response.StatusCode}, 响应内容: {responseContent}");
+                            failCount++;
+                        }
+
+                        // 添加延迟,避免请求过于频繁
+                        await Task.Delay(3000); // 延迟3秒
+                    }
+                    catch (Exception ex)
+                    {
+                        _logger.LogError(ex, $"为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据时发生异常");
+                        failCount++;
+                    }
+                }
+
+                _logger.LogInformation($"绩效生成任务完成!成功:{successCount},失败:{failCount},总计:{users.Count}");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError(ex, $"调用绩效生成任务失败 ErrorMsg:{ex.Message} " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
+            }
+
+            await Task.CompletedTask;
+        }
+    }
+}
+

+ 5 - 0
OASystem/OASystem.Api/OAMethodLib/Quartz/QuartzFactory.cs

@@ -43,18 +43,23 @@ namespace QuzrtzJob.Factory
                             //.WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever())//每六十秒执行一次
                             .WithCronSchedule("0 0 0 * * ? ") //每天零点零分点触发
                             .Build();
+            var performanceTrigger = TriggerBuilder.Create()
+                            .WithCronSchedule("0 0 5 1 * ?") //每月1号5点执行
+                            .Build();
 
             //5、创建任务
             var jobDetail = JobBuilder.Create<ALiYunPostMessageJob>().WithIdentity("job1", "group").Build();
             var taskJobDetail = JobBuilder.Create<TaskJob>().WithIdentity("job2", "group").Build();
             var taskMsgJobDetail = JobBuilder.Create<TaskNewsFeedJob>().WithIdentity("job3", "group").Build();
             var teamCurrencyJobDetail = JobBuilder.Create<GroupTeamCurrencyJob>().WithIdentity("job4", "group").Build();
+            var performanceJobDetail = JobBuilder.Create<PerformanceJob>().WithIdentity("job5", "group").Build();
 
             //6、将触发器和任务器绑定到调度器中
             await _scheduler.ScheduleJob(jobDetail, trigger);
             await _scheduler.ScheduleJob(taskJobDetail, taskTrigger);
             await _scheduler.ScheduleJob(taskMsgJobDetail, taskMsgTrigger);
             await _scheduler.ScheduleJob(teamCurrencyJobDetail, teamCurrencyTrigger);
+            await _scheduler.ScheduleJob(performanceJobDetail, performanceTrigger);
 
 
             return await Task.FromResult("将触发器和任务器绑定到调度器中完成");

+ 1 - 0
OASystem/OASystem.Api/Program.cs

@@ -539,6 +539,7 @@ builder.Services.AddSingleton<QuartzFactory>();
 builder.Services.AddSingleton<ALiYunPostMessageJob>();
 builder.Services.AddSingleton<TaskJob>();
 builder.Services.AddSingleton<TaskNewsFeedJob>();
+builder.Services.AddSingleton<PerformanceJob>();
 //# new business
 builder.Services.AddControllersWithViews();
 builder.Services.AddSingleton<IAPNsService, APNsService>();