AttendanceSummaryMonthMetricsHelper.cs
27.8 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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 AttendanceSummaryMonthMetricsHelper
{
private const string PersonalLeaveType = "事假";
private const string SickLeaveType = "病假";
/// <summary>
/// 单月扩展指标
/// </summary>
public sealed class MonthMetrics
{
/// <summary>应休天数(考勤组月应休额度,优先取当月打卡规则快照中的分组配置)</summary>
public decimal EntitledRestDays { get; set; }
/// <summary>到岗天数(正常+迟到)</summary>
public decimal OnDutyDays { get; set; }
/// <summary>工作天数(应休+到岗)</summary>
public decimal CompositeWorkDays { get; set; }
/// <summary>带薪请假天数(请假状态中假种非事假、非病假;不含病假状态)</summary>
public decimal PaidLeaveDays { get; set; }
/// <summary>请假天数(请假+病假状态合计)</summary>
public decimal LeaveDaysTotal { get; set; }
/// <summary>迟到或早退分钟大于 0 的天数</summary>
public decimal LateEarlyDays { get; set; }
/// <summary>旷工天数</summary>
public decimal AbsenteeismDays { get; set; }
/// <summary>补卡天数(含流程补卡与后台补卡)</summary>
public decimal SupplementDays { get; set; }
/// <summary>未放行补卡天数(补卡且 SupplementCountAsNormal != 1)</summary>
public decimal BlockingSupplementDays { get; set; }
/// <summary>补卡维度是否可算全勤(无未放行补卡日)</summary>
public bool IsFullAttendanceEligible { get; set; } = true;
/// <summary>迟到/早退规则为「固定金额」时,自 F_RuleSnapshotJson 汇总</summary>
public decimal LateDeductionAmount { get; set; }
/// <summary>事假/病假扣款依赖日薪×倍率;未传日薪时为 0</summary>
public decimal LeaveDeductionAmount { get; set; }
/// <summary>旷工规则为「固定金额」时,自 F_AllRuleSnapshotJson 的旷工规则表取首条匹配单日区间</summary>
public decimal AbsenteeismDeductionAmount { get; set; }
/// <summary>缺卡次数(当月补卡上班/下班各计 1 次)</summary>
public int MissingCardCount { get; set; }
/// <summary>缺卡扣款金额(按忘记打卡规则阶梯:总次数×每次扣款)</summary>
public decimal MissingCardDeductionAmount { get; set; }
}
/// <summary>
/// 按用户当月有效打卡记录计算扩展指标(须已按日折叠为每日一条,与汇总同步口径一致)。
/// </summary>
/// <param name="perDayRecords">该用户该月「每日一条」记录</param>
/// <param name="fallbackMonthlyRestDays">无快照时的月应休兜底(主档分组)</param>
/// <param name="dailySalaryForLeaveDeduct">日薪;为空则请假扣款金额为 0</param>
/// <param name="punchTargetsJsonByWorkflowId">流程补卡申请单 F_PUNCHTARGETSJSON,键为流程/表单 ID</param>
public static MonthMetrics Compute(
IReadOnlyList<LqAttendanceRecordEntity> perDayRecords,
int fallbackMonthlyRestDays,
decimal? dailySalaryForLeaveDeduct = null,
IReadOnlyDictionary<string, string> punchTargetsJsonByWorkflowId = null)
{
var metrics = new MonthMetrics();
if (perDayRecords == null || perDayRecords.Count == 0)
{
metrics.EntitledRestDays = fallbackMonthlyRestDays;
metrics.CompositeWorkDays = metrics.EntitledRestDays + metrics.OnDutyDays;
return metrics;
}
var entitled = TryResolveMonthlyRestDays(perDayRecords, fallbackMonthlyRestDays);
metrics.EntitledRestDays = entitled;
decimal? leaveRate = null;
decimal? sickRate = null;
foreach (var r in perDayRecords)
{
TryReadBaseLeaveRates(r.AllRuleSnapshotJson, ref leaveRate, ref sickRate);
}
foreach (var r in perDayRecords)
{
var st = r.Status;
if (st == (int)AttendanceRecordStatusEnum.正常 || st == (int)AttendanceRecordStatusEnum.迟到)
{
metrics.OnDutyDays += 1;
}
if (st == (int)AttendanceRecordStatusEnum.请假)
{
metrics.LeaveDaysTotal += 1;
var lt = ResolveLeaveType(r);
if (IsPaidLeaveCategory(lt))
{
metrics.PaidLeaveDays += 1;
}
if (dailySalaryForLeaveDeduct.HasValue && leaveRate.HasValue
&& string.Equals(lt, PersonalLeaveType, StringComparison.Ordinal))
{
metrics.LeaveDeductionAmount += dailySalaryForLeaveDeduct.Value * leaveRate.Value;
}
}
else if (st == (int)AttendanceRecordStatusEnum.病假)
{
metrics.LeaveDaysTotal += 1;
if (dailySalaryForLeaveDeduct.HasValue && sickRate.HasValue)
{
metrics.LeaveDeductionAmount += dailySalaryForLeaveDeduct.Value * sickRate.Value;
}
}
if (r.LateMinutes > 0 || r.EarlyLeaveMinutes > 0)
{
metrics.LateEarlyDays += 1;
}
if (st == (int)AttendanceRecordStatusEnum.旷工)
{
metrics.AbsenteeismDays += 1;
}
if (IsSupplementRecord(r))
{
metrics.SupplementDays += 1;
if (!IsSupplementCountAsNormal(r))
{
metrics.BlockingSupplementDays += 1;
}
}
metrics.LateDeductionAmount += TrySumFixedLateEarlyDeduction(r);
if (st == (int)AttendanceRecordStatusEnum.旷工)
{
metrics.AbsenteeismDeductionAmount += TryPickFixedAbsenteeismDeduction(r.AllRuleSnapshotJson);
}
}
metrics.CompositeWorkDays = metrics.EntitledRestDays + metrics.OnDutyDays;
metrics.IsFullAttendanceEligible = metrics.BlockingSupplementDays <= 0
&& !perDayRecords.Any(HasHalfDayLeaveWorkflow);
foreach (var r in perDayRecords)
{
metrics.MissingCardCount += CountSupplementPunchSlots(r, punchTargetsJsonByWorkflowId);
}
string allJsonForMissingCard = null;
foreach (var r in perDayRecords.OrderByDescending(x => x.AttendanceDate))
{
if (!string.IsNullOrWhiteSpace(r.AllRuleSnapshotJson))
{
allJsonForMissingCard = r.AllRuleSnapshotJson;
break;
}
}
metrics.MissingCardDeductionAmount = CalcMissingCardDeduction(metrics.MissingCardCount, allJsonForMissingCard);
return metrics;
}
/// <summary>
/// 统计单条补卡记录新增的打卡次数(上班、下班各计 1 次)。
/// </summary>
public static int CountSupplementPunchSlots(
LqAttendanceRecordEntity record,
IReadOnlyDictionary<string, string> punchTargetsJsonByWorkflowId)
{
if (!IsSupplementRecord(record))
{
return 0;
}
var fromAdjust = TryCountSupplementSlotsFromAdjustDetail(record.AdjustDetailJson);
if (fromAdjust.HasValue)
{
return fromAdjust.Value;
}
var json = ResolvePunchTargetsJson(record, punchTargetsJsonByWorkflowId);
if (!string.IsNullOrWhiteSpace(json))
{
return CountSupplementSlotsFromPunchTargets(json, record.AttendanceDate);
}
return 0;
}
/// <summary>
/// 按忘记打卡规则阶梯计算缺卡扣款:匹配区间后 总次数×每次扣款金额。
/// </summary>
public static decimal CalcMissingCardDeduction(int totalCount, string allRuleSnapshotJson)
{
if (totalCount <= 0 || string.IsNullOrWhiteSpace(allRuleSnapshotJson))
{
return 0m;
}
try
{
var o = JObject.Parse(allRuleSnapshotJson);
var arr = o["allRules"]?["missingCardRules"] as JArray;
if (arr == null || arr.Count == 0)
{
return 0m;
}
foreach (var token in arr)
{
var minCount = token["minCount"]?.Value<int?>() ?? 1;
var maxCount = token["maxCount"]?.Value<int?>();
if (totalCount < minCount)
{
continue;
}
if (maxCount.HasValue && totalCount >= maxCount.Value)
{
continue;
}
var deductPerTime = token["deductPerTime"]?.Value<decimal?>() ?? 0m;
return totalCount * deductPerTime;
}
}
catch
{
// ignore
}
return 0m;
}
/// <summary>
/// 补卡维度整月是否可算全勤(当月任一未放行补卡日则否)。
/// </summary>
public static bool IsFullAttendanceEligible(IReadOnlyList<LqAttendanceRecordEntity> perDayRecords)
{
if (perDayRecords == null || perDayRecords.Count == 0)
{
return true;
}
foreach (var r in perDayRecords)
{
if (IsSupplementRecord(r) && !IsSupplementCountAsNormal(r))
{
return false;
}
if (HasHalfDayLeaveWorkflow(r))
{
return false;
}
}
return true;
}
/// <summary>
/// 当日是否存在半天假流程(半天假不计全勤)。
/// </summary>
public static bool HasHalfDayLeaveWorkflow(LqAttendanceRecordEntity record)
{
var workflows = ParseRelatedWorkflows(record?.RelatedWorkflowsJson);
return workflows.Any(x => x != null
&& x.type == "请假"
&& x.leaveFraction.HasValue
&& x.leaveFraction.Value > 0m
&& x.leaveFraction.Value < 1m);
}
/// <summary>
/// 是否为补卡日(勿仅用 IsManual:请假同步也会置 1)。
/// </summary>
public static bool IsSupplementRecord(LqAttendanceRecordEntity record)
{
if (record == null)
{
return false;
}
if (record.SupplementTime.HasValue)
{
return true;
}
if (!string.IsNullOrWhiteSpace(record.SupplementWorkflowId))
{
return true;
}
if (!string.IsNullOrWhiteSpace(record.SupplementRemark)
&& (!string.IsNullOrWhiteSpace(record.SupplementOperatorId)
|| !string.IsNullOrWhiteSpace(record.SupplementOperatorName)))
{
return true;
}
var workflows = ParseRelatedWorkflows(record.RelatedWorkflowsJson);
return workflows.Any(x => x != null && x.type == "补卡");
}
/// <summary>
/// 补卡日是否已放行按正常考勤计入全勤。
/// </summary>
public static bool IsSupplementCountAsNormal(LqAttendanceRecordEntity record)
{
return record != null && record.SupplementCountAsNormal == 1;
}
/// <summary>
/// 将原始当月记录按日取最新一条(UpdateTime 优先)。
/// </summary>
public static List<LqAttendanceRecordEntity> CollapseToLatestPerDay(
IEnumerable<LqAttendanceRecordEntity> monthRecords)
{
var list = monthRecords?.Where(x => x != null).ToList() ?? new List<LqAttendanceRecordEntity>();
return list
.GroupBy(x => x.AttendanceDate.Date)
.Select(g => g.OrderByDescending(x => x.UpdateTime ?? x.CreateTime ?? DateTime.MinValue).First())
.OrderBy(x => x.AttendanceDate)
.ToList();
}
private static int TryResolveMonthlyRestDays(
IReadOnlyList<LqAttendanceRecordEntity> perDayRecords,
int fallback)
{
foreach (var r in perDayRecords.OrderByDescending(x => x.AttendanceDate))
{
var v = TryGetMonthlyRestFromRuleSnapshot(r.RuleSnapshotJson);
if (v.HasValue)
{
return Math.Max(0, v.Value);
}
}
return Math.Max(0, fallback);
}
private static int? TryGetMonthlyRestFromRuleSnapshot(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
var o = JObject.Parse(json);
var rg = o["restGroup"];
var fromRest = rg?["monthlyRestDays"]?.Value<int?>();
if (fromRest.HasValue)
{
return fromRest;
}
var ag = o["attendanceGroup"];
return ag?["monthlyRestDays"]?.Value<int?>();
}
catch
{
return null;
}
}
private static void TryReadBaseLeaveRates(
string allJson,
ref decimal? leaveRate,
ref decimal? sickRate)
{
if (string.IsNullOrWhiteSpace(allJson) || (leaveRate.HasValue && sickRate.HasValue))
{
return;
}
try
{
var o = JObject.Parse(allJson);
var bs = o["baseSetting"];
if (bs == null)
{
return;
}
if (!leaveRate.HasValue)
{
leaveRate = bs["leaveDeductDailySalaryRate"]?.Value<decimal?>();
}
if (!sickRate.HasValue)
{
sickRate = bs["sickLeaveDeductDailySalaryRate"]?.Value<decimal?>();
}
}
catch
{
// ignore
}
}
private static decimal TrySumFixedLateEarlyDeduction(LqAttendanceRecordEntity r)
{
if (string.IsNullOrWhiteSpace(r?.RuleSnapshotJson))
{
return 0m;
}
try
{
var o = JObject.Parse(r.RuleSnapshotJson);
decimal sum = 0;
if (r.LateMinutes > 0)
{
sum += ReadFixedDeductAmount(o["lateRule"]);
}
if (r.EarlyLeaveMinutes > 0)
{
sum += ReadFixedDeductAmount(o["earlyLeaveRule"]);
}
return sum;
}
catch
{
return 0m;
}
}
private static decimal ReadFixedDeductAmount(JToken rule)
{
if (rule == null || rule.Type == JTokenType.Null)
{
return 0m;
}
var mode = rule["deductMode"]?.Value<int?>();
if (mode != (int)AttendanceDeductModeEnum.FixedAmount)
{
return 0m;
}
return rule["deductValue"]?.Value<decimal?>() ?? 0m;
}
private static decimal TryPickFixedAbsenteeismDeduction(string allJson)
{
if (string.IsNullOrWhiteSpace(allJson))
{
return 0m;
}
try
{
var o = JObject.Parse(allJson);
var arr = o["allRules"]?["absenteeismRules"] as JArray;
if (arr == null)
{
return 0m;
}
foreach (var token in arr)
{
var minDays = token["minDays"]?.Value<decimal?>() ?? 1m;
var maxDays = token["maxDays"]?.Value<decimal?>();
if (minDays > 1m)
{
continue;
}
if (maxDays.HasValue && maxDays.Value <= 1m)
{
continue;
}
var mode = token["deductMode"]?.Value<int?>();
if (mode != (int)AttendanceDeductModeEnum.FixedAmount)
{
continue;
}
return token["deductValue"]?.Value<decimal?>() ?? 0m;
}
}
catch
{
// ignore
}
return 0m;
}
private static string ResolveLeaveType(LqAttendanceRecordEntity r)
{
var workflows = ParseRelatedWorkflows(r.RelatedWorkflowsJson);
var fromWf = workflows
.FirstOrDefault(x => x != null && x.type == "请假" && !string.IsNullOrWhiteSpace(x.leaveType));
if (fromWf != null)
{
return fromWf.leaveType.Trim();
}
return TryGetLeaveTypeLabelFromSyncRemark(r.Remark);
}
private static List<RelatedWorkflowItem> ParseRelatedWorkflows(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new List<RelatedWorkflowItem>();
}
try
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<RelatedWorkflowItem>>(json)
?? new List<RelatedWorkflowItem>();
}
catch
{
return new List<RelatedWorkflowItem>();
}
}
private static string TryGetLeaveTypeLabelFromSyncRemark(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;
}
private static bool IsPaidLeaveCategory(string leaveType)
{
if (string.IsNullOrWhiteSpace(leaveType))
{
return false;
}
if (string.Equals(leaveType, PersonalLeaveType, StringComparison.Ordinal)
|| string.Equals(leaveType, SickLeaveType, StringComparison.Ordinal))
{
return false;
}
return true;
}
private static int? TryCountSupplementSlotsFromAdjustDetail(string adjustDetailJson)
{
if (string.IsNullOrWhiteSpace(adjustDetailJson))
{
return null;
}
try
{
var o = JObject.Parse(adjustDetailJson);
var before = o["before"];
var after = o["after"];
if (before == null || after == null)
{
return null;
}
var count = 0;
if (IsEmptyPunchTimeToken(before["punchInTime"]) && !IsEmptyPunchTimeToken(after["punchInTime"]))
{
count += 1;
}
if (IsEmptyPunchTimeToken(before["punchOutTime"]) && !IsEmptyPunchTimeToken(after["punchOutTime"]))
{
count += 1;
}
return count;
}
catch
{
return null;
}
}
private static bool IsEmptyPunchTimeToken(JToken token)
{
if (token == null || token.Type == JTokenType.Null)
{
return true;
}
return string.IsNullOrWhiteSpace(token.ToString());
}
private static string ResolvePunchTargetsJson(
LqAttendanceRecordEntity record,
IReadOnlyDictionary<string, string> punchTargetsJsonByWorkflowId)
{
if (record == null || punchTargetsJsonByWorkflowId == null || punchTargetsJsonByWorkflowId.Count == 0)
{
return null;
}
if (!string.IsNullOrWhiteSpace(record.SupplementWorkflowId)
&& punchTargetsJsonByWorkflowId.TryGetValue(record.SupplementWorkflowId.Trim(), out var json))
{
return json;
}
var workflows = ParseRelatedWorkflows(record.RelatedWorkflowsJson);
foreach (var wf in workflows.Where(x => x != null && x.type == "补卡"))
{
if (!string.IsNullOrWhiteSpace(wf.id)
&& punchTargetsJsonByWorkflowId.TryGetValue(wf.id.Trim(), out json))
{
return json;
}
}
return null;
}
private static int CountSupplementSlotsFromPunchTargets(string punchTargetsJson, DateTime attendanceDate)
{
var lines = ParsePunchApplyTargetLinesFromJson(punchTargetsJson);
var line = FindPunchApplyLineForDate(lines, attendanceDate.Date);
if (line == null)
{
return 0;
}
var count = 0;
if (line.punchIn)
{
count += 1;
}
if (line.punchOut)
{
count += 1;
}
return count;
}
private static List<PunchApplyTargetLineLite> ParsePunchApplyTargetLinesFromJson(string json)
{
var list = new List<PunchApplyTargetLineLite>();
if (string.IsNullOrWhiteSpace(json))
{
return list;
}
try
{
var token = JToken.Parse(json.Trim());
JArray arr = null;
if (token.Type == JTokenType.Array)
{
arr = (JArray)token;
}
else if (token is JObject jo)
{
if (jo["punchTargets"] is JArray a1)
{
arr = a1;
}
else if (jo["targets"] is JArray a2)
{
arr = a2;
}
else if (jo["data"] is JArray a3)
{
arr = a3;
}
}
if (arr != null)
{
foreach (var item in arr)
{
if (item == null || item.Type != JTokenType.Object)
{
continue;
}
var o = (JObject)item;
var dateStr = (string)o["date"] ?? (string)o["Date"];
var punchIn = o["punchIn"]?.Value<bool>() ?? o["PunchIn"]?.Value<bool>() ?? false;
var punchOut = o["punchOut"]?.Value<bool>() ?? o["PunchOut"]?.Value<bool>() ?? false;
list.Add(new PunchApplyTargetLineLite
{
date = dateStr,
punchIn = punchIn,
punchOut = punchOut
});
}
}
}
catch
{
// fall through
}
if (list.Count > 0)
{
return list;
}
try
{
return JsonConvert.DeserializeObject<List<PunchApplyTargetLineLite>>(json) ?? new List<PunchApplyTargetLineLite>();
}
catch
{
return list;
}
}
private static PunchApplyTargetLineLite FindPunchApplyLineForDate(
List<PunchApplyTargetLineLite> lines,
DateTime attendanceDay)
{
var effective = lines?.Where(l => l != null && (l.punchIn || l.punchOut)).ToList()
?? new List<PunchApplyTargetLineLite>();
if (effective.Count == 0)
{
return null;
}
var matched = effective.FirstOrDefault(l => MatchPunchApplyLineDate(l.date, attendanceDay));
if (matched != null)
{
return matched;
}
if (effective.Count != 1)
{
return null;
}
var only = effective[0];
if (string.IsNullOrWhiteSpace(only.date))
{
return only;
}
if (!TryParseLineDateFlexible(only.date, out var parsed))
{
return only;
}
return parsed.Date == attendanceDay.Date ? only : null;
}
private static bool MatchPunchApplyLineDate(string lineDate, DateTime attendanceDay)
{
if (string.IsNullOrWhiteSpace(lineDate))
{
return false;
}
return TryParseLineDateFlexible(lineDate, out var d) && d.Date == attendanceDay.Date;
}
private static bool TryParseLineDateFlexible(string lineDate, out DateTime parsed)
{
parsed = default;
if (string.IsNullOrWhiteSpace(lineDate))
{
return false;
}
var t = lineDate.Trim();
var formats = new[]
{
"yyyy-MM-dd",
"yyyy/MM/dd",
"yyyy/M/d",
"yyyy/MM/d",
"yyyy-M-d",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.fff"
};
foreach (var fmt in formats)
{
if (DateTime.TryParseExact(t, fmt, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out parsed))
{
return true;
}
}
return DateTime.TryParse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out parsed);
}
private sealed class PunchApplyTargetLineLite
{
public string date { get; set; }
public bool punchIn { get; set; }
public bool punchOut { get; set; }
}
}
}