using Furion.DependencyInjection; using Furion.DistributedIDGenerator; using Furion.DynamicApiController; using Furion.FriendlyException; using Furion.JsonSerialization; using Furion.Localization; using Mapster; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Myshipping.Application.Entity; using Myshipping.Application.Helper; using Myshipping.Core; using Myshipping.Core.Entity; using Myshipping.Core.Service; using MySqlX.XDevAPI.Common; using Npoi.Mapper; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.PTG; using NPOI.Util; using SqlSugar; using StackExchange.Profiling.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myshipping.Application { /// /// 服务流程 /// [ApiDescriptionSettings("Application", Name = "ServiceWorkFlowBase", Order = 20)] public class ServiceWorkFlowBaseService : IServiceWorkFlowBaseService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _serviceWorkFlowBaseRepository; private readonly SqlSugarRepository _serviceWorkFlowActivitiesInfoRepository; private readonly SqlSugarRepository _serviceWorkFlowProjectRelationRepository; private readonly SqlSugarRepository _serviceWorkFlowActivitiesRelationRepository; private readonly SqlSugarRepository _serviceWorkFlowActivitiesSubRelationRepository; private readonly SqlSugarRepository _serviceWorkFlowReleaseInfoRepository; private readonly SqlSugarRepository _serviceWorkFlowActivitiesTriggerRelationRepository; private readonly SqlSugarRepository _statusSkuBaseInfoRepository; private readonly ILogger _logger; private readonly ICache _cache; private readonly CacheOptions _cacheOptions; const string CONST_CACHE_ENABLE_PROJECT = "service_project_list_enable"; const string CONST_CACHE_ENABLE_PROJECT_STATUS = "service_project_status_list_enable"; public ServiceWorkFlowBaseService(SqlSugarRepository serviceWorkFlowBaseRepository, ILogger logger, SqlSugarRepository serviceWorkFlowActivitiesInfoRepository, SqlSugarRepository serviceWorkFlowProjectRelationRepository, SqlSugarRepository serviceWorkFlowActivitiesRelationRepository, SqlSugarRepository serviceWorkFlowActivitiesSubRelationRepository, SqlSugarRepository serviceWorkFlowActivitiesTriggerRelationRepository, SqlSugarRepository serviceWorkFlowReleaseInfoRepository, SqlSugarRepository statusSkuBaseInfoRepository, IOptions cacheOptions, Func resolveNamed) { _serviceWorkFlowBaseRepository = serviceWorkFlowBaseRepository; _serviceWorkFlowActivitiesInfoRepository = serviceWorkFlowActivitiesInfoRepository; _serviceWorkFlowProjectRelationRepository = serviceWorkFlowProjectRelationRepository; _serviceWorkFlowActivitiesRelationRepository = serviceWorkFlowActivitiesRelationRepository; _logger = logger; _serviceWorkFlowActivitiesSubRelationRepository = serviceWorkFlowActivitiesSubRelationRepository; _serviceWorkFlowReleaseInfoRepository = serviceWorkFlowReleaseInfoRepository; _serviceWorkFlowActivitiesTriggerRelationRepository = serviceWorkFlowActivitiesTriggerRelationRepository; _statusSkuBaseInfoRepository = statusSkuBaseInfoRepository; _cacheOptions = cacheOptions.Value; _cache = resolveNamed(_cacheOptions.CacheType.ToString(), default) as ICache; } /// /// 保存 /// /// 服务流程详情 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/Save")] public async Task Save([FromBody] ServiceWorkFlowBaseDto info) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var id = await InnerSave(info); result.succ = true; result.msg = "保存成功"; result.ext = id; } catch (Exception ex) { result.succ = false; result.msg = $"保存服务项目异常,原因:{ex.Message}"; } return result; } #region 保存服务流程活动 /// /// 保存服务流程活动 /// /// 保存服务流程活动详情 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/SaveWFActivities")] public async Task SaveWFActivities([FromBody] ServiceWorkFlowActivitiesDto info) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { /* 1、状态有记录。 2、同一状态不能有相同的显示名称 3、已经关联服务流程的,并且已经发布的不能修改内容。(只可以新增) */ var entity = info.Adapt(); if (string.IsNullOrWhiteSpace(entity.STATUS_SKU_ID)) { throw Oops.Oh($"状态不能为空", typeof(InvalidOperationException)); } if (string.IsNullOrWhiteSpace(entity.SHOW_NAME) || entity.SHOW_NAME.Length < 2) { throw Oops.Oh($"状态显示名称不能为空,并且不能少于2个字符", typeof(InvalidOperationException)); } //同一状态不能有相同的显示名称 var checkList = _serviceWorkFlowActivitiesInfoRepository.AsQueryable() .Where(a=>a.STATUS_SKU_ID == entity.STATUS_SKU_ID && a.SHOW_NAME == entity.SHOW_NAME && a.PK_ID != entity.PK_ID).ToList(); if (checkList.Count > 0) throw Oops.Oh($"已存在相同的状态设置,不能保存", typeof(InvalidOperationException)); //_logger.LogInformation($"服务项目保存 JSON={JSON.Serialize(entity)} user={UserManager.UserId}"); if (string.IsNullOrWhiteSpace(entity.PK_ID)) { entity.PK_ID = IDGen.NextID().ToString(); _serviceWorkFlowActivitiesInfoRepository.Insert(entity); } else { //已经关联服务流程的,并且已经发布的不能修改内容。(只可以新增) var wfRelation = _serviceWorkFlowActivitiesRelationRepository.AsQueryable() .Where(a=>a.SERVICE_ACTIVITIES_ID == entity.PK_ID) .ToList(); if (wfRelation.Count > 0) { var currArg = wfRelation.Select(a=>a.SERVICE_WORKFLOW_ID).Distinct().ToList(); if (_serviceWorkFlowBaseRepository.AsQueryable().Any(a => currArg.Any(b => b == a.PK_ID) && (!string.IsNullOrWhiteSpace(a.RELEASE_VERSION) || a.IS_LOCK == 1))) { throw Oops.Oh($"当前状态已关联发布流程,不能保存", typeof(InvalidOperationException)); } } entity.UpdatedTime = DateTime.Now; entity.UpdatedUserId = UserManager.UserId; entity.UpdatedUserName = UserManager.Name; await _serviceWorkFlowActivitiesInfoRepository.AsUpdateable(entity).IgnoreColumns(it => new { it.TenantId, it.TenantName, it.CreatedTime, it.CreatedUserId, it.CreatedUserName, it.IsDeleted, }).ExecuteCommandAsync(); } result.succ = true; result.msg = "保存成功"; result.ext = entity.PK_ID; } catch (Exception ex) { result.succ = false; result.msg = $"保存服务流程活动异常,原因:{ex.Message}"; } return result; } #endregion #region 保存内部方法 /// /// 保存内部方法 /// /// 服务流程详情 /// 是否启用 /// 返回派车Id [SqlSugarUnitOfWork] private async Task InnerSave(ServiceWorkFlowBaseDto info, bool isSetEnable = false) { ServiceWorkFlowBaseInfo entity = info.Adapt(); if (isSetEnable) { if (string.IsNullOrWhiteSpace(entity.SERVICE_WORKFLOW_CODE) || string.IsNullOrWhiteSpace(entity.SERVICE_WORKFLOW_NAME)) { throw Oops.Oh($"服务流程代码或名称不能为空", typeof(InvalidOperationException)); } entity.IS_ENABLE = 1; } if (entity == null) throw Oops.Oh($"服务流程不能为空", typeof(InvalidOperationException)); if(entity.BELONG_TENANT_ID == 0) { entity.BELONG_TENANT_ID = UserManager.TENANT_ID; entity.BELONG_TENANT_NAME = UserManager.TENANT_NAME; } if (string.IsNullOrWhiteSpace(info.ServiceWorkflowCode)) { if (_serviceWorkFlowBaseRepository.AsQueryable().Any(a => a.SERVICE_WORKFLOW_CODE.Equals(info.ServiceWorkflowCode) && a.PK_ID != info.PKId)) { _logger.LogInformation($"服务流程代码已存在不能重复保存"); throw Oops.Oh($"服务流程代码已存在不能重复保存", typeof(InvalidOperationException)); } } if (info.StatusSkuList != null && info.StatusSkuList.Count > 0) { if (info.StatusSkuList.Any(a => a.IsContainsSub == 1 && (a.SubList == null || a.SubList.Count == 0))) { throw Oops.Oh($"状态已选择包含子状态,子状态列表不能为空", typeof(InvalidOperationException)); } if (info.StatusSkuList.Any(a => a.SortNo == 0)) throw Oops.Oh($"状态必需指定大于零的顺序号", typeof(InvalidOperationException)); if (info.StatusSkuList.GroupBy(a => a.SortNo).Any(a => a.ToList().Count > 1)) throw Oops.Oh($"状态顺序号不能重复", typeof(InvalidOperationException)); info.StatusSkuList = info.StatusSkuList.OrderBy(a => a.SortNo).Select((a, idx) => { if (a.SubList == null || a.SubList.Count == 0) { a.SortNo = idx + 1; return a; } a.SortNo = idx + 1; a.SubList = a.SubList.OrderBy(b => b.SortNo).Select((b, sidx) => { b.SortNo = sidx + 1; return b; }).ToList(); return a; }).ToList(); } _logger.LogInformation($"服务流程保存 JSON={JSON.Serialize(entity)} user={UserManager.UserId}"); string currVersion = string.Empty; if (string.IsNullOrWhiteSpace(entity.PK_ID)) { entity.PK_ID = IDGen.NextID().ToString(); entity.DEVELOP_VERSION = "DEVELOP"; currVersion = entity.DEVELOP_VERSION; if (info.StatusSkuList != null && info.StatusSkuList.Count > 0) { entity.STATUS_NUM = info.StatusSkuList.Sum(a => { if (a.SubList != null) return a.SubList.Count + 1; return 1; }); } _serviceWorkFlowBaseRepository.Insert(entity); } else { var model = InnerGetInfo(entity.PK_ID); _logger.LogInformation($"更新状态前,获取原始记录 JSON={JSON.Serialize(model)}"); ValidateServiceWorkFlow(entity, OperateTypeEnum.Save); entity.UpdatedTime = DateTime.Now; entity.UpdatedUserId = UserManager.UserId; entity.UpdatedUserName = UserManager.Name; if (!isSetEnable) { entity.IS_ENABLE = model.IS_ENABLE; } entity.IS_LOCK = model.IS_LOCK; if (string.IsNullOrWhiteSpace(model.DEVELOP_VERSION)) { if(!string.IsNullOrWhiteSpace(model.RELEASE_VERSION)) { entity.DEVELOP_VERSION = "DEVELOP"; } } else { entity.DEVELOP_VERSION = model.DEVELOP_VERSION; } currVersion = entity.DEVELOP_VERSION; if (info.StatusSkuList != null && info.StatusSkuList.Count > 0) { entity.STATUS_NUM = info.StatusSkuList.Sum(a => { if (a.SubList != null) return a.SubList.Count + 1; return 1; }); } await _serviceWorkFlowBaseRepository.AsUpdateable(entity).IgnoreColumns(it => new { it.TenantId, it.TenantName, it.CreatedTime, it.CreatedUserId, it.CreatedUserName, it.IsDeleted, it.RELEASE_VERSION, it.PUBLISH_DATE, it.PUBLISH_ER, it.PUBLISH_NAME, it.IS_LOCK }).ExecuteCommandAsync(); currVersion = entity.DEVELOP_VERSION; //批量删除服务流程与服务项目关系(物理删除) _serviceWorkFlowProjectRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == entity.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程与服务活动关系(物理删除) _serviceWorkFlowActivitiesRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == entity.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程活动与子活动的关系(物理删除) _serviceWorkFlowActivitiesSubRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == entity.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程与服务流程活动触发器关系(物理删除) _serviceWorkFlowActivitiesTriggerRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == entity.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); } //服务流程与服务项目关系 if (info.ServiceProject != null && !string.IsNullOrWhiteSpace(info.ServiceProject.PKId)) { var wfRelationProject = new ServiceWorkFlowProjectRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = entity.PK_ID, SERVICE_PROJECT_ID = info.ServiceProject.PKId, WF_VERSION = currVersion }; //插入关系 await _serviceWorkFlowProjectRelationRepository.InsertAsync(wfRelationProject); } //服务流程与服务活动关系 if (info.StatusSkuList != null && info.StatusSkuList.Count > 0) { info.StatusSkuList.ForEach(async sku => { var wfRelationActivities = new ServiceWorkFlowActivitiesRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = entity.PK_ID, SERVICE_ACTIVITIES_ID = sku.PKId, SORT_NO = sku.SortNo, IS_CONTAINS_SUB = sku.IsContainsSub, VAL_TYPE = !string.IsNullOrWhiteSpace(sku.ValType)? sku.ValType: StatusSKUValTypeEnum.DATETIME.ToString(), WF_VERSION = currVersion }; await _serviceWorkFlowActivitiesRelationRepository.InsertAsync(wfRelationActivities); //处理子状态 if(sku.IsContainsSub == 1) { sku.SubList.ForEach(async sub => { var wfRelationActivitiesSub = new ServiceWorkFlowActivitiesSubRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = entity.PK_ID, SERVICE_ACTIVITIES_ID = sku.PKId, SUB_SERVICE_ACTIVITIES_ID = sub.PKId, SORT_NO = sub.SortNo, VAL_TYPE = !string.IsNullOrWhiteSpace(sku.ValType) ? sku.ValType : StatusSKUValTypeEnum.DATETIME.ToString(), WF_VERSION = currVersion }; await _serviceWorkFlowActivitiesSubRelationRepository.InsertAsync(wfRelationActivitiesSub); sub.StatusTriggerList.ForEach(async trg => { var triggerRela = new ServiceWorkFlowActivitiesTriggerRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = entity.PK_ID, SERVICE_ACTIVITIES_ID = sub.PKId, STATUS_TRIGGER_ID = trg.PKId, WF_VERSION = currVersion }; await _serviceWorkFlowActivitiesTriggerRelationRepository.InsertAsync(triggerRela); }); }); } if(sku.StatusTriggerList != null && sku.StatusTriggerList.Count > 0) { sku.StatusTriggerList.ForEach(async trg => { var triggerRela = new ServiceWorkFlowActivitiesTriggerRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = entity.PK_ID, SERVICE_ACTIVITIES_ID = sku.PKId, STATUS_TRIGGER_ID = trg.PKId, WF_VERSION = currVersion }; await _serviceWorkFlowActivitiesTriggerRelationRepository.InsertAsync(triggerRela); }); } }); } return entity.PK_ID; } #endregion #region 校验 /// /// 校验 /// /// 服务流程详情 /// 操作类型枚举 /// private void ValidateServiceWorkFlow(ServiceWorkFlowBaseInfo entity, OperateTypeEnum opTypeEnum) { /* 1、服务流程代码和名称不能低于2个字符。 */ if (opTypeEnum == OperateTypeEnum.Save) { if (_serviceWorkFlowProjectRelationRepository.AsQueryable().Any(a => a.SERVICE_PROJECT_ID == entity.PK_ID)) { throw Oops.Oh($"当前服务项目已关联服务流程,不能修改", typeof(InvalidOperationException)); } if (entity.SERVICE_WORKFLOW_CODE.Length < 2 || entity.SERVICE_WORKFLOW_NAME.Length < 2) throw Oops.Oh($"服务流程代码和状态名称不能小于2个字符,不能修改", typeof(InvalidOperationException)); } } #endregion #region 单票查询 /// /// 单票查询 /// /// 服务流程主键 private ServiceWorkFlowBaseInfo InnerGetInfo(string pkId) { if (string.IsNullOrWhiteSpace(pkId)) { throw Oops.Oh($"状态主键不能为空", typeof(InvalidOperationException)); } var model = _serviceWorkFlowBaseRepository.AsQueryable().First(a => a.PK_ID == pkId); if (model == null) throw Oops.Oh($"状态获取失败,状态信息不存在或已作废", typeof(InvalidOperationException)); return model; } #endregion #region 单票查询显示详情 /// /// 单票查询显示详情 /// /// 服务流程主键 private ServiceWorkFlowBaseShowDto InnerGetShowInfo(string pkId) { var model = InnerGetInfo(pkId); var showModel = model.Adapt(); /* 1、获取关联的服务项目(单条) 2、获取关联的服务活动列表(多条) */ string currVersion = string.Empty; if(!string.IsNullOrWhiteSpace(model.DEVELOP_VERSION)) { currVersion = model.DEVELOP_VERSION; } else { currVersion = model.RELEASE_VERSION; } var projectInfo = _serviceWorkFlowProjectRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, prj) => rela.SERVICE_PROJECT_ID == prj.PK_ID) .Where(rela => rela.SERVICE_WORKFLOW_ID == pkId && rela.WF_VERSION == currVersion) .Select((rela, prj) => prj).First(); if (projectInfo != null) { showModel.ServiceProject = projectInfo.Adapt(); } var activitiesList = _serviceWorkFlowActivitiesRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, act) => rela.SERVICE_ACTIVITIES_ID == act.PK_ID && rela.WF_VERSION == currVersion) .LeftJoin((rela, act, sku) => act.STATUS_SKU_ID == sku.PK_ID) .Where((rela,act,sku)=> rela.SERVICE_WORKFLOW_ID == pkId && rela.WF_VERSION == currVersion) .Select((rela, act, sku) => new { Act = act, Sku = sku, SortNo = rela.SORT_NO, IsSub = rela.IS_CONTAINS_SUB,ValType = rela.VAL_TYPE }) .ToList(); if (activitiesList.Count > 0) { showModel.StatusSkuList = activitiesList.OrderBy(a => a.SortNo) .Select(a => { var actModel = a.Act.Adapt(); actModel.SortNo = a.SortNo; actModel.IsContainsSub = a.IsSub; actModel.ValType = a.ValType; actModel.statusSkuBase = a.Sku.Adapt(); return actModel; }).ToList(); var currArg = showModel.StatusSkuList.Select(a=>a.PKId).Distinct().ToList(); var triggerList = _serviceWorkFlowActivitiesTriggerRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, trig) => rela.STATUS_TRIGGER_ID == trig.PK_ID) .LeftJoin((rela,trig,cond)=> trig.PK_ID == cond.P_ID) .LeftJoin((rela,trig,cond,nxt)=> cond.P_ID == nxt.CONDITION_ID) .Where((rela, trig,cond,nxt) => currArg.Contains(rela.SERVICE_ACTIVITIES_ID) && rela.WF_VERSION == currVersion) .Select((rela, trig, cond, nxt) => new { Rela = rela, Trigger = trig, Condition = cond, Next = nxt }).ToList(); if(triggerList.Count > 0) { showModel.StatusSkuList = showModel.StatusSkuList.GroupJoin(triggerList, l => l.PKId, r => r.Rela.SERVICE_ACTIVITIES_ID, (l, r) => { var currList = r.ToList(); if (currList.Count > 0 && currList.Any(a=>a.Trigger != null)) { l.StatusTriggerList = currList.GroupBy(c => c.Trigger.PK_ID) .Select(c => { var currTriggerList = c.ToList(); var triggerDto = currTriggerList.FirstOrDefault().Trigger.Adapt(); triggerDto.ConditionList = currTriggerList.GroupBy(d => d.Condition) .Select(d => { var currCondList = d.ToList(); var condDto = currCondList.FirstOrDefault().Condition.Adapt(); if (currCondList.Any(e => e.Next != null)) condDto.NextActList = currCondList.Select(e => e.Next.Adapt()).ToList(); return condDto; }).ToList(); return triggerDto; }).ToList(); } return l; }).ToList(); } } var activitiesSubList = _serviceWorkFlowActivitiesSubRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, act) => rela.SUB_SERVICE_ACTIVITIES_ID == act.PK_ID && rela.WF_VERSION == currVersion) .LeftJoin((rela, act, sku) => act.STATUS_SKU_ID == sku.PK_ID) .Where((rela, act, sku) => rela.SERVICE_WORKFLOW_ID == pkId && rela.WF_VERSION == currVersion) .Select((rela, act, sku) => new { Act = act, Sku = sku, SortNo = rela.SORT_NO, ParentId = rela.SERVICE_ACTIVITIES_ID }) .ToList(); if(activitiesSubList.Count > 0) { var currArg = activitiesSubList.Select(a => a.Act.PK_ID).Distinct().ToList(); var triggerList = _serviceWorkFlowActivitiesTriggerRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, trig) => rela.STATUS_TRIGGER_ID == trig.PK_ID) .LeftJoin((rela, trig, cond) => trig.PK_ID == cond.P_ID) .LeftJoin((rela, trig, cond, nxt) => cond.P_ID == nxt.CONDITION_ID) .Where((rela, trig, cond, nxt) => currArg.Contains(rela.SERVICE_ACTIVITIES_ID) && rela.WF_VERSION == currVersion) .Select((rela, trig, cond, nxt) => new { Rela = rela, Trigger = trig, Condition = cond, Next = nxt }).ToList(); var subList = activitiesSubList .GroupBy(a => a.ParentId) .Select(a => { var currArg = a.ToList(); return new { Key = a.Key, SubList = currArg.OrderBy(b=>b.SortNo) .Select(b => { var actModel = b.Act.Adapt(); actModel.SortNo = b.SortNo; actModel.statusSkuBase = b.Sku.Adapt(); if(triggerList.Any(e=>e.Rela.SERVICE_ACTIVITIES_ID == b.Act.PK_ID)) { actModel.StatusTriggerList = triggerList.Where(e=> e.Rela.SERVICE_ACTIVITIES_ID == b.Act.PK_ID) .GroupBy(c => c.Trigger.PK_ID) .Select(c => { var currTriggerList = c.ToList(); var triggerDto = currTriggerList.FirstOrDefault().Trigger.Adapt(); triggerDto.ConditionList = currTriggerList.GroupBy(d => d.Condition) .Select(d => { var currCondList = d.ToList(); var condDto = currCondList.FirstOrDefault().Condition.Adapt(); if (currCondList.Any(e => e.Next != null)) condDto.NextActList = currCondList.Select(e => e.Next.Adapt()).ToList(); return condDto; }).ToList(); return triggerDto; }).ToList(); } return actModel; }).ToList() }; }); showModel.StatusSkuList.GroupJoin(subList, l => l.PKId, r => r.Key, (l, r) => { var currArg = r.ToList(); if (currArg.Count == 0) return l; l.SubList = currArg.FirstOrDefault().SubList.ToList(); return l; }).ToList(); } return showModel; } #endregion /// /// 通过服务活动主键获取所有相关服务流程列表 /// /// 服务活动主键数组 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/GetServiceWorkFlowListByActivities")] public async Task GetServiceWorkFlowListByActivities([FromBody]string[] activitiesArgs) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { /* 1、通过服务活动ID获取所有关联的服务流程详情列表 2、轮询服务流程列表,组织详细的服务流程列表 */ var activitiesList = _serviceWorkFlowActivitiesRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, wf) => rela.SERVICE_WORKFLOW_ID == wf.PK_ID && rela.WF_VERSION == wf.RELEASE_VERSION) .Where((rela,wf) => activitiesArgs.Contains(rela.SERVICE_ACTIVITIES_ID) && !wf.IsDeleted && wf.IS_ENABLE == 1) .Select((rela, wf) => wf).Distinct().ToList(); var subActList = _serviceWorkFlowActivitiesSubRelationRepository.AsQueryable().Filter(null, true) .LeftJoin((rela, wf) => rela.SERVICE_WORKFLOW_ID == wf.PK_ID && rela.WF_VERSION == wf.RELEASE_VERSION) .Where((rela, wf) => activitiesArgs.Contains(rela.SUB_SERVICE_ACTIVITIES_ID) && !wf.IsDeleted && wf.IS_ENABLE == 1) .Select((rela, wf) => wf).Distinct().ToList(); if(subActList.Count > 0) { activitiesList.AddRange(subActList); //去重 activitiesList = activitiesList.Distinct().ToList(); } if(activitiesList.Count == 0) { _logger.LogInformation($"{JSON.Serialize(activitiesArgs)} 未检索到有效服务流程"); throw Oops.Oh("未检索到有效服务流程", typeof(InvalidOperationException)); } var wfArg = activitiesList.Select(a => a.PK_ID).ToArray(); var mergeList = _serviceWorkFlowBaseRepository.AsQueryable().Filter(null, true) .LeftJoin((wf, rela) => wf.PK_ID == rela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .LeftJoin((wf,rela, act) => rela.SERVICE_ACTIVITIES_ID == act.PK_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .LeftJoin((wf,rela, act, sku) => act.STATUS_SKU_ID == sku.PK_ID) .Where((wf) => wfArg.Contains(wf.PK_ID)) .Select((wf,rela, act, sku) => new { WF = wf, Act = act, Sku = sku, SortNo = rela.SORT_NO, IsSub = rela.IS_CONTAINS_SUB, ValType = rela.VAL_TYPE }) .ToList(); var mergeSubList = _serviceWorkFlowBaseRepository.AsQueryable().Filter(null, true) .LeftJoin((wf, rela) => wf.PK_ID == rela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .LeftJoin((wf, rela, act) => rela.SUB_SERVICE_ACTIVITIES_ID == act.PK_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .LeftJoin((wf, rela, act, sku) => act.STATUS_SKU_ID == sku.PK_ID) .Where((wf) => wfArg.Contains(wf.PK_ID)) .Select((wf,rela, act, sku) => new { WF = wf, Act = act, Sku = sku, SortNo = rela.SORT_NO, ParentId = rela.SERVICE_ACTIVITIES_ID, ValType = rela.VAL_TYPE }) .ToList(); var prjectList = _serviceWorkFlowBaseRepository.AsQueryable().Filter(null, true) .LeftJoin((wf, rela) => wf.PK_ID == rela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .LeftJoin((wf,rela, prj) => rela.SERVICE_PROJECT_ID == prj.PK_ID) .Where((wf) => wfArg.Contains(wf.PK_ID)) .Select((wf,rela, prj) => new{ WF = wf, Rela = rela,Prj = prj }).ToList(); var list = mergeList.GroupBy(a => a.WF.PK_ID) .Select(a => { var model = a.FirstOrDefault().WF; var showModel = model.Adapt(); showModel.StatusSkuList = a.ToList().OrderBy(a => a.SortNo) .Select(a => { var actModel = a.Act.Adapt(); actModel.SortNo = a.SortNo; actModel.IsContainsSub = a.IsSub; actModel.ValType = a.ValType; actModel.statusSkuBase = a.Sku.Adapt(); if(a.IsSub == 1) { actModel.SubList = mergeSubList.Where( b => b.WF.PK_ID == a.WF.PK_ID && b.ParentId == a.Act.PK_ID) .OrderBy(b => b.SortNo) .Select(b => { var actModel = b.Act.Adapt(); actModel.SortNo = b.SortNo; actModel.statusSkuBase = b.Sku.Adapt(); return actModel; }).ToList(); } return actModel; }).ToList(); return showModel; }).ToList(); list = list.GroupJoin(prjectList, l => l.PKId, r => r.WF.PK_ID, (l, r) => { var currList = r.ToList(); l.ServiceProject = currList.FirstOrDefault().Prj.Adapt(); return l; }).ToList(); result.succ = true; result.ext = list; } catch (Exception ex) { result.succ = false; result.msg = $"保存服务流程活动异常,原因:{ex.Message}"; } return result; } #region 保存并启用 /// /// 保存并启用 /// /// 服务流程详情 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/SaveAndEnable")] public async Task SaveAndEnable(ServiceWorkFlowBaseDto info) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var id = await InnerSave(info, true); result.succ = true; result.msg = "执行成功"; result.ext = id; } catch (Exception ex) { result.succ = false; result.msg = $"保存并启用状态异常,原因:{ex.Message}"; } return result; } #endregion #region 处理服务流程内部方法 /// /// 处理服务流程内部方法 /// /// 服务流程详情 /// 操作类型 /// 返回回执 private async Task InnerExcuteServiceWF(ServiceWorkFlowBaseInfo model, OperateTypeEnum opTypeEnum) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); result.bno = model?.SERVICE_WORKFLOW_NAME; try { if (model == null) throw Oops.Oh($"服务流程获取失败,服务流程信息不存在或已作废", typeof(InvalidOperationException)); _logger.LogInformation($"更新服务流程前,获取原始记录 JSON={JSON.Serialize(model)}"); model.UpdatedTime = DateTime.Now; model.UpdatedUserId = UserManager.UserId; model.UpdatedUserName = UserManager.Name; if (opTypeEnum == OperateTypeEnum.SetEnable) { if (string.IsNullOrWhiteSpace(model.SERVICE_WORKFLOW_CODE) || string.IsNullOrWhiteSpace(model.SERVICE_WORKFLOW_NAME)) { throw Oops.Oh($"服务流程代码或名称不能为空", typeof(InvalidOperationException)); } model.IS_ENABLE = 1; await _serviceWorkFlowBaseRepository.AsUpdateable(model).UpdateColumns(it => new { it.IS_ENABLE, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName }).ExecuteCommandAsync(); } else if (opTypeEnum == OperateTypeEnum.SetUnEnable) { ValidateServiceWorkFlow(model, opTypeEnum); model.IS_ENABLE = 0; await _serviceWorkFlowBaseRepository.AsUpdateable(model).UpdateColumns(it => new { it.IS_ENABLE, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName }).ExecuteCommandAsync(); } else if (opTypeEnum == OperateTypeEnum.Delete) { ValidateServiceWorkFlow(model, opTypeEnum); model.IsDeleted = true; await _serviceWorkFlowBaseRepository.AsUpdateable(model).UpdateColumns(it => new { it.IsDeleted, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName }).ExecuteCommandAsync(); } result.succ = true; result.msg = "执行成功"; } catch (Exception ex) { result.succ = false; result.msg = $"执行启用异常,原因:{ex.Message}"; } return result; } #endregion /// /// 启用 /// /// 服务流程主键数组 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/SetEnable")] public async Task SetEnable([FromBody]string[] pkIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (pkIds.Length == 0) { throw Oops.Oh($"服务流程主键数组不能为空", typeof(InvalidOperationException)); } var list = _serviceWorkFlowBaseRepository.AsQueryable() .Where(a => pkIds.Contains(a.PK_ID)).ToList(); if (list.Count == 0) throw Oops.Oh($"服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); if (list.Count != pkIds.Length) throw Oops.Oh($"部分服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); List rltList = new List(); list.ForEach(pr => { rltList.Add(InnerExcuteServiceWF(pr, OperateTypeEnum.SetEnable).GetAwaiter().GetResult()); }); result.succ = true; result.msg = rltList.FirstOrDefault().msg; result.ext = rltList; var succ = rltList.Count(x => x.succ); var fail = rltList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } } catch (Exception ex) { result.succ = false; result.msg = $"启用服务项目异常,原因:{ex.Message}"; } return result; } /// /// 取消启用 /// /// 服务流程主键数组 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/SetUnEnable")] public async Task SetUnEnable([FromBody]string[] pkIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (pkIds.Length == 0) { throw Oops.Oh($"服务流程主键数组不能为空", typeof(InvalidOperationException)); } var list = _serviceWorkFlowBaseRepository.AsQueryable() .Where(a => pkIds.Contains(a.PK_ID)).ToList(); if (list.Count == 0) throw Oops.Oh($"服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); if (list.Count != pkIds.Length) throw Oops.Oh($"部分服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); List rltList = new List(); list.ForEach(pr => { rltList.Add(InnerExcuteServiceWF(pr, OperateTypeEnum.SetUnEnable).GetAwaiter().GetResult()); }); result.succ = true; result.msg = rltList.FirstOrDefault().msg; result.ext = rltList; var succ = rltList.Count(x => x.succ); var fail = rltList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } } catch (Exception ex) { result.succ = false; result.msg = $"启用服务项目异常,原因:{ex.Message}"; } return result; } /// /// 删除 /// /// 服务流程主键 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/Delete")] public async Task Delete([FromBody]string[] pkIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (pkIds.Length == 0) { throw Oops.Oh($"服务流程主键数组不能为空", typeof(InvalidOperationException)); } var list = _serviceWorkFlowBaseRepository.AsQueryable() .Where(a => pkIds.Contains(a.PK_ID)).ToList(); if (list.Count == 0) throw Oops.Oh($"服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); if (list.Count != pkIds.Length) throw Oops.Oh($"部分服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); List rltList = new List(); list.ForEach(pr => { rltList.Add(InnerExcuteServiceWF(pr, OperateTypeEnum.Delete).GetAwaiter().GetResult()); }); result.succ = true; result.msg = rltList.FirstOrDefault().msg; result.ext = rltList; var succ = rltList.Count(x => x.succ); var fail = rltList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } } catch (Exception ex) { result.succ = false; result.msg = $"启用服务项目异常,原因:{ex.Message}"; } return result; } /// /// 复制 /// /// 服务流程主键 /// 返回回执 [HttpGet("/ServiceWorkFlowBase/Copy")] public async Task Copy([FromQuery] string pkId) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { /* 复制整票服务流程详情(服务项目和服务流程活动) */ var model = InnerGetInfo(pkId); result.succ = true; result.msg = "执行成功"; } catch (Exception ex) { result.succ = false; result.msg = $"执行启用异常,原因:{ex.Message}"; } return result; } /// /// 获取服务流程详情 /// /// 服务流程主键 /// 返回回执 [HttpGet("/ServiceWorkFlowBase/GetInfo")] public async Task GetInfo([FromQuery]string pkId) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { result.succ = true; result.ext = InnerGetShowInfo(pkId); } catch (Exception ex) { result.succ = false; result.msg = $"获取服务流程详情异常,原因:{ex.Message}"; } return result; } /// /// 检索服务流程列表 /// /// 检索值 /// 最大返回行数(默认15) /// 返回回执 [HttpGet("/ServiceWorkFlowBase/QueryList")] public async Task QueryList([FromQuery]string queryItem, [FromQuery] int topNum = 15) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var list = await _serviceWorkFlowBaseRepository.AsQueryable().Where(a => a.IS_ENABLE == 1 && !a.IsDeleted && (a.SERVICE_WORKFLOW_CODE.Contains(queryItem) || a.SERVICE_WORKFLOW_NAME.Contains(queryItem))) .Take(topNum).ToListAsync(); result.succ = true; result.ext = list.Adapt>(); } catch (Exception ex) { result.succ = false; result.msg = $"检索状态列表异常,原因:{ex.Message}"; } return result; } /// /// 服务流程台账查询 /// /// 服务流程台账查询请求 /// 返回结果 [HttpPost("/ServiceWorkFlowBase/GetPage")] public async Task> GetPageAsync([FromBody]QueryServiceWorkFlowBaseDto QuerySearch) { //制单日期 DateTime createBegin = DateTime.MinValue; DateTime createEnd = DateTime.MinValue; //更新日期 DateTime updateBegin = DateTime.MinValue; DateTime updateEnd = DateTime.MinValue; //制单日期 if (!string.IsNullOrWhiteSpace(QuerySearch.CreateBegin)) { if (!DateTime.TryParse(QuerySearch.CreateBegin, out createBegin)) throw Oops.Oh($"创建起始日期格式错误,{QuerySearch.CreateBegin}"); } if (!string.IsNullOrWhiteSpace(QuerySearch.CreateEnd)) { if (!DateTime.TryParse(QuerySearch.CreateEnd, out createEnd)) throw Oops.Oh($"创建结束日期格式错误,{QuerySearch.CreateEnd}"); createEnd = createEnd.AddDays(1); } //更新日期 if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateBegin)) { if (!DateTime.TryParse(QuerySearch.UpdateBegin, out updateBegin)) throw Oops.Oh($"更新起始日期格式错误,{QuerySearch.UpdateBegin}"); } if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateEnd)) { if (!DateTime.TryParse(QuerySearch.UpdateEnd, out updateEnd)) throw Oops.Oh($"更新结束日期格式错误,{QuerySearch.UpdateEnd}"); updateEnd = updateEnd.AddDays(1); } string entityOrderCol = "CreatedTime"; //这里因为返回给前端的台账数据是DTO,所以这里排序时候需要转换成Entity对应的字段 if (!string.IsNullOrWhiteSpace(QuerySearch.SortField)) entityOrderCol = MapsterExtHelper.GetAdaptProperty(QuerySearch.SortField); var entities = await _serviceWorkFlowBaseRepository.AsQueryable() .WhereIF(createBegin != DateTime.MinValue, t => t.CreatedTime >= createBegin) .WhereIF(createEnd != DateTime.MinValue, t => t.CreatedTime < createEnd) .WhereIF(updateBegin != DateTime.MinValue, t => t.UpdatedTime.HasValue && t.UpdatedTime.Value >= updateBegin) .WhereIF(updateEnd != DateTime.MinValue, t => t.UpdatedTime.HasValue && t.UpdatedTime.Value < updateEnd) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.IsEnable) && QuerySearch.IsEnable == "1", t => t.IS_ENABLE == 1) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.IsEnable) && QuerySearch.IsEnable == "2", t => t.IS_ENABLE == 0) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.ServiceWorkflowName), t => t.SERVICE_WORKFLOW_NAME.Contains(QuerySearch.ServiceWorkflowName) || t.SERVICE_WORKFLOW_CODE.Contains(QuerySearch.ServiceWorkflowName)) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.ServiceWorkflowNote), t => t.SERVICE_WORKFLOW_NOTE.Contains(QuerySearch.ServiceWorkflowNote)) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.CreateUser), t => t.CreatedUserName.Contains(QuerySearch.CreateUser)) .WhereIF(!string.IsNullOrWhiteSpace(QuerySearch.UpdateUser), t => t.UpdatedUserName.Contains(QuerySearch.UpdateUser)) .OrderBy(entityOrderCol + (QuerySearch.descSort ? " asc " : " desc ")) .ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize); return entities.Adapt>(); } /// /// 发布服务流程 /// /// 服务流程主键数组 /// 返回回执 [HttpPost("/ServiceWorkFlowBase/PublishRelease")] public async Task PublishRelease([FromBody]string[] pkIds) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { if (pkIds.Length == 0) { throw Oops.Oh($"服务流程主键数组不能为空", typeof(InvalidOperationException)); } var list = _serviceWorkFlowBaseRepository.AsQueryable() .Where(a => pkIds.Contains(a.PK_ID)).ToList(); if (list.Count == 0) throw Oops.Oh($"服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); if (list.Count != pkIds.Length) throw Oops.Oh($"部分服务流程获取失败,请服务流程信息是否存在", typeof(InvalidOperationException)); List rltList = new List(); list.ForEach(pr => { rltList.Add(InnerPublishReleasServiceWF(pr).GetAwaiter().GetResult()); }); //写入缓存 await SetServiceProjectCacheInfo(list.FirstOrDefault().TenantId.ToString()); result.succ = true; result.msg = rltList.FirstOrDefault().msg; result.ext = rltList; var succ = rltList.Count(x => x.succ); var fail = rltList.Count(x => !x.succ); if (succ > 0) { result.batchTotal = succ.ToString(); } else { result.batchTotal = "- "; } if (fail > 0) { result.batchTotal += "/" + fail.ToString(); } else { result.batchTotal += " -"; } } catch (Exception ex) { result.succ = false; result.msg = $"执行失败,原因:{ex.Message}"; } return result; } #region 发布服务流程内部方法 /// /// 发布服务流程内部方法 /// /// 服务流程详情 /// 返回回执 [SqlSugarUnitOfWork] private async Task InnerPublishReleasServiceWF(ServiceWorkFlowBaseInfo model) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); result.bno = model?.SERVICE_WORKFLOW_NAME; try { if (model == null) throw Oops.Oh($"服务流程获取失败,服务流程信息不存在或已作废", typeof(InvalidOperationException)); if(string.IsNullOrWhiteSpace(model.DEVELOP_VERSION)) throw Oops.Oh($"服务流程未修改,不需要重复发布", typeof(InvalidOperationException)); var lastReleaseInfo = _serviceWorkFlowReleaseInfoRepository.AsQueryable() .First(a => a.SERVICE_WF_ID == model.PK_ID && a.IS_DEL == 0); int currNum = lastReleaseInfo == null ? 1 : lastReleaseInfo.TOTAL_NUM; ServiceWorkFlowReleaseInfo releaseInfo = new ServiceWorkFlowReleaseInfo { PK_ID = IDGen.NextID().ToString(), SERVICE_WF_ID = model.PK_ID, PUBLISH_DATE = DateTime.Now, IS_DEL = 0, PUBLISH_ER = UserManager.UserId, PUBLISH_NAME = UserManager.Name, TOTAL_NUM = currNum + 1, }; if (lastReleaseInfo != null) { releaseInfo.LAST_PK_ID = lastReleaseInfo.PK_ID; lastReleaseInfo.IS_DEL = 1; _serviceWorkFlowReleaseInfoRepository.AsUpdateable(lastReleaseInfo).UpdateColumns(it => new { it.IS_DEL }).ExecuteCommand(); } //写入发布表 _serviceWorkFlowReleaseInfoRepository.Insert(releaseInfo); releaseInfo = _serviceWorkFlowReleaseInfoRepository.AsQueryable() .First(a => a.SERVICE_WF_ID == model.PK_ID && a.IS_DEL == 0); string releaseVersion = releaseInfo.RELEASE_VERSION; var wfBaseInfo = InnerGetShowInfo(model.PK_ID); string currVersion = wfBaseInfo.DevelopVersion; model.RELEASE_VERSION = releaseVersion; model.UpdatedTime = DateTime.Now; model.UpdatedUserId = UserManager.UserId; model.UpdatedUserName = UserManager.Name; model.PUBLISH_DATE = releaseInfo.PUBLISH_DATE; model.PUBLISH_ER = releaseInfo.PUBLISH_ER; model.PUBLISH_NAME = releaseInfo.PUBLISH_NAME; await _serviceWorkFlowBaseRepository.AsUpdateable(model).UpdateColumns(it => new { it.RELEASE_VERSION, it.UpdatedTime, it.UpdatedUserId, it.UpdatedUserName, it.PUBLISH_ER, it.PUBLISH_NAME, it.PUBLISH_DATE }).ExecuteCommandAsync(); //重新写入关系 //服务流程与服务项目关系 if (wfBaseInfo.ServiceProject != null && !string.IsNullOrWhiteSpace(wfBaseInfo.ServiceProject.PKId)) { var wfRelationProject = new ServiceWorkFlowProjectRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = wfBaseInfo.PKId, SERVICE_PROJECT_ID = wfBaseInfo.ServiceProject.PKId, WF_VERSION = releaseVersion }; //插入关系 await _serviceWorkFlowProjectRelationRepository.InsertAsync(wfRelationProject); } //服务流程与服务活动关系 if (wfBaseInfo.StatusSkuList != null && wfBaseInfo.StatusSkuList.Count > 0) { wfBaseInfo.StatusSkuList.ForEach(async sku => { var wfRelationActivities = new ServiceWorkFlowActivitiesRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = wfBaseInfo.PKId, SERVICE_ACTIVITIES_ID = sku.PKId, SORT_NO = sku.SortNo, IS_CONTAINS_SUB = sku.IsContainsSub, VAL_TYPE = !string.IsNullOrWhiteSpace(sku.ValType) ? sku.ValType : StatusSKUValTypeEnum.DATETIME.ToString(), WF_VERSION = releaseVersion }; await _serviceWorkFlowActivitiesRelationRepository.InsertAsync(wfRelationActivities); //处理子状态 if (sku.IsContainsSub == 1) { sku.SubList.ForEach(async sub => { var wfRelationActivitiesSub = new ServiceWorkFlowActivitiesSubRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = wfBaseInfo.PKId, SERVICE_ACTIVITIES_ID = sku.PKId, SUB_SERVICE_ACTIVITIES_ID = sub.PKId, SORT_NO = sub.SortNo, VAL_TYPE = !string.IsNullOrWhiteSpace(sku.ValType) ? sku.ValType : StatusSKUValTypeEnum.DATETIME.ToString(), WF_VERSION = releaseVersion }; await _serviceWorkFlowActivitiesSubRelationRepository.InsertAsync(wfRelationActivitiesSub); sub.StatusTriggerList.ForEach(async trg => { var triggerRela = new ServiceWorkFlowActivitiesTriggerRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = wfBaseInfo.PKId, SERVICE_ACTIVITIES_ID = sub.PKId, STATUS_TRIGGER_ID = trg.PKId, WF_VERSION = releaseVersion }; await _serviceWorkFlowActivitiesTriggerRelationRepository.InsertAsync(triggerRela); }); }); } if (sku.StatusTriggerList != null && sku.StatusTriggerList.Count > 0) { sku.StatusTriggerList.ForEach(async trg => { var triggerRela = new ServiceWorkFlowActivitiesTriggerRelation { PK_ID = IDGen.NextID().ToString(), SERVICE_WORKFLOW_ID = wfBaseInfo.PKId, SERVICE_ACTIVITIES_ID = sku.PKId, STATUS_TRIGGER_ID = trg.PKId, WF_VERSION = releaseVersion }; await _serviceWorkFlowActivitiesTriggerRelationRepository.InsertAsync(triggerRela); }); } }); } //批量删除服务流程与服务项目关系(物理删除) _serviceWorkFlowProjectRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == model.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程与服务活动关系(物理删除) _serviceWorkFlowActivitiesRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == model.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程活动与子活动的关系(物理删除) _serviceWorkFlowActivitiesSubRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == model.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); //批量删除服务流程与服务流程活动触发器关系(物理删除) _serviceWorkFlowActivitiesTriggerRelationRepository.EntityContext.Deleteable() .EnableQueryFilter().Where(a => a.SERVICE_WORKFLOW_ID == model.PK_ID && a.WF_VERSION == currVersion).ExecuteCommand(); var updateModel = _serviceWorkFlowBaseRepository.FirstOrDefault(a => a.PK_ID == model.PK_ID); updateModel.DEVELOP_VERSION = null; await _serviceWorkFlowBaseRepository.AsUpdateable(updateModel).UpdateColumns(it => new { it.DEVELOP_VERSION, }).ExecuteCommandAsync(); result.succ = true; result.msg = "发布成功"; } catch (Exception ex) { result.succ = false; result.msg = $"执行失败,原因:{ex.Message}"; } return result; } #endregion #region 获取展示服务流程时间轴列表 /// /// 获取展示服务流程时间轴列表 /// /// 服务流程主键 /// 返回回执 [HttpGet("/ServiceWorkFlowBase/GetShowTimeLine")] public async Task GetShowTimeLine([FromQuery] string pkId) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var showModel = new ServiceWorkFlowRunDto(); /* 根据已保存的服务流程生成测试数据 */ var model = InnerGetShowInfo(pkId); if(model != null) { showModel.PKId = pkId; if(model.ServiceProject != null) { showModel.ServiceProjectName = model.ServiceProject.ServiceProjectName; showModel.ServiceProjectCode = model.ServiceProject.ServiceProjectCode; } if (model.StatusSkuList != null && model.StatusSkuList.Count > 0) { int endSortNo = model.StatusSkuList.Max(a => a.SortNo); DateTime startDate = DateTime.Now.AddDays(-(endSortNo + 1)); showModel.ActivitiesList = model.StatusSkuList.Select(a => { var runModel = new ServiceWorkFlowActivitiesRunDto { PKId = Guid.NewGuid().ToString(), ActDate = startDate.AddDays(a.SortNo), ActId = a.PKId, ExecSortNo = a.SortNo, ActVal = string.Empty, IsStart = (a.SortNo == 1) ? 1 : 0, IsEnd = (a.SortNo == endSortNo) ? 1 : 0, IsYield = 1, RunId = Guid.NewGuid().ToString(), ShowName = a.ShowName, SourceType = "AUTO", StatusSKUCode = a.statusSkuBase.StatusSKUCode, StatusSKUId = a.StatusSKUId }; if(a.IsContainsSub == 1) { int endSubSortNo = a.SubList.Max(a => a.SortNo); DateTime startSubDate = DateTime.Now.AddDays(-(endSubSortNo + 1)); runModel.SubList = a.SubList.Select(b => { var subModel = new ServiceWorkFlowActivitiesRunSubDto { PKId = Guid.NewGuid().ToString(), ActDate = startSubDate.AddDays(b.SortNo), ActId = b.PKId, ExecSortNo = b.SortNo, ActVal = string.Empty, IsStart = (b.SortNo == 1) ? 1 : 0, IsEnd = (b.SortNo == endSortNo) ? 1 : 0, IsYield = 1, RunId = Guid.NewGuid().ToString(), ShowName = b.ShowName, SourceType = "AUTO", StatusSKUCode = b.statusSkuBase.StatusSKUCode, StatusSKUId = b.StatusSKUId }; return subModel; }).ToList(); } return runModel; }).ToList(); } } result.succ = true; result.ext = showModel; } catch (Exception ex) { result.succ = false; result.msg = $"检索状态列表异常,原因:{ex.Message}"; } return result; } #endregion #region 检索服务流程活动列表 /// /// 检索服务流程活动列表 /// /// 检索值 /// 最大返回行数(默认15) /// 返回回执 [HttpGet("/ServiceWorkFlowBase/QueryActivitiesList")] public async Task QueryActivitiesList([FromQuery]string queryItem, [FromQuery] int topNum = 15) { TaskManageOrderResultDto result = new TaskManageOrderResultDto(); try { var list = await _serviceWorkFlowActivitiesInfoRepository.AsQueryable() .LeftJoin((act,sku)=>act.STATUS_SKU_ID == sku.PK_ID) .Where((act,sku) => !act.IsDeleted && (string.IsNullOrWhiteSpace(queryItem) || act.SHOW_NAME.Contains(queryItem))) .Take(topNum).Select((act,sku)=> new {Act = act,SKU = sku}).ToListAsync(); List resultList = new List(); if(list.Count > 0) { resultList = list.Select(a => { var info = a.Act.Adapt(); info.statusSkuBase = a.SKU.Adapt(); return info; }).ToList(); } result.succ = true; result.ext = resultList; } catch (Exception ex) { result.succ = false; result.msg = $"检索服务流程活动列表异常,原因:{ex.Message}"; } return result; } #endregion #region 检索可用的服务项目列表 /// /// 检索可用的服务项目列表 /// /// 租户ID /// 是否不从缓存取值 /// 返回回执 [HttpGet("/ServiceWorkFlowBase/GetEnableProjectList")] public async Task> GetEnableProjectList([FromQuery]string tenantId, [FromQuery] bool isAvoidCache = false) { List projectList = _cache.Get>($"{CONST_CACHE_ENABLE_PROJECT}_{tenantId}"); if (isAvoidCache || projectList == null || projectList.Count == 0) { var statusList = ReloadServiceProjectCacheInfo(tenantId); projectList = statusList.Select(a => new ServiceProjectBaseDto { PKId = a.ProjectPKId, ServiceProjectCode = a.ProjectCode, ServiceProjectName = a.ProjectName, SortNo = a.SortNo }).OrderBy(a => a.SortNo).ToList(); await _cache.SetAsync($"{CONST_CACHE_ENABLE_PROJECT}_{tenantId}", projectList, TimeSpan.FromHours(8)); } return projectList; } #endregion #region 检索可用的服务项目和状态列表 /// /// 检索可用的服务项目和状态列表 /// /// 租户ID /// 是否不从缓存取值 /// 返回回执 [HttpGet("/ServiceWorkFlowBase/GetEnableProjectWithStatusList")] public async Task> GetEnableProjectWithStatusList([FromQuery] string tenantId, [FromQuery] bool isAvoidCache = false) { if(string.IsNullOrWhiteSpace(tenantId)) { throw Oops.Oh($"租户ID不能为空", typeof(InvalidOperationException)); } List statusList = _cache.Get>($"{CONST_CACHE_ENABLE_PROJECT_STATUS}_{tenantId}"); if (isAvoidCache || statusList == null || statusList.Count == 0) { statusList = ReloadServiceProjectCacheInfo(tenantId); await _cache.SetAsync($"{CONST_CACHE_ENABLE_PROJECT_STATUS}_{tenantId}", statusList, TimeSpan.FromHours(8)); } return statusList; } #endregion #region 缓存租户下可用的服务流程详情 /// /// 缓存租户下可用的服务流程详情 /// /// 租户ID /// private async Task SetServiceProjectCacheInfo(string tenantId) { try { var statusList = ReloadServiceProjectCacheInfo(tenantId); await _cache.SetAsync($"{CONST_CACHE_ENABLE_PROJECT_STATUS}_{tenantId}", statusList, TimeSpan.FromHours(8)); _logger.LogInformation($"租户下可用的服务流程详情并写入缓存完成"); var projectList = statusList.Select(a => new ServiceProjectBaseDto { PKId = a.ProjectPKId, ServiceProjectCode = a.ProjectCode, ServiceProjectName = a.ProjectName, SortNo = a.SortNo }).OrderBy(a => a.SortNo).ToList(); await _cache.SetAsync($"{CONST_CACHE_ENABLE_PROJECT}_{tenantId}", projectList, TimeSpan.FromHours(8)); _logger.LogInformation($"租户下可用的服务写入缓存完成"); } catch(Exception ex) { _logger.LogInformation($"租户下可用的服务流程详情并写入缓存异常,原因:{ex.Message}"); throw Oops.Oh($"租户下可用的服务流程详情并写入缓存异常,原因:{ex.Message}", typeof(InvalidOperationException)); } } #endregion #region 提取租户下可用的服务流程详情 /// /// 提取租户下可用的服务流程详情 /// /// 租户ID /// 返回列表 private List ReloadServiceProjectCacheInfo(string tenantId) { var statusSKUList = _statusSkuBaseInfoRepository.AsQueryable().Filter(null, true) .Where(a => !a.IsDeleted && a.IS_ENABLE == 1 && a.TenantId == long.Parse(tenantId)).ToList(); /* 读取当前租户可用的已发布的流程详情,并写入缓存。 * 1、流程关联服务项目。 2、流程关联流程活动。 3、流程关联流程活动的子活动。 4、活动关联状态。 5、活动关联触发器。 6、写入缓存。 */ var list = _serviceWorkFlowBaseRepository.AsQueryable().Filter(null, true) .InnerJoin((wf, rela) => wf.PK_ID == rela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .InnerJoin((wf, rela, prj) => rela.SERVICE_PROJECT_ID == prj.PK_ID) .InnerJoin((wf, rela, prj, arela) => wf.PK_ID == arela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == arela.WF_VERSION) .InnerJoin((wf, rela, prj, arela, act) => arela.SERVICE_ACTIVITIES_ID == act.PK_ID) .LeftJoin((wf, rela, prj, arela, act, trgrela) => wf.PK_ID == trgrela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == trgrela.WF_VERSION && act.PK_ID == trgrela.SERVICE_ACTIVITIES_ID) .LeftJoin((wf, rela, prj, arela, act, trgrela, trg) => trgrela.STATUS_TRIGGER_ID == trg.PK_ID) .Where((wf, rela, prj, arela, act) => !string.IsNullOrWhiteSpace(wf.RELEASE_VERSION) && wf.BELONG_TENANT_ID == long.Parse(tenantId) && wf.IS_ENABLE == 1 && !wf.IsDeleted) .Select((wf, rela, prj, arela, act) => new { WF = wf,Project = prj, ARela = arela, Act = act }).ToList(); List subActList = new List(); if (list.Any(a => a.ARela.IS_CONTAINS_SUB == 1)) { //如果存在子活动的,需要关联 var sublist = _serviceWorkFlowBaseRepository.AsQueryable().Filter(null, true) .InnerJoin((wf, rela) => wf.PK_ID == rela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == rela.WF_VERSION) .InnerJoin((wf, rela, act) => rela.SUB_SERVICE_ACTIVITIES_ID == act.PK_ID) .LeftJoin((wf, rela, act, trgrela) => wf.PK_ID == trgrela.SERVICE_WORKFLOW_ID && wf.RELEASE_VERSION == trgrela.WF_VERSION && act.PK_ID == trgrela.SERVICE_ACTIVITIES_ID) .LeftJoin((wf, rela, act, trgrela, trg) => trgrela.STATUS_TRIGGER_ID == trg.PK_ID) .Where((wf, rela, act, trgrela, trg) => !string.IsNullOrWhiteSpace(wf.RELEASE_VERSION) && wf.BELONG_TENANT_ID == long.Parse(tenantId) && wf.IS_ENABLE == 1 && !wf.IsDeleted) .Select((wf, rela, act) => new { WF = wf, Rela = rela, Act = act }).ToList(); subActList = sublist.GroupBy(a=>a.Rela.SERVICE_ACTIVITIES_ID) .Select(a => { var currList = a.ToList(); var act = currList.FirstOrDefault().Act; var rela = currList.FirstOrDefault().Rela; var wf = currList.FirstOrDefault().WF; var dto = new ServiceProjectStatusDto { ActPKId = rela.SERVICE_ACTIVITIES_ID, WFPKId = wf.PK_ID, HasChild = false, SubStatusList = new List() }; dto.SubStatusList = currList.Select(e => { var skuInfo = statusSKUList.FirstOrDefault(t => t.PK_ID == e.Act.STATUS_SKU_ID); var itemDto = new ServiceProjectStatusDto { SkuPKId = e.Act.STATUS_SKU_ID, ActPKId = e.Act.PK_ID, ShowName = e.Act.SHOW_NAME, ActSortNo = e.Rela.SORT_NO, WFPKId = wf.PK_ID, StatusSKUCode = skuInfo.STATUS_SKU_CODE, StatusSKUName = skuInfo.STATUS_SKU_NAME, BackgroundColor = skuInfo.BACKGROUND_COLOR, SortNo = skuInfo.SORT_NO, HasChild = false, ParentActPKId = e.Rela.SERVICE_ACTIVITIES_ID, SubStatusList = new List(), TriggerList = new List() }; return itemDto; }).ToList(); return dto; }).ToList(); } var statusList = list.GroupBy(a => a.WF.PK_ID) .Select(a => { var currList = a.ToList(); var wf = currList.FirstOrDefault().WF; var project = currList.FirstOrDefault().Project; ServiceProjectWithStatusDto baseDto = new ServiceProjectWithStatusDto { ProjectPKId = project.PK_ID, ProjectCode = project.SERVICE_PROJECT_CODE, ProjectName = project.SERVICE_PROJECT_NAME, SortNo = project.SORT_NO, WFPKId = wf.PK_ID, WFCode = wf.SERVICE_WORKFLOW_CODE, ReleaseVersion = wf.RELEASE_VERSION, ReleaseDate = wf.PUBLISH_DATE.Value, StatusList = new List() }; baseDto.StatusList = currList .GroupBy(b => b.Act.PK_ID) .Select(c => { var currActList = c.ToList(); var act = currActList.FirstOrDefault().Act; var ARela = currActList.FirstOrDefault().ARela; var skuInfo = statusSKUList.FirstOrDefault(e => e.PK_ID == act.STATUS_SKU_ID); var dto = new ServiceProjectStatusDto { SkuPKId = act.STATUS_SKU_ID, ActPKId = act.PK_ID, ShowName = act.SHOW_NAME, ActSortNo = ARela.SORT_NO, WFPKId = wf.PK_ID, StatusSKUCode = skuInfo.STATUS_SKU_CODE, StatusSKUName = skuInfo.STATUS_SKU_NAME, BackgroundColor = skuInfo.BACKGROUND_COLOR, SortNo = skuInfo.SORT_NO, HasChild = ARela.IS_CONTAINS_SUB == 1 ? true : false, SubStatusList = new List(), TriggerList = new List() }; if(ARela.IS_CONTAINS_SUB == 1) { dto.SubStatusList = subActList.FirstOrDefault(e=>e.ActPKId == act.PK_ID).SubStatusList; } return dto; }).ToList(); return baseDto; }).ToList(); return statusList; } #endregion #region 获取可用的服务项目字典列表 /// /// 获取可用的服务项目字典列表 /// /// 是否重新加载缓存 /// [HttpGet("/ServiceWorkFlowBase/GetEnableProjectDictTreeList")] public async Task> GetEnableProjectDictTreeList([FromQuery] bool isAvoidCache = false) { List resultList = new List(); var list = await GetEnableProjectList(UserManager.TENANT_ID.ToString(), isAvoidCache); if(list.Count > 0) { resultList.Add(new Core.Service.DictTreeOutput { Code = "booking_service_item", Name = "订舱服务项目", Children = list.OrderBy(a => a.SortNo).Select(a => new DictTreeOutput { Code = a.ServiceProjectCode, Name = a.ServiceProjectName }).ToList() }); } return resultList; } #endregion #region 获取可用的服务状态字典列表 /// /// 获取可用的服务状态字典列表 /// /// 是否重新加载缓存 /// [HttpGet("/ServiceWorkFlowBase/GetEnableStatusDictTreeList")] public async Task> GetEnableStatusDictTreeList([FromQuery] bool isAvoidCache = false) { List resultList = new List(); var list = await GetEnableProjectWithStatusList(UserManager.TENANT_ID.ToString(), isAvoidCache); if (list.Count > 0) { resultList.Add(new Core.Service.DictTreeOutput { Code = "booking_goods_status", Name = "订舱货物状态", Children = list.OrderBy(a => a.SortNo).SelectMany(a => { var rltList = new List(); a.StatusList.ForEach(b => { rltList.Add(new DictTreeOutput { Code = b.StatusSKUCode, Name = b.StatusSKUName, Remark = b.BackgroundColor }); if (b.SubStatusList != null && b.SubStatusList.Count > 0) { rltList.AddRange(b.SubStatusList.Select(c => new DictTreeOutput { Code = c.StatusSKUCode, Name = c.StatusSKUName, Remark = c.BackgroundColor }).ToList()); } }); return rltList; }).ToList() }); } return resultList; } #endregion } }