using DS.Module.Core; using DS.Module.Core.Data; using DS.Module.Core.Extensions; using DS.Module.Core.Helpers; using DS.Module.DjyServiceStatus; using DS.Module.SqlSugar; using DS.Module.UserModule; using DS.WMS.Core.Code.Interface; using DS.WMS.Core.TaskPlat.Dtos; using DS.WMS.Core.TaskPlat.Entity; using DS.WMS.Core.TaskPlat.Interface; using Mapster; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using SqlSugar; namespace DS.WMS.Core.TaskPlat.Method { public class TaskManageService : TaskManageBaseService, ITaskManageService { private readonly ICodeCtnService codeCtnService; public TaskManageService(IUser user, ILogger logger, ISaasDbService saasDbService, IServiceProvider serviceProvider, IWebHostEnvironment environment, ICodeCtnService codeCtnService) : base(user, logger, saasDbService, serviceProvider, environment) { this.codeCtnService = codeCtnService; } #region 对工作流提供的接口 /// /// 工作流设置任务在个人下的状态 /// /// 业务主键 /// 业务类型 /// 业务状态 /// 状态发生时间 /// 要设置任务状态的人员列表 public async Task SetTaskUserStatus(long bsno, TaskBaseTypeEnum taskBaseTypeEnum, TaskStatusEnum taskStatusEnum, DateTime? statusTime, List userInfos) { SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); TaskBaseInfo taskInfo = await tenantDb.Queryable() .OrderByDescending(a => a.CreateTime) .FirstAsync(t => t.OUT_BS_NO == bsno && t.TASK_TYPE == taskBaseTypeEnum.ToString()); if (taskInfo == null) { logger.LogInformation($"根据bsno:【{bsno}】,TaskBaseTypeEnum:【{taskBaseTypeEnum}】未查询到任务"); return DataResult.Failed(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.DataQueryNoData))); } logger.LogInformation("接收到任务个人状态修改报文 任务主键={id} 状态设置={status} 人员列表={userList}", taskInfo.Id, taskStatusEnum.ToString(), JsonConvert.SerializeObject(userInfos)); var userIdList = userInfos.Select(x => x.RecvUserId).ToList(); var taskBaseAllocationList = await tenantDb.Queryable() .Where(x => x.TaskId == taskInfo.Id && userIdList.Contains(x.UserId)) .ToListAsync(); if (taskBaseAllocationList.Any()) { taskBaseAllocationList.ForEach(x => { x.Status = taskStatusEnum.ToString(); x.StatusName = taskStatusEnum.EnumDescription(); x.StatusTime = statusTime; }); await tenantDb.Updateable(taskBaseAllocationList).UpdateColumns(x => new { x.UpdateBy, x.UpdateTime, x.UpdateUserName, x.Status, x.StatusName, x.StatusTime }).ExecuteCommandAsync(); } return DataResult.Successed(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.DataUpdateSuccess))); } /// /// 设置任务状态 /// /// 业务主键 /// 业务类型 /// 业务状态 /// 状态发生时间 public async Task SetTaskStatus(long bsno, TaskBaseTypeEnum taskBaseTypeEnum, TaskStatusEnum taskStatusEnum, DateTime? statusTime) { SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); TaskBaseInfo taskInfo = await tenantDb.Queryable() .OrderByDescending(a => a.CreateTime) .FirstAsync(t => t.OUT_BS_NO == bsno && t.TASK_TYPE == taskBaseTypeEnum.ToString()); if (taskInfo == null) { logger.LogInformation($"根据bsno:【{bsno}】,TaskBaseTypeEnum:【{taskBaseTypeEnum}】未查询到任务"); return DataResult.Failed(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.DataQueryNoData))); } logger.LogInformation("接收到任务状态修改报文 任务主键={id} 状态设置={status}", taskInfo.Id, taskStatusEnum.ToString()); taskInfo.STATUS = taskStatusEnum.ToString(); taskInfo.STATUS_NAME = taskStatusEnum.EnumDescription(); taskInfo.RealUserId = long.Parse(user.UserId); taskInfo.RealUserName = user.UserName; await tenantDb.Updateable(taskInfo).UpdateColumns(x => new { x.UpdateBy, x.UpdateTime, x.UpdateUserName, x.STATUS, x.STATUS_NAME, x.RealUserId, x.RealUserName }).ExecuteCommandAsync(); var taskBaseAllocationList = await tenantDb.Queryable().Where(x => x.TaskId == taskInfo.Id).ToListAsync(); if (taskBaseAllocationList.Count != 0) { taskBaseAllocationList.ForEach(x => { x.Status = taskStatusEnum.ToString(); x.StatusName = taskStatusEnum.EnumDescription(); x.StatusTime = statusTime; }); await tenantDb.Updateable(taskBaseAllocationList).UpdateColumns(x => new { x.UpdateBy, x.UpdateTime, x.UpdateUserName, x.Status, x.StatusName, x.StatusTime }).ExecuteCommandAsync(); } return DataResult.Successed(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.DataUpdateSuccess))); } /// /// 工作流任务转交 /// /// 业务主键 /// 业务类型 /// 要转交的人员信息列表 public async Task TransferTask(long bsno, TaskBaseTypeEnum taskBaseTypeEnum, List userInfos) { SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); try { var taskId = await tenantDb.Queryable() .Where(t => t.OUT_BS_NO == bsno && t.TASK_TYPE == taskBaseTypeEnum.ToString()) .OrderByDescending(a => a.CreateTime) .Select(t => t.Id) .FirstAsync(); if (taskId == null || taskId == 0) { logger.LogInformation($"根据bsno:【{bsno}】,TaskBaseTypeEnum:【{taskBaseTypeEnum}】未查询到任务"); return DataResult.Failed(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.DataQueryNoData))); } logger.LogInformation("接收到任务转交报文 任务主键={id} 转交人员列表={userinfo}", taskId, JsonConvert.SerializeObject(userInfos)); await tenantDb.Ado.BeginTranAsync(); await tenantDb.Deleteable(x => x.TaskId == taskId).ExecuteCommandHasChangeAsync(); var allocationList = userInfos.Select(x => new TaskBaseAllocation { TaskId = (long)taskId, UserId = x.RecvUserId, UserName = x.RecvUserName, Status = TaskStatusEnum.Create.ToString(), StatusName = TaskStatusEnum.Create.EnumDescription(), }).ToList(); await tenantDb.Insertable(allocationList).ExecuteCommandAsync(); await tenantDb.Ado.CommitTranAsync(); return DataResult.Successed("操作成功!", MultiLanguageConst.DataUpdateSuccess); } catch (Exception) { await tenantDb.Ado.RollbackTranAsync(); throw; } } #endregion /// /// 创建任务公共方法 /// /// /// /// /// public async Task InitTaskJob(TaskManageOrderMessageInfo info, IFormFile file = null, IFormFile modifyFile = null) { string batchNo = Guid.NewGuid().ToString(); try { logger.LogInformation("批次={no} 接收到创建任务报文 报文={msg}", batchNo, JsonConvert.SerializeObject(info)); SqlSugarScopeProvider tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); TaskBaseInfo taskInfo = null; // 如果业务主键不为空,则通过业务主键进行重复判断 if (info.Head.BSNO is not null or 0) { taskInfo = await tenantDb.Queryable() .Where(t => t.OUT_BS_NO == info.Head.BSNO) .WhereIF(info.Main.IsCheckExistsByTaskType, t => t.TASK_TYPE == info.Main.TaskType.ToString()) .OrderByDescending(a => a.CreateTime) .FirstAsync(); } // 否则通过Head.GID进行判断 else { taskInfo = await tenantDb.Queryable() .Where(t => t.OUT_BUSI_NO == $"{info.Head.SenderId}_{info.Head.GID}") .WhereIF(info.Main.IsCheckExistsByTaskType, t => t.TASK_TYPE == info.Main.TaskType.ToString()) .OrderByDescending(a => a.CreateTime) .FirstAsync(); } // 只要任务最后一次处理任务的状态是已取消、已完成,就可以重入新的任务 if (taskInfo != null && taskInfo.STATUS != TaskStatusEnum.Cancel.ToString() && taskInfo.STATUS != TaskStatusEnum.Complete.ToString()) { logger.LogInformation("批次={no} 状态已存在,不能重复创建任务 status={status}", batchNo, taskInfo.STATUS); throw new Exception($"状态已存在,不能重复创建任务"); } logger.LogInformation("批次={no} 接收到创建任务报文 结束查询任务 {msg}", batchNo, taskInfo == null ? "不存在" : "存在"); //如果文件路径不为空 判断文件是否真实存在 if (!string.IsNullOrWhiteSpace(info.Main.FilePath) && !File.Exists(info.Main.FilePath)) { throw new Exception(string.Format("{0}文件不存在", info.Main.FilePath)); } //如果文件路径不为空 判断文件是否真实存在 if (!string.IsNullOrWhiteSpace(info.Main.ModifyFile) && !File.Exists(info.Main.ModifyFile)) { throw new Exception(string.Format("{0}文件不存在", info.Main.ModifyFile)); } taskInfo = new TaskBaseInfo { Id = SnowFlakeSingle.Instance.NextId(), STATUS = TaskStatusEnum.Create.ToString(), STATUS_NAME = TaskStatusEnum.Create.EnumDescription(), IS_EXCEPT = 0, IS_COMPLETE = 0, MBL_NO = info.Main.MBlNo, TASK_TYPE = info.Main.TaskType.ToString(), //TASK_BASE_TYPE = info.Main.TaskType.ToString(), CARRIER_ID = info.Main.CarrierId?.Trim(), //IS_PUBLIC = string.IsNullOrWhiteSpace(info.Main.TaskUserId) ? 1 : 0, IS_PUBLIC = 1, BOOK_ORDER_NO = info.Main.BookingOrderNo, OUT_BUSI_NO = $"{info.Head.SenderId}_{info.Head.GID}", TASK_TITLE = info.Main.TaskTitle, TASK_DESP = info.Main.TaskDesp, TASK_SOURCE = info.Main.TaskSource.ToString(), TASK_SOURCE_NAME = info.Main.TaskSource.EnumDescription(), VESSEL_VOYNO = info.Main.VesselVoyno?.Trim(), CONTA_INFO = info.Main.ContaInfo, TASK_REQ_USERNAME = info.Main.TaskUserName, YARD_NAME = info.Main.YardName, ETD = info.Main.ETD, CUSTOMER_ID = info.Main.CustomerId, CUSTOMER_NAME = info.Main.CustomerName, BATCH_STATIC = info.Main.BatchStatic, //DJYUserId = info.Head.DJYUserId, OUT_BS_NO = info.Head.BSNO, CreateTime = DateTime.Now, }; if (Enum.TryParse(typeof(TaskBaseTypeEnum), taskInfo.TASK_TYPE, out object? taskTypeTemp)) { taskInfo.TASK_TYPE_NAME = ((TaskBaseTypeEnum)taskTypeTemp).EnumDescription(); } // 人员字段说明: // TaskBaseInfo.CreateBy 创建人:谁创建的,只有一个人(可能是某个租户的管理员,因为任务可以由外部(邮件)创建,无法为每个人创建接口授权信息) // TaskBaseInfo.TASK_REQ_USERID 制单人:只有一个人,使用任务创建报文中传入的TaskUserId // TaskBaseAllocation.UserId 任务关系:任务属于谁,谁能够查看并处理,可能是多个人(可能是多个人一起处理);取值优先级:info.Main.RecvUserInfoList>关联订单 // TaskBaseInfo.RealUserId 实际操作人:谁实际处理的,只有一个人(但是工作流过来的任务会由多个人处理) // 创建人 taskInfo.CreateBy = long.Parse(user.UserId); taskInfo.CreateUserName = user.UserName; // 制单人 long taskReqUserId = 0; if (!string.IsNullOrWhiteSpace(info.Main.TaskUserId)) { if (long.TryParse(info.Main.TaskUserId, out taskReqUserId)) { taskInfo.TASK_REQ_USERID = taskReqUserId; taskInfo.TASK_REQ_USERNAME = info.Main.TaskUserName; } } logger.LogInformation("批次={no} 获取登录人详情 recvUserId={recvUserId} UserId={UserId}", batchNo, info.Main.RecvUserId, user.UserId); // 任务所属人员列表 // 如果明确指出接收人(接收人列表),则将任务作为个人任务 if (info.Main.RecvUserInfoList?.Count > 0) { logger.LogInformation("批次={no} 接收人列表 recvUserList={recvUserList} ", batchNo, JsonConvert.SerializeObject(info.Main.RecvUserInfoList)); taskInfo.IS_PUBLIC = 0; var allocationList = info.Main.RecvUserInfoList.Select(x => new TaskBaseAllocation { TaskId = taskInfo.Id, UserId = x.RecvUserId, UserName = x.RecvUserName, Status = TaskStatusEnum.Create.ToString(), StatusName = TaskStatusEnum.Create.EnumDescription(), StatusTime = DateTime.Now }).ToList(); await tenantDb.Insertable(allocationList).ExecuteCommandAsync(); } // 否则判断任务关联订单,如果能关联到,则判断任务设置的角色;如果有设置,则将任务挂载到订单的指定角色上;如果没关联到或者没有设置,则作为公共任务 //else //{ // // 1.查找任务的匹配设置 // var allotSet = await tenantDb.Queryable().Where(x => x.TaskType == info.Main.TaskType.ToString()).FirstAsync(); // if (allotSet != null) // { // // 2. 根据提单号查找订单\根据订舱编号查找订单\... // // 3. 查找订单之后,获取匹配设置参数,得到人员Id列表; // // 4. 获取任务Id // // 5. 存关系 // } //} if (info.Main != null && info.Main.TruckInfo != null && info.Main.TruckInfo.NeedArriveTime.HasValue) { taskInfo.NeedArriveTime = info.Main.TruckInfo.NeedArriveTime; } await tenantDb.Insertable(taskInfo).ExecuteCommandAsync(); if (!string.IsNullOrWhiteSpace(info.Main.FilePath)) { string attachFileType = string.Empty; string fileCategory = string.Empty; if (TaskBaseTypeEnum.BC.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcfiles"; fileCategory = TaskFileCategoryEnum.BC.ToString(); } else if (TaskBaseTypeEnum.BC_MODIFY.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcmodifyfiles"; fileCategory = TaskFileCategoryEnum.BC_MODIFY.ToString(); } else if (TaskBaseTypeEnum.CANCELLATION.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bccancelfiles"; fileCategory = TaskFileCategoryEnum.BC_CANCEL.ToString(); } else if (TaskBaseTypeEnum.DRAFT.ToString() == taskInfo.TASK_TYPE) { attachFileType = "draftfiles"; fileCategory = TaskFileCategoryEnum.DRAFT.ToString(); } else if (TaskBaseTypeEnum.SI_FEEDBACK.ToString() == taskInfo.TASK_TYPE) { attachFileType = "sisubmittedfiles"; fileCategory = TaskFileCategoryEnum.SI_SUBMITTED.ToString(); } else if (TaskBaseTypeEnum.ROUTE_CUT_CHANGE.ToString() == taskInfo.TASK_TYPE) { attachFileType = "advisoryfiles"; fileCategory = TaskFileCategoryEnum.ADVISORY.ToString(); } if (info.Main.FileList == null) { info.Main.FileList = new List(); } info.Main.FileList.Add(new TaskManageOrderFileInfo { PKId = SnowFlakeSingle.Instance.NextId(), FileName = Path.GetFileName(info.Main.FilePath), FileType = Path.GetExtension(info.Main.FilePath).ToLower(), FilePath = info.Main.FilePath, FileCategory = fileCategory }); } else { if (file != null) { var bytes = file.ToByteArray(); string attachFileType = string.Empty; string fileCategory = string.Empty; if (TaskBaseTypeEnum.BC.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcfiles"; fileCategory = TaskFileCategoryEnum.BC.ToString(); } else if (TaskBaseTypeEnum.BC_MODIFY.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcmodifyfiles"; fileCategory = TaskFileCategoryEnum.BC_MODIFY.ToString(); } else if (TaskBaseTypeEnum.CANCELLATION.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bccancelfiles"; fileCategory = TaskFileCategoryEnum.BC_CANCEL.ToString(); } else if (TaskBaseTypeEnum.DRAFT.ToString() == taskInfo.TASK_TYPE) { attachFileType = "draftfiles"; fileCategory = TaskFileCategoryEnum.DRAFT.ToString(); } else if (TaskBaseTypeEnum.SI_FEEDBACK.ToString() == taskInfo.TASK_TYPE) { attachFileType = "sisubmittedfiles"; fileCategory = TaskFileCategoryEnum.SI_SUBMITTED.ToString(); } else if (TaskBaseTypeEnum.ROUTE_CUT_CHANGE.ToString() == taskInfo.TASK_TYPE) { attachFileType = "advisoryfiles"; fileCategory = TaskFileCategoryEnum.ADVISORY.ToString(); } var noExtensionFileName = Path.GetFileNameWithoutExtension(file.FileName); var fileFullName = await SaveFile(taskInfo.Id.ToString(), bytes, batchNo, noExtensionFileName, GetFileType(file.FileName), attachFileType); if (!string.IsNullOrWhiteSpace(fileFullName)) { if (info.Main.FileList == null) { info.Main.FileList = new List(); } info.Main.FileList.Add(new TaskManageOrderFileInfo { PKId = SnowFlakeSingle.Instance.NextId(), FileName = file.FileName, FileType = Path.GetExtension(file.FileName).ToLower(), FilePath = fileFullName, FileCategory = fileCategory }); } } } if (!string.IsNullOrWhiteSpace(info.Main.ModifyFile)) { string fileCategory = string.Empty; if (TaskBaseTypeEnum.BC.ToString() == taskInfo.TASK_TYPE) fileCategory = TaskFileCategoryEnum.BC_NOTICE.ToString(); else if (TaskBaseTypeEnum.BC_MODIFY.ToString() == taskInfo.TASK_TYPE) fileCategory = TaskFileCategoryEnum.BC_MODIFY_NOTICE.ToString(); else if (TaskBaseTypeEnum.CANCELLATION.ToString() == taskInfo.TASK_TYPE) fileCategory = TaskFileCategoryEnum.BC_CANCEL_NOTICE.ToString(); else if (TaskBaseTypeEnum.DRAFT.ToString() == taskInfo.TASK_TYPE) fileCategory = TaskFileCategoryEnum.DRAFT_NOTICE.ToString(); if (info.Main.FileList == null) info.Main.FileList = new List(); info.Main.FileList.Add(new TaskManageOrderFileInfo { PKId = SnowFlakeSingle.Instance.NextId(), FileName = Path.GetFileName(info.Main.ModifyFile), FileType = Path.GetExtension(info.Main.ModifyFile).ToLower(), FilePath = info.Main.FilePath, FileCategory = fileCategory }); } else { if (modifyFile != null) { var bytes = modifyFile.ToByteArray(); string attachFileType = string.Empty; string fileCategory = string.Empty; if (TaskBaseTypeEnum.BC.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcnoticefiles"; fileCategory = TaskFileCategoryEnum.BC_NOTICE.ToString(); } else if (TaskBaseTypeEnum.BC_MODIFY.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bcmodifynoticefiles"; fileCategory = TaskFileCategoryEnum.BC_MODIFY_NOTICE.ToString(); } else if (TaskBaseTypeEnum.CANCELLATION.ToString() == taskInfo.TASK_TYPE) { attachFileType = "bccancelnoticefiles"; fileCategory = TaskFileCategoryEnum.BC_CANCEL_NOTICE.ToString(); } else if (TaskBaseTypeEnum.DRAFT.ToString() == taskInfo.TASK_TYPE) { attachFileType = "draftnoticefiles"; fileCategory = TaskFileCategoryEnum.DRAFT_NOTICE.ToString(); } var noExtensionFileName = Path.GetFileNameWithoutExtension(modifyFile.FileName); var fileFullName = await SaveFile(taskInfo.Id.ToString(), bytes, batchNo, noExtensionFileName, GetFileType(modifyFile.FileName), attachFileType); if (!string.IsNullOrWhiteSpace(fileFullName)) { if (info.Main.FileList == null) { info.Main.FileList = new List(); } info.Main.FileList.Add(new TaskManageOrderFileInfo { PKId = SnowFlakeSingle.Instance.NextId(), FileName = modifyFile.FileName, FileType = Path.GetExtension(modifyFile.FileName).ToLower(), FilePath = fileFullName, FileCategory = fileCategory }); } } } #region 附件 //附件 if (info.Main.FileList != null && info.Main.FileList.Count > 0) { var fileList = info.Main.FileList.Select(file => { var fileInfo = new TaskFileInfo(); fileInfo.Id = SnowFlakeSingle.Instance.NextId(); fileInfo.TASK_PKID = taskInfo.Id; fileInfo.CreateBy = taskInfo.CreateBy; fileInfo.CreateTime = taskInfo.CreateTime; //fileInfo.CreatedUserName = taskInfo.CreatedUserName; //fileInfo.TenantId = taskInfo.TenantId; //fileInfo.TenantName = taskInfo.TenantName; fileInfo.FILE_PATH = file.FilePath; fileInfo.FILE_NAME = file.FileName; fileInfo.FILE_TYPE = file.FileType; if (string.IsNullOrWhiteSpace(file.FileCategory)) { if (TaskBaseTypeEnum.BC.ToString() == taskInfo.TASK_TYPE) { fileInfo.FILE_CATEGORY = TaskFileCategoryEnum.BC.ToString(); fileInfo.FILE_CATEGORY_NAME = TaskFileCategoryEnum.BC.EnumDescription(); } else if (TaskBaseTypeEnum.BC_MODIFY.ToString() == taskInfo.TASK_TYPE) { fileInfo.FILE_CATEGORY = TaskFileCategoryEnum.BC_MODIFY.ToString(); fileInfo.FILE_CATEGORY_NAME = TaskFileCategoryEnum.BC_MODIFY.EnumDescription(); } } else { TaskFileCategoryEnum fileCategoryEnum = TaskFileCategoryEnum.NONE; System.Enum.TryParse(file.FileCategory, out fileCategoryEnum); fileInfo.FILE_CATEGORY = fileCategoryEnum.ToString(); fileInfo.FILE_CATEGORY_NAME = fileCategoryEnum.EnumDescription(); } if (string.IsNullOrWhiteSpace(fileInfo.FILE_NAME)) { var fileModel = new FileInfo(file.FilePath); fileInfo.FILE_NAME = fileModel.Name; fileInfo.FILE_TYPE = fileModel.Extension?.Replace(".", ""); } return fileInfo; }).ToList(); await tenantDb.Insertable(fileList).ExecuteCommandAsync(); } #endregion #region 邮件 //邮件 if (info.Main.EmailList != null && info.Main.EmailList.Count > 0) { var emailList = info.Main.EmailList.Select(email => { var emailInfo = new TaskEmail(); emailInfo.Id = SnowFlakeSingle.Instance.NextId(); emailInfo.TASK_PKID = taskInfo.Id; emailInfo.CreateTime = taskInfo.CreateTime; emailInfo.CreateBy = taskInfo.CreateBy; emailInfo.MAIL_PATH = email.MailPath; return emailInfo; }).ToList(); await tenantDb.Insertable(emailList).ExecuteCommandAsync(); } #endregion #region SI反馈入库 //SI反馈入库 if (info.Main.TaskType == TaskBaseTypeEnum.SI_FEEDBACK) { if (info.Main.SIFeedBack == null) throw new Exception($"任务类型={info.Main.TaskType.ToString()} SIFeedBack信息必传"); TaskSiSubmitted taskSISubmitted = info.Main.SIFeedBack.Adapt(); //taskSISubmitted.Id = SnowFlakeSingle.Instance.NextId(); taskSISubmitted.TASK_ID = taskInfo.Id; taskSISubmitted.CreateTime = taskInfo.CreateTime; taskSISubmitted.CreateBy = taskInfo.CreateBy; await tenantDb.Insertable(taskSISubmitted).ExecuteReturnEntityAsync(); //SI反馈箱信息入库 if (info.Main.SIFeedBack.ContaList != null && info.Main.SIFeedBack.ContaList.Count > 0) { var codeCtnCache = (await codeCtnService.GetAllList())?.Data ?? new List(); info.Main.SIFeedBack.ContaList.ForEach(ctn => { var contaInfo = ctn.Adapt(); contaInfo.P_PKID = taskSISubmitted.Id; if (string.IsNullOrWhiteSpace(contaInfo.CTNCODE) && !string.IsNullOrWhiteSpace(contaInfo.CTNALL)) { if (codeCtnCache != null && codeCtnCache.Count > 0) { var ctnCodeInfo = codeCtnCache.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.CtnName) && x.CtnName.Equals(contaInfo.CTNALL, StringComparison.OrdinalIgnoreCase)); if (ctnCodeInfo != null) { contaInfo.CTNCODE = ctnCodeInfo.EdiCode; } } } tenantDb.Insertable(contaInfo).ExecuteCommand(); }); } // 执行自动化操作 TaskFlowDataContext dataContext = new( (TaskFlowDataNameConst.TaskBCId, taskInfo.Id) ); TaskFlowRuner taskFlow = new TaskFlowRuner(tenantDb, serviceProvider); await taskFlow.Run(info.Main.TaskType, taskInfo.Id, dataContext); } #endregion #region BC 任务 if (info.Main.TaskType == TaskBaseTypeEnum.BC || info.Main.TaskType == TaskBaseTypeEnum.BC_MODIFY || info.Main.TaskType == TaskBaseTypeEnum.CANCELLATION) { //异步写入 var bcInfo = info.Main.BCInfo.Adapt(); bcInfo.Id = SnowFlakeSingle.Instance.NextId(); bcInfo.TASK_ID = taskInfo.Id; bcInfo.CreateBy = taskInfo.CreateBy; bcInfo.CreateTime = taskInfo.CreateTime; if (info.Main.BCInfo.BookingSlotId.HasValue && info.Main.BCInfo.BookingSlotId.Value > 0) bcInfo.BOOKING_SLOT_ID = info.Main.BCInfo.BookingSlotId.Value; await tenantDb.Insertable(bcInfo).ExecuteCommandAsync(); //异步写入集装箱 var ctnCodeList = (await codeCtnService.GetAllList()).Data ?? new List(); var ctnList = info.Main.BCInfo.CtnList.Select(ctn => { var bcCtnInfo = ctn.Adapt(); bcCtnInfo.Id = SnowFlakeSingle.Instance.NextId(); bcCtnInfo.P_ID = bcInfo.Id; if (string.IsNullOrEmpty(bcCtnInfo.CTNCODE)) { var ctnCode = ctnCodeList.FirstOrDefault(a => !string.IsNullOrWhiteSpace(a.CtnName) && a.CtnName.Equals(bcCtnInfo.CTNALL, StringComparison.OrdinalIgnoreCase)); bcCtnInfo.CTNCODE = ctnCode != null ? ctnCode.EdiCode : "(箱型未收录)"; } bcInfo.CreateBy = taskInfo.CreateBy; bcInfo.CreateTime = taskInfo.CreateTime; return bcCtnInfo; }).ToList(); await tenantDb.Insertable(ctnList).ExecuteCommandAsync(); /* BC_MODIFY 1、检索对应舱位,提取比对差异结果 2、检索舱位对应的订舱信息,如果有则生成用户通知邮件 3、推送钉钉消息@操作人 通知收到变更 CANCELLATION 1、检索舱位对应的订舱信息,如果有则生成用户通知邮件 2、推送钉钉消息@操作人 通知收到变更 */ // 执行自动化操作 TaskFlowDataContext dataContext = new( (TaskFlowDataNameConst.TaskManageOrderMessageInfo, info), (TaskFlowDataNameConst.TaskBCId, bcInfo.Id), (TaskFlowDataNameConst.BCFile, file), (TaskFlowDataNameConst.AmendmentFile, modifyFile) ); TaskFlowRuner taskFlow = new TaskFlowRuner(tenantDb, serviceProvider); await taskFlow.Run(info.Main.TaskType, taskInfo.Id, dataContext); } #endregion var taskNo = await tenantDb.Queryable().Where(a => a.Id == taskInfo.Id).Select(a => a.TASK_NO).FirstAsync(); //回写任务号 var result = new DataResult(ResultCode.Success, "新增任务成功", data: taskNo); return await Task.FromResult(result); } catch (Exception ex) { logger.LogError(ex, "任务台:初始化任务的过程中发生未知异常,批次号={no}", batchNo); return DataResult.Failed(ex.Message); } } /// /// 任务台台账列表查询 /// public async Task>> GetPageAsync(PageRequest querySearch) { var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); if (querySearch.OtherQueryCondition == null) { throw new ArgumentNullException(nameof(querySearch.OtherQueryCondition)); } //序列化查询条件 List? whereList = null; if (!string.IsNullOrEmpty(querySearch.QueryCondition)) { whereList = tenantDb.Utilities.JsonToConditionalModels(querySearch.QueryCondition); if (whereList != null) { foreach (var item in whereList) { if (item is ConditionalModel model) { if (!model.FieldName.StartsWith("t.")) { model.FieldName = "t." + model.FieldName; } } } } } // 格式化参数 TaskBaseTypeEnum? taskType = null; if (Enum.TryParse(typeof(TaskBaseTypeEnum), querySearch.OtherQueryCondition?.TaskType, out object? temp)) { taskType = (TaskBaseTypeEnum)temp; }; TaskStatLevelEnum? taskStatLevel = null; //TaskStatLevelEnum? taskStatLevel = TaskStatLevelEnum.PUBLIC; if (Enum.TryParse(typeof(TaskStatLevelEnum), querySearch.OtherQueryCondition?.TaskCategory, out object? tempStat)) { taskStatLevel = (TaskStatLevelEnum)tempStat; } else { //throw new ArgumentException("TaskCategory"); } var userId = long.Parse(user.UserId); DataResult> result; switch (taskType) { case TaskBaseTypeEnum.BC: { var queryable = tenantDb.Queryable() .LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { Id = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.BUSI_TYPE, bc.SHIPPER, bc.CONSIGNEE, bc.NOTIFYPARTY, bc.BC_MODIFY_TIMES, bc.BC_MODIFY_DATE, //bc.MBL_NO, bc.VESSEL, bc.VOYNO, bc.CARRIER, bc.PLACERECEIPT, bc.PORTLOAD, bc.CLOSING_DATE, bc.VGM_CUTOFF_TIME, bc.ETA, //bc.ETD, bc.POD_ETA, bc.CUT_SINGLE_TIME, bc.PORTDISCHARGE, bc.PLACEDELIVERY, bc.SHIPPING_METHOD, bc.SERVICE, bc.PRETRANS_MODE, bc.DESCRIPTION, bc.ISSUEPLACE, bc.COLLECTION_TERMINAL, bc.CONTRACTNO, bc.PREPARDAT, bc.SHIP_AGENT, bc.YARD, bc.YARD_CONTACT_USR, bc.YARD_CONTACT_TEL, bc.FST_CUSTOMER_SER_USRNAME, bc.FST_CUSTOMER_SER_TEL, bc.FST_CUSTOMER_SER_EMAIL, bc.REMARK1, bc.CY_CUTOFF_TIME, bc.CARRIERID, bc.LANECODE, bc.LANENAME, bc.CARRIAGE_TYPE, bc.CARRIAGE_TYPE_NAME, bc.BOOKING_SLOT_TYPE, bc.BOOKING_SLOT_TYPE_NAME, bc.CTN_STAT, bc.WEEK_AT, bc.DETENSION_FREE_DAYS, bc.SI_CUT_DATE, bc.MANIFEST_CUT_DATE, bc.MDGF_CUT_DATE, bc.TRANSFER_PORT_1, bc.TRANSFER_PORT_2, bc.SECOND_VESSEL, bc.SECOND_VOYNO, bc.SECOND_ETD, bc.SECOND_ETA, //bc.STATUS, bc.FILE_MD5, bc.LAST_TOBOOKING_DATE, bc.FROM_EMAIL, bc.RECV_EMAIL, bc.BOOKING_ORDER_ID, bc.BOOKING_SLOT_ID, bc.BOOKING_COMFIRM_DATE, bc.BATCH_NO, bc.CUSTOM_SI_CUT_DATE, bc.IS_SET_AUTO_EMAIL, bc.IS_SEND_EMAIL, bc.DIFF_NUM, bc.AUTO_SEND_USER, bc.PROCESS_STATUS, bc.PROCESS_RESULT, bc.PROCESS_DATE, bc.PRICE_CALCULATION_DATE }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.SI_FEEDBACK: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.CARRIER, //bc.MBL_NO, bc.TAKE_ISSUETYPE_NAME, bc.ISSUETYPE, bc.NOTICE_DATE, bc.BOOKING_ID, bc.SUBMITTED_DATE, bc.BILLOF_NUM, bc.RELEASE_INSTRUCTION, bc.SI_SUBTYPE, bc.SHIPPER, bc.CONSIGNEE, bc.NOTIFYPARTY, bc.NOTIFYPARTY2, bc.TRANSPORT_RECEIVER, bc.MARKS, bc.HSCODE, bc.DESCRIPTION, bc.PKGS, bc.KINDPKGS, bc.KGS, bc.CBM, bc.VESSEL, bc.VOYNO, bc.COMMODITY, bc.PLACERECEIPTID, bc.PLACERECEIPT, bc.PORTLOADID, bc.PORTLOAD, bc.PORTDISCHARGEID, bc.PORTDISCHARGE, bc.PLACEDELIVERYID, bc.PLACEDELIVERY, bc.PROCESS_STATUS, bc.IS_SET_AUTO_UPD_BOOKING, bc.PROCESS_RESULT, bc.PROCESS_DATE, bc.DIFF_NUM, bc.IS_UPDATE_BOOKING, bc.UPDATE_BOOKING_DATE }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.INVOICE_BILL_MAIL: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_PKID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_PKID, //bc.MBL_NO, bc.INVOICE_NO, bc.CANCEL_NO, bc.TOTAL_AMOUNT, bc.IS_DONGSH_RECV, bc.IS_DONGSH_RESULT, bc.DONGSH_RECV_TIME, bc.DONGSH_RESULT_TIME, bc.DONGSH_RECV_REASON }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.TRUCK_DISPATCH: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.BookingTruckId, bc.BookingId, bc.TruckId, bc.TruckCode, bc.TruckName, bc.ToName, bc.Attn, bc.AttnTel, bc.AttnMail, bc.AttnFax, bc.FromName, bc.FromTel, bc.FromMail, bc.FromMobile, bc.FromFax, bc.KGS, bc.Fee, bc.PayMethod, bc.PayMethodName, bc.TruckTime, bc.YARDID, bc.YARD, bc.YARDCONTRACT, bc.YARDCONTRACTTEL, bc.FactoryId, bc.FactoryCode, bc.FactoryName, bc.FactoryContact, bc.FactoryTel, bc.ReturnTime, bc.InYardID, bc.InYard, bc.InYardContact, bc.InYardContractTel, //bc.NeedArriveTime, bc.ClosingTime, bc.PickUpTime, bc.IsGuaJi, //bc.Status, bc.Attention, bc.Remark, bc.DispatcherId, bc.DispatcherName, bc.TruckFlowNo, bc.TaskNo, bc.Vessel, bc.VoyNo, bc.MBLNo, bc.CntrTotal, bc.FactoryAddr }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.CUT_MODIFY: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.CARRIER, bc.VESSEL, bc.VOYNO, bc.NOTICE_DATE }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.ROLLING_NOMINATION: case TaskBaseTypeEnum.TRANSFER_NOMINATION: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.PLAN_TYPE, bc.BATCH_NO, bc.CARRIERID, bc.CARRIER, bc.CONFIRM_DEAD_LINE, bc.READ_CREATE_TIME, bc.ROLL_DOUBLE_REMARK, bc.PLAN_TXT, //bc.REMARK, bc.TASK_BATCH_TOTAL, bc.TASK_BATCH_PER_TOTAL }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.DRAFT: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.CARRIER, //bc.MBL_NO, bc.BOOKING_ID, bc.IS_CHANGE, bc.IS_EMAIL_SEND, bc.SEND_EMAIL_DATE, bc.NOTICE_DATE, }) .Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.POD_DISCHARGE_FULL: case TaskBaseTypeEnum.POD_GATEOUT_FULL: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.CARRIER, bc.NOTICE_TYPE, bc.NOTICE_TYPE_NAME, //bc.MBL_NO, bc.NOTICE_DATE }).Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.CAUTION_NOTICE: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.SOURCE_SYSTEM, bc.SOURCE_BUSI_TYPE, bc.SOURCE_BUSI_TYPENAME, bc.NOTIFY_CONTENT, //bc.MBL_NO, bc.CARRIER, bc.CAUTION_NOTICE_TYPE, bc.IS_WEEK_DIFF, bc.IS_PRICE_DATE_DIFF, bc.IS_TRANSFER, bc.IS_VESSEL_CHANGE, bc.IS_CUT_DATE_ADVANCED, bc.BOOKING_ID, bc.BOOKING_SLOT_ID, bc.SOURCE_TASK_ID, bc.OLD_VAL, bc.NEW_VAL, }).Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } case TaskBaseTypeEnum.ROUTE_CUT_CHANGE: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId) .LeftJoin((t, a, bc) => t.Id == bc.TASK_ID); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a, bc) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime, bc.TASK_ID, bc.VESSEL, bc.VOYNO, bc.CARRIER, bc.READ_PORTLOAD, bc.ORIG_ETD, bc.MDGF_CUT_DATE, bc.ETA, //bc.ETD, bc.SI_CUT_DATE, bc.TM_SHIFT_CUT_DATE, bc.VGM_CUTOFF_TIME, bc.CY_CUT_DATE, bc.ROUTE_CODE, bc.EMAIL_SUBJECT, bc.WEEK, bc.PORTLOADID, bc.PORTLOAD }).Distinct().ToQueryPageAsync(querySearch.PageCondition); return result; } default: { var queryable = tenantDb.Queryable().LeftJoin((t, a) => t.Id == a.TaskId); SetCondition(queryable, whereList, taskType, taskStatLevel, querySearch.OtherQueryCondition!.Status, userId); result = await queryable.Select((t, a) => new { PK_ID = t.Id.SelectAll(), TASK_USER_STATUS = a.Status, TASK_USER_STATUS_NAME = a.StatusName, TASK_USER_STATUS_TIME = a.StatusTime }).Distinct().ToQueryPageAsync(querySearch.PageCondition); //var sql = queryable.Select((t, a) => new //{ // PK_ID = t.Id.SelectAll(), // TASK_USER_STATUS = a.Status, // TASK_USER_STATUS_NAME = a.StatusName, // TASK_USER_STATUS_TIME = a.StatusTime //}).Distinct().ToSqlString(); return result; } } } /// /// 获取登陆人相关的任务统计信息 /// /// 是否强制计算 /// 返回回执 public async Task> GetCurrentTotalStat(bool isReCalc) { TaskUserStatResultInfo resultInfo = new TaskUserStatResultInfo { LevelTop = new List(), LevelNext = new List(), LevelTree = new List() }; /* 1、首先判断当前登陆人是否有统计记录,如果没有触发统计生成统计记录。 2、如果isReCalc=true,表示强制重新统计数据,并重新更新统计数据。 3、按照统计类型(个人/公共)、任务状态、是否异常分组汇总,并写入统计表。 */ //var userTendInfo = await _sysUserRepository.AsQueryable() // .LeftJoin((usr, ten) => usr.TenantId == ten.Id) // .Where(usr => usr.Id == UserManager.UserId) // .Select((usr, ten) => new { User = usr, Tend = ten }).FirstAsync(); //if (userTendInfo == null) // throw Oops.Oh($"当前用户关联租户信息获取失败"); ////var statList = _taskStatManageInfoRepository.AsQueryable().Where(t => (t.USER_ID == userTendInfo.User.Id ////&& t.STAT_TYPE == TaskStatLevelEnum.PERSON.ToString()) || (t.COMP_ID == userTendInfo.Tend.Id && t.STAT_TYPE == TaskStatLevelEnum.PUBLIC.ToString())).ToList(); ////菜单375504048771141=我的任务台账 //List userlist = await _sysDataUserMenuService.GetDataScopeList(MenuConst.MenuTaskManage); //bool isAdmin = userlist == null; var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); var userId = long.Parse(user.UserId); //任务列表分组统计 var groupList = await tenantDb.Queryable() .LeftJoin((t, a) => t.Id == a.TaskId) .Where((t, a) => t.IS_PUBLIC == 1 || (t.IS_PUBLIC == 0 && a.Status != null && (t.CreateBy == userId || a.UserId == userId))) .GroupBy((t, a) => new { t.TASK_TYPE, t.STATUS, a.Status, t.IS_PUBLIC }) .Select((t, a) => new { Total = SqlFunc.AggregateDistinctCount(t.Id), TaskType = t.TASK_TYPE, TStatus = t.STATUS, AStatus = a.Status, //IsExcept = t.IS_EXCEPT, IsPublic = t.IS_PUBLIC }).ToListAsync(); //var sql = tenantDb.Queryable() // .LeftJoin((t, a) => t.Id == a.TaskId) // .Where((t, a) => t.IS_PUBLIC == 1 || (t.IS_PUBLIC == 0 && a.Status != null && (t.CreateBy == userId || a.UserId == userId))) // .GroupBy((t, a) => new { t.TASK_TYPE, t.STATUS, a.Status, t.IS_PUBLIC }) // .Select((t, a) => new // { // Total = SqlFunc.AggregateDistinctCount(t.Id), // TaskType = t.TASK_TYPE, // TStatus = t.STATUS, // AStatus = a.Status, // //IsExcept = t.IS_EXCEPT, // IsPublic = t.IS_PUBLIC // }).ToSqlString(); //var exceptList = groupList // .Where(t => t.IsExcept == 1).ToList(); var personList = groupList .Where(t => t.IsPublic == 0).ToList(); var publicList = groupList .Where(t => t.IsPublic == 1).ToList(); #region 异常 //if (exceptList.Count > 0) //{ // resultInfo.LevelTop.Add(new TaskUserStatItem // { // Key = TaskStatLevelEnum.EXCPTION.ToString(), // Name = TaskStatLevelEnum.EXCPTION.EnumDescription(), // Total = exceptList.Sum(t => t.Total), // SortNo = (int)TaskStatLevelEnum.EXCPTION, // ActionKey = TaskStatLevelEnum.EXCPTION.ToString() // }); // var nextList = new List(); // exceptList.GroupBy(t => t.Status) // .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) // .ToList().ForEach(t => // { // TaskStatusEnum currEnum = (TaskStatusEnum)System.Enum.Parse(typeof(TaskStatusEnum), t.Key); // nextList.Add(new TaskUserStatItemNext // { // TopKey = TaskStatLevelEnum.EXCPTION.ToString(), // Key = currEnum.ToString(), // Name = currEnum.EnumDescription(), // Total = t.Total, // SortNo = (int)currEnum, // ActionKey = $"{TaskStatLevelEnum.EXCPTION.ToString()}#{currEnum.ToString()}" // }); // }); // if (nextList.Count > 0) // resultInfo.LevelNext.AddRange(nextList.OrderBy(t => t.SortNo).ToList()); // exceptList.GroupBy(t => new { t.Status, t.TaskType }) // .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) // .ToList().ForEach(t => // { // //TaskBusiTypeEnum currEnum = (TaskBusiTypeEnum)System.Enum.Parse(typeof(TaskBusiTypeEnum), t.Key.TaskType); // TaskBaseTypeEnum currEnum = (TaskBaseTypeEnum)System.Enum.Parse(typeof(TaskBaseTypeEnum), t.Key.TaskType); // resultInfo.LevelTree.Add(new TaskUserStatItemTree // { // TopKey = TaskStatLevelEnum.EXCPTION.ToString(), // NextKey = t.Key.Status, // Key = currEnum.ToString(), // Name = currEnum.EnumDescription(), // Total = t.Total, // SortNo = (int)currEnum, // ActionKey = $"{TaskStatLevelEnum.EXCPTION.ToString()}#{t.Key.Status}#{currEnum.ToString()}" // }); // }); //} #endregion #region 个人 if (personList.Count > 0) { resultInfo.LevelTop.Add(new TaskUserStatItem { Key = TaskStatLevelEnum.PERSON.ToString(), Name = TaskStatLevelEnum.PERSON.EnumDescription(), Total = personList.Sum(t => t.Total), SortNo = (int)TaskStatLevelEnum.PERSON, ActionKey = TaskStatLevelEnum.PERSON.ToString() }); var nextList = new List(); personList.GroupBy(t => t.AStatus) .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) .ToList().ForEach(t => { if (Enum.TryParse(t.Key, out TaskStatusEnum currEnum)) { nextList.Add(new TaskUserStatItemNext { TopKey = TaskStatLevelEnum.PERSON.ToString(), Key = currEnum.ToString(), Name = currEnum.EnumDescription(), Total = t.Total, SortNo = (int)currEnum, ActionKey = $"{TaskStatLevelEnum.PERSON}#{currEnum}" }); } }); if (nextList.Count > 0) resultInfo.LevelNext.AddRange(nextList.OrderBy(t => t.SortNo).ToList()); personList.GroupBy(t => new { t.AStatus, t.TaskType }) .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) .ToList().ForEach(t => { if (Enum.TryParse(t.Key.TaskType, out TaskBaseTypeEnum currEnum)) { resultInfo.LevelTree.Add(new TaskUserStatItemTree { TopKey = TaskStatLevelEnum.PERSON.ToString(), NextKey = t.Key.AStatus, Key = currEnum.ToString(), Name = currEnum.EnumDescription(), Total = t.Total, SortNo = (int)currEnum, ActionKey = $"{TaskStatLevelEnum.PERSON}#{t.Key.AStatus}#{currEnum}" }); } }); } #endregion #region 公共 if (publicList.Count > 0) { resultInfo.LevelTop.Add(new TaskUserStatItem { Key = TaskStatLevelEnum.PUBLIC.ToString(), Name = TaskStatLevelEnum.PUBLIC.EnumDescription(), Total = publicList.Sum(t => t.Total), SortNo = (int)TaskStatLevelEnum.PUBLIC, ActionKey = TaskStatLevelEnum.PUBLIC.ToString() }); var nextList = new List(); publicList.GroupBy(t => t.TStatus) .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) .ToList().ForEach(t => { if (Enum.TryParse(t.Key, out TaskStatusEnum currEnum)) { nextList.Add(new TaskUserStatItemNext { TopKey = TaskStatLevelEnum.PUBLIC.ToString(), Key = currEnum.ToString(), Name = currEnum.EnumDescription(), Total = t.Total, SortNo = (int)currEnum, ActionKey = $"{TaskStatLevelEnum.PUBLIC}#{currEnum}" }); } }); if (nextList.Count > 0) resultInfo.LevelNext.AddRange(nextList.OrderBy(t => t.SortNo).ToList()); publicList.GroupBy(t => new { t.TStatus, t.TaskType }) .Select(t => new { Key = t.Key, Total = t.ToList().Sum(p => p.Total) }) .ToList().ForEach(t => { if (Enum.TryParse(t.Key.TaskType, out TaskBaseTypeEnum currEnum)) { resultInfo.LevelTree.Add(new TaskUserStatItemTree { TopKey = TaskStatLevelEnum.PUBLIC.ToString(), NextKey = t.Key.TStatus, Key = currEnum.ToString(), Name = currEnum.EnumDescription(), Total = t.Total, SortNo = (int)currEnum, ActionKey = $"{TaskStatLevelEnum.PUBLIC}#{t.Key.TStatus}#{currEnum}" }); } }); } #endregion if (resultInfo.LevelTree != null && resultInfo.LevelTree.Count > 0) { resultInfo.LevelTree = resultInfo.LevelTree.OrderBy(x => x.SortNo).ToList(); } return DataResult.Success(resultInfo); } /// /// 取消任务(可批量) /// /// 任务主键数组 /// 返回结果 public async Task> CancelTask(long[] ids) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); var userId = long.Parse(user.UserId); string batchNo = Guid.NewGuid().ToString(); var taskList = await tenantDb.Queryable() .Where(x => ids.Contains(x.Id)).ToListAsync(); List taskRunList = new List(); logger.LogInformation("批次={no} ids={ids} 取消任务开始", batchNo, string.Join(",", ids)); var noList = ids.Select((a, idx) => new { no = idx + 1, id = a }).ToList(); //serviceProvider.GetRequiredService(); foreach (var bk in taskList) { var sortNo = noList.FirstOrDefault(a => a.id == bk.Id).no; taskRunList.Add(await InnerManualTask(batchNo, bk, TaskOperTypeEnum.CANCEL_TASK, sortNo)); } result.succ = true; result.msg = "执行成功"; var downResultList = taskRunList.Select(x => x).ToList(); if (downResultList.Any(x => !x.succ)) { result.succ = false; result.msg = "执行失败"; } else { result.succ = true; result.msg = downResultList.FirstOrDefault().msg; } result.ext = downResultList; var succ = downResultList.Count(x => x.succ); var fail = downResultList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } return DataResult.Success(result); } /// /// 单票执行任务 /// /// 批次号 /// 任务详情 /// 操作类型 /// 顺序号 /// 返回回执 private async Task InnerManualTask(string batchNo, TaskBaseInfo model, TaskOperTypeEnum taskOperTypeEnum, int sortNo) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); result.bno = model.TASK_NO; try { var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); var userId = long.Parse(user.UserId); if (taskOperTypeEnum == TaskOperTypeEnum.COMPLETE_TASK) { if (model.TASK_TYPE == TaskBaseTypeEnum.TRUCK_DISPATCH.ToString()) { if (model.STATUS == TaskStatusEnum.Cancel.ToString()) { throw new Exception(string.Format(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.TaskCannotCompleteWhenStatusMismatch)), TaskStatusEnum.Cancel.EnumDescription())); } } if (model.TASK_TYPE == TaskBaseTypeEnum.CANCELLATION.ToString()) { //收到订舱已被取消邮件后生成的任务,如果点击完成,(订舱状态变为【退舱】,注意这里还需要确认) } model.COMPLETE_DATE = DateTime.Now; model.COMPLETE_DEAL = TaskCompleteDealEnum.MANUAL.ToString(); model.COMPLETE_DEAL = TaskCompleteDealEnum.MANUAL.EnumDescription(); model.IS_COMPLETE = 1; model.STATUS = TaskStatusEnum.Complete.ToString(); model.STATUS_NAME = TaskStatusEnum.Complete.EnumDescription(); await tenantDb.Updateable(model).UpdateColumns(it => new { it.COMPLETE_DATE, it.COMPLETE_DEAL, it.COMPLETE_DEAL_NAME, it.IS_COMPLETE, it.STATUS, it.STATUS_NAME, it.UpdateBy, it.UpdateTime, it.UpdateUserName }).ExecuteCommandAsync(); } else if (taskOperTypeEnum == TaskOperTypeEnum.CANCEL_TASK) { if (model.TASK_TYPE == TaskBaseTypeEnum.CHANGE_SHIP.ToString()) { model.STATUS = TaskStatusEnum.Cancel.ToString(); model.STATUS_NAME = TaskStatusEnum.Cancel.EnumDescription(); await tenantDb.Updateable(model).UpdateColumns(it => new { it.COMPLETE_DATE, it.COMPLETE_DEAL, it.COMPLETE_DEAL_NAME, it.IS_COMPLETE, it.STATUS, it.STATUS_NAME, it.UpdateBy, it.UpdateTime, it.UpdateUserName }).ExecuteCommandAsync(); } else if (model.TASK_TYPE == TaskBaseTypeEnum.ABORT_CHANGE_SHIP.ToString()) { /* 1.如果原换船通知已经接受,需要把原船名航次恢复并通知客户取消换船。 2.如果原换船通知未作处理,点击接受或者结束任务时提示:本票货存在未处理换船通知,请先结束原换船任务然后结束本任务。 3.如果原换船任务为结束任务,在取消换船任务点接受时,提示未做换船,请点击结束任务。 */ // 查询同票主单的是否有未处理的换船通知 // _taskBaseInfoRepository.AsQueryable().Where(t=>t.MBL_NO.Equals(taskBaseInfo.MBL_NO) && ) } else { model.STATUS = TaskStatusEnum.Cancel.ToString(); model.STATUS_NAME = TaskStatusEnum.Cancel.EnumDescription(); await tenantDb.Updateable(model).UpdateColumns(it => new { it.STATUS, it.STATUS_NAME, it.UpdateBy, it.UpdateTime, it.UpdateUserName }).ExecuteCommandAsync(); } } result.succ = true; result.msg = "执行成功"; } catch (Exception ex) { result.succ = false; result.msg = ex.Message; } return result; } /// /// 完成任务(可批量) /// /// 任务主键数组 /// 返回结果 public async Task> CompleteTask(long[] ids) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); var tenantDb = saasDbService.GetBizDbScopeById(user.TenantId); var userId = long.Parse(user.UserId); string batchNo = Guid.NewGuid().ToString(); var taskList = await tenantDb.Queryable() .Where(x => ids.Contains(x.Id)).ToListAsync(); List taskRunList = new List(); logger.LogInformation("批次={no} ids={ids} 完成任务开始", batchNo, string.Join(",", ids)); var noList = ids.Select((a, idx) => new { no = idx + 1, id = a }).ToList(); foreach (var bk in taskList) { var sortNo = noList.FirstOrDefault(a => a.id == bk.Id).no; taskRunList.Add(await InnerManualTask(batchNo, bk, TaskOperTypeEnum.COMPLETE_TASK, sortNo)); } result.succ = true; result.msg = "执行成功"; var downResultList = taskRunList.Select(x => x).ToList(); if (downResultList.Any(x => !x.succ)) { result.succ = false; result.msg = "执行失败"; } else { result.succ = true; result.msg = downResultList.FirstOrDefault().msg; } result.ext = downResultList; var succ = downResultList.Count(x => x.succ); var fail = downResultList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } return DataResult.Success(result); } /// /// 设置条件的方法,用于 /// private void SetCondition(ISugarQueryable queryable, List? whereList, TaskBaseTypeEnum? taskType, TaskStatLevelEnum? taskStatLevel, string status, long userId) { queryable.Where(whereList) .WhereIF(taskType != null, (t, a) => t.TASK_TYPE == taskType.ToString()) .WhereIF(taskStatLevel == TaskStatLevelEnum.PUBLIC, (t, a) => t.IS_PUBLIC == 1 && t.STATUS == status) .WhereIF(taskStatLevel == TaskStatLevelEnum.PERSON, (t, a) => t.IS_PUBLIC == 0 && (t.CreateBy == userId || a.UserId == userId) && a.Status == status) .OrderByDescending(t => t.Id); } /// /// 设置条件的方法,用于 /// private void SetCondition(ISugarQueryable queryable, List? whereList, TaskBaseTypeEnum? taskType, TaskStatLevelEnum? taskStatLevel, string status, long userId) { queryable.Where(whereList) .WhereIF(taskType != null, (t, a) => t.TASK_TYPE == taskType.ToString()) .WhereIF(taskStatLevel == TaskStatLevelEnum.PUBLIC, (t, a) => t.IS_PUBLIC == 1 && t.STATUS == status) .WhereIF(taskStatLevel == TaskStatLevelEnum.PERSON, (t, a) => t.IS_PUBLIC == 0 && (t.CreateBy == userId || a.UserId == userId) && a.Status == status) .OrderByDescending(t => t.Id); } } }