AttendanceRestMonthSettlementHelper.cs 20 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NCC.Extend.Entitys.Dto.LqAttendanceRecord;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_attendance_record;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NCC.Extend
{
    /// <summary>
    /// 月末应休结算口径:带薪上班天数换应得应休,超额应休从后往前转事假。
    /// </summary>
    public static class AttendanceRestMonthSettlementHelper
    {
        public const string RestLeaveType = "休假";
        public const string RestLeaveTypeAlias = "应休";
        public const string PersonalLeaveType = "事假";
        public const string SickLeaveType = "病假";
        public const string AnnualLeaveType = "年假";
        public const string MarriageLeaveType = "婚假";
        public const string FuneralLeaveType = "丧假";
        public const string WelfareLeaveType = "福利假";
        public const string MaternityLeaveType = "产假";
        public const string SettlementToPersonal = "toPersonal";
        public const string SettlementReverted = "reverted";
        public const string WorkflowLeaveType = "请假";

        /// <summary>应休时段(含已转事假的原应休)。</summary>
        public sealed class RestSegment
        {
            public DateTime Date { get; set; }

            /// <summary>am / pm / full</summary>
            public string HalfPeriod { get; set; }

            public decimal Days { get; set; }

            public string LeaveApplyId { get; set; }

            public string BillNo { get; set; }

            public string LeaveType { get; set; }

            public bool Converted { get; set; }

            public LqAttendanceRecordEntity Record { get; set; }

            public RelatedWorkflowItem Workflow { get; set; }
        }

        /// <summary>
        /// 带薪上班天数:到岗(正常/迟到/公休已打卡)+ 年/婚/丧/福利/产假;应休、事假、病假、旷工、缺卡不计。
        /// </summary>
        public static decimal CalcPaidWorkDays(IReadOnlyList<LqAttendanceRecordEntity> perDayRecords)
        {
            decimal total = 0m;
            if (perDayRecords == null)
            {
                return total;
            }

            foreach (var record in perDayRecords)
            {
                if (record == null)
                {
                    continue;
                }

                var day = 0m;
                var status = record.Status;
                var leaveItems = ParseLeaveWorkflows(record.RelatedWorkflowsJson);
                var paidLeave = 0m;
                var unpaidLeave = 0m;
                foreach (var item in leaveItems)
                {
                    var fraction = ResolveItemDays(item);
                    if (IsPaidWorkLeaveType(item.leaveType))
                    {
                        paidLeave += fraction;
                    }
                    else if (IsUnpaidLeaveType(item.leaveType))
                    {
                        unpaidLeave += fraction;
                    }
                }

                if (leaveItems.Count == 0)
                {
                    var remarkType = TryGetLeaveTypeFromRemark(record.Remark);
                    if (IsPaidWorkLeaveType(remarkType))
                    {
                        paidLeave = status == (int)AttendanceRecordStatusEnum.请假
                            || status == (int)AttendanceRecordStatusEnum.病假
                            ? 1m
                            : 0m;
                    }
                    else if (IsUnpaidLeaveType(remarkType)
                        || status == (int)AttendanceRecordStatusEnum.病假)
                    {
                        unpaidLeave = 1m;
                    }
                }

                var isOnDuty = status == (int)AttendanceRecordStatusEnum.正常
                    || status == (int)AttendanceRecordStatusEnum.迟到
                    || IsWorkedRestDay(record);
                if (isOnDuty)
                {
                    day += Math.Max(0m, 1m - unpaidLeave);
                }

                day += paidLeave;
                if (day > 1m)
                {
                    day = 1m;
                }

                total += day;
            }

            return total;
        }

        /// <summary>实际应得应休:min(月应休上限, 向下取整(带薪上班÷N))。</summary>
        public static decimal CalcEntitledRestDays(decimal paidWorkDays, int restUnlockCycle, decimal monthlyCap)
        {
            var cap = Math.Max(0m, monthlyCap);
            if (restUnlockCycle <= 0)
            {
                return cap;
            }

            var earned = Math.Floor(paidWorkDays / restUnlockCycle);
            return Math.Min(cap, Math.Max(0m, earned));
        }

        /// <summary>已提交应休(仅假种休假/应休,不含公休、不含已转事假)。</summary>
        public static decimal CalcSubmittedRestLeaveDays(IReadOnlyList<LqAttendanceRecordEntity> perDayRecords)
        {
            return CollectRestSegments(perDayRecords).Where(x => !x.Converted).Sum(x => x.Days);
        }

        public static List<RestSegment> CollectRestSegments(IReadOnlyList<LqAttendanceRecordEntity> perDayRecords)
        {
            var list = new List<RestSegment>();
            if (perDayRecords == null)
            {
                return list;
            }

            foreach (var record in perDayRecords.Where(x => x != null).OrderBy(x => x.AttendanceDate))
            {
                var items = ParseLeaveWorkflows(record.RelatedWorkflowsJson);
                if (items.Count == 0)
                {
                    var remarkType = TryGetLeaveTypeFromRemark(record.Remark);
                    if (IsRestLeaveType(remarkType)
                        || (record.Status == (int)AttendanceRecordStatusEnum.请假 && IsRestLeaveType(remarkType)))
                    {
                        if (IsRestLeaveType(remarkType))
                        {
                            list.Add(new RestSegment
                            {
                                Date = record.AttendanceDate.Date,
                                HalfPeriod = "full",
                                Days = 1m,
                                LeaveType = RestLeaveType,
                                Record = record
                            });
                        }
                    }

                    continue;
                }

                foreach (var item in items)
                {
                    var converted = string.Equals(item.restSettlement, SettlementToPersonal, StringComparison.Ordinal);
                    if (!converted && !IsRestLeaveType(item.leaveType))
                    {
                        continue;
                    }

                    if (converted && !IsPersonalLeaveType(item.leaveType) && !IsRestLeaveType(item.originalLeaveType))
                    {
                        continue;
                    }

                    if (!converted && !IsRestLeaveType(item.leaveType))
                    {
                        continue;
                    }

                    list.Add(new RestSegment
                    {
                        Date = record.AttendanceDate.Date,
                        HalfPeriod = NormalizeHalfPeriod(item.halfPeriod, item.leaveFraction),
                        Days = ResolveItemDays(item),
                        LeaveApplyId = item.id,
                        BillNo = item.billNo,
                        LeaveType = string.IsNullOrWhiteSpace(item.leaveType) ? RestLeaveType : item.leaveType.Trim(),
                        Converted = converted,
                        Record = record,
                        Workflow = item
                    });
                }
            }

            return list;
        }

        public static IEnumerable<RestSegment> OrderForConvert(IEnumerable<RestSegment> segments)
        {
            return (segments ?? Enumerable.Empty<RestSegment>())
                .OrderByDescending(x => x.Date)
                .ThenByDescending(x => HalfSort(x.HalfPeriod));
        }

        public static IEnumerable<RestSegment> OrderForRevert(IEnumerable<RestSegment> segments)
        {
            return (segments ?? Enumerable.Empty<RestSegment>())
                .OrderBy(x => x.Date)
                .ThenBy(x => HalfSort(x.HalfPeriod));
        }

        public static int TryResolveRestUnlockCycle(
            IReadOnlyList<LqAttendanceRecordEntity> perDayRecords,
            int fallbackRestUnlockCycle = 0)
        {
            if (perDayRecords != null)
            {
                foreach (var record in perDayRecords.OrderByDescending(x => x.AttendanceDate))
                {
                    var cycle = TryGetRestUnlockCycleFromSnapshot(record?.RuleSnapshotJson)
                        ?? TryGetRestUnlockCycleFromSnapshot(record?.AllRuleSnapshotJson);
                    // 快照里写 0 表示当时未启用 N,继续往后找;都没有再用主档兜底
                    if (cycle.GetValueOrDefault() > 0)
                    {
                        return cycle.Value;
                    }
                }
            }

            return Math.Max(0, fallbackRestUnlockCycle);
        }

        public static string BuildReason(
            int year,
            int month,
            decimal paidWorkDays,
            int cycle,
            decimal monthlyCap,
            decimal entitled,
            decimal submitted,
            decimal excess,
            DateTime date,
            string halfPeriod,
            decimal days,
            string action)
        {
            var halfText = halfPeriod == "am" ? "上午" : halfPeriod == "pm" ? "下午" : "全天";
            var actionText = string.Equals(action, SettlementReverted, StringComparison.Ordinal)
                ? "由事假改回应休"
                : "由应休转为事假";
            return
                $"月末应休结算:{year}年{month}月带薪上班 {FormatDays(paidWorkDays)} 天,规则每上满 {cycle} 天计 1 天应休," +
                $"月应休上限 {FormatDays(monthlyCap)} 天,实际应得 {FormatDays(entitled)} 天;" +
                $"已提交应休 {FormatDays(submitted)} 天,超出 {FormatDays(Math.Max(0m, excess))} 天。" +
                $"将 {date:yyyy-MM-dd}({halfText} {FormatDays(days)} 天){actionText}。";
        }

        public static string FormatDays(decimal days)
        {
            return days % 1m == 0m ? days.ToString("0", CultureInfo.InvariantCulture)
                : days.ToString("0.##", CultureInfo.InvariantCulture);
        }

        public static string ShortAttendanceRemark(string reason)
        {
            if (string.IsNullOrWhiteSpace(reason))
            {
                return "月末应休结算:应休转事假";
            }

            var text = reason.Trim();
            return text.Length <= 180 ? text : text.Substring(0, 180);
        }

        public static bool IsRestLeaveType(string leaveType)
        {
            return string.Equals(leaveType?.Trim(), RestLeaveType, StringComparison.Ordinal)
                || string.Equals(leaveType?.Trim(), RestLeaveTypeAlias, StringComparison.Ordinal);
        }

        public static bool IsPersonalLeaveType(string leaveType)
        {
            return string.Equals(leaveType?.Trim(), PersonalLeaveType, StringComparison.Ordinal);
        }

        public static bool IsMonthClosed(int year, int month, DateTime today)
        {
            var last = new DateTime(year, month, DateTime.DaysInMonth(year, month));
            return today.Date > last;
        }

        /// <summary>结算用考勤截止(不含):未满月截止到明天 0 点,只统计到今天。</summary>
        public static DateTime GetSettleRecordEnd(int year, int month, DateTime today)
        {
            var monthEnd = new DateTime(year, month, 1).AddMonths(1);
            if (today.Date >= monthEnd)
            {
                return monthEnd;
            }

            var nextDay = today.Date.AddDays(1);
            return nextDay < monthEnd ? nextDay : monthEnd;
        }

        public static List<RelatedWorkflowItem> ParseLeaveWorkflows(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return new List<RelatedWorkflowItem>();
            }

            try
            {
                return JsonConvert.DeserializeObject<List<RelatedWorkflowItem>>(json)
                    ?.Where(x => x != null && string.Equals(x.type, WorkflowLeaveType, StringComparison.Ordinal))
                    .ToList()
                    ?? new List<RelatedWorkflowItem>();
            }
            catch
            {
                return new List<RelatedWorkflowItem>();
            }
        }

        public static string ReplaceLeaveTypeInRemark(string remark, string fromType, string toType)
        {
            if (string.IsNullOrWhiteSpace(remark) || string.IsNullOrWhiteSpace(fromType) || string.IsNullOrWhiteSpace(toType))
            {
                return remark;
            }

            return remark.Replace($"请假审批通过:{fromType}", $"请假审批通过:{toType}", StringComparison.Ordinal);
        }

        public static string AppendReason(string current, string reason)
        {
            if (string.IsNullOrWhiteSpace(reason))
            {
                return current;
            }

            if (string.IsNullOrWhiteSpace(current))
            {
                return reason;
            }

            if (current.IndexOf(reason, StringComparison.Ordinal) >= 0)
            {
                return current;
            }

            return current.TrimEnd() + "\n" + reason;
        }

        /// <summary>去掉结算追加行,回滚时还原原始事由/备注。</summary>
        public static string StripSettlementLines(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return text;
            }

            var kept = text
                .Replace("\r\n", "\n")
                .Split('\n')
                .Where(line => !line.TrimStart().StartsWith("月末应休结算", StringComparison.Ordinal))
                .ToArray();
            var result = string.Join("\n", kept).Trim();
            return string.IsNullOrEmpty(result) ? null : result;
        }

        /// <summary>按天数比例折算请假小时。</summary>
        public static string ScaleLeaveHour(string leaveHour, decimal fromDays, decimal toDays)
        {
            if (fromDays <= 0m || toDays < 0m)
            {
                return leaveHour;
            }

            if (!decimal.TryParse(leaveHour, NumberStyles.Any, CultureInfo.InvariantCulture, out var hours)
                && !decimal.TryParse(leaveHour, NumberStyles.Any, CultureInfo.CurrentCulture, out hours))
            {
                return leaveHour;
            }

            return FormatDays(hours * toDays / fromDays);
        }

        public static string ReplaceTitleLeaveType(string title, string fromType, string toType)
        {
            if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(toType))
            {
                return title;
            }

            var result = title;
            if (!string.IsNullOrWhiteSpace(fromType) && result.IndexOf(fromType, StringComparison.Ordinal) >= 0)
            {
                result = result.Replace(fromType, toType, StringComparison.Ordinal);
            }

            if (string.Equals(toType, PersonalLeaveType, StringComparison.Ordinal)
                && result.IndexOf("应休", StringComparison.Ordinal) >= 0
                && result.IndexOf("事假", StringComparison.Ordinal) < 0)
            {
                result = result.Replace("应休", "事假", StringComparison.Ordinal);
            }

            if (string.Equals(toType, RestLeaveType, StringComparison.Ordinal)
                && result.IndexOf("事假申请", StringComparison.Ordinal) >= 0)
            {
                result = result.Replace("事假申请", "应休申请", StringComparison.Ordinal);
            }

            return result;
        }

        public static List<RelatedWorkflowItem> ParseRelatedWorkflows(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return new List<RelatedWorkflowItem>();
            }

            try
            {
                return JsonConvert.DeserializeObject<List<RelatedWorkflowItem>>(json)
                    ?.Where(x => x != null)
                    .ToList()
                    ?? new List<RelatedWorkflowItem>();
            }
            catch
            {
                return new List<RelatedWorkflowItem>();
            }
        }

        private static bool IsPaidWorkLeaveType(string leaveType)
        {
            var t = leaveType?.Trim();
            return string.Equals(t, AnnualLeaveType, StringComparison.Ordinal)
                || string.Equals(t, MarriageLeaveType, StringComparison.Ordinal)
                || string.Equals(t, FuneralLeaveType, StringComparison.Ordinal)
                || string.Equals(t, WelfareLeaveType, StringComparison.Ordinal)
                || string.Equals(t, MaternityLeaveType, StringComparison.Ordinal);
        }

        private static bool IsUnpaidLeaveType(string leaveType)
        {
            return IsRestLeaveType(leaveType)
                || IsPersonalLeaveType(leaveType)
                || string.Equals(leaveType?.Trim(), SickLeaveType, StringComparison.Ordinal);
        }

        private static bool IsWorkedRestDay(LqAttendanceRecordEntity record)
        {
            return record != null
                && record.Status == (int)AttendanceRecordStatusEnum.休息
                && (record.PunchInTime.HasValue || record.PunchOutTime.HasValue);
        }

        private static decimal ResolveItemDays(RelatedWorkflowItem item)
        {
            if (item?.leaveFraction != null && item.leaveFraction.Value > 0m)
            {
                return item.leaveFraction.Value >= 1m ? 1m : 0.5m;
            }

            var half = NormalizeHalfPeriod(item?.halfPeriod, item?.leaveFraction);
            return half == "full" ? 1m : 0.5m;
        }

        private static string NormalizeHalfPeriod(string halfPeriod, decimal? leaveFraction)
        {
            var token = (halfPeriod ?? string.Empty).Trim().ToLowerInvariant();
            if (token == "am" || token == "pm")
            {
                return token;
            }

            if (leaveFraction.HasValue && leaveFraction.Value > 0m && leaveFraction.Value < 1m)
            {
                return "am";
            }

            return "full";
        }

        private static int HalfSort(string halfPeriod)
        {
            return halfPeriod == "pm" ? 2 : halfPeriod == "full" ? 1 : 0;
        }

        private static int? TryGetRestUnlockCycleFromSnapshot(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return null;
            }

            try
            {
                var o = JObject.Parse(json);
                return o["restGroup"]?["restUnlockCycle"]?.Value<int?>()
                    ?? o["currentRestGroup"]?["restUnlockCycle"]?.Value<int?>();
            }
            catch
            {
                return null;
            }
        }

        private static string TryGetLeaveTypeFromRemark(string remark)
        {
            if (string.IsNullOrWhiteSpace(remark))
            {
                return null;
            }

            const string prefix = "请假审批通过:";
            var idx = remark.IndexOf(prefix, StringComparison.Ordinal);
            if (idx < 0)
            {
                return null;
            }

            var tail = remark.Substring(idx + prefix.Length);
            var paren = tail.IndexOf('(');
            if (paren <= 0)
            {
                return null;
            }

            var label = tail.Substring(0, paren).Trim();
            return string.IsNullOrEmpty(label) ? null : label;
        }
    }
}