using NCC.Common.Core.Manager; using NCC.Common.Enum; using NCC.Common.Extension; using NCC.Common.Filter; using NCC.Dependency; using NCC.DynamicApiController; using NCC.FriendlyException; using NCC.Extend.Interfaces.LqReimbursementApplication; using Mapster; using Microsoft.AspNetCore.Mvc; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NCC.Extend.Entitys; using NCC.Extend.Entitys.Dto.LqReimbursementApplication; using NCC.Extend.Entitys.lq_reimbursement_application_node; using NCC.Extend.Entitys.lq_reimbursement_application_node_user; using NCC.Extend.Entitys.lq_reimbursement_approval_record; using Yitter.IdGenerator; using NCC.Common.Helper; using NCC.JsonSerialization; using NCC.Common.Model.NPOI; using NCC.Common.Configuration; using NCC.DataEncryption; using NCC.ClayObject; namespace NCC.Extend.LqReimbursementApplication { /// /// 报销申请表服务 /// [ApiDescriptionSettings(Tag = "Extend", Name = "LqReimbursementApplication", Order = 200)] [Route("api/Extend/[controller]")] public class LqReimbursementApplicationService : ILqReimbursementApplicationService, IDynamicApiController, ITransient { private readonly ISqlSugarRepository _lqReimbursementApplicationRepository; private readonly SqlSugarScope _db; private readonly IUserManager _userManager; /// /// 初始化一个类型的新实例 /// public LqReimbursementApplicationService( ISqlSugarRepository lqReimbursementApplicationRepository, IUserManager userManager) { _lqReimbursementApplicationRepository = lqReimbursementApplicationRepository; _db = _lqReimbursementApplicationRepository.Context; _userManager = userManager; } /// /// 获取报销申请表详情(包含表单和流程信息) /// /// 申请编号 /// [HttpGet("{id}")] public async Task GetInfo(string id) { var entity = await _db.Queryable().FirstAsync(p => p.Id == id); _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005); var output = entity.Adapt(); // 获取节点配置 var nodes = await _db.Queryable() .Where(x => x.ApplicationId == id) .OrderBy(x => x.NodeOrder) .ToListAsync(); // 获取每个节点的审批人 var nodeUsers = await _db.Queryable() .Where(x => x.ApplicationId == id) .OrderBy(x => x.NodeOrder) .OrderBy(x => x.SortOrder) .ToListAsync(); // 获取审批历史 var approvalRecords = await _db.Queryable() .Where(x => x.ApplicationId == id) .OrderBy(x => x.NodeOrder) .OrderBy(x => x.ApprovalTime) .ToListAsync(); // 组装节点信息 var nodeList = nodes.Select(n => new { nodeId = n.Id, nodeOrder = n.NodeOrder, nodeName = n.NodeName, approvalType = n.ApprovalType, isRequired = n.IsRequired, approvers = nodeUsers.Where(u => u.NodeId == n.Id).Select(u => new { userId = u.UserId, userName = u.UserName, sortOrder = u.SortOrder }).ToList(), approvalRecords = approvalRecords.Where(r => r.NodeId == n.Id).Select(r => new { approverName = r.ApproverName, approvalResult = r.ApprovalResult, approvalOpinion = r.ApprovalOpinion, approvalTime = r.ApprovalTime }).ToList() }).ToList(); // 获取当前节点审批人 var currentApprovers = new List(); if (entity.CurrentNodeOrder.HasValue && entity.CurrentNodeOrder > 0) { currentApprovers = nodeUsers .Where(u => u.NodeOrder == entity.CurrentNodeOrder.Value) .Select(u => new { userId = u.UserId, userName = u.UserName }) .Cast() .ToList(); } return new { form = output, nodes = nodeList, currentApprovers = currentApprovers, currentNodeOrder = entity.CurrentNodeOrder, approvalStatus = entity.ApprovalStatus ?? entity.ApproveStatus, returnedReason = entity.ReturnedReason }; } /// /// 获取报销申请表列表 /// /// 请求参数 /// [HttpGet("")] public async Task GetList([FromQuery] LqReimbursementApplicationListQueryInput input) { var sidx = input.sidx == null ? "id" : input.sidx; List queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject>() : null; DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null; DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null; List queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject>() : null; DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null; DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null; var query = _db.Queryable() .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id)) .WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId)) .WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName)) .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId)) .WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0)) .WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59)) .WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount)) .WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser)) .WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => (p.ApprovalStatus ?? p.ApproveStatus).Contains(input.approveStatus)) // .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0)) //.WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59)) .WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId)) .OrderBy(sidx + " " + input.sort); var total = await query.CountAsync(); var entities = await query.ToPageListAsync(input.currentPage, input.pageSize); // 获取当前审批人信息 var applicationIds = entities.Select(x => x.Id).ToList(); var currentApprovers = new List(); if (applicationIds.Any()) { var approverList = await _db.Queryable() .Where(x => applicationIds.Contains(x.ApplicationId)) .InnerJoin((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder) .Select((u, a) => new { applicationId = a.Id, approverName = u.UserName }) .ToListAsync(); currentApprovers = approverList.Cast().ToList(); } var approverDict = currentApprovers .GroupBy(x => (string)x.applicationId) .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName))); // 组装返回数据 var result = entities.Select(item => new LqReimbursementApplicationListOutput { id = item.Id, applicationUserId = item.ApplicationUserId, applicationUserName = item.ApplicationUserName, applicationStoreId = item.ApplicationStoreId, applicationTime = item.ApplicationTime, amount = item.Amount, approveUser = item.ApproveUser, approveStatus = item.ApprovalStatus ?? item.ApproveStatus, approveTime = item.ApproveTime, purchaseRecordsId = item.PurchaseRecordsId, currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null, currentNodeOrder = item.CurrentNodeOrder, nodeCount = item.NodeCount }).ToList(); return PageResult.SqlSugarPageResult( new SqlSugarPagedList { list = result, pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total } }); } /// /// 新建报销申请表 /// /// 参数 /// [HttpPost("")] public async Task Create([FromBody] LqReimbursementApplicationCrInput input) { var userInfo = await _userManager.GetUserInfo(); var entity = input.Adapt(); entity.Id = YitIdHelper.NextId().ToString(); try { //开启事务 _db.BeginTran(); // 1. 验证节点配置 if (input.nodes == null || input.nodes.Count < 3 || input.nodes.Count > 5) { throw new Exception("节点数量必须在3-5个之间"); } // 验证节点顺序是否连续(1, 2, 3, ...) var nodeOrders = input.nodes.Select(n => n.nodeOrder).OrderBy(x => x).ToList(); for (int i = 0; i < nodeOrders.Count; i++) { if (nodeOrders[i] != i + 1) { throw new Exception($"节点顺序必须连续,从1开始"); } } // 验证每个节点至少有一个审批人 foreach (var node in input.nodes) { if (node.approverIds == null || node.approverIds.Count == 0) { throw new Exception($"节点{node.nodeOrder}({node.nodeName})必须至少指定一个审批人"); } } // 2. 设置报销申请初始状态 entity.NodeCount = input.nodes.Count; entity.CurrentNodeOrder = 0; entity.ApprovalStatus = "待审批"; entity.ApplicationTime = DateTime.Now; if (string.IsNullOrEmpty(entity.ApplicationUserId)) { entity.ApplicationUserId = userInfo.userId; } if (string.IsNullOrEmpty(entity.ApplicationUserName)) { entity.ApplicationUserName = userInfo.userName; } // 3. 保存报销申请表(不使用IgnoreColumns,确保新字段被保存) var isOk = await _db.Insertable(entity).ExecuteCommandAsync(); if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000); // 4. 创建节点配置 if (input.nodes != null && input.nodes.Count > 0) { foreach (var nodeConfig in input.nodes) { var node = new LqReimbursementApplicationNodeEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = entity.Id, NodeOrder = nodeConfig.nodeOrder, NodeName = nodeConfig.nodeName, ApprovalType = nodeConfig.approvalType ?? "会签", IsRequired = 1, CreateTime = DateTime.Now }; var nodeResult = await _db.Insertable(node).ExecuteCommandAsync(); if (nodeResult <= 0) { throw new Exception($"创建节点{nodeConfig.nodeOrder}失败"); } // 5. 创建节点审批人 if (nodeConfig.approverIds != null && nodeConfig.approverIds.Count > 0) { for (int i = 0; i < nodeConfig.approverIds.Count; i++) { var nodeUser = new LqReimbursementApplicationNodeUserEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = entity.Id, NodeId = node.Id, NodeOrder = nodeConfig.nodeOrder, UserId = nodeConfig.approverIds[i], UserName = nodeConfig.approverNames != null && i < nodeConfig.approverNames.Count ? nodeConfig.approverNames[i] : null, SortOrder = i + 1, CreateTime = DateTime.Now }; var userResult = await _db.Insertable(nodeUser).ExecuteCommandAsync(); if (userResult <= 0) { throw new Exception($"创建节点{nodeConfig.nodeOrder}的审批人{nodeConfig.approverIds[i]}失败"); } } } } } // 6. 更新购买记录的审批单编号和审批状态为"待审批" if (input.selectedPurchaseRecordIds != null && input.selectedPurchaseRecordIds.Count > 0) { // 先更新ApplicationId await _db.Updateable() .SetColumns(it => it.ApplicationId == entity.Id) .Where(it => input.selectedPurchaseRecordIds.Contains(it.Id)) .ExecuteCommandAsync(); // 再更新ApproveStatus(分开更新确保都能执行) await _db.Updateable() .SetColumns(it => it.ApproveStatus == "待审批") .Where(it => input.selectedPurchaseRecordIds.Contains(it.Id)) .ExecuteCommandAsync(); } //关闭事务 _db.CommitTran(); } catch (Exception) { //回滚事务 _db.RollbackTran(); throw; } } /// /// 获取报销申请表无分页列表 /// /// 请求参数 /// [NonAction] public async Task GetNoPagingList([FromQuery] LqReimbursementApplicationListQueryInput input) { var sidx = input.sidx == null ? "id" : input.sidx; List queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject>() : null; DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null; DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null; List queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject>() : null; DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null; DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null; var data = await _db.Queryable() .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id)) .WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId)) .WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName)) .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId)) .WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0)) .WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59)) .WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount)) .WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser)) .WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => p.ApproveStatus.Contains(input.approveStatus)) // .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0)) // .WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59)) .WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId)) .Select(it => new LqReimbursementApplicationListOutput { id = it.Id, applicationUserId = it.ApplicationUserId, applicationUserName = it.ApplicationUserName, applicationStoreId = it.ApplicationStoreId, applicationTime = it.ApplicationTime, amount = it.Amount, approveUser = it.ApproveUser, approveStatus = it.ApproveStatus, approveTime = it.ApproveTime, purchaseRecordsId = it.PurchaseRecordsId, }).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync(); return data; } /// /// 导出报销申请表 /// /// 请求参数 /// [HttpGet("Actions/Export")] public async Task Export([FromQuery] LqReimbursementApplicationListQueryInput input) { var userInfo = await _userManager.GetUserInfo(); var exportData = new List(); if (input.dataType == 0) { var data = Clay.Object(await this.GetList(input)); exportData = data.Solidify>().list; } else { exportData = await this.GetNoPagingList(input); } List paramList = "[{\"value\":\"申请编号\",\"field\":\"id\"},{\"value\":\"申请人编号\",\"field\":\"applicationUserId\"},{\"value\":\"申请人姓名\",\"field\":\"applicationUserName\"},{\"value\":\"申请门店\",\"field\":\"applicationStoreId\"},{\"value\":\"申请时间\",\"field\":\"applicationTime\"},{\"value\":\"总金额\",\"field\":\"amount\"},{\"value\":\"审批人\",\"field\":\"approveUser\"},{\"value\":\"审批结果\",\"field\":\"approveStatus\"},{\"value\":\"审批时间\",\"field\":\"approveTime\"},{\"value\":\"关联购买编号\",\"field\":\"purchaseRecordsId\"},]".ToList(); ExcelConfig excelconfig = new ExcelConfig(); excelconfig.FileName = "报销申请表.xls"; excelconfig.HeadFont = "微软雅黑"; excelconfig.HeadPoint = 10; excelconfig.IsAllSizeColumn = true; excelconfig.ColumnModel = new List(); List selectKeyList = input.selectKey.Split(',').ToList(); foreach (var item in selectKeyList) { var isExist = paramList.Find(p => p.field == item); if (isExist != null) { excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value }); } } var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName; ExcelExportHelper.Export(exportData, excelconfig, addPath); var fileName = _userManager.UserId + "|" + addPath + "|xls"; var output = new { name = excelconfig.FileName, url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC") }; return output; } /// /// 批量删除报销申请表 /// /// 主键数组 /// [HttpPost("batchRemove")] public async Task BatchRemove([FromBody] List ids) { var entitys = await _db.Queryable().In(it => it.Id, ids).ToListAsync(); if (entitys.Count > 0) { try { //开启事务 _db.BeginTran(); //批量删除报销申请表 await _db.Deleteable().In(d => d.Id, ids).ExecuteCommandAsync(); //关闭事务 _db.CommitTran(); } catch (Exception) { //回滚事务 _db.RollbackTran(); throw NCCException.Oh(ErrorCode.COM1002); } } } /// /// 更新报销申请表 /// /// 主键 /// 参数 /// [HttpPut("{id}")] public async Task Update(string id, [FromBody] LqReimbursementApplicationUpInput input) { try { //开启事务 _db.BeginTran(); // 获取原有的关联购买记录ID var oldEntity = await _db.Queryable().FirstAsync(p => p.Id == id); var oldIds = new List(); if (oldEntity != null && !string.IsNullOrEmpty(oldEntity.PurchaseRecordsId)) { // 获取原有购买记录ID列表 oldIds = oldEntity.PurchaseRecordsId.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToList(); } // 获取新的购买记录ID列表 var newIds = input.selectedPurchaseRecordIds ?? new List(); // 确保 purchaseRecordsId 字段包含所有选中的记录ID(逗号分隔) if (newIds.Count > 0) { input.purchaseRecordsId = string.Join(",", newIds); } else { input.purchaseRecordsId = null; } // 找出需要移除关联的记录(在旧列表中但不在新列表中) var idsToRemove = oldIds.Where(x => !newIds.Contains(x)).ToList(); if (idsToRemove.Count > 0) { // 清除这些购买记录的审批单编号和审批状态 await _db.Updateable() .SetColumns(it => new LqPurchaseRecordsEntity { ApplicationId = null, ApproveStatus = "未审批" }) .Where(it => idsToRemove.Contains(it.Id)) .ExecuteCommandAsync(); } // 更新报销申请表(确保 purchaseRecordsId 字段被正确更新) var entity = input.Adapt(); var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync(); if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001); // 更新所有选中的购买记录的审批单编号和审批状态为"待审批" // 包括新追加的记录和已存在的记录(确保状态正确) if (newIds.Count > 0) { // 先更新ApplicationId await _db.Updateable() .SetColumns(it => it.ApplicationId == id) .Where(it => newIds.Contains(it.Id)) .ExecuteCommandAsync(); // 再更新ApproveStatus(分开更新确保都能执行) await _db.Updateable() .SetColumns(it => it.ApproveStatus == "待审批") .Where(it => newIds.Contains(it.Id)) .ExecuteCommandAsync(); } //关闭事务 _db.CommitTran(); } catch (Exception) { //回滚事务 _db.RollbackTran(); throw; } } /// /// 删除报销申请表 /// /// [HttpDelete("{id}")] public async Task Delete(string id) { var entity = await _db.Queryable().FirstAsync(p => p.Id == id); _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005); var isOk = await _db.Deleteable().Where(d => d.Id == id).ExecuteCommandAsync(); if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002); } /// /// 提交审批(进入第一个节点) /// /// 申请编号 /// [HttpPost("{id}/Actions/SubmitApproval")] public async Task SubmitApproval(string id) { var entity = await _db.Queryable().FirstAsync(p => p.Id == id); _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005); // 允许"待审批"和"已退回"状态的申请提交审批 if (entity.CurrentNodeOrder != 0 && entity.ApprovalStatus != "已退回") { throw new Exception("该申请已经提交审批,不能重复提交"); } if (entity.NodeCount == null || entity.NodeCount < 3 || entity.NodeCount > 5) { throw new Exception("节点配置异常,无法提交审批"); } try { _db.BeginTran(); // 获取第一个节点 var firstNode = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == 1) .FirstAsync(); if (firstNode == null) { throw new Exception("未找到第一个审批节点配置"); } // 更新报销申请状态 entity.CurrentNodeOrder = 1; entity.CurrentNodeId = firstNode.Id; entity.ApprovalStatus = "审批中"; await _db.Updateable(entity).ExecuteCommandAsync(); // 为第一个节点的每个审批人创建待审批记录 var firstNodeApprovers = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == 1) .ToListAsync(); foreach (var approver in firstNodeApprovers) { var record = new LqReimbursementApprovalRecordEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = id, NodeId = firstNode.Id, NodeOrder = 1, ApproverId = approver.UserId, ApproverName = approver.UserName, ApprovalResult = "待审批", IsCurrentNode = 1, ApprovalTime = null }; await _db.Insertable(record).ExecuteCommandAsync(); } _db.CommitTran(); } catch (Exception) { _db.RollbackTran(); throw; } } /// /// 审批操作(通过/不通过/退回) /// /// 申请编号 /// 审批结果:通过/不通过/退回 /// 审批意见 /// [HttpPost("{id}/Actions/Approve")] public async Task Approve(string id, [FromQuery] string result, [FromQuery] string opinion = "") { var userInfo = await _userManager.GetUserInfo(); var entity = await _db.Queryable().FirstAsync(p => p.Id == id); _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005); if (entity.CurrentNodeOrder == null || entity.CurrentNodeOrder == 0) { throw new Exception("该申请尚未提交审批"); } if (entity.ApprovalStatus != "审批中") { throw new Exception($"该申请当前状态为{entity.ApprovalStatus},无法进行审批操作"); } // 验证当前用户是否有审批权限(管理员可以审批所有节点) var isAdmin = userInfo.isAdministrator; if (!isAdmin) { var hasPermission = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder && x.UserId == userInfo.userId) .AnyAsync(); if (!hasPermission) { throw new Exception("您没有当前节点的审批权限"); } } // 检查是否已经审批过 var hasApproved = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder && x.ApproverId == userInfo.userId && x.ApprovalResult != "待审批") .AnyAsync(); if (hasApproved) { throw new Exception("您已经审批过该节点"); } try { _db.BeginTran(); // 获取当前节点信息 var currentNode = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder) .FirstAsync(); if (currentNode == null) { throw new Exception("未找到当前节点配置"); } // 更新待审批记录为已审批(如果存在待审批记录) var existingRecord = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder && x.ApproverId == userInfo.userId && x.ApprovalResult == "待审批") .FirstAsync(); if (existingRecord != null) { // 更新现有记录 existingRecord.ApprovalResult = result; existingRecord.ApprovalOpinion = opinion; existingRecord.ApprovalTime = DateTime.Now; await _db.Updateable(existingRecord).ExecuteCommandAsync(); } else { // 创建新记录(如果不存在) var approvalRecord = new LqReimbursementApprovalRecordEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = id, NodeId = currentNode.Id, NodeOrder = entity.CurrentNodeOrder.Value, ApproverId = userInfo.userId, ApproverName = userInfo.userName, ApprovalResult = result, ApprovalOpinion = opinion, ApprovalTime = DateTime.Now, IsCurrentNode = 1 }; await _db.Insertable(approvalRecord).ExecuteCommandAsync(); } // 根据审批结果处理 if (result == "不通过") { // 不通过:审批结束 entity.ApprovalStatus = "未通过"; await _db.Updateable(entity).ExecuteCommandAsync(); // 更新所有购买记录状态为"未通过"(通过ApplicationId关联更新) await _db.Updateable() .SetColumns(it => new LqPurchaseRecordsEntity { ApproveStatus = "未通过", ApproveTime = DateTime.Now, ApproveUser = userInfo.userId }) .Where(it => it.ApplicationId == id) .ExecuteCommandAsync(); } else if (result == "退回") { // 退回:退回到上一节点 if (entity.CurrentNodeOrder == 1) { // 退回到申请人 entity.CurrentNodeOrder = 0; entity.ApprovalStatus = "已退回"; entity.ReturnedNodeOrder = 0; entity.ReturnedReason = opinion; entity.CurrentNodeId = null; } else { // 退回到上一节点 entity.CurrentNodeOrder -= 1; entity.ReturnedNodeOrder = entity.CurrentNodeOrder; entity.ReturnedReason = opinion; // 获取上一节点信息 var prevNode = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder) .FirstAsync(); if (prevNode != null) { entity.CurrentNodeId = prevNode.Id; } // 清除上一节点的所有审批记录(重新审批) await _db.Deleteable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder) .ExecuteCommandAsync(); // 为上一节点的每个审批人创建新的待审批记录 var prevNodeApprovers = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder) .ToListAsync(); foreach (var approver in prevNodeApprovers) { var record = new LqReimbursementApprovalRecordEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = id, NodeId = prevNode.Id, NodeOrder = entity.CurrentNodeOrder.Value, ApproverId = approver.UserId, ApproverName = approver.UserName, ApprovalResult = "待审批", IsCurrentNode = 1, ApprovalTime = null }; await _db.Insertable(record).ExecuteCommandAsync(); } } await _db.Updateable(entity).ExecuteCommandAsync(); } else if (result == "通过") { // 通过:判断是否需要进入下一个节点 bool shouldMoveToNext = false; if (currentNode.ApprovalType == "或签") { // 或签:任意一个审批人通过,立即进入下一个节点 shouldMoveToNext = true; } else // 会签 { // 会签:检查是否所有审批人都已通过 var approvers = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder) .Select(x => x.UserId) .ToListAsync(); var approvedUsers = await _db.Queryable() .Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder && x.ApprovalResult == "通过") .Select(x => x.ApproverId) .Distinct() .ToListAsync(); if (approvers.Count == approvedUsers.Count) { // 所有人都已通过 shouldMoveToNext = true; } } if (shouldMoveToNext) { // 进入下一个节点或完成审批 await MoveToNextNode(id, userInfo.userId); } } _db.CommitTran(); } catch (Exception) { _db.RollbackTran(); throw; } } /// /// 进入下一个节点 /// private async Task MoveToNextNode(string applicationId, string approveUserId) { var entity = await _db.Queryable() .FirstAsync(x => x.Id == applicationId); // 判断是否是最后一个节点 if (entity.CurrentNodeOrder >= entity.NodeCount) { // 审批完成 entity.CurrentNodeOrder = entity.NodeCount + 1; entity.ApprovalStatus = "已通过"; entity.CurrentNodeId = null; await _db.Updateable(entity).ExecuteCommandAsync(); // 更新所有购买记录状态为"已审批" // 通过ApplicationId关联更新,因为PurchaseRecordsId可能为空 await _db.Updateable() .SetColumns(it => new LqPurchaseRecordsEntity { ApproveStatus = "已审批", ApproveTime = DateTime.Now, ApproveUser = approveUserId }) .Where(it => it.ApplicationId == applicationId) .ExecuteCommandAsync(); } else { // 进入下一个节点 entity.CurrentNodeOrder += 1; // 获取下一个节点信息 var nextNode = await _db.Queryable() .Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder) .FirstAsync(); if (nextNode == null) { throw new Exception($"未找到节点{entity.CurrentNodeOrder}的配置"); } entity.CurrentNodeId = nextNode.Id; entity.ApprovalStatus = "审批中"; await _db.Updateable(entity).ExecuteCommandAsync(); // 清除之前的当前节点标记 await _db.Updateable() .SetColumns(it => new LqReimbursementApprovalRecordEntity { IsCurrentNode = 0 }) .Where(it => it.ApplicationId == applicationId) .ExecuteCommandAsync(); // 为下一个节点的每个审批人创建待审批记录 var nextNodeApprovers = await _db.Queryable() .Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder) .ToListAsync(); foreach (var approver in nextNodeApprovers) { var record = new LqReimbursementApprovalRecordEntity { Id = YitIdHelper.NextId().ToString(), ApplicationId = applicationId, NodeId = nextNode.Id, NodeOrder = entity.CurrentNodeOrder.Value, ApproverId = approver.UserId, ApproverName = approver.UserName, ApprovalResult = "待审批", IsCurrentNode = 1, ApprovalTime = null }; await _db.Insertable(record).ExecuteCommandAsync(); } } } /// /// 获取所有待办列表(管理员用,所有待审批的申请) /// /// 查询参数 /// [HttpGet("Actions/AllPendingApproval")] public async Task GetAllPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input) { var sidx = input.sidx == null ? "id" : input.sidx; // 管理员可以查看所有待审批的申请 var query = _db.Queryable() .Where(x => x.ApprovalStatus == "审批中") .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId)) .OrderBy(sidx + " " + input.sort); var total = await query.CountAsync(); var entities = await query.ToPageListAsync(input.currentPage, input.pageSize); // 获取当前审批人信息 var applicationIds = entities.Select(x => x.Id).ToList(); var currentApprovers = new List(); if (applicationIds.Any()) { var approverList = await _db.Queryable() .Where(x => applicationIds.Contains(x.ApplicationId)) .InnerJoin((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder) .Select((u, a) => new { applicationId = a.Id, approverName = u.UserName }) .ToListAsync(); currentApprovers = approverList.Cast().ToList(); } var approverDict = currentApprovers .GroupBy(x => (string)x.applicationId) .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName))); // 组装返回数据 var result = entities.Select(item => new LqReimbursementApplicationListOutput { id = item.Id, applicationUserId = item.ApplicationUserId, applicationUserName = item.ApplicationUserName, applicationStoreId = item.ApplicationStoreId, applicationTime = item.ApplicationTime, amount = item.Amount, approveUser = item.ApproveUser, approveStatus = item.ApprovalStatus ?? item.ApproveStatus, approveTime = item.ApproveTime, purchaseRecordsId = item.PurchaseRecordsId, currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null, currentNodeOrder = item.CurrentNodeOrder, nodeCount = item.NodeCount }).ToList(); return PageResult.SqlSugarPageResult( new SqlSugarPagedList { list = result, pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total } }); } /// /// 获取待审批列表(当前用户作为审批人的申请) /// /// 查询参数 /// [HttpGet("Actions/PendingApproval")] public async Task GetPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input) { var userInfo = await _userManager.GetUserInfo(); var sidx = input.sidx == null ? "id" : input.sidx; // 查询当前用户作为审批人的节点 var userNodeOrders = await _db.Queryable() .Where(x => x.UserId == userInfo.userId) .Select(x => new { x.ApplicationId, x.NodeOrder }) .ToListAsync(); if (!userNodeOrders.Any()) { return PageResult.SqlSugarPageResult( new SqlSugarPagedList { list = new List(), pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = 0 } }); } // 获取用户有权限的申请ID和节点顺序 var userApplications = userNodeOrders .GroupBy(x => x.ApplicationId) .ToDictionary(g => g.Key, g => g.Select(x => x.NodeOrder).ToList()); var applicationIds = userApplications.Keys.ToList(); // 查询这些申请中,当前节点是用户有权限的节点,且状态为"审批中"的申请 var query = _db.Queryable() .Where(x => applicationIds.Contains(x.Id) && x.ApprovalStatus == "审批中") .Where(x => userApplications.ContainsKey(x.Id) && userApplications[x.Id].Contains(x.CurrentNodeOrder ?? 0)) .WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId)) .OrderBy(sidx + " " + input.sort); var total = await query.CountAsync(); var entities = await query.ToPageListAsync(input.currentPage, input.pageSize); // 获取当前审批人信息 var resultApplicationIds = entities.Select(x => x.Id).ToList(); var currentApprovers = new List(); if (resultApplicationIds.Any()) { var approverList = await _db.Queryable() .Where(x => resultApplicationIds.Contains(x.ApplicationId)) .InnerJoin((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder) .Select((u, a) => new { applicationId = a.Id, approverName = u.UserName }) .ToListAsync(); currentApprovers = approverList.Cast().ToList(); } var approverDict = currentApprovers .GroupBy(x => (string)x.applicationId) .ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName))); // 组装返回数据 var result = entities.Select(item => new LqReimbursementApplicationListOutput { id = item.Id, applicationUserId = item.ApplicationUserId, applicationUserName = item.ApplicationUserName, applicationStoreId = item.ApplicationStoreId, applicationTime = item.ApplicationTime, amount = item.Amount, approveUser = item.ApproveUser, approveStatus = item.ApprovalStatus ?? item.ApproveStatus, approveTime = item.ApproveTime, purchaseRecordsId = item.PurchaseRecordsId, currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null, currentNodeOrder = item.CurrentNodeOrder, nodeCount = item.NodeCount }).ToList(); return PageResult.SqlSugarPageResult( new SqlSugarPagedList { list = result, pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total } }); } /// /// 获取审批历史 /// /// 申请编号 /// [HttpGet("{id}/Actions/ApprovalHistory")] public async Task GetApprovalHistory(string id) { // 先查询审批记录 var approvalRecords = await _db.Queryable() .Where(x => x.ApplicationId == id) .OrderBy(x => x.NodeOrder) .OrderBy(x => x.ApprovalTime) .ToListAsync(); // 获取节点信息 if (approvalRecords.Any()) { var nodeIds = approvalRecords.Select(x => x.NodeId).Distinct().ToList(); var nodes = await _db.Queryable() .Where(x => nodeIds.Contains(x.Id)) .ToListAsync(); var nodeDict = nodes.ToDictionary(x => x.Id, x => x.NodeName); // 组装结果 var records = approvalRecords.Select(r => new { nodeOrder = r.NodeOrder, nodeName = nodeDict.ContainsKey(r.NodeId) ? nodeDict[r.NodeId] : null, approverName = r.ApproverName, approvalResult = r.ApprovalResult, approvalOpinion = r.ApprovalOpinion, approvalTime = r.ApprovalTime }).ToList(); return records; } return new List(); } } }