using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ewide.Core;
using Ewide.RoadFlowLite.Utility;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.Localization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using RoadFlow.Data;
using RoadFlow.Utility;
using SqlSugar;
namespace Ewide.RoadFlowLite.Serivce.FlowDesign
{
///
/// 工作流设计器服务
///
[Route("/api/roadflow/FlowDesign/")]
[ApiDescriptionSettings("RoadFlow")]
public class FlowDesignSerivce:IFlowDesignService ,IDynamicApiController, ITransient
{
private readonly IDictionary _dicRepo;
private readonly IRepository _sysUserRepo;
private readonly IFlow _flowRepo;
private readonly IUserManager _userManager;
private readonly IFlowTask _flowTaskRepo;
private readonly IFlowDynamic _flowDynamicRepo;
private readonly IFlowButton _flowButtonRepo;
private readonly ILog _logRepo;
private readonly IFlowApiSystem _flowApiSystemRepo;
private readonly RoadFlow.Data.IDbConnection _dbConnectionRepo;
//private readonly IStringLocalizer _localizer=L.Text;
private readonly IApplibrary _applibrary;
private readonly IFlowEntrust _flowEntrust;
private readonly IUserDummy _userDummy;
private readonly IFlowComment _flowComment;
public FlowDesignSerivce(IDictionary dicRepo,
IRepository sysUserRepo,
IFlow flowRepo,
IUserManager manager,
IFlowTask flowTaskRepo,
IFlowDynamic flowDynamicRepo,
IFlowButton flowButtonRepo,
ILog logRopo,
IFlowApiSystem flowApiSystemRepo,
RoadFlow.Data.IDbConnection dbConnectionRepo,
IApplibrary applibrary,
IFlowEntrust flowEntrust,
IUserDummy userDummy,
IFlowComment flowComment
)
{
_dicRepo = dicRepo;
_sysUserRepo = sysUserRepo;
_flowRepo = flowRepo;
_flowTaskRepo = flowTaskRepo;
_userManager = manager;
_flowDynamicRepo = flowDynamicRepo;
_flowButtonRepo = flowButtonRepo;
_logRepo = logRopo;
_flowApiSystemRepo = flowApiSystemRepo;
_dbConnectionRepo = dbConnectionRepo;
_applibrary = applibrary;
_flowEntrust = flowEntrust;
_userDummy = userDummy;
_flowComment = flowComment;
}
[HttpGet("hello")]
[AllowAnonymous]
public dynamic Hello()
{
string hello = "hello".DESEncrypt();
return hello + ":" + hello.DESDecrypt();
}
#region 流程按钮管理
///
/// 得到按钮列表
///
///
[HttpPost("GetButtonList")]
public dynamic GetButtonList([FromBody] JObject args)
{
string title = args.GetJsonValue("title");
var buttons = title.IsNullOrWhiteSpace()
? _flowButtonRepo.GetAll()
: _flowButtonRepo.GetAll().FindAll(p => p.Title.ContainsIgnoreCase(title.Trim()));
JArray jArray = new JArray();
//string lang = RoadFlow.Utility.Tools.GetCurrentLanguage(HttpContext);
foreach (var button in buttons)
{
JObject jObject = new JObject()
{
{ "Id", button.Id },
//{ "Title", flowButton.GetLanguageTitle(button, out string note, lang) },
{ "Title", button.Title },
{ "Ico", button.Ico },
//{ "Note", note },
{ "Note", button.Note },
{ "Sort", button.Sort },
};
jArray.Add(jObject);
}
return jArray;
}
///
/// 得到按钮实体
///
///
[HttpGet("GetButton")]
public dynamic GetButton(string id)
{
//string id = args.GetJsonValue("id", isThrowExp: true);
if (!id.IsGuid(out Guid guid))
{
return null;
}
var model =_flowButtonRepo.GetOneById(id);
if (model == null)
{
return null;
}
return model;
}
///
/// 保存按钮
///
///
///
[HttpPost("SaveButton")]
public string SaveButton([FromBody] JObject args)
{
string id = args.GetJsonValue("id");
var buttonModel = new RoadFlow.Model.rf_flowbutton
{
Ico = args.GetJsonValue("Ico"),
Note = args.GetJsonValue("Note"),
Script = args.GetJsonValue("Script"),
Sort = args.GetJsonIntValue("Sort") ?? 0,
Title = args.GetJsonValue("Title"),
};
if (id.IsGuid(out Guid buttonId))
{
buttonModel.Id = id;
var oldModel = _flowButtonRepo.GetOneById(id);
_flowButtonRepo.Update(buttonModel); ;
_logRepo.Add("修改了流程按钮-" + buttonModel.Title, CurrentUserId: _userManager.UserId, type: LogType.系统管理, oldContents: oldModel.ToString(), newContents: buttonModel.ToString());
}
else
{
buttonModel.Id = GuidExtensions.NewGuid().ToString();
_flowButtonRepo.Add(buttonModel);
_logRepo.Add("添加了流程按钮-" + buttonModel.Title, CurrentUserId: _userManager.UserId, buttonModel.ToString(), LogType.系统管理);
}
//return RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["SaveSuccessfully"].Value);
return "保存成功";
}
///
/// 删除按钮
///
///
[HttpPost("DeleteButton")]
public string DeleteButton([FromBody] JObject args)
{
string ids = args.GetJsonValue("ids", isThrowExp: true);
List flowButtons = new();
foreach (string id in ids.Split(','))
{
if (!id.IsGuid(out Guid guid))
{
continue;
}
var buttonModel = _flowButtonRepo.GetOneById(id);
if (null == buttonModel)
{
continue;
}
flowButtons.Add(buttonModel);
}
_flowButtonRepo.Delete(flowButtons);
_logRepo.Add("删除了流程按钮", CurrentUserId: _userManager.UserId, flowButtons.Serialize(), LogType.系统管理);
return "共删除 "+flowButtons.Count+" 个按钮";
//_localizer["TotalDelete"].Value + flowButtons.Count.ToString() + _localizer["ButtonCount"].Value;
}
///
/// 得到按钮
///
///
[HttpGet("GetButtons")]
public dynamic GetButtons()
{
var buttons = _flowButtonRepo.GetAll();
JArray jArray = new JArray();
foreach (var button in buttons)
{
jArray.Add(new JObject() {
{ "id", button.Id.ToString() },
{ "title", button.Title },
{ "ico", button.Ico },
{ "note", button.Note},
{ "current", false }
});
}
return jArray;
}
#endregion
#region API系统管理
///
/// 得到api系统combox选项
///
///
[HttpGet("GetApiSystemOptions")]
public dynamic GetApiSystemOptions()
{
var systems = _flowApiSystemRepo.GetAll();
JArray jArray = new JArray();
foreach (var system in systems)
{
jArray.Add(new JObject()
{
{ "value", system.Id.ToString() },
{ "title", system.Name }
});
}
return jArray;
}
///
/// 查询API系统列表
///
///
[HttpPost("GetApiSystemList")]
public dynamic GetApiSystemList(string title)
{
//string title = Request.Forms("title");
var apiSystems = title.IsNullOrWhiteSpace()
?_flowApiSystemRepo.GetAll()
: _flowApiSystemRepo.GetAll().FindAll(p => p.Name.ContainsIgnoreCase(title.Trim()));
JArray jArray = new JArray();
foreach (var apiSystem in apiSystems.OrderBy(p => p.Sort))
{
JObject jObject = new JObject()
{
{ "Id", apiSystem.Id },
{ "Name", apiSystem.Name },
{ "SystemCode", apiSystem.SystemCode },
{ "SystemIP", apiSystem.SystemIP },
{ "Note", apiSystem.Note },
{ "Sort", apiSystem.Sort },
};
jArray.Add(jObject);
}
return jArray;
}
///
/// 查询API系统
///
///
[HttpGet("GetApiSystem")]
public dynamic GetApiSystem(string id)
{
//string id = Request.Querys("id");
if (!id.IsGuid(out Guid guid))
{
return new JObject();
}
var apiModel = _flowApiSystemRepo.GetOneById(id);
if (apiModel == null)
{
return new JObject();
}
return apiModel.ToJObject();
}
///
/// 保存API系统
///
///
///
[HttpPost("SaveApiSystem")]
public string SaveApiSystem([FromBody] RoadFlow.Model.rf_flowapisystem flowApiSystemModel)
{
//RoadFlow.Business.FlowApiSystem flowApiSystem = new RoadFlow.Business.FlowApiSystem();
string id = flowApiSystemModel.Id;//Request.Querys("id");
if (id.IsGuid(out Guid systemId))
{
var oldModel = _flowApiSystemRepo.GetOneById(id);
if (oldModel == null)
throw Oops.Oh("该id不存在");
_flowApiSystemRepo.Update(flowApiSystemModel);
_logRepo.Add("修改了API系统-" + flowApiSystemModel.Name,CurrentUserId:_userManager.UserId, type: LogType.系统管理, oldContents: oldModel.ToString(), newContents: flowApiSystemModel.ToString());
}
else
{
flowApiSystemModel.Id = GuidExtensions.NewGuid().ToString();
_flowApiSystemRepo.Add(flowApiSystemModel);
_logRepo.Add("添加了API系统-" + flowApiSystemModel.Name,_userManager.UserId, flowApiSystemModel.ToString(), LogType.系统管理);
}
return "保存成功";
}
///
/// 删除API系统
///
///
[HttpPost("DeleteApiSystem")]
public string DeleteApiSystem([FromBody] JObject args)
{
string ids = args.GetJsonValue("ids");
List flowApiSystems = new List();
foreach (string id in ids.Split(','))
{
if (!id.IsGuid(out Guid guid))
{
continue;
}
var apiModel = _flowApiSystemRepo.GetOneById(id);
if (null == apiModel)
{
continue;
}
flowApiSystems.Add(apiModel);
}
int count =_flowApiSystemRepo.Delete(flowApiSystems.ToArray());
_logRepo.Add("删除了API接口系统",_userManager.UserId ,flowApiSystems.Serialize(),LogType.系统管理);
return "共删除 "+count+" 条记录";
//RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["TotalDelete"].Value + flowApiSystems.Count.ToString() + localizer["Items"].Value);
}
#endregion
#region 流程设计
///
/// 得到流程列表
///
///
[HttpPost("GetFlowList")]
public dynamic GetFlowList([FromBody] JObject args)
{
string name = args.GetJsonValue("name");
string typeId = args.GetJsonValue("type");
int? number = args.GetJsonIntValue("number");
int? size = args.GetJsonIntValue("size");
string order = args.GetJsonValue("order");
if (order.IsNullOrWhiteSpace())
{
order = "Name asc";
}
var typeIds = new List();
if (typeId.IsGuid(out Guid typeGuidId))
{
var childsId = _dicRepo.GetAllChildsId(typeId);
typeId = childsId.JoinSqlIn();
typeIds = childsId.Select(a => { return a.ToString(); }).ToList();
}
else
{
typeId = string.Empty;
}
var flows = _flowRepo.GetPagerList(out int total, size ?? 0, number ?? 0, _flowRepo.GetManageFlowIds(_userManager.UserId), name, typeIds, order);
JArray jArray = new JArray();
List uids = new List();
foreach (var flow in flows)
{
JObject jObject = new JObject()
{
{ "Id",flow.Id .ToString() },
{ "Name", flow.Name.ToString() },
{ "CreateDate", flow.CreateDate.ToString().IsDateTime(out DateTime dateTime) ? dateTime.ToDateTimeString() : string.Empty },
{ "CreateUser",flow.CreateUser },
{ "Status", _flowRepo.GetStatusTitle(flow.Status, null) },
{ "Status1",flow.Status.ToString().ToInt() },
};
uids.Add(flow.CreateUser);
jArray.Add(jObject);
}
List users =_sysUserRepo.DetachedEntities.Where(x => uids.Contains(x.Id)).ToList();
foreach (var j in jArray)
{
string uid = j["CreateUser"].ToString();
j["CreateUser"] = users.FirstOrDefault(x => x.Id == uid)?.Name;
}
JObject jObject1 = new JObject
{
{ "total", total },
{ "rows", jArray }
};
return jObject1;
}
///
/// 得到流程JSON
///
///
[HttpPost("GetFlowJson")]
public dynamic GetFlowJson([FromBody] JObject args)
{
string flowId = args.GetJsonValue("flowid", isThrowExp: true);
bool isNew = "1".Equals(args.GetJsonValue("isnew"));
var flowModel = flowId.IsGuid(out Guid flowGuid) ? _flowRepo.GetOneById(flowId) : null;
if (null == flowModel)
{
if (isNew)
{
//新建流程,初始化选项
//Guid userId = Current.GetUserId(Request);
var userId = _userManager.UserId;
JObject jObject = new JObject()
{
{ "id", GuidExtensions.NewGuid() },
{ "type", args.GetJsonValue("typeid") },
{ "manager", RoadFlow.Data.IOrganize.PREFIX_USER + userId.ToString() },
{ "instanceManager", RoadFlow.Data.IOrganize.PREFIX_USER + userId.ToString() },
};
return jObject;
}
else
{
throw Oops.Oh("流程未找到");
}
}
else
{
//如果包含动态步骤则JSON要从rf_flowdynamic表中取
string groupId = args.GetJsonValue("groupid");//, isThrowExp: true);//组id
if (groupId.IsGuid(out Guid groupGuid))
{
string dynamicstepid = args.GetJsonValue("dynamicstepid");
if (!dynamicstepid.IsGuid(out Guid dynamicStepGuid))//动态步骤步骤id
{
var groupTasks = _flowTaskRepo.GetListByGroupId(groupId);
var dynamicStep = groupTasks.Find(p => p.BeforeStepId.IsNullOrEmpty() && p.BeforeStepId.IsNotEmptyGuid());
if (dynamicStep != null)
{
dynamicstepid = dynamicStep.BeforeStepId;
}
}
if (dynamicStepGuid.IsNotEmptyGuid())
{
var flowDynamicModel = _flowDynamicRepo.Get(dynamicstepid, groupId);
string dynamicFlowJSON = null == flowDynamicModel ? "{}" : flowDynamicModel.FlowJSON;
return new { EnableDynamicStep = RoadFlow.Utility.Config.EnableDynamicStep ? "1" : "0", data = JObject.Parse(dynamicFlowJSON) };
}
}
//========================================
JObject jObject = JObject.Parse(flowModel.DesignerJSON);
return new { EnableDynamicStep = RoadFlow.Utility.Config.EnableDynamicStep ? "1" : "0", data = jObject };
}
}
///
/// 得到数据连接
///
///
[HttpGet("GetDBConns")]
public dynamic GetDBConns()
{
var conns = _dbConnectionRepo.GetAll();
return conns;
}
///
/// 得到一个连接表的字段
///
///
[HttpPost("GetConnTableFields")]
public dynamic GetConnTableFields([FromBody] JObject args)
{
var connId = args.GetJsonGuidValue("connid", isThrowExp: true);
string table = args.GetJsonValue("table");
JArray jArray = new JArray();
var fields = _dbConnectionRepo.GetTableFields(connId.Value.ToString(), table.Trim());
foreach (var field in fields)
{
jArray.Add(new JObject() {
{ "name", field.FieldName },
{ "type", field.Type },
{ "size", field.Size },
{ "comment", field.Comment },
});
}
return jArray;
}
///
/// 得到一个连接对应的表
///
///
[HttpGet("GetConnTables")]
public dynamic GetConnTables(string connid)
{
// var connId = args.GetJsonGuidValue("connid", isThrowExp: true);
string connId = connid;
JArray jArray = new JArray();
var tables = _dbConnectionRepo.GetTables(connId);
foreach (var table in tables)
{
jArray.Add(new JObject() { { "table", table.Key }, { "note", table.Value } });
}
return jArray;
}
///
/// 得到工作角色选项
///
///
[HttpGet("GetWorkRoleOptions")]
public dynamic GetWorkRoleOptions()
{
var workDict = this._dicRepo.GetOneByCode("Organize_Work_Role");
if (workDict == null)
{
//return RoadFlowCommon.Tools.GetReturnJsonString(jArray: new JArray());
throw Oops.Oh("Code有误");
}
string lang = Tools.GetCurrentLanguage();
string roleTitle = this._dicRepo.GetLanguageTitle(workDict, lang);
var dicts = this._dicRepo.GetChilds(workDict.Id);
JArray jArray = new JArray();
foreach (var dict in dicts)
{
jArray.Add(new JObject()
{
{ "value", dict.Id.ToLower() + "|1" },
{ "title", "发起者" + roleTitle + "-" + this._dicRepo.GetLanguageTitle(dict, lang) }
});
}
foreach (var dict in dicts)
{
jArray.Add(new JObject()
{
{ "value", dict.Id.ToLower() + "|2" },
//{ "title", localizer["Sender"].Value + roleTitle + "-" + dictionary.GetLanguageTitle(dict, lang) }
{ "title", "发送者" + roleTitle + "-" + this._dicRepo.GetLanguageTitle(dict, lang) }
});
}
//return RoadFlowCommon.Tools.GetReturnJsonString(jArray: jArray);
return jArray;
}
///
/// 得到工作角色选项(只是选项,没有加发起者,发送者。)
///
///
[HttpGet("GetWorkRoleOptions1")]
public dynamic GetWorkRoleOptions1()
{
var workDict = this._dicRepo.GetOneByCode("Organize_Work_Role");
if (workDict == null)
{
throw Oops.Oh("Code有误");
}
string lang = Tools.GetCurrentLanguage();
var dicts = this._dicRepo.GetChilds(workDict.Id);
JArray jArray = new JArray();
foreach (var dict in dicts)
{
jArray.Add(new JObject()
{
{ "value", dict.Id.ToLower() },
{ "title", this._dicRepo.GetLanguageTitle(dict, lang) }
});
}
return jArray;
}
[HttpPost("SaveFlow")]
[AllowAnonymous]
public string SaveFlow([FromBody] JObject args)
{
string opation = args.GetJsonValue("opation");
string json = args.GetJsonValue("json");
string msg = string.Empty;
string successMsg = string.Empty;
switch (opation)
{
case "save":
msg = _flowRepo.Save(json);
successMsg = "保存成功";//_localizer["SaveSuccessfully"].Value;
break;
case "install":
msg = _flowRepo.Install(json);
successMsg = "发布成功";//_localizer["PublishSuccessfully"].Value;
break;
case "uninstall":
msg = _flowRepo.UnInstall(json, 2);
successMsg = "卸载成功";// _localizer["UninstallSuccessfully"].Value;
break;
case "delete":
msg = _flowRepo.UnInstall(json, 3);
successMsg = "删除成功";//_localizer["DeleteSuccessfully"].Value;
break;
}
if ("1".Equals(msg))
{
return successMsg;
}
else
{
return msg;
}
}
///
/// 流程另存为
///
///
[HttpPost("SaveAsFlow")]
public string SaveAsFlow([FromBody] JObject args)
{
string newName = args.GetJsonValue("newName");
string id = args.GetJsonValue("id");
if (!id.IsGuid(out Guid flowId) || newName.IsNullOrWhiteSpace())
{
return "链接id或表名错误";//_localizer["ConnectionIdOrTableNameError"].Value;
}
string msg = _flowRepo.SaveAs(id, newName.Trim());
return msg;
}
///
/// 恢复删除流程
///
///
[HttpGet("RecoveryFlow")]
public string RecoveryFlow(string id)
{
//string id = args.GetJsonValue("id");
if (!id.IsGuid(out Guid flowId))
{
return "流程保存出错";//_localizer["Save_FlowIdError"].Value;
}
var flowModel = _flowRepo.Get(id);
if (null == flowModel)
{
return string.Empty;
}
flowModel.Status = 0;
_flowRepo.Update(flowModel);
_logRepo.Add("恢复了删除流程-" + flowModel.Name,_userManager.UserId, flowId.ToString(),LogType.流程管理);
return "恢复成功";//_localizer["NotFoundrecoveryFlow"].Value;
}
///
/// 删除流程(作删除标记)
///
///
[HttpPost("DeleteFlow")]
public string DeleteFlow([FromBody] JObject args)
{
string ids = args.GetJsonValue("ids");
foreach (string id in ids.Split(','))
{
if (!id.IsGuid(out Guid flowId))
{
continue;
}
var flowModel = _flowRepo.Get(id);
if (null == flowModel)
{
continue;
}
flowModel.Status = 3;
_flowRepo.Update(flowModel);
_flowRepo.ClearCache(id);
_logRepo.Add("删除了流程(作删除标记)-" + flowModel.Name, _userManager.UserId,id, LogType.流程管理);
}
return "删除成功"; //_localizer["DeleteSuccessfully"].Value;
}
///
/// 彻底删除流程
///
///
[HttpPost("ThoroughDeleteFlow")]
public string ThoroughDeleteFlow([FromBody] JObject args)
{
string ids = args.GetJsonValue("ids");
foreach (string id in ids.Split(','))
{
if (!id.IsGuid(out Guid flowId))
{
continue;
}
var flowModel = _flowRepo.Get(id);
if (null == flowModel)
{
continue;
}
_flowRepo.Delete(flowModel);
//删除应用程序库
var appModel = _applibrary.GetByCode(flowModel.Id.ToString());
if (null != appModel)
{
_applibrary.Delete(appModel.Id);
}
//删除流程实例
_flowRepo.DeleteBy(x=>x.Id==flowModel.Id);
_logRepo.Add("彻底删除了流程-" + flowModel.Name,_userManager.UserId, flowModel.ToString(), LogType.流程管理);
}
return "彻底删除成功";//_localizer["DeleteSuccessfully"].Value;
}
///
/// 导入流程
///
///
[HttpPost("ImportFlow")]
public string ImportFlow([FromBody] JObject args)
{
var files = args.GetJsonValue("files");
if (files.IsNullOrWhiteSpace())
{
return "未选中导入文件";//_localizer["NoSelectImportFile"].Value;
}
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
foreach (string file in files.Split(','))
{
string filePath = RoadFlow.Utility.Config.FilePath + file.DESDecrypt();
if (!System.IO.File.Exists(filePath))
{
continue;
}
var stream = System.IO.File.OpenRead(filePath);
int count = (int)stream.Length;
byte[] b = new byte[count];
stream.Read(b, 0, count);
string json = System.Text.Encoding.UTF8.GetString(b);
string msg = _flowRepo.ImportFlow(json, false);
stream.Close();
stream.DisposeAsync();
try
{
System.IO.File.Delete(filePath);
}
catch (IOException err)
{
_logRepo.Add(err);
}
if (!"1".Equals(msg))
{
stringBuilder.Append(msg + ",");
}
}
string msg1 = stringBuilder.ToString();
return msg1.IsNullOrWhiteSpace() ? "导入成功" /* _localizer["ImportSuccessfully"].Value */: msg1;
}
///
/// 得到已删除流程列表
///
///
[HttpPost("GetRemoveFlowList")]
public dynamic GetRemoveFlowList([FromBody] JObject args)
{
string name = args.GetJsonValue("name");
int number = args.GetJsonValue("number").ToInt();
int size = args.GetJsonValue("size").ToInt();
string order = args.GetJsonValue("order");
if (order.IsNullOrWhiteSpace())
{
order = "CreateDate asc";
}
string userId = _userManager.UserId;
var flows = _flowRepo.GetPagerList(out int total, size, number, _flowRepo.GetManageFlowIds(userId), name,string.Empty, order, 3);
JArray jArray = new JArray();
List uids = new List();
foreach (var dr in flows)
{
JObject jObject = new JObject()
{
{ "Id", dr.Id },
{ "Name", dr.Name },
{ "CreateDate", dr.CreateDate.ToShortDateTimeString() },
{ "CreateUser",dr.CreateUser},
};
uids.Add(dr.CreateUser.ToString());
jArray.Add(jObject);
}
var rtn =_sysUserRepo.DetachedEntities.Where(x => uids.Contains(x.Id)).ToList();
foreach (JObject j in jArray)
{
string userid = j["CreateUser"].ToString();
j["CreateUser"] =rtn.Find(x => x.Id == userid)?.Name;
}
JObject jObject1 = new JObject
{
{ "total", total },
{ "rows", jArray }
};
return jObject1;
}
///
/// 得到流程选项
///
///
[HttpGet("GetFlowOptions")]
public dynamic GetFlowOptions()
{
var flows = _flowRepo.GetAll().Where(p => p.Status == 1).GroupBy(p => p.FlowType);
JArray jArray = new JArray();
var dictRootId = _dicRepo.GetIdByCode("system_applibrarytype_flow");
var dicts = _dicRepo.GetAllChilds(dictRootId, true);
foreach (var dict in dicts)
{
var flows1 = flows.Where(p => p.Key == dict.Id);
if (!flows1.Any())
{
continue;
}
//string dictTitle = dictionary.GetAllParentTitle(dict.Id, true, false, dictRootId.ToString());
foreach (var flow in flows1)
{
foreach (var f in flow.OrderBy(p => p.Name))
{
jArray.Add(new JObject()
{
{ "value", f.Id.ToString() },
{ "title", f.Name + " - " + dict.Title },
});
}
}
}
return jArray;
}
#endregion
#region 流程委托
///
/// 查询自己的委托
///
///
[HttpPost("GetEntrusts")]
public dynamic GetEntrusts([FromBody] JObject args)
{
int number = args.GetJsonValue("number").ToInt();
int size = args.GetJsonValue("size").ToInt();
string order = args.GetJsonValue("order");
if (order.IsNullOrWhiteSpace())
{
order = "WriteTime desc";
}
if (_userManager.UserId.IsNullOrWhiteSpace())
{
return new JObject() { { "total", 0 }, { "rows", new JArray() } };
//RoadFlowCommon.Tools.GetReturnJsonString(jObject: new JObject() { { "total", 0 }, { "rows", new JArray() } });
}
return GetPageEntrusts(size, number, _userManager.UserId, string.Empty, string.Empty, order);
}
///
/// 查询所有委托
///
///
[HttpPost("GetAllEntrusts")]
public dynamic GetAllEntrusts([FromBody] JObject args)
{
string userId = args.GetJsonValue("userId");
string date1 = args.GetJsonValue("date1");
string date2 = args.GetJsonValue("date2");
int number = args.GetJsonValue("number").ToInt();
int size = args.GetJsonValue("size").ToInt();
string order = args.GetJsonValue("order");
if (order.IsNullOrWhiteSpace())
{
order = "WriteTime desc";
}
return GetPageEntrusts(size, number, userId.RemoveUserPrefix(), date1, date2, order);
}
///
/// 查询一页委托
///
///
private dynamic GetPageEntrusts(int size, int number, string userId, string date1, string date2, string order)
{
List entrusts = _flowEntrust.GetPagerList(out int total, size, number, userId, date1, date2, order);
JArray jArray = new JArray();
List uids = new();
foreach (RoadFlow.Model.rf_flowentrust dr in entrusts)
{
DateTime startTime = dr.StartTime;
DateTime endTime = dr.EndTime;
DateTime now = DateExtensions.Now;
string status;
if (startTime >= now)
{
status = "" + "未开始" + "";//localizer["NoStart"].Value
}
else if (endTime <= now)
{
status = "" + "已完成" + "";//localizer["Finished"].Value
}
else
{
status = "" +"进行中" + ""; //localizer["Entrusting"].Value
}
//_sysUserRepo.DetachedEntities.FirstOrDefault(x => x.Id == dr.UserId)
JObject jObject = new JObject
{
{ "Id", dr.Id },
{ "UserId",dr.UserId },
{ "ToUserId", _userDummy.GetNames(dr.ToUserId) },
{ "FlowId", !dr.FlowId.IsGuid() ? "所有流程" : _flowRepo.GetOneById(dr.FlowId)?.Name },//localizer["AllFlows"].Value
{ "WriteTime", dr.WriteTime.ToShortDateTimeString() },
{ "StartTime", startTime.ToShortDateTimeString() },
{ "EndTime", endTime.ToShortDateTimeString() },
{ "Note", dr.Note },
{ "Status", status },
{ "Opation", "" }
};
uids.Add(dr.UserId);
jArray.Add(jObject);
}
var users = _sysUserRepo.DetachedEntities.Where(x =>uids.Contains( x.Id));
foreach (var j in jArray)
{
j["UserId"] = users.FirstOrDefault(x => x.Id == j["UserId"].ToString())?.Name;
}
JObject json = new JObject() {
{ "total", total }
};
json.Add("rows", jArray);
return json;//RoadFlowCommon.Tools.GetReturnJsonString(jObject: json);
}
///
/// 查询一个委托
///
///
[HttpGet("GetEntrust")]
public dynamic GetEntrust(string id)
{
RoadFlow.Model.rf_flowentrust flowEntrustModel = null;
if (id.IsGuid())
{
flowEntrustModel = _flowEntrust.GetOneById(id);
}
if (flowEntrustModel == null)
{
flowEntrustModel = new RoadFlow.Model.rf_flowentrust();
}
return flowEntrustModel.ToJObject();//RoadFlowCommon.Tools.GetReturnJsonString(jObject: flowEntrustModel.ToJObject());
}
///
/// 删除委托
///
///
[HttpPost("DeleteEntrust")]
public string DeleteEntrust([FromBody] JObject args)
{
string ids = args.GetJsonValue("ids");
List flowEntrusts = new ();
foreach (string id in ids.Split(','))
{
if (!id.IsGuid())
{
continue;
}
var model = _flowEntrust.GetOneById(id);
if (null != model)
{
flowEntrusts.Add(model);
}
}
_flowEntrust.Delete(flowEntrusts);
_logRepo.Add("删除了委托",_userManager.UserId ,Newtonsoft.Json.JsonConvert.SerializeObject(flowEntrusts), LogType.流程管理);
return "删除成功";
//RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["DeleteSuccessfully"].Value);
}
///
/// 保存委托
///
///
[HttpPost("SaveEntrust")]
public string SaveEntrust([FromBody] JObject args)
{
string id = args.GetJsonValue("id");
bool isoneself = "1".Equals(args.GetJsonValue("isoneself"));
string UserId = args.GetJsonValue("UserId");
string ToUserId = args.GetJsonValue("ToUserId");
string StartTime = args.GetJsonValue("StartTime");
string EndTime = args.GetJsonValue("EndTime");
string FlowId = args.GetJsonValue("FlowId");
string Note = args.GetJsonValue("Note");
if (ToUserId.IsNullOrEmpty() || !StartTime.IsDateTime(out DateTime sTime) || !EndTime.IsDateTime(out DateTime eTime))
{
throw Oops.Oh("数据验证出错");
//return "数据验证出错";
//RoadFlowCommon.Tools.GetReturnJsonString(false, localizer["DataValidError"].Value);
}
RoadFlow.Model.rf_flowentrust flowEntrustModel = null;
RoadFlow.Model.rf_flowentrust flowEntrust = new RoadFlow.Model.rf_flowentrust();
bool isAdd = true;
if (id.IsGuid())
{
flowEntrustModel = _flowEntrust.GetOneById(id);
isAdd = false;
}
if (flowEntrustModel == null)
{
isAdd = true;
flowEntrustModel = new RoadFlow.Model.rf_flowentrust
{
Id = GuidExtensions.NewGuid().ToString(),
};
}
var userModel = _userManager.User;
flowEntrustModel.UserId = isoneself ? userModel.Id : UserId.RemoveUserPrefix();
flowEntrustModel.ToUserId = ToUserId;
flowEntrustModel.StartTime = sTime;
flowEntrustModel.EndTime = eTime;
flowEntrustModel.FlowId = FlowId.IsGuid(out Guid fid) ? FlowId : GuidExtensions.NewGuid().ToString();
if (!Note.IsNullOrWhiteSpace())
{
flowEntrustModel.Note = Note;
}
else
{
flowEntrustModel.Note = null;
}
flowEntrustModel.WriteTime = DateExtensions.Now;
if (isAdd)
{
_flowEntrust.Add(flowEntrustModel);
_logRepo.Add("添加了委托(" + userModel.Name + ")",_userManager.UserId, flowEntrustModel.ToString(), LogType.流程管理);
}
else
{
_flowEntrust.Update(flowEntrustModel);
_logRepo.Add("修改了委托(" + userModel.Name + ")", _userManager.UserId,flowEntrustModel.ToString(), LogType.流程管理);
}
return "保存成功";//RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["SaveSuccessfully"].Value);
}
#endregion
#region 流程意见管理
///
/// 得到自己的常用意见选项
///
///
[HttpGet("GetFlowCommentOptions")]
public dynamic GetFlowCommentOptions()
{
JArray commentArray = new JArray();
var comments = _flowComment.GetListByUserId(_userManager.UserId);
foreach (var comment in comments)
{
commentArray.Add(new JObject() { { "value", comment.Comments }, { "title", comment.Comments } });
}
return commentArray;
//RoadFlowCommon.Tools.GetReturnJsonString(jArray: commentArray);
}
//得到自己的意见列表
[HttpPost("GetComments")]
public dynamic GetComments()
{
//Guid userId = Current.GetUserId(Request);
var comments = _flowComment.GetAll().FindAll(p => p.UserId == _userManager.UserId);
JArray jArray = new JArray();
foreach (var comment in comments)
{
JObject jObject = new JObject
{
{ "Id", comment.Id },
{ "Comments", comment.Comments },
{ "AddType", comment.AddType == 0 ? "用户添加":"管理员添加" },// localizer["UserAdd"].Value : localizer["AdministratorAdd"].Value },
{ "Sort", comment.Sort },
{ "Opation", "" }
};
jArray.Add(jObject);
}
return jArray;
//RoadFlowCommon.Tools.GetReturnJsonString(jArray: jArray);
}
//得到管理员管理的意见列表
[HttpPost("GetAllComments")]
public dynamic GetAllComments([FromBody] JObject args)
{
string queryComment = args.GetJsonValue("comment");
string userId = args.GetJsonValue("userId");
int number = args.GetJsonValue("number").ToInt();
int size = args.GetJsonValue("size").ToInt();
string order = args.GetJsonValue("order");
if (order.IsNullOrWhiteSpace())
{
order = "Sort asc";
}
var comments = _flowComment.GetPagerList(out int total, size, number, queryComment, userId, order);
JArray jArray = new JArray();
foreach (var comment in comments)
{
JObject jObject = new JObject
{
{ "Id", comment.Id },
{ "Comments", comment.Comments },
{ "UserId", comment.UserId.IsNullOrWhiteSpace() ? "全员":_userDummy.GetNames(comment.UserId) },//localizer["AllUsers"].Value : user.GetName(comment.UserId) },
{ "AddType", comment.AddType == 0 ? "用户添加":"管理员添加" },// localizer["UserAdd"].Value : localizer["AdministratorAdd"].Value },
{ "Sort", comment.Sort },
{ "Opation", "" }
};
jArray.Add(jObject);
}
JObject json = new JObject() {
{ "total", total }
};
json.Add("rows", jArray);
return json;// RoadFlowCommon.Tools.GetReturnJsonString(jObject: json);
}
///
/// 查询一个意见
///
///
[HttpGet("GetComment")]
public dynamic GetComment(string id)
{
var commentModel = _flowComment.GetOneById(id);
return commentModel.ToJObject();
// RoadFlowCommon.Tools.GetReturnJsonString(jObject: commentModel == null? new JObject() : commentModel.ToJObject());
}
///
/// 保存意见
///
///
[HttpPost("SaveComment")]
public string SaveComment([FromBody] JObject args)
{
string id =args.GetJsonValue("id");
bool isoneself = "1".Equals(args.GetJsonValue("isoneself"));
string Comments = args.GetJsonValue("Comments");
string UserId = args.GetJsonValue("UserId");
string AddType = args.GetJsonValue("AddType");
string Sort = args.GetJsonValue("Sort");
if (Comments.IsNullOrWhiteSpace())
{
throw Oops.Oh("意见不得为空");
//return RoadFlowCommon.Tools.GetReturnJsonString(false, localizer["OpitionEmpty"].Value);
}
RoadFlow.Model.rf_flowcomment flowCommentModel = null;
if (id.IsGuid(out Guid guid))
{
flowCommentModel = _flowComment.GetOneById(id);
}
bool isAdd = false;
if (flowCommentModel == null)
{
flowCommentModel = new RoadFlow.Model.rf_flowcomment
{
Id = GuidExtensions.NewGuid().ToString(),
AddType = isoneself ? 0 : 1
};
isAdd = true;
}
flowCommentModel.Comments = Comments.Trim();
flowCommentModel.UserId = isoneself ? _userManager.UserId : UserId.RemoveUserPrefix();
flowCommentModel.Sort = Sort.ToInt(0);
if (isAdd)
{
_flowComment.Add(flowCommentModel);
_logRepo.Add("添加了流程意见",_userManager.UserId, flowCommentModel.ToString(), LogType.流程管理);
}
else
{
_flowComment.Update(flowCommentModel);
_logRepo.Add("修改了流程意见", _userManager.UserId, flowCommentModel.ToString(), LogType.流程管理);
}
return "保存成功";//RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["SaveSuccessfully"].Value);
}
///
/// 删除意见
///
///
[HttpPost("DeleteComment")]
public string DeleteComment([FromBody] JObject args)
{
string[] ids = args.GetJsonValue("ids").Split(',');
List flowComments = new ();
var all = _flowComment.GetAll();
foreach (string id in ids)
{
if (!id.IsGuid())
{
continue;
}
var comment = all.Find(p => p.Id == id);
if (null == comment)
{
continue;
}
flowComments.Add(comment);
}
_flowComment.Delete(flowComments);
_logRepo.Add("删除了流程意见",_userManager.UserId, Newtonsoft.Json.JsonConvert.SerializeObject(flowComments), LogType.流程管理);
return "删除成功";//RoadFlowCommon.Tools.GetReturnJsonString(true, localizer["DeleteSuccessfully"].Value);
}
#endregion
}
}