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
{
///
/// 月末应休结算口径:带薪上班天数换应得应休,超额应休从后往前转事假。
///
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 = "请假";
/// 应休时段(含已转事假的原应休)。
public sealed class RestSegment
{
public DateTime Date { get; set; }
/// am / pm / full
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; }
}
///
/// 带薪上班天数:到岗(正常/迟到/公休已打卡)+ 年/婚/丧/福利/产假;应休、事假、病假、旷工、缺卡不计。
///
public static decimal CalcPaidWorkDays(IReadOnlyList 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;
}
/// 实际应得应休:min(月应休上限, 向下取整(带薪上班÷N))。
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));
}
/// 已提交应休(仅假种休假/应休,不含公休、不含已转事假)。
public static decimal CalcSubmittedRestLeaveDays(IReadOnlyList perDayRecords)
{
return CollectRestSegments(perDayRecords).Where(x => !x.Converted).Sum(x => x.Days);
}
public static List CollectRestSegments(IReadOnlyList perDayRecords)
{
var list = new List();
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 OrderForConvert(IEnumerable segments)
{
return (segments ?? Enumerable.Empty())
.OrderByDescending(x => x.Date)
.ThenByDescending(x => HalfSort(x.HalfPeriod));
}
public static IEnumerable OrderForRevert(IEnumerable segments)
{
return (segments ?? Enumerable.Empty())
.OrderBy(x => x.Date)
.ThenBy(x => HalfSort(x.HalfPeriod));
}
public static int TryResolveRestUnlockCycle(
IReadOnlyList 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;
}
/// 结算用考勤截止(不含):未满月截止到明天 0 点,只统计到今天。
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 ParseLeaveWorkflows(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new List();
}
try
{
return JsonConvert.DeserializeObject>(json)
?.Where(x => x != null && string.Equals(x.type, WorkflowLeaveType, StringComparison.Ordinal))
.ToList()
?? new List();
}
catch
{
return new List();
}
}
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;
}
/// 去掉结算追加行,回滚时还原原始事由/备注。
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;
}
/// 按天数比例折算请假小时。
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 ParseRelatedWorkflows(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new List();
}
try
{
return JsonConvert.DeserializeObject>(json)
?.Where(x => x != null)
.ToList()
?? new List();
}
catch
{
return new List();
}
}
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()
?? o["currentRestGroup"]?["restUnlockCycle"]?.Value();
}
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;
}
}
}