using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NCC.Common.Core.Manager; using NCC.Common.Enum; using NCC.Dependency; using NCC.DynamicApiController; using NCC.Extend.Entitys.Dto.LqAttendanceRecord; using NCC.Extend.Entitys.Dto.LqAttendanceRestSettlement; using NCC.Extend.Entitys.Enum; using NCC.Extend.Entitys.flow_task; using NCC.Extend.Entitys.lq_attendance_group; using NCC.Extend.Entitys.lq_attendance_record; using NCC.Extend.Entitys.lq_attendance_rest_group; using NCC.Extend.Entitys.lq_mdxx; using NCC.Extend.Entitys.wform_leaveapply; using NCC.Extend.Helpers; using NCC.Extend.Interfaces.BusinessOperationLog; using NCC.Extend.Interfaces.LqAttendanceRestSettlement; using NCC.FriendlyException; using NCC.System.Entitys.Permission; using Newtonsoft.Json; using SqlSugar; using Yitter.IdGenerator; namespace NCC.Extend { /// /// 月末应休结算 /// [ApiDescriptionSettings(Tag = "绿纤应休结算", Name = "LqAttendanceRestSettlement", Order = 201)] [Route("api/Extend/[controller]")] [ApiController] public class LqAttendanceRestSettlementService : ILqAttendanceRestSettlementService, IDynamicApiController, ITransient { private const string BizModule = "考勤应休结算"; private const string ActionSettleToPersonal = "应休转事假"; private const string ActionRevertToOriginal = "回归原始打卡数据"; private const int FlowTaskStatusAdopt = 2; private readonly ISqlSugarClient _db; private readonly IUserManager _userManager; private readonly IBusinessOperationLogService _businessOperationLogService; private readonly ILogger _logger; public LqAttendanceRestSettlementService( ISqlSugarClient db, IUserManager userManager, IBusinessOperationLogService businessOperationLogService, ILogger logger) { _db = db; _userManager = userManager; _businessOperationLogService = businessOperationLogService; _logger = logger; } /// /// 预览指定年月应休结算(不落库) /// /// /// 按带薪上班天数÷应休规则 N 计算应得应休,列出将从后往前转事假或改回应休的时段。 /// /// 示例请求: /// `GET /api/Extend/LqAttendanceRestSettlement/Preview?year=2026&month=9&userId=` /// /// 参数说明: /// - year: 年 /// - month: 月 /// - userId: 可选,仅预览该员工 /// /// 年 /// 月 /// 员工ID,可空 /// 预览结果 /// 预览成功 /// 参数错误 /// 服务器错误 [HttpGet("Preview")] public Task Preview( [FromQuery] int year, [FromQuery] int month, [FromQuery] string userId = null, [FromQuery] int? restUnlockCycle = null, [FromQuery] int? monthlyRestDays = null) { return SettleMonthAsync(new AttendanceRestMonthSettlementInput { year = year, month = month, userId = userId, dryRun = true, restUnlockCycle = restUnlockCycle, monthlyRestDays = monthlyRestDays }); } /// /// 结算指定年月应休(未满月仅预览不落库) /// /// /// 按带薪上班天数计算应得应休;未满月按截至当天已有考勤计算,但默认只预览不落库,月末后方可正式结算落库。 /// 已请应休超过应得的,从该月最后应休时段往前改为事假,并回写已通过休假单(整单改假种或拆单)。 /// 之后上班天数增加再结算可改回。未来月份不能落库。dryRun 为 true 时始终不落库。 /// /// 示例请求: /// ```json /// { "year": 2026, "month": 10, "userId": "", "dryRun": true } /// ``` /// /// 参数说明: /// - year: 年 /// - month: 月 /// - userId: 可选 /// - dryRun: true 只预览 /// /// 结算入参 /// 结算结果 /// 成功 /// 参数错误 /// 服务器错误 [HttpPost("Settle")] public Task SettleMonthAsync([FromBody] AttendanceRestMonthSettlementInput input) { return SettleMonthCoreAsync(input); } /// /// 回归原始打卡数据 /// /// /// 撤销指定年月月末应休结算对请假单与考勤关联的改写:假种回休假、删除拆单 JS 单、考勤 JSON/备注按 original* 还原;不删除原始打卡时刻。 /// 对该月每人将 desiredConverted 置 0,已 Converted 段全部走改回逻辑;未满月也可落库(dryRun 为 true 时仍只预览)。 /// /// 示例请求: /// ```json /// { "year": 2026, "month": 10, "userId": "", "dryRun": false } /// ``` /// /// 参数说明: /// - year: 年 /// - month: 月 /// - userId: 可选,仅处理该员工 /// - dryRun: true 只预览不落库 /// /// 年月与可选员工、是否预览 /// 改回段数、涉及人数等汇总 /// 成功 /// 参数错误 /// 服务器错误 [HttpPost("RevertToOriginal")] public Task RevertToOriginalAsync([FromBody] AttendanceRestMonthSettlementInput input) { input ??= new AttendanceRestMonthSettlementInput(); input.forceRevertConverted = true; return SettleMonthCoreAsync(input); } private async Task SettleMonthCoreAsync(AttendanceRestMonthSettlementInput input) { input ??= new AttendanceRestMonthSettlementInput(); if (input.year < 2000 || input.year > 3000) { throw NCCException.Oh("年份参数无效"); } if (input.month < 1 || input.month > 12) { throw NCCException.Oh("月份无效"); } var today = DateTime.Today; var isFutureMonth = input.year > today.Year || (input.year == today.Year && input.month > today.Month); if (isFutureMonth && !input.dryRun && !input.forceRevertConverted) { throw NCCException.Oh("未来月份不能结算应休"); } if (isFutureMonth && !input.dryRun && input.forceRevertConverted) { throw NCCException.Oh("未来月份不能回归原始打卡数据"); } var monthClosed = AttendanceRestMonthSettlementHelper.IsMonthClosed(input.year, input.month, today); var persist = !input.dryRun && !isFutureMonth && (monthClosed || input.forceRevertConverted); var batchActionCode = input.forceRevertConverted ? ActionRevertToOriginal : ActionSettleToPersonal; var monthStart = new DateTime(input.year, input.month, 1); var monthEnd = AttendanceRestMonthSettlementHelper.GetSettleRecordEnd(input.year, input.month, today); var batchId = YitIdHelper.NextId().ToString(); var users = await LoadTargetUsersAsync(input.userId, monthStart, monthEnd); if (input.skipUserIds != null && input.skipUserIds.Count > 0) { var skip = new HashSet( input.skipUserIds.Where(x => !string.IsNullOrWhiteSpace(x)), StringComparer.Ordinal); users = users.Where(x => !skip.Contains(x.Id)).ToList(); } var userResults = new List(); var changedUserCount = 0; var convertedCount = 0; var revertedCount = 0; foreach (var user in users) { var restGroup = await ResolveRestGroupAsync(user); var cycle = restGroup?.RestUnlockCycle ?? 0; var monthlyCap = restGroup?.MonthlyRestDays ?? 0; if (!string.IsNullOrWhiteSpace(input.userId) && input.restUnlockCycle.GetValueOrDefault() > 0) { cycle = input.restUnlockCycle.Value; } if (!string.IsNullOrWhiteSpace(input.userId) && input.monthlyRestDays.GetValueOrDefault() > 0) { monthlyCap = input.monthlyRestDays.Value; } if (cycle <= 0 || monthlyCap < 0) { continue; } var records = await _db.Queryable() .Where(x => x.UserId == user.Id && x.IsEffective == StatusEnum.有效.GetHashCode() && x.AttendanceDate >= monthStart && x.AttendanceDate < monthEnd) .ToListAsync(); var perDay = AttendanceSummaryMonthMetricsHelper.CollapseToLatestPerDay(records); var paidWork = AttendanceRestMonthSettlementHelper.CalcPaidWorkDays(perDay); var entitled = AttendanceRestMonthSettlementHelper.CalcEntitledRestDays(paidWork, cycle, monthlyCap); var segments = AttendanceRestMonthSettlementHelper.CollectRestSegments(perDay); var currentRest = segments.Where(x => !x.Converted).Sum(x => x.Days); var converted = segments.Where(x => x.Converted).Sum(x => x.Days); var desiredConverted = input.forceRevertConverted ? 0m : Math.Max(0m, currentRest + converted - entitled); var actions = BuildActions( segments, desiredConverted, converted, input.year, input.month, paidWork, cycle, monthlyCap, entitled, currentRest + converted); if (actions.Count == 0 && string.IsNullOrWhiteSpace(input.userId)) { continue; } foreach (var action in actions) { if (action.Revert) { revertedCount += 1; } else { convertedCount += 1; } } if (persist && actions.Count > 0) { foreach (var action in actions) { if (action.Revert) { await RevertSegmentAsync(action, batchId); } else { await ConvertSegmentAsync(action, batchId); } } await WriteUserLogAsync( user, input, batchId, batchActionCode, paidWork, cycle, monthlyCap, entitled, currentRest, actions); } if (actions.Count > 0) { changedUserCount += 1; } userResults.Add(new { userId = user.Id, userName = user.RealName, paidWorkDays = paidWork, restUnlockCycle = cycle, monthlyRestDays = monthlyCap, entitledRestDays = entitled, submittedRestDays = currentRest, alreadyConvertedDays = converted, desiredConvertedDays = desiredConverted, actions = actions.Select(x => new { revert = x.Revert, date = x.Date.ToString("yyyy-MM-dd"), halfPeriod = x.HalfPeriod, days = x.Days, leaveApplyId = x.LeaveApplyId, billNo = x.BillNo, reason = x.Reason }).ToList() }); } string summary; if (input.forceRevertConverted) { summary = $"{input.year}年{input.month}月回归原始打卡数据{(persist ? string.Empty : "预览")}:涉及 {changedUserCount} 人," + $"改回 {revertedCount} 段{(input.dryRun ? "(dryRun)" : string.Empty)}"; } else { summary = $"{input.year}年{input.month}月应休结算{(persist ? string.Empty : "预览")}:涉及 {changedUserCount} 人," + $"转事假 {convertedCount} 段,改回 {revertedCount} 段"; } if (persist) { await BusinessOperationLogHelper.SafeWriteAsync( _businessOperationLogService, _logger, BizModule, batchActionCode, "lq_attendance_record", batchId, summary, JsonConvert.SerializeObject(new { input.year, input.month, input.userId, input.dryRun, input.forceRevertConverted, batchId, changedUserCount, convertedCount, revertedCount })); } var message = BuildSettlementMessage( summary, persist, input.dryRun, monthClosed, input.forceRevertConverted, isFutureMonth, today); return new { year = input.year, month = input.month, dryRun = !persist, monthClosed, forceRevertConverted = input.forceRevertConverted, batchId, changedUserCount, convertedCount, revertedCount, message, users = userResults }; } private static string BuildSettlementMessage( string summary, bool persist, bool dryRun, bool monthClosed, bool forceRevertConverted, bool isFutureMonth, DateTime today) { if (isFutureMonth && !dryRun && !persist) { return forceRevertConverted ? $"{summary}。未来月份不能回归原始打卡数据。" : $"{summary}。未来月份不能结算。"; } if (persist) { return summary; } if (dryRun) { return $"{summary}。dryRun 预览,不落库。"; } if (!monthClosed && !forceRevertConverted) { return $"{summary}。未满月仅预览,不落库;按截至 {today:yyyy-MM-dd} 已有考勤计算,月末后方可正式结算。"; } return summary; } private async Task> LoadTargetUsersAsync(string userId, DateTime monthStart, DateTime monthEnd) { if (!string.IsNullOrWhiteSpace(userId)) { return await _db.Queryable() .Where(x => x.Id == userId.Trim() && x.DeleteMark == null) .Select(x => new UserEntity { Id = x.Id, RealName = x.RealName, Mdid = x.Mdid, AttendanceRestGroupId = x.AttendanceRestGroupId }) .ToListAsync(); } var userIds = await _db.Queryable() .Where(x => x.IsEffective == StatusEnum.有效.GetHashCode() && x.AttendanceDate >= monthStart && x.AttendanceDate < monthEnd) .Select(x => x.UserId) .Distinct() .ToListAsync(); if (userIds.Count == 0) { return new List(); } return await _db.Queryable() .Where(x => userIds.Contains(x.Id) && x.DeleteMark == null) .Select(x => new UserEntity { Id = x.Id, RealName = x.RealName, Mdid = x.Mdid, AttendanceRestGroupId = x.AttendanceRestGroupId }) .ToListAsync(); } private async Task ResolveRestGroupAsync(UserEntity user) { if (!string.IsNullOrWhiteSpace(user.AttendanceRestGroupId)) { var byUser = await _db.Queryable() .Where(x => x.Id == user.AttendanceRestGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0) .FirstAsync(); if (byUser != null) { return byUser; } } if (string.IsNullOrWhiteSpace(user.Mdid)) { return null; } var store = await _db.Queryable() .Where(x => x.Id == user.Mdid) .FirstAsync(); if (string.IsNullOrWhiteSpace(store?.AttendanceGroupId)) { return null; } var group = await _db.Queryable() .Where(x => x.Id == store.AttendanceGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0) .FirstAsync(); if (string.IsNullOrWhiteSpace(group?.DefaultRestGroupId)) { return null; } return await _db.Queryable() .Where(x => x.Id == group.DefaultRestGroupId && SqlFunc.IsNull(x.DeleteMark, 0) == 0) .FirstAsync(); } private static List BuildActions( List segments, decimal desiredConverted, decimal alreadyConverted, int year, int month, decimal paidWork, int cycle, decimal monthlyCap, decimal entitled, decimal submittedTotal) { var actions = new List(); var currentConverted = alreadyConverted; if (currentConverted > desiredConverted) { var remain = currentConverted - desiredConverted; foreach (var seg in AttendanceRestMonthSettlementHelper.OrderForRevert(segments.Where(x => x.Converted))) { if (remain <= 0m) { break; } var take = Math.Min(seg.Days, remain); actions.Add(CreateAction(seg, take, true, year, month, paidWork, cycle, monthlyCap, entitled, submittedTotal)); remain -= take; } } else if (currentConverted < desiredConverted) { var remain = desiredConverted - currentConverted; foreach (var seg in AttendanceRestMonthSettlementHelper.OrderForConvert(segments.Where(x => !x.Converted))) { if (remain <= 0m) { break; } var take = Math.Min(seg.Days, remain); actions.Add(CreateAction(seg, take, false, year, month, paidWork, cycle, monthlyCap, entitled, submittedTotal)); remain -= take; } } return actions; } private static SettleAction CreateAction( AttendanceRestMonthSettlementHelper.RestSegment seg, decimal days, bool revert, int year, int month, decimal paidWork, int cycle, decimal monthlyCap, decimal entitled, decimal submittedTotal) { var half = days < seg.Days && seg.HalfPeriod == "full" ? "pm" : seg.HalfPeriod; var excess = Math.Max(0m, submittedTotal - entitled); return new SettleAction { Revert = revert, Date = seg.Date, HalfPeriod = half, Days = days, LeaveApplyId = seg.LeaveApplyId, BillNo = seg.BillNo, Record = seg.Record, Workflow = seg.Workflow, Reason = AttendanceRestMonthSettlementHelper.BuildReason( year, month, paidWork, cycle, monthlyCap, entitled, submittedTotal, excess, seg.Date, half, days, revert ? AttendanceRestMonthSettlementHelper.SettlementReverted : AttendanceRestMonthSettlementHelper.SettlementToPersonal) }; } private async Task ConvertSegmentAsync(SettleAction action, string batchId) { if (action.Record == null) { return; } WformLeaveApplyEntityLite leave = null; if (!string.IsNullOrWhiteSpace(action.LeaveApplyId)) { leave = await _db.Queryable() .Where(x => x.Id == action.LeaveApplyId) .FirstAsync(); } var snapshot = leave == null ? null : new WformLeaveApplyEntityLite { Id = leave.Id, BillNo = leave.BillNo, FlowTitle = leave.FlowTitle, LeaveType = leave.LeaveType, LeaveReason = AttendanceRestMonthSettlementHelper.StripSettlementLines(leave.LeaveReason), LeaveStartTime = leave.LeaveStartTime, LeaveEndTime = leave.LeaveEndTime, LeaveDayCount = leave.LeaveDayCount, LeaveHour = leave.LeaveHour, Description = ParseDays(leave.LeaveDayCount) >= 1m ? AttendanceHalfDayLeaveHelper.StripDayHalfPeriodFromDescription(leave.Description) : leave.Description }; if (snapshot != null && string.IsNullOrWhiteSpace(snapshot.Description)) { snapshot.Description = null; } var split = false; WformLeaveApplyEntityLite newLeave = null; if (leave != null) { var remainDays = ParseDays(leave.LeaveDayCount) - action.Days; if (remainDays > 0m) { split = true; newLeave = await SplitToPersonalAsync(leave, action, batchId); await ShrinkOriginalLeaveAsync(leave, action, remainDays); } else { await ChangeWholeLeaveToPersonalAsync(leave, action); } } await UpdateAttendanceForConvertAsync(action, batchId, snapshot ?? leave, newLeave, split); } private async Task RevertSegmentAsync(SettleAction action, string batchId) { if (action.Record == null || action.Workflow == null) { return; } var wf = action.Workflow; var originalId = !string.IsNullOrWhiteSpace(wf.originalLeaveId) ? wf.originalLeaveId : action.LeaveApplyId; var original = string.IsNullOrWhiteSpace(originalId) ? null : await _db.Queryable().Where(x => x.Id == originalId).FirstAsync(); if (original != null && !string.IsNullOrWhiteSpace(wf.originalLeaveStart)) { original.LeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; original.LeaveStartTime = ParseDateTime(wf.originalLeaveStart) ?? original.LeaveStartTime; original.LeaveEndTime = ParseDateTime(wf.originalLeaveEnd) ?? original.LeaveEndTime; original.LeaveDayCount = string.IsNullOrWhiteSpace(wf.originalLeaveDayCount) ? original.LeaveDayCount : wf.originalLeaveDayCount; original.Description = string.IsNullOrWhiteSpace(wf.originalDescription) ? null : wf.originalDescription; original.LeaveReason = string.IsNullOrWhiteSpace(wf.originalLeaveReason) ? AttendanceRestMonthSettlementHelper.StripSettlementLines(original.LeaveReason) : wf.originalLeaveReason; original.LeaveHour = string.IsNullOrWhiteSpace(wf.originalLeaveHour) ? original.LeaveHour : wf.originalLeaveHour; if (!string.IsNullOrWhiteSpace(wf.originalFlowTitle)) { original.FlowTitle = wf.originalFlowTitle; } await _db.Updateable(original).ExecuteCommandAsync(); await UpdateFlowTitleAsync(original.Id, original.FlowTitle); } else if (original != null) { original.LeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; original.FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType( original.FlowTitle, AttendanceRestMonthSettlementHelper.PersonalLeaveType, AttendanceRestMonthSettlementHelper.RestLeaveType); original.LeaveReason = string.IsNullOrWhiteSpace(wf.originalLeaveReason) ? AttendanceRestMonthSettlementHelper.StripSettlementLines(original.LeaveReason) : wf.originalLeaveReason; await _db.Updateable(original).ExecuteCommandAsync(); await UpdateFlowTitleAsync(original.Id, original.FlowTitle); } if (!string.IsNullOrWhiteSpace(wf.splitNewLeaveId) && wf.splitNewLeaveId != originalId) { await _db.Deleteable() .Where(x => x.Id == wf.splitNewLeaveId) .ExecuteCommandAsync(); await _db.Deleteable() .Where(x => x.Id == wf.splitNewLeaveId) .ExecuteCommandAsync(); } await UpdateAttendanceForRevertAsync(action, batchId, original); } private async Task ChangeWholeLeaveToPersonalAsync(WformLeaveApplyEntityLite leave, SettleAction action) { leave.LeaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType; leave.FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType( leave.FlowTitle, AttendanceRestMonthSettlementHelper.RestLeaveType, AttendanceRestMonthSettlementHelper.PersonalLeaveType); leave.LeaveReason = AttendanceRestMonthSettlementHelper.AppendReason(leave.LeaveReason, action.Reason); await _db.Updateable(leave).ExecuteCommandAsync(); await UpdateFlowTitleAsync(leave.Id, leave.FlowTitle); } private async Task ShrinkOriginalLeaveAsync(WformLeaveApplyEntityLite leave, SettleAction action, decimal remainDays) { if (leave.LeaveEndTime.HasValue && action.Date == leave.LeaveEndTime.Value.Date) { if (action.HalfPeriod == "pm" && action.Days < 1m) { leave.LeaveEndTime = action.Date.AddHours(12); leave.Description = AttendanceHalfDayLeaveHelper.EmbedDayHalfPeriodInDescription( leave.Description, "am"); } else { leave.LeaveEndTime = action.Date.AddDays(-1).AddHours(23).AddMinutes(59); if (remainDays == decimal.Truncate(remainDays)) { leave.Description = AttendanceHalfDayLeaveHelper.StripDayHalfPeriodFromDescription(leave.Description); } } } var originalDays = ParseDays(leave.LeaveDayCount); leave.LeaveDayCount = AttendanceRestMonthSettlementHelper.FormatDays(remainDays); leave.LeaveHour = AttendanceRestMonthSettlementHelper.ScaleLeaveHour( leave.LeaveHour, originalDays, remainDays); await _db.Updateable(leave).ExecuteCommandAsync(); } private async Task SplitToPersonalAsync( WformLeaveApplyEntityLite original, SettleAction action, string batchId) { var newId = YitIdHelper.NextId().ToString(); var billNo = BuildSplitBillNo(original.BillNo); var start = action.HalfPeriod == "pm" ? action.Date.AddHours(13) : action.Date; var end = action.HalfPeriod == "am" ? action.Date.AddHours(12) : action.Date.AddHours(23).AddMinutes(59); var description = AttendanceHalfDayLeaveHelper.EmbedDayHalfPeriodInDescription( $"月末应休结算拆单,原单 {original.BillNo},批次 {batchId}", action.Days < 1m ? action.HalfPeriod : null); var entity = new WformLeaveApplyEntityLite { Id = newId, FlowId = original.FlowId, FlowTitle = AttendanceRestMonthSettlementHelper.ReplaceTitleLeaveType( original.FlowTitle, AttendanceRestMonthSettlementHelper.RestLeaveType, AttendanceRestMonthSettlementHelper.PersonalLeaveType) + "(月末应休结算)", FlowUrgent = original.FlowUrgent, BillNo = billNo, ApplyUser = original.ApplyUser, ApplyDate = DateTime.Now, ApplyDept = original.ApplyDept, ApplyDeptId = original.ApplyDeptId, ApplyPost = original.ApplyPost, LeaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType, LeaveReason = action.Reason, LeaveStartTime = start, LeaveEndTime = end, LeaveDayCount = AttendanceRestMonthSettlementHelper.FormatDays(action.Days), LeaveHour = AttendanceRestMonthSettlementHelper.ScaleLeaveHour( original.LeaveHour, ParseDays(original.LeaveDayCount), action.Days), FileJson = original.FileJson, Description = description }; await _db.Insertable(entity).ExecuteCommandAsync(); var srcTask = await _db.Queryable() .Where(x => x.Id == original.Id && x.DeleteMark == null) .FirstAsync(); if (srcTask != null) { await _db.Insertable(new FlowTaskLiteEntity { Id = newId, ProcessId = newId, EnCode = billNo, FullName = entity.FlowTitle, FlowId = srcTask.FlowId, FlowCode = srcTask.FlowCode, FlowName = srcTask.FlowName, ThisStepId = srcTask.ThisStepId, Status = FlowTaskStatusAdopt, EnabledMark = 1, CreatorTime = DateTime.Now, CreatorUserId = srcTask.CreatorUserId, DeleteMark = null }).ExecuteCommandAsync(); } return entity; } private async Task UpdateAttendanceForConvertAsync( SettleAction action, string batchId, WformLeaveApplyEntityLite original, WformLeaveApplyEntityLite newLeave, bool split) { var record = action.Record; var workflows = AttendanceRestMonthSettlementHelper.ParseRelatedWorkflows(record.RelatedWorkflowsJson); if (workflows.Count == 0 && action.Workflow != null) { workflows.Add(action.Workflow); } var target = FindWorkflow(workflows, action); if (target == null) { target = new RelatedWorkflowItem { type = AttendanceRestMonthSettlementHelper.WorkflowLeaveType, id = original?.Id ?? action.LeaveApplyId, billNo = original?.BillNo ?? action.BillNo, leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType }; workflows.Add(target); } var splitFullToHalf = split && action.Days < 1m && string.Equals(action.HalfPeriod, "pm", StringComparison.Ordinal) && (target.leaveFraction == null || target.leaveFraction >= 1m); if (splitFullToHalf) { var converted = BuildConvertedWorkflow(action, batchId, original, newLeave, split, "pm", 0.5m); converted.flowId = target.flowId; converted.flowCode = target.flowCode; converted.formType = target.formType; converted.flowStatus = target.flowStatus; converted.taskNodeId = target.taskNodeId; converted.originalLeaveFraction = target.leaveFraction ?? 1m; converted.originalHalfPeriod = target.halfPeriod; converted.originalRemark = AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark); target.leaveFraction = 0.5m; target.halfPeriod = "am"; target.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; target.restSettlement = null; target.restSettlementBatchId = null; target.restSettlementReason = null; workflows.Add(converted); } else { FillSettlementSnapshot(target, original, action, batchId, newLeave, split); ApplyConvertedWorkflowFields(target, action, original, newLeave); } record.RelatedWorkflowsJson = JsonConvert.SerializeObject(workflows); var remark = AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark); if (!splitFullToHalf) { remark = AttendanceRestMonthSettlementHelper.ReplaceLeaveTypeInRemark( remark, AttendanceRestMonthSettlementHelper.RestLeaveType, AttendanceRestMonthSettlementHelper.PersonalLeaveType); } record.Remark = AttendanceRestMonthSettlementHelper.AppendReason( remark, AttendanceRestMonthSettlementHelper.ShortAttendanceRemark(action.Reason)); if (record.Remark != null && record.Remark.Length > 500) { record.Remark = record.Remark.Substring(0, 500); } if (record.Status == (int)AttendanceRecordStatusEnum.请假 || record.Status == (int)AttendanceRecordStatusEnum.休息) { record.Status = (int)AttendanceRecordStatusEnum.请假; } record.UpdateTime = DateTime.Now; record.UpdateUserId = _userManager.UserId ?? "system"; await _db.Updateable(record) .UpdateColumns(x => new { x.RelatedWorkflowsJson, x.Remark, x.Status, x.UpdateTime, x.UpdateUserId }) .ExecuteCommandAsync(); } private async Task UpdateAttendanceForRevertAsync( SettleAction action, string batchId, WformLeaveApplyEntityLite original) { var record = action.Record; var workflows = AttendanceRestMonthSettlementHelper.ParseRelatedWorkflows(record.RelatedWorkflowsJson); var target = FindWorkflow(workflows, action); var originalRemark = target?.originalRemark ?? action.Workflow?.originalRemark ?? AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark); if (target != null) { MergeRevertedWorkflow(workflows, target, original, action, batchId); } record.RelatedWorkflowsJson = JsonConvert.SerializeObject(workflows); record.Remark = string.IsNullOrWhiteSpace(originalRemark) ? AttendanceRestMonthSettlementHelper.ReplaceLeaveTypeInRemark( AttendanceRestMonthSettlementHelper.StripSettlementLines(record.Remark), AttendanceRestMonthSettlementHelper.PersonalLeaveType, AttendanceRestMonthSettlementHelper.RestLeaveType) : originalRemark; record.UpdateTime = DateTime.Now; record.UpdateUserId = _userManager.UserId ?? "system"; await _db.Updateable(record) .UpdateColumns(x => new { x.RelatedWorkflowsJson, x.Remark, x.UpdateTime, x.UpdateUserId }) .ExecuteCommandAsync(); } private static void MergeRevertedWorkflow( List workflows, RelatedWorkflowItem target, WformLeaveApplyEntityLite original, SettleAction action, string batchId) { var originalId = original?.Id ?? target.originalLeaveId ?? action.LeaveApplyId; var originalBillNo = original?.BillNo ?? target.originalBillNo ?? action.BillNo; var sibling = workflows.FirstOrDefault(x => x != null && x != target && string.Equals(x.type, AttendanceRestMonthSettlementHelper.WorkflowLeaveType, StringComparison.Ordinal) && (x.id == originalId || x.billNo == originalBillNo) && !string.Equals(x.restSettlement, AttendanceRestMonthSettlementHelper.SettlementToPersonal, StringComparison.Ordinal)); if (sibling != null) { sibling.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; sibling.id = originalId; sibling.billNo = originalBillNo; sibling.leaveFraction = target.originalLeaveFraction ?? 1m; sibling.halfPeriod = string.IsNullOrWhiteSpace(target.originalHalfPeriod) ? null : target.originalHalfPeriod; sibling.restSettlement = AttendanceRestMonthSettlementHelper.SettlementReverted; sibling.restSettlementBatchId = batchId; sibling.restSettlementReason = action.Reason; sibling.splitNewLeaveId = null; sibling.splitNewBillNo = null; sibling.remark = target.originalRemark ?? sibling.remark; workflows.Remove(target); return; } target.leaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; target.id = originalId; target.billNo = originalBillNo; target.leaveFraction = target.originalLeaveFraction ?? target.leaveFraction; target.halfPeriod = string.IsNullOrWhiteSpace(target.originalHalfPeriod) ? (string.Equals(action.HalfPeriod, "full", StringComparison.Ordinal) ? null : target.halfPeriod) : target.originalHalfPeriod; target.restSettlement = AttendanceRestMonthSettlementHelper.SettlementReverted; target.restSettlementBatchId = batchId; target.restSettlementReason = action.Reason; target.splitNewLeaveId = null; target.splitNewBillNo = null; target.remark = target.originalRemark ?? target.remark; } private static RelatedWorkflowItem FindWorkflow(List workflows, SettleAction action) { if (action.Workflow != null) { var byRef = workflows.FirstOrDefault(x => ReferenceEquals(x, action.Workflow)); if (byRef != null) { return byRef; } } return workflows.FirstOrDefault(x => (!string.IsNullOrWhiteSpace(action.LeaveApplyId) && x.id == action.LeaveApplyId) || (!string.IsNullOrWhiteSpace(action.BillNo) && x.billNo == action.BillNo)); } private static void FillSettlementSnapshot( RelatedWorkflowItem target, WformLeaveApplyEntityLite original, SettleAction action, string batchId, WformLeaveApplyEntityLite newLeave, bool split) { target.restSettlement = AttendanceRestMonthSettlementHelper.SettlementToPersonal; target.restSettlementBatchId = batchId; target.restSettlementReason = action.Reason; target.originalLeaveType = AttendanceRestMonthSettlementHelper.RestLeaveType; target.originalLeaveId = original?.Id ?? action.LeaveApplyId; target.originalBillNo = original?.BillNo ?? action.BillNo; target.originalLeaveStart = original?.LeaveStartTime?.ToString("yyyy-MM-dd HH:mm:ss"); target.originalLeaveEnd = original?.LeaveEndTime?.ToString("yyyy-MM-dd HH:mm:ss"); target.originalLeaveDayCount = original?.LeaveDayCount; target.originalDescription = original?.Description; target.originalLeaveReason = original?.LeaveReason; target.originalFlowTitle = original?.FlowTitle; target.originalLeaveHour = original?.LeaveHour; target.originalLeaveFraction = action.Workflow?.leaveFraction ?? target.leaveFraction; target.originalHalfPeriod = action.Workflow?.halfPeriod ?? target.halfPeriod; target.originalRemark = AttendanceRestMonthSettlementHelper.StripSettlementLines(action.Record?.Remark); if (split && newLeave != null) { target.splitNewLeaveId = newLeave.Id; target.splitNewBillNo = newLeave.BillNo; } } private static void ApplyConvertedWorkflowFields( RelatedWorkflowItem target, SettleAction action, WformLeaveApplyEntityLite original, WformLeaveApplyEntityLite newLeave) { target.leaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType; target.leaveFraction = action.Days; target.halfPeriod = action.HalfPeriod == "full" ? null : action.HalfPeriod; target.remark = action.Reason; if (newLeave != null) { target.id = newLeave.Id; target.billNo = newLeave.BillNo; } else if (original != null) { target.id = original.Id; target.billNo = original.BillNo; } } private static RelatedWorkflowItem BuildConvertedWorkflow( SettleAction action, string batchId, WformLeaveApplyEntityLite original, WformLeaveApplyEntityLite newLeave, bool split, string halfPeriod, decimal days) { var item = new RelatedWorkflowItem { type = AttendanceRestMonthSettlementHelper.WorkflowLeaveType, leaveType = AttendanceRestMonthSettlementHelper.PersonalLeaveType, leaveFraction = days, halfPeriod = halfPeriod, remark = action.Reason, time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), id = newLeave?.Id ?? original?.Id, billNo = newLeave?.BillNo ?? original?.BillNo }; FillSettlementSnapshot(item, original, action, batchId, newLeave, split); return item; } private async Task UpdateFlowTitleAsync(string taskId, string title) { if (string.IsNullOrWhiteSpace(taskId) || string.IsNullOrWhiteSpace(title)) { return; } await _db.Updateable() .SetColumns(x => x.FullName == title) .Where(x => x.Id == taskId) .ExecuteCommandAsync(); } private async Task WriteUserLogAsync( UserEntity user, AttendanceRestMonthSettlementInput input, string batchId, string actionCode, decimal paidWork, int cycle, decimal monthlyCap, decimal entitled, decimal submitted, List actions) { var perUserSummary = input.forceRevertConverted ? $"{user.RealName} {input.year}年{input.month}月回归原始打卡数据,改回 {actions.Count(x => x.Revert)} 段" : $"{user.RealName} {input.year}年{input.month}月应休结算,带薪上班 {AttendanceRestMonthSettlementHelper.FormatDays(paidWork)} 天,应得 {AttendanceRestMonthSettlementHelper.FormatDays(entitled)} 天"; await BusinessOperationLogHelper.SafeWriteAsync( _businessOperationLogService, _logger, BizModule, actionCode, "WFORM_LEAVEAPPLY", user.Id, perUserSummary, JsonConvert.SerializeObject(new { batchId, userId = user.Id, userName = user.RealName, input.year, input.month, input.forceRevertConverted, paidWork, cycle, monthlyCap, entitled, submitted, actions = actions.Select(x => new { x.Revert, date = x.Date.ToString("yyyy-MM-dd"), x.HalfPeriod, x.Days, x.LeaveApplyId, x.BillNo, x.Reason }) })); } private static string BuildSplitBillNo(string originalBillNo) { var prefix = string.IsNullOrWhiteSpace(originalBillNo) ? "REST" : originalBillNo.Trim(); return $"{prefix}-JS{DateTime.Now:MMddHHmmss}"; } private static decimal ParseDays(string value) { if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var days) || decimal.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out days)) { return days; } return 0m; } private static DateTime? ParseDateTime(string value) { if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt) || DateTime.TryParse(value, out dt)) { return dt; } return null; } private sealed class SettleAction { public bool Revert { get; set; } public DateTime Date { get; set; } public string HalfPeriod { get; set; } public decimal Days { get; set; } public string LeaveApplyId { get; set; } public string BillNo { get; set; } public string Reason { get; set; } public LqAttendanceRecordEntity Record { get; set; } public RelatedWorkflowItem Workflow { get; set; } } } }