using Furion.DependencyInjection; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RoadFlow.Utility; using Microsoft.Extensions.Localization; using Newtonsoft.Json.Linq; using Ewide.Core; using System.IO; using Microsoft.Extensions.Caching.Memory; using Furion; namespace RoadFlow.Data { public class Flow : RoadFlowRepository, IFlow, ITransient { IUserManager _userManager = App.GetService(); /// /// 查询一页数据 /// /// /// /// /// 可管理的流程ID /// /// /// /// public List GetPagerList(out int count, int size, int number, List flowIdList, string name, List types, string order, int status = -1) { int total = 0; var list = db.Queryable() .WhereIF(status != -1, a => a.Status == status) .WhereIF(status == -1, a => a.Status != 3) .WhereIF(flowIdList != null && flowIdList.Count > 0, a => flowIdList.Contains(a.Id)) //.WhereIF(flowIdList == null || flowIdList.Count == 0, a => 1 == 0) .WhereIF(!name.IsNullOrWhiteSpace(), a => a.Name.Contains(name.Trim())) .WhereIF(types != null && types.Count > 0, a => types.Contains(a.FlowType)) .Select(a => new Model.rf_flow { Id = a.Id, Name = a.Name, CreateDate = a.CreateDate, CreateUser = a.CreateUser, Status = a.Status, Note = a.Note, SystemId = a.SystemId }) .ToPageList(number, size, ref total); count = total; return list; } public List GetPagerList(out int count, int size, int number, List flowIdList, string name, string type, string order, int status = -1) { List types = new(); if (!type.IsNullOrWhiteSpace()) { types.Add(type); } return this.GetPagerList(out count, size, number, flowIdList, name, types, order, status); } /// /// 得到一个用户可管理的流程 /// /// /// public List GetManageFlowIds(string userId) { var flows = GetManageFlow(userId); List guids = new List(); foreach (var flow in flows) { guids.Add(flow.Id); } return guids; } /// /// 得到一个用户可管理的流程 /// /// /// public List GetManageFlow(string userId) { var all = GetAll(); if (all.Count == 0) { return new(); } return all.FindAll(p => p.Manager.ContainsIgnoreCase(userId)); } /// /// 得到状态显示 /// /// /// 语言包 /// public string GetStatusTitle(int status, IStringLocalizer localizer = null) { switch (status) { case 0: return localizer == null ? "设计中" : localizer["State_Designing"].Value; case 1: return localizer == null ? "已安装" : localizer["State_Installed"].Value; case 2: return localizer == null ? "已卸载" : localizer["State_Uninstalled"].Value; case 3: return localizer == null ? "已删除" : localizer["State_Deleted"].Value; default: return string.Empty; } } /// /// 保存流程 /// /// /// 语言包 /// public string Save(string json, IStringLocalizer localizer = null) { JObject jObject; try { jObject = JObject.Parse(json); } catch { return localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; } if (null == jObject) { return localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; } string flowId = jObject.Value("id"); string name = jObject.Value("name"); string type = jObject.Value("type"); string systemId = jObject.Value("systemId"); if (!flowId.IsGuid(out Guid fid)) { return localizer == null ? "流程ID错误" : localizer["Save_FlowIdError"].Value; } if (name.IsNullOrWhiteSpace()) { return localizer == null ? "流程名称为空" : localizer["Save_FlowNameEmpty"].Value; } if (!type.IsGuid(out Guid typeId)) { return localizer == null ? "流程分类错误" : localizer["Save_FlowTypeError"].Value; } Model.rf_flow flowModel = this.Get(flowId); bool isAdd = false; if (null == flowModel) { isAdd = true; flowModel = new Model.rf_flow { Id = flowId, CreateDate = DateExtensions.Now, CreateUser = _userManager.UserId, Status = 0 }; } flowModel.DesignerJSON = json; flowModel.InstanceManager = jObject.Value("instanceManager"); flowModel.Manager = jObject.Value("manager"); flowModel.Name = name; flowModel.FlowType = type; flowModel.Note = jObject.Value("note"); flowModel.SystemId = systemId.IsGuid(out Guid guid) ? systemId : new Guid().ToString(); if (isAdd) { this.Add(flowModel); } else { this.Update(flowModel); } new Log().Add("保存了流程-" + flowModel.Name, _userManager.UserId, json, LogType.流程管理); return "1"; } /// /// 查询一个流程 /// /// /// public Model.rf_flow Get(string id) { return GetOneById(id);//GetAll().Find(p => p.Id == id); } /// /// 流程另存为 /// /// 流程ID /// 新的流程名称 /// 返回guid字符串表示成功(新流程的ID),其它为错误信息 /// 语言包 public string SaveAs(string flowId, string newFlowName, IStringLocalizer localizer = null) { var flowModel = Get(flowId); if (null == flowModel) { return localizer == null ? "未找到要另存的流程!" : localizer["SaveAsSave_NotFindFlow"]; } flowModel.Id = GuidExtensions.NewGuid().ToString(); flowModel.CreateDate = DateExtensions.Now; if (flowModel.InstallDate.HasValue) { flowModel.InstallDate = flowModel.CreateDate; } flowModel.Name = newFlowName; JObject jObject = null; if (!flowModel.RunJSON.IsNullOrWhiteSpace()) { jObject = JObject.Parse(flowModel.RunJSON); } else if (!flowModel.DesignerJSON.IsNullOrWhiteSpace()) { jObject = JObject.Parse(flowModel.DesignerJSON); } if (jObject != null) { jObject["id"] = flowModel.Id.ToString(); jObject["name"] = flowModel.Name; JArray lines = jObject.Value("lines"); foreach (JObject stepJObject in jObject.Value("steps")) { string stepNewId = GuidExtensions.NewGuid().ToString(); string stepOldId = stepJObject.Value("id"); foreach (JObject lineJObject in lines) { if (lineJObject.Value("from").EqualsIgnoreCase(stepOldId)) { lineJObject["from"] = stepNewId; } if (lineJObject.Value("to").EqualsIgnoreCase(stepOldId)) { lineJObject["to"] = stepNewId; } } stepJObject["id"] = stepNewId; } foreach (JObject lineJObject1 in lines) { lineJObject1["id"] = GuidExtensions.NewGuid().ToString(); } } string json = jObject.ToString(Newtonsoft.Json.Formatting.None); if (!flowModel.RunJSON.IsNullOrWhiteSpace()) { flowModel.RunJSON = json; } if (!flowModel.DesignerJSON.IsNullOrWhiteSpace()) { flowModel.DesignerJSON = json; } Add(flowModel); return flowModel.Id.ToString(); } /// /// 安装流程 /// /// /// 日志标题 /// 语言包 /// public string Install(string json, IStringLocalizer localizer = null) { string saveMsg = Save(json, localizer); if (!"1".Equals(saveMsg)) { return saveMsg; } var flowRunModel = GetFlowRunModel(json, out string errMsg, localizer: localizer); if (null == flowRunModel) { return errMsg; } var flowModel = Get(flowRunModel.Id.ToString()); if (null == flowModel) { return localizer == null ? "未找到流程实体" : localizer["Install_NoFindFlowModel"].Value; } flowModel.InstallDate = DateExtensions.Now; flowModel.InstallUser = _userManager.UserId; flowModel.RunJSON = json; flowModel.Status = 1; this.Install(flowModel); //清除运行时缓存 ClearCache(flowModel.Id); new Log().Add("发布安装了流程-" + flowModel.Name, _userManager.UserId, json, LogType.流程管理, others: errMsg); return "1"; } /// /// 安装流程 /// /// 流程实体 /// 应用程序库实体 public int Install(Model.rf_flow flow) { //取消了事务,sqlsugra的事务没弄懂 #region 加入到应用程序库 var applibraryModel = new Applibrary().GetAll().Find(p => p.Code.EqualsIgnoreCase(flow.Id.ToString())); bool isAdd = false; if (null == applibraryModel) { isAdd = true; applibraryModel = new Model.rf_applibrary { Id = GuidExtensions.NewGuid().ToString() }; } applibraryModel.Title = flow.Name; applibraryModel.Address = "/flow/run/index?flowid=" + flow.Id.ToString(); applibraryModel.Code = flow.Id.ToString(); applibraryModel.OpenMode = 0; applibraryModel.Type = flow.FlowType; applibraryModel.Note = flow.Note; //多语言设定流程名称(这里暂时设定一样,没有区分语言) applibraryModel.Title_en = applibraryModel.Title_en.IsNullOrWhiteSpace() ? flow.Name : applibraryModel.Title_en; applibraryModel.Title_zh = applibraryModel.Title_zh.IsNullOrWhiteSpace() ? flow.Name : applibraryModel.Title_zh; if (isAdd) { new Applibrary().Add(applibraryModel); } else { new Applibrary().Update(applibraryModel); } #endregion this.Update(flow); ClearCache(); new Applibrary().ClearCache(); return 1; } /// /// 卸载或作删除标记流程 /// /// /// 日志标题 /// 状态,2卸载 3删除 /// 语言包 /// public string UnInstall(string json, int status, IStringLocalizer localizer = null) { JObject jObject; try { jObject = JObject.Parse(json); } catch { return localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; } if (null == jObject) { return localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; } string flowId = jObject.Value("id"); if (!flowId.IsGuid(out Guid flowGuid)) { return localizer == null ? "流程id错误" : localizer["Save_JsonParseError"].Value; } var flowModel = Get(flowGuid.ToString()); if (null == flowModel) { return localizer == null ? "未找到流程实体" : localizer["Install_NoFindFlowModel"].Value; } flowModel.Status = status; Update(flowModel); //清除运行时缓存 ClearCache(flowModel.Id); new Log().Add((status == 2 ? "卸载" : status == 3 ? "作删除标记" : "") + "流程-" + flowModel.Name,_userManager.UserId, json, LogType.流程管理); return "1"; } /// /// 得到流程运行时实体 /// /// 流程设置JSON /// 加载错误时的错误信息 /// 语言包 /// public Model.FlowRun GetFlowRunModel(string json, out string errMsg, IStringLocalizer localizer = null) { errMsg = string.Empty; JObject jObject = null; try { jObject = JObject.Parse(json); } catch { errMsg = localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; return null; } if (null == jObject) { errMsg = localizer == null ? "JSON解析错误" : localizer["Save_JsonParseError"].Value; return null; } string id = jObject.Value("id"); string name = jObject.Value("name"); string type = jObject.Value("type"); string systemId = jObject.Value("systemId"); string mananger = jObject.Value("manager"); string instanceManager = jObject.Value("instanceManager"); if (!id.IsGuid(out Guid flowId)) { errMsg = localizer == null ? "流程ID错误" : localizer["Save_FlowIdError"].Value; return null; } if (name.IsNullOrWhiteSpace()) { errMsg = localizer == null ? "流程名称为空" : localizer["Save_FlowNameEmpty"].Value; return null; } if (!type.IsGuid(out Guid typeId)) { errMsg = localizer == null ? "流程分类错误" : localizer["Save_FlowTypeError"].Value; return null; } if (mananger.IsNullOrWhiteSpace()) { errMsg = localizer == null ? "流程管理者为空" : localizer["Install_ManagerEmpty"].Value; return null; } if (instanceManager.IsNullOrWhiteSpace()) { errMsg = localizer == null ? "流程实例管理者为空" : localizer["Install_InstanceManagerEmpty"].Value; return null; } var flowModel = Get(id); if (null == flowModel) { errMsg = localizer == null ? "未找到该流程" : localizer["Install_NoFindFlowModel"].Value; return null; } var flowRunModel = new Model.FlowRun { Id = flowId, Name = name, Type = typeId, Manager = mananger, InstanceManager = instanceManager, FirstStepId = Guid.Empty, Note = jObject.Value("note"), SystemId = systemId.IsGuid(out Guid guid) ? guid : new Guid?(), Debug = jObject.Value("debug").IsInt(out int debug) ? debug : 0, DebugUserIds = new Organize().GetAllUsersId(jObject.Value("debugUsers")), Status = flowModel.Status, CreateDate = flowModel.CreateDate, CreateUserId = flowModel.CreateUser, InstallDate = flowModel.InstallDate, InstallUserId = flowModel.InstallUser, Ico = jObject.Value("ico"), Color = jObject.Value("color") }; #region 流程数据库连接信息 JArray dbsArray = jObject.Value("databases"); List databases = new List(); if (null != dbsArray) { foreach (JObject dbs in dbsArray) { Model.FlowRunModel.Database database = new Model.FlowRunModel.Database { ConnectionId = dbs.Value("link").IsGuid(out Guid cid) ? cid : Guid.Empty, ConnectionName = dbs.Value("linkName"), Table = dbs.Value("table"), PrimaryKey = dbs.Value("primaryKey") }; databases.Add(database); } } flowRunModel.Databases = databases; #endregion #region 流程标识字段信息 JObject titleFieldObject = jObject.Value("titleField"); Model.FlowRunModel.TitleField titleField = new Model.FlowRunModel.TitleField(); if (null != titleFieldObject) { titleField.ConnectionId = titleFieldObject.Value("link").IsGuid(out Guid cid) ? cid : Guid.Empty; titleField.Table = titleFieldObject.Value("table"); titleField.Field = titleFieldObject.Value("field"); titleField.Value = titleFieldObject.Value("value"); titleField.EventCompleted = titleFieldObject.Value("eventCompleted"); titleField.EventStop = titleFieldObject.Value("eventStop"); } flowRunModel.TitleField = titleField; #endregion #region 步骤基本信息 JArray stepArray = jObject.Value("steps"); List steps = new List(); if (null != stepArray) { foreach (JObject stepObject in stepArray) { Model.FlowRunModel.Step stepModel = new Model.FlowRunModel.Step(); #region 坐标信息 JObject positionObject = stepObject.Value("position"); if (null != positionObject) { stepModel.Position_X = positionObject.Value("x").IsDecimal(out decimal x) ? x : 0; stepModel.Position_Y = positionObject.Value("y").IsDecimal(out decimal y) ? y : 0; } #endregion #region 步骤信息 stepModel.Archives = stepObject.Value("archives").IsBool(out bool archivesBool) ? archivesBool ? 1 : 0 : stepObject.Value("archives").IsInt(out int archives) ? archives : 0; stepModel.ExpiredPrompt = stepObject.Value("expiredPrompt").IsBool(out bool expiredBool) ? expiredBool ? 1 : 0 : stepObject.Value("expiredPrompt").IsInt(out int expiredPrompt) ? expiredPrompt : 0; stepModel.ExpiredPromptDays = stepObject.Value("expiredPromptDays").IsDecimal(out decimal expiredPromptDays) ? expiredPromptDays : 0; stepModel.Id = stepObject.Value("id").IsGuid(out Guid sid) ? sid : Guid.Empty; stepModel.Type = stepObject.Value("type").EqualsIgnoreCase("normal") ? 0 : 1; stepModel.Name = stepObject.Value("name"); stepModel.Dynamic = Config.EnableDynamicStep == false ? 0 : stepObject.Value("dynamic").ToInt(0); stepModel.DynamicField = stepObject.Value("dynamicField"); stepModel.Note = stepObject.Value("note"); stepModel.CommentDisplay = stepObject.Value("opinionDisplay").IsBool(out bool opinionBool) ? opinionBool ? 1 : 0 : stepObject.Value("opinionDisplay").IsInt(out int opinionDisplay) ? opinionDisplay : 0; stepModel.SignatureType = stepObject.Value("signatureType").IsInt(out int signatureType) ? signatureType : 0; stepModel.WorkTime = stepObject.Value("workTime").IsDecimal(out decimal workTime) ? workTime : 0; stepModel.SendShowMessage = stepObject.Value("sendShowMsg"); stepModel.BackShowMessage = stepObject.Value("backShowMsg"); stepModel.SendSetWorkTime = stepObject.Value("sendSetWorkTime").IsBool(out bool sendBool) ? sendBool ? 1 : 0 : stepObject.Value("sendSetWorkTime").IsInt(out int sendSetWorkTime) ? sendSetWorkTime : 0; stepModel.ExpiredExecuteModel = stepObject.Value("timeOutModel").IsInt(out int timeOutModel) ? timeOutModel : 0; stepModel.DataEditModel = stepObject.Value("dataEditModel").IsInt(out int dataEditModel) ? dataEditModel : 0; stepModel.Attachment = stepObject.Value("attachment").IsBool(out bool attachmentBool) ? attachmentBool ? 1 : 0 : stepObject.Value("attachment").ToInt(0); stepModel.BatchExecute = stepObject.Value("batch").IsBool(out bool batchBool) ? batchBool ? 1 : 0 : stepObject.Value("batch").ToInt(0); #region 基本信息 JObject baseObject = stepObject.Value("behavior"); Model.FlowRunModel.StepBase stepBaseModel = new Model.FlowRunModel.StepBase(); if (null != baseObject) { stepBaseModel.BackModel = baseObject.Value("backModel").IsInt(out int backModel) ? backModel : 0; if (baseObject.Value("backStep").IsGuid(out Guid backStepId)) { stepBaseModel.BackStepId = backStepId; } stepBaseModel.BackType = baseObject.Value("backType").IsInt(out int backType) ? backType : 0; stepBaseModel.BackSelectUser = baseObject.Value("backSelectUser").IsBool(out bool backUserBool) ? backUserBool ? 1 : 0 : baseObject.Value("backSelectUser").IsInt(out int backSelectUser) ? backSelectUser : 0; stepBaseModel.DefaultHandler = baseObject.Value("defaultHandler"); stepBaseModel.FlowType = baseObject.Value("flowType").IsInt(out int flowType) ? flowType : 2; if (baseObject.Value("handlerStep").IsGuid(out Guid handlerStepId)) { stepBaseModel.HandlerStepId = handlerStepId; } stepBaseModel.HandlerType = baseObject.Value("handlerType"); stepBaseModel.HanlderModel = baseObject.Value("hanlderModel").IsInt(out int hanlderModel) ? hanlderModel : 0; stepBaseModel.HanlderModelGroup = baseObject.Value("hanlderModelGroup").IsInt(out int hanlderModelGroup) ? hanlderModelGroup : 0; stepBaseModel.Percentage = baseObject.Value("percentage").IsDecimal(out decimal percentage) ? percentage : 0; stepBaseModel.RunSelect = baseObject.Value("runSelect").IsBool(out bool runBool) ? runBool ? 1 : 0 : baseObject.Value("runSelect").IsInt(out int runSelect) ? runSelect : 0; stepBaseModel.SelectRange = baseObject.Value("selectRange"); stepBaseModel.SelectRangeForDefaultHandler = baseObject.Value("selectRangeForDefaultHandler").ToInt(-1); stepBaseModel.ValueField = baseObject.Value("valueField"); stepBaseModel.LastHadler = baseObject.Value("lastHandler").IsBool(out bool lastBool) ? lastBool ? 1 : 0 : baseObject.Value("lastHandler").IsInt(out int lastHandler) ? lastHandler : 0; stepBaseModel.Countersignature = baseObject.Value("countersignature").IsInt(out int countersignature) ? countersignature : 0; stepBaseModel.CountersignatureStartStepId = baseObject.Value("countersignatureStartStep").IsGuid(out Guid countersignatureStartStepId) ? new Guid?(countersignatureStartStepId) : new Guid?(); stepBaseModel.CountersignaturePercentage = baseObject.Value("countersignaturePercentage").IsDecimal(out decimal countersignaturePercentage) ? countersignaturePercentage : 0; stepBaseModel.SubFlowStrategy = baseObject.Value("subflowstrategy").IsInt(out int subflowstrategy) ? subflowstrategy : 0; stepBaseModel.ConcurrentModel = baseObject.Value("concurrentModel").IsBool(out bool concurrentBool) ? concurrentBool ? 1 : 0 : baseObject.Value("concurrentModel").IsInt(out int concurrentModel) ? concurrentModel : 0; stepBaseModel.DefaultHandlerSqlOrMethod = baseObject.Value("defaultHandlerSqlOrMethod"); stepBaseModel.AutoConfirm = baseObject.Value("autoConfirm").IsBool(out bool autoBool) ? autoBool ? 1 : 0 : baseObject.Value("autoConfirm").ToInt(0); stepBaseModel.SkipIdenticalUser = baseObject.Value("skipIdenticalUser").IsBool(out bool skipBool) ? skipBool ? 1 : 0 : baseObject.Value("skipIdenticalUser").ToInt(0); stepBaseModel.SkipMethod = baseObject.Value("skipMethod"); stepBaseModel.SendToBackStep = baseObject.Value("sendToBackStep").IsBool(out bool sendToBool) ? sendToBool ? 1 : 0 : baseObject.Value("sendToBackStep").ToInt(0); } stepModel.StepBase = stepBaseModel; #endregion #region 抄送 Model.FlowRunModel.StepCopyFor stepCopyForModel = new Model.FlowRunModel.StepCopyFor(); JObject copyForObject = stepObject.Value("copyFor"); if (null != copyForObject) { stepCopyForModel.MemberId = copyForObject.Value("memberId"); stepCopyForModel.HandlerType = copyForObject.ContainsJArray("handlerType", out string handlerString) ? handlerString : copyForObject.Value("handlerType"); stepCopyForModel.Steps = copyForObject.ContainsJArray("steps", out string stepsString) ? stepsString : copyForObject.Value("steps"); stepCopyForModel.MethodOrSql = copyForObject.Value("methodOrSql"); stepCopyForModel.CopyforTime = copyForObject.Value("time").ToInt(0); stepCopyForModel.SendMessageType = copyForObject.ContainsJArray("messageType", out string msgTypeString) ? msgTypeString : copyForObject.Value("messageType"); } stepModel.StepCopyFor = stepCopyForModel; #endregion #region 按钮信息 List stepButtons = new List(); JArray buttonArray = stepObject.Value("buttons"); if (null != buttonArray) { foreach (JObject buttonObject in buttonArray) { Model.FlowRunModel.StepButton stepButtonModel = new Model.FlowRunModel.StepButton(); if (buttonObject.Value("id").IsGuid(out Guid bid)) { var flowButtonModel = new FlowButton().Get(bid.ToString()); stepButtonModel.Id = bid; stepButtonModel.Note = ""; string showTitle = buttonObject.Value("showTitle"); stepButtonModel.ShowTitle = showTitle; stepButtonModel.Sort = buttonObject.Value("sort"); //2020-11-24注释掉,便于多语言时,没有设置ShowTitle时根据语言读取按钮Title。 //if (null != flowButtonModel) //{ // stepButtonModel.Note = flowButtonModel.Note; // stepButtonModel.ShowTitle = showTitle.IsNullOrWhiteSpace() ? flowButtonModel.Title : showTitle; //} } stepButtons.Add(stepButtonModel); } } stepModel.StepButtons = stepButtons; #endregion #region 事件 JObject eventObject = stepObject.Value("event"); Model.FlowRunModel.StepEvent stepEventModel = new Model.FlowRunModel.StepEvent(); if (null != eventObject) { stepEventModel.BackAfter = eventObject.Value("backAfter"); stepEventModel.BackPassAfter = eventObject.Value("backPassAfter"); stepEventModel.BackBefore = eventObject.Value("backBefore"); stepEventModel.SubmitAfter = eventObject.Value("submitAfter"); stepEventModel.SubmitPassAfter = eventObject.Value("submitPassAfter"); stepEventModel.SubmitBefore = eventObject.Value("submitBefore"); stepEventModel.SubFlowActivationBefore = eventObject.Value("subflowActivationBefore"); stepEventModel.SubFlowCompletedBefore = eventObject.Value("subflowCompletedBefore"); } stepModel.StepEvent = stepEventModel; #endregion #region 表单 JArray formArray = stepObject.Value("forms"); Model.FlowRunModel.StepForm stepFormModel = new Model.FlowRunModel.StepForm(); if (null != formArray && formArray.Count > 0) { JObject formObject = (JObject)formArray.First; if (formObject.Value("id").IsGuid(out Guid formId)) { stepFormModel.Id = formId; } stepFormModel.Name = formObject.Value("name"); if (formObject.Value("idApp").IsGuid(out Guid appId)) { stepFormModel.MobileId = appId; } stepFormModel.MobileName = formObject.Value("nameApp"); } stepModel.StepForm = stepFormModel; #endregion #region 字段状态 JArray fieldArray = stepObject.Value("fieldStatus"); List stepFieldStatuses = new List(); if (null != fieldArray) { foreach (JObject fieldObject in fieldArray) { Model.FlowRunModel.StepFieldStatus stepFieldStatusModel = new Model.FlowRunModel.StepFieldStatus { Check = fieldObject.Value("check").IsInt(out int check) ? check : 0, Field = fieldObject.Value("field"), Status = fieldObject.Value("status").IsInt(out int status) ? status : 0 }; stepFieldStatuses.Add(stepFieldStatusModel); } } stepModel.StepFieldStatuses = stepFieldStatuses; #endregion #region 子流程 JObject subflowObject = stepObject.Value("subflow"); Model.FlowRunModel.StepSubFlow stepSubFlowModel = new Model.FlowRunModel.StepSubFlow(); if (null != subflowObject) { if (subflowObject.Value("flowId").IsGuid(out Guid subId)) { stepSubFlowModel.SubFlowId = subId; } stepSubFlowModel.SubFlowStrategy = subflowObject.Value("flowStrategy").IsInt(out int flowStrategy) ? flowStrategy : 0; stepSubFlowModel.TaskType = subflowObject.Value("taskType").IsInt(out int taskType) ? taskType : 0; } stepModel.StepSubFlow = stepSubFlowModel; #endregion steps.Add(stepModel); #endregion } } flowRunModel.Steps = steps; if (steps.Count == 0) { errMsg = localizer == null ? "流程至少需要一个步骤" : localizer["Install_OneStep"].Value; return null; } #endregion #region 连线信息 JArray lineArray = jObject.Value("lines"); List lines = new List(); if (null != lineArray) { foreach (JObject lineObject in lineArray) { Model.FlowRunModel.Line lineModel = new Model.FlowRunModel.Line { Id = lineObject.Value("id").IsGuid(out Guid lid) ? lid : Guid.Empty, FromId = lineObject.Value("from").IsGuid(out Guid fid) ? fid : Guid.Empty, ToId = lineObject.Value("to").IsGuid(out Guid tid) ? tid : Guid.Empty, CustomMethod = lineObject.Value("customMethod"), SqlWhere = lineObject.Value("sql"), JudgeType = lineObject.Value("judagType").ToInt(0) }; if (lineObject.Value("organize") != null) { lineModel.OrganizeExpression = lineObject.Value("organize").ToString(Newtonsoft.Json.Formatting.None); } lines.Add(lineModel); } } flowRunModel.Lines = lines; #endregion #region 设置开始步骤 Model.FlowRunModel.Step firstStep = null; foreach (var step in flowRunModel.Steps) { if (flowRunModel.Lines.Find(p => p.ToId == step.Id) == null) { firstStep = step; break; } } if (null == firstStep) { errMsg = localizer == null ? "流程没有开始步骤" : localizer["Install_NotStartStep"].Value; return null; } flowRunModel.FirstStepId = firstStep.Id; #endregion return flowRunModel; } /// /// 导入流程 /// /// /// 是否要创建表单文件,VUE导入时不需要创建 /// 返回1表示成功,其它为错误信息 public string ImportFlow(string json, bool createFormFile = true) { if (json.IsNullOrWhiteSpace()) { return "要导入的JSON为空!"; } JObject jObject; try { jObject = JObject.Parse(json); } catch { return "json解析错误!"; } var flows = jObject.Value("flows"); if (null != flows) { foreach (JObject flow in flows) { Model.rf_flow flowModel = flow.ToObject(); if (null == flowModel) { continue; } if (Get(flowModel.Id) != null) { Update(flowModel); } else { Add(flowModel); } } } var applibarys = jObject.Value("applibrarys"); if (null != applibarys) { foreach (JObject app in applibarys) { Model.rf_applibrary appLibraryModel = app.ToObject(); if (null == appLibraryModel) { continue; } if (new Applibrary().GetOneById(appLibraryModel.Id) != null) { new Applibrary().Update(appLibraryModel); } else { new Applibrary().Add(appLibraryModel); } } } var forms = jObject.Value("forms"); //Form bform = new Form(); if (null != forms) { foreach (JObject form in forms) { Model.rf_form formModel = form.ToObject(); if (null == formModel) { continue; } if (new Form().GetOneById(formModel.Id) != null) { new Form().Update(formModel); } else { new Form().Add(formModel); } //如果表单状态是发布,要发布表单 if (createFormFile && formModel.Status == 1) { #region 写入文件 string webRootPath = Tools.GetWebRootPath(); string path = webRootPath + "/RoadFlowResources/scripts/formDesigner/form/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string file = path + formModel.Id + ".rfhtml"; Stream stream = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); stream.SetLength(0); StreamWriter sw = new StreamWriter(stream, Encoding.UTF8); sw.Write(formModel.RunHtml); sw.Close(); stream.Close(); #endregion } } } return "1"; } /// /// 查询一页数据 /// /// /// /// /// /// /// /// /// 状态-1表示查询未删除的流程 /// /// /// 得到一个用户可以发起的流程运行时实体列表 /// /// /// public List GetStartFlows(string userId) { List flowRuns = new List(); var flows = GetAll(); foreach (var flow in flows) { var flowRunModel = GetFlowRunModel(flow.Id); if (null == flowRunModel || flowRunModel.Status != 1 || flowRunModel.FirstStepId.IsEmptyGuid()) { continue; } var firstStepModel = flowRunModel.Steps.Find(p => p.Id == flowRunModel.FirstStepId); if (null == firstStepModel) { continue; } if (firstStepModel.StepBase.DefaultHandler.IsNullOrWhiteSpace() || new UserDummy().Contains(firstStepModel.StepBase.DefaultHandler, userId)) { flowRuns.Add(flowRunModel); } } return flowRuns; } /// /// 得到流程运行时实体 /// /// 流程ID /// 是否从缓存中取 /// 当前任务实体(动态步骤时要取动态的步骤流程运行时实体) /// public Model.FlowRun GetFlowRunModel(string id, bool isCache = true, RoadFlow.Model.rf_flowtask currentTask = null) { //如果当前任务有之前步骤ID,则从动态流程中取JSON if (null != currentTask && currentTask.BeforeStepId.IsNotEmptyGuid()) { string key = CACHEKEY + "_" + currentTask.BeforeStepId + "_" + currentTask.GroupId; if (isCache) { object obj = this._memoryCache.Get(key); if (null != obj) { return (Model.FlowRun)obj; } } var flowDynamicModel = new FlowDynamic().Get(currentTask.BeforeStepId, currentTask.GroupId); var runModel = null == flowDynamicModel || flowDynamicModel.FlowJSON.IsNullOrWhiteSpace() ? null : GetFlowRunModel(flowDynamicModel.FlowJSON, out string msg1); if (null != runModel) { this._memoryCache.Set(key, runModel); //Cache.IO.Insert(key, runModel); } return runModel; } //========================================= string cacheKey = CACHEKEY + id; if (isCache) { object obj = _memoryCache.Get(cacheKey); if (null != obj) { return (Model.FlowRun)obj; } } var flowModel = Get(id); if (null == flowModel) { return null; } var flowRunModel = GetFlowRunModel(flowModel.RunJSON.IsNullOrWhiteSpace() ? flowModel.DesignerJSON : flowModel.RunJSON, out string msg); if (null != flowRunModel) { _memoryCache.Set(cacheKey, flowRunModel); } return flowRunModel; } /// /// 得到步骤名称 /// /// /// /// public string GetStepName(string flowId, Guid stepId) { return flowId.IsNullOrWhiteSpace() ? string.Empty : GetStepName(GetFlowRunModel(flowId), stepId); } /// /// 得到步骤名称 /// /// /// /// public string GetStepName(Model.FlowRun flowRunModel, Guid stepId) { if (null == flowRunModel) { return string.Empty; } if (stepId.IsEmptyGuid()) { stepId = flowRunModel.FirstStepId; } var step = flowRunModel.Steps.Find(p => p.Id == stepId); return null == step ? string.Empty : step.Name; } /// /// 得到一个流程步骤的下一步骤集合 /// /// 流程运行时实体 /// 步骤ID /// public List GetNextSteps(Model.FlowRun flowRunModel, Guid stepId) { List steps = new List(); if (null == flowRunModel) { return steps; } var lines = flowRunModel.Lines.FindAll(p => p.FromId == stepId); foreach (var line in lines) { var step = flowRunModel.Steps.Find(p => p.Id == line.ToId); if (null != step) { steps.Add(step); } } return steps.Count > 0 ? steps.OrderBy(p => p.Position_Y).ThenBy(p => p.Position_X).ToList() : steps; } /// /// 得到一个步骤的前面步骤集合 /// /// /// /// public List GetPrevSteps(Model.FlowRun flowRunModel, string stepId) { List steps = new List(); if (null == flowRunModel || stepId.IsNullOrWhiteSpace()) { return steps; } var lines = flowRunModel.Lines.FindAll(p => p.ToId == stepId.ToGuid()); foreach (var line in lines) { var step = flowRunModel.Steps.Find(p => p.Id == line.FromId); if (null != step) { steps.Add(step); } } return steps; } /// /// 得到两个步骤之间的步骤集合 /// /// /// 开始步骤Id /// 结束步骤Id /// public List GetRangeSteps(Model.FlowRun flowRunModel, Guid stepId1, Guid stepId2) { if (stepId1.IsEmptyGuid()) { return new List(); } var nextSteps = GetNextSteps(flowRunModel, stepId1); foreach (var nextStep in nextSteps) { var allNextSteps = GetAllNextSteps(flowRunModel, nextStep.Id); if (allNextSteps.Exists(p => p.Id == stepId2)) { List steps = new List() { nextStep }; foreach (var step in allNextSteps) { steps.Add(step); if (step.Id == stepId2) { return steps; } } } } return new List(); } /// /// 得到一个步骤的所有后续步骤集合 /// /// /// /// public List GetAllNextSteps(Model.FlowRun flowRunModel, Guid stepId) { List steps = new List(); AddNextSteps(flowRunModel, stepId, stepId, steps); return steps; } /// /// 递归添加一个步骤的后续步骤 /// /// /// /// 开始的步骤ID /// private void AddNextSteps(Model.FlowRun flowRunModel, Guid stepId, Guid startStepId, List steps) { var nexts = GetNextSteps(flowRunModel, stepId); foreach (var step in nexts) { if (!steps.Exists(p => p.Id == step.Id) && step.Id != startStepId) { steps.Add(step); } } foreach (var step in nexts) { if (step.Id != startStepId) { AddNextSteps(flowRunModel, step.Id, startStepId, steps); } } } /// /// 得到流程运行时实体 /// /// 流程ID /// 是否从缓存中取 /// 当前任务实体(动态步骤时要取动态的步骤流程运行时实体) /// public Model.FlowRun GetFlowRunModel(Guid id, bool isCache = true, Model.rf_flowtask currentTask = null) { //如果当前任务有之前步骤ID,则从动态流程中取JSON if (null != currentTask && currentTask.BeforeStepId.IsNotEmptyGuid()) { string key = CACHEKEY + "_" + currentTask.BeforeStepId + "_" + currentTask.GroupId; if (isCache) { object obj = _memoryCache.Get(key); if (null != obj) { return (Model.FlowRun)obj; } } var flowDynamicModel = new FlowDynamic().Get(currentTask.BeforeStepId, currentTask.GroupId); var runModel = null == flowDynamicModel || flowDynamicModel.FlowJSON.IsNullOrWhiteSpace() ? null : GetFlowRunModel(flowDynamicModel.FlowJSON, out string msg1); if (null != runModel) { _memoryCache.Set(key, runModel); } return runModel; } //========================================= string cacheKey = CACHEKEY + id.ToString(); if (isCache) { object obj = _memoryCache.Get(cacheKey); if (null != obj) { return (Model.FlowRun)obj; } } var flowModel = Get(id.ToString()); if (null == flowModel) { return null; } var flowRunModel = GetFlowRunModel(flowModel.RunJSON.IsNullOrWhiteSpace() ? flowModel.DesignerJSON : flowModel.RunJSON, out string msg); if (null != flowRunModel) { _memoryCache.Set(cacheKey, flowRunModel); } return flowRunModel; } /// /// 判断一个步骤是否是最后一步 /// /// 流程运行时实体 /// 步骤ID /// public bool IsLastStep(Model.FlowRun flowRunModel, Guid stepId) { if (null == flowRunModel || flowRunModel.Lines.Count == 0) { return true; } return !flowRunModel.Lines.Exists(p => p.FromId == stepId); } /// /// 得到一个用户可管理实例的流程 /// /// /// public List GetManageInstanceFlowIds(string userId) { var flows = GetListBy(x => x.InstanceManager.ToLower().Contains(userId.ToLower())); List guids = new List(); foreach (var flow in flows) { guids.Add(flow.Id); } return guids; } } }