using System.Linq.Expressions; using DS.Module.Core; using DS.Module.Core.Data; using DS.Module.Core.Extensions; using DS.Module.DjyServiceStatus; using DS.WMS.Core.Invoice.Dtos; using DS.WMS.Core.Op.Dtos; using DS.WMS.Core.Op.Entity; using DS.WMS.Core.Op.Interface; using DS.WMS.Core.Op.Method; using DS.WMS.Core.Sys.Entity; using DS.WMS.Core.TaskInteraction.Dtos; using DS.WMS.Core.TaskInteraction.Entity; using DS.WMS.Core.TaskInteraction.Interface; using DS.WMS.Core.TaskPlat.Dtos; using DS.WMS.Core.TaskPlat.Entity; using LanguageExt; using Mapster; using Masuit.Tools.Systems; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using NPOI.SS.Formula.Functions; using SqlSugar; namespace DS.WMS.Core.TaskInteraction.Method { /// /// 海运出口任务交互服务 /// public class SeaExportTaskService : TaskService, ISeaExportTaskService { const TaskBaseTypeEnum BL_CONFIRM_TASK = TaskBaseTypeEnum.WAIT_BILL_CONFIRM; readonly Lazy djyService; readonly Lazy seaComService; /// /// 初始化 /// /// public SeaExportTaskService(IServiceProvider provider) : base(provider) { djyService = new Lazy(provider.GetRequiredService()); seaComService = new Lazy(provider.GetRequiredService()); } public override async Task CreateTaskAsync(TaskCreationRequest request, bool useTransaction = true) { if (request.TaskType == TaskBaseTypeEnum.WAIT_BILL_CONFIRM) { request.Steps ??= []; if (!request.Steps.Exists(x => x.Type == StepType.OPConfirm)) { request.Steps.Add(new TaskStepDto { Type = StepType.OPConfirm, Name = StepType.OPConfirm.ToString() }); } } try { #region //第二次提交判断 var check = await GetTasks(request.BusinessId, request.BusinessType, false, request.TaskType); await TenantDb.Ado.BeginTranAsync(); if (check.Count > 0) { //货物状态 var goodsStatus = TenantDb.Queryable().First(x => x.StatusCode == "TIJIAO" && x.BusinessId == request.BusinessId); if (goodsStatus == null) { var gsCfg = TenantDb.Queryable().First(x => x.SystemCode == "TIJIAO"); if (gsCfg != null) { var gs = new BookingGoodsStatus() { BusinessId = request.BusinessId, ConfigId = gsCfg.Id, FinishTime = DateTime.Now, FinishUserName = User.UserId.IsNull() ? "超级管理员" : User.UserName, FinishBy = User.UserId.IsNull() ? 0 : long.Parse(User.UserId), StatusCode = gsCfg.SystemCode, StatusName = gsCfg.StatusName, }; await TenantDb.Insertable(gs).ExecuteCommandAsync(); } } //主单状态变更 var order = TenantDb.Queryable().Filter(null, true).First(x => x.Id == request.BusinessId); var oldOrder = order.Adapt(); order.BusinessStatusName = "已提交"; order.BusinessStatus = "TIJIAO"; await TenantDb.Updateable(order).UpdateColumns(x => new { x.BusinessStatusName, x.BusinessStatus }).EnableDiffLogEvent().ExecuteCommandAsync(); // 记录日志 await seaComService.Value.SaveSeaExportLogAsync(new SeaExportSaveLog() { OperateType = "Update", OldOrder = oldOrder, NewOrder = order, SourceCode = "CreateTaskAsync", SourceName = "审单再次提交更新", }, TenantDb); } #endregion var res1 = await base.CreateTaskAsync(request, true); if (res1.Succeeded) { await TenantDb.Ado.CommitTranAsync(); if (check.Count > 0) { //更新大简云货物状态 var pushModel = new EmbedServiceProjectStatusDto { businessId = request.BusinessId.ToString(), SourceType = 1, StatusCodes = new List { new EmbedServiceProjectStatusDetailDto{ StatusCode = "TIJIAO" } } }; await djyStatusService.Value.SaveServiceStatus(pushModel); } return res1; } else { await TenantDb.Ado.RollbackTranAsync(); return res1; } } catch (Exception) { await TenantDb.Ado.RollbackTranAsync(); throw; } } /// /// 创建关联子任务 /// /// /// public async Task CreateSubTaskAsync(IEnumerable request) { if (request == null || !request.Any()) return; var first = request.First(); var taskTypes = request.Select(x => x.TaskType).Distinct().ToArray(); var existTypes = await GetQuery(first.BusinessId, first.BusinessType, taskTypes).Select(x => x.TaskType).ToListAsync(); //移除已存在的任务类型 request = request.Where(x => !existTypes.Contains(x.TaskType)); if (!request.Any()) return; long userId = long.Parse(User.UserId); long tenatId = long.Parse(User.TenantId); string tenatName = Db.Queryable().Where(x => x.Id == tenatId).Select(x => x.Name).First(); var dt = DateTime.Now; var defaultUsers = await FillInUserInfoAsync(first.RecvUserIdList); var biz = await TenantDb.Queryable().Select(x => new { x.Id, x.CustomerNo, x.MBLNO, x.Vessel, x.Voyno, x.ETD, x.DischargePortId, x.DischargePortCode, x.DischargePort, x.LoadPortId, x.LoadPortCode, x.LoadPort, x.CarrierId, x.Carrier, //x.BookingNo, //x.HBLNO, //x.CustomerNum, }).FirstAsync(x => x.Id == first.BusinessId); var taskList = new List(); var taskLogList = new List(); //获取任务接收人 var dic = await GetRecvUsersAsync(first.BusinessId, first.BusinessType, request.Select(x => x.TaskType).ToList()); foreach (var item in request) { var recvUsers = dic[item.TaskType]; var info = new TaskManageOrderMessageInfo { Head = new TaskManageOrderMessageHeadInfo { GID = Guid.NewGuid().ToString(), BSNO = item.BusinessId, MessageType = "WORK_FLOW_TASK", SenderId = "WorkFlow", SenderName = "工作流平台", ReceiverId = "TaskManage", ReceiverName = "任务管理平台", Version = "1.0", RequestDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), RequestAction = "Add" }, Main = new TaskManageOrderMessageMainInfo { TaskType = item.TaskType, TaskSource = TaskSourceEnum.WORK_FLOW, TaskUserId = User.UserId, TaskUserName = User.UserName, RecvUserInfoList = recvUsers ?? defaultUsers, TaskTenatId = tenatId, TaskTenatName = tenatName, IsCheckExistsByTaskType = true } }; info.Main.TaskDesp = info.Main.TaskTitle = $"【{item.TaskType.GetDescription()}】{biz?.CustomerNo} {biz?.Vessel} {biz?.Voyno} ETD:{biz?.ETD?.ToString("yyyy-MM-dd")}"; info.Main.CustomerNo = biz?.CustomerNo; info.Main.MBlNo = biz?.MBLNO; info.Main.ETD = biz?.ETD; info.Main.PortDischarge = biz?.DischargePort; info.Main.PortDischargeCode = biz?.DischargePortCode; info.Main.PortDischargeId = biz?.DischargePortId; info.Main.PortLoad = biz?.LoadPort; info.Main.PortLoadId = biz?.LoadPortId; info.Main.PortLoadCode = biz?.LoadPortCode; info.Main.CarrierId = biz?.Carrier; info.Main.CarrierPK = biz?.CarrierId; //info.Main.HBLNO = biz?.HBLNO; //info.Main.BookingNo = biz?.BookingNo; //info.Main.CustomsNum = biz?.CustomerNum; var result = await ManagerService.InitTaskJob(info); if (!result.Succeeded) continue; var task = new BusinessTask { BusinessId = item.BusinessId, BusinessType = item.BusinessType, TaskType = item.TaskType, TaskStatus = TaskStatusEnum.Create, RecvUsers = info.Main.RecvUserInfoList == null ? string.Empty : string.Join(",", info.Main.RecvUserInfoList.Select(x => x.RecvUserId)), CreateBy = userId, CreateTime = dt }; taskList.Add(task); taskLogList.Add(new BusinessTaskLog { BusinessId = task.BusinessId, BusinessType = task.BusinessType, CreateBy = userId, CreateTime = dt, RecvUsers = info.Main.RecvUserInfoList == null ? null : string.Join(",", info.Main.RecvUserInfoList.Select(x => x.RecvUserName)), TaskStatus = task.TaskStatus, TaskType = task.TaskType }); } await TenantDb.Insertable(taskList).ExecuteCommandAsync(); await TenantDb.Insertable(taskLogList).ExecuteCommandAsync(); } /// /// 创建关联子任务 /// /// /// public async Task CreateSubTaskAsync(BusinessTask task) { var list = await GetSubRequestAsync(task.BusinessId, task.BusinessType.GetValueOrDefault()); await CreateSubTaskAsync(list.FindAll(x => x.TaskType != TaskBaseTypeEnum.NOT_SPECIFIED).OrderBy(x => x.TaskType)); } /// /// 生成关联子任务 /// /// /// public async Task GenerateSubTaskAsync(TaskFlowDataContext dataContext) { ArgumentNullException.ThrowIfNull(dataContext, nameof(dataContext)); var task = dataContext.GetOrDefault(TaskFlowDataNameConst.BusinessTask); if (task != null) await CreateSubTaskAsync(task); } /// /// 获取提单确认信息 /// /// 业务ID /// 业务类型 /// public async Task> GetBLConfirmationAsync(long bsId, BusinessType bsType) { var confirmation = new TaskGroup { BusinessId = bsId, BusinessType = bsType, }; var mainTask = await TenantDb.Queryable() .LeftJoin((t, s) => t.BusinessId == s.Id) .Where((t, s) => t.TaskType == BL_CONFIRM_TASK && t.BusinessId == bsId && t.BusinessType == bsType) .OrderByDescending((t, s) => t.CreateTime) .Select((t, s) => new BLTask { BLNumber = s.MBLNO, Id = t.Id, BusinessId = t.BusinessId, BusinessType = t.BusinessType, ParentBusinessId = t.ParentBusinessId, ParentId = t.ParentId, TaskType = t.TaskType, TaskStatus = t.TaskStatus, RecvUsers = t.RecvUsers, IsMainBL = true, Steps = SqlFunc.Subqueryable().Where(ts => ts.TaskId == t.Id).ToList(ts => new TaskStepDto { }, true) }).FirstAsync(); if (mainTask == null) return DataResult.Success(confirmation); var list = await TenantDb.Queryable() .LeftJoin((t, b) => t.BusinessId == b.Id) .Where((t, b) => t.ParentBusinessId == bsId && t.BusinessType == bsType) .Select((t, b) => new BLTask { BLNumber = b.HBLNO, Id = t.Id, BusinessId = t.BusinessId, BusinessType = t.BusinessType, ParentBusinessId = t.ParentBusinessId, ParentId = t.ParentId, TaskType = t.TaskType, TaskStatus = t.TaskStatus, RecvUsers = t.RecvUsers, IsMainBL = false, Steps = SqlFunc.Subqueryable().Where(ts => ts.TaskId == t.Id).ToList(ts => new TaskStepDto { }, true) }).ToListAsync(); list.Insert(0, mainTask); confirmation.Tasks = list; if (confirmation.Tasks.Count > 0) { var ids = confirmation.Tasks.SelectMany(x => x.RecvUserIds).Distinct(); var userList = await Db.Queryable().Where(x => ids.Contains(x.Id)) .Select(x => new { x.Id, x.UserName }).ToListAsync(); foreach (var item in confirmation.Tasks) { item.RecvUserList = userList.Where(x => item.RecvUserIds.Contains(x.Id)) .Select(x => x.UserName).ToArray(); } } return DataResult.Success(confirmation); } /// /// 获取海运出口查询对象 /// /// 查询条件 /// public ISugarQueryable AsQueryable(Expression>? expression = null) { return TenantDb.Queryable().WhereIF(expression != null, expression); } protected override async Task OnTaskCreated(BusinessTask task) { if (task.TaskType == TaskBaseTypeEnum.WAIT_BOOKING) { var order = await AsQueryable(x => x.Id == task.BusinessId).Select(x => new { x.BookingNo, x.MBLNO }).FirstAsync(); //订单已有订舱编号或提单号,当前任务直接完成 if (order != null && (!order.BookingNo.IsNullOrEmpty() || !order.MBLNO.IsNullOrEmpty())) { string taskDesc = "因订单已存在"; if (!order.BookingNo.IsNullOrEmpty()) { taskDesc += $"订舱编号({order.BookingNo})、"; } if (!order.MBLNO.IsNullOrEmpty()) { taskDesc += $"提单号({order.MBLNO})、"; } taskDesc = taskDesc.Remove(taskDesc.Length - 1) + "而跳过订舱"; await SetTaskStatusAsync(new TaskUpdateRequest { BusinessId = task.BusinessId, BusinessType = task.BusinessType, TaskTypeName = task.TaskType.ToString(), TaskStatus = TaskStatusEnum.Complete, TaskDesc = taskDesc }, false); } } return DataResult.Success; } internal async Task> GetSubRequestAsync(long id, BusinessType businessType, params long[]? recvUsers) { var svcItem = await TenantDb.Queryable().Where(x => x.Id == id) .Select(x => x.ServiceItem).FirstAsync(); if (string.IsNullOrEmpty(svcItem)) return []; var svcItems = svcItem.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => "WAIT_" + x.ToUpperInvariant()).ToList(); List requests = new List(svcItems.Count); for (int i = 0; i < svcItems.Count; i++) { if (Enum.TryParse(svcItems[i], true, out TaskBaseTypeEnum taskType)) { var req = new TaskCreationRequest { BusinessId = id, BusinessType = businessType, RecvUserIdList = recvUsers, TaskTypeName = taskType.ToString() }; requests.Add(req); } } return requests; } } }