SystemBackgroundService.cs
12.1 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
using HHECS.WorkHourStatistics.Dtos;
using HHECS.WorkHourStatistics.Models;
using NPOI.SS.Formula.Functions;
namespace HHECS.WorkHourStatistics.Service
{
public class SystemBackgroundService : BackgroundService
{
private readonly IFreeSql _freeSql;
private readonly HttpService _httpService;
private readonly ILogger<SystemBackgroundService> _logger;
public SystemBackgroundService(IFreeSql freeSql, HttpService httpService, ILogger<SystemBackgroundService> logger)
{
_freeSql = freeSql;
_httpService = httpService;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var _actionA = DateTime.MinValue;
var _actionB = DateTime.MinValue;
while (!stoppingToken.IsCancellationRequested)
{
try
{
if ((DateTime.Now - _actionA).TotalSeconds >= 8)
{
//生成日期记录
_actionA = DateTime.Now;
GenerateCalendar();
//同步部门数据
var departmentResult = _httpService.GetDepartment();
var oldDepartment = _freeSql.Queryable<Department>().ToList();
if (departmentResult.Success)
{
static string keySelector(Department department) => department.Id;
var addTemps = departmentResult.Data.ExceptBy(oldDepartment.Select(keySelector), keySelector).ToList();
var updateTemps = departmentResult.Data.IntersectBy(oldDepartment.Select(keySelector), keySelector).ToList();
var removeTemps = oldDepartment.ExceptBy(departmentResult.Data.Select(keySelector), keySelector).ToList();
_freeSql.Insert(addTemps).ExecuteAffrows();
_freeSql.Update<Department>().SetSource(updateTemps).ExecuteAffrows();
_freeSql.Delete<Department>().Where(removeTemps).ExecuteAffrows();
}
//同步用户数据
var personResult = _httpService.GetPersons();
var oldPersons = _freeSql.Queryable<Person>().ToList();
if (personResult.Success)
{
static string keySelector(Person person) => person.Id;
var addTemps = personResult.Data.ExceptBy(oldPersons.Select(keySelector), keySelector).ToList();
var updateTemps = personResult.Data.ExceptBy(oldPersons.Select(keySelector), keySelector).ToList();
var removeTemps = oldPersons.ExceptBy(personResult.Data.Select(keySelector), keySelector).ToList();
_freeSql.Insert(addTemps).ExecuteAffrows();
_freeSql.Update<Person>().SetSource(updateTemps).ExecuteAffrows();
_freeSql.Delete<Person>().Where(removeTemps).ExecuteAffrows();
}
var personWorkNo = _freeSql.Queryable<Person>().ToList(x => x.Number);
//同步打卡数据
var calendars = _freeSql.Queryable<CalendarRecord>().Where(x => !x.IsSync && x.Date < DateTime.Today).OrderBy(x => x.Date).ToList();
foreach (var calendar in calendars)
{
var isEmpty = false;
var pageIndex = 1;
var workRecordDtos = new List<WorkRecordDto>();
var currentDate = calendar.Date.ToString("yyyy-MM-dd");
var isOk = false;//是否每页都获取成功
do
{
//打卡接口调用频率 10次/分钟
await Task.Delay(6000, stoppingToken);
var workRecordResult = _httpService.GetWorkRecod(currentDate, pageIndex);
if (!workRecordResult.Success)
{
_freeSql.Update<CalendarRecord>(calendar.Id).Set(x => x.ErrorMessage, workRecordResult.Msg).ExecuteAffrows();
_logger.LogError($"[{currentDate}]考勤数据同步失败:{workRecordResult.Msg}");
isOk = false;
workRecordDtos.Clear();//获取数据失败,则清空,不同步
break;
}
isOk = true;
if (workRecordResult.Data.Count == 0)
{
isEmpty = true;
break;
}
pageIndex++;
//存储
workRecordDtos.AddRange(workRecordResult.Data);
} while (!isEmpty);
if (isOk)
{
if (workRecordDtos.Count != 0)
{
var addTemps = new List<WorkRecord>();
var updateTemps = new List<WorkRecord>();
var oldWorkRecords = _freeSql.Queryable<WorkRecord>().Where(x => x.BaseWorkCard.Date == calendar.Date).ToList();
foreach (var item in workRecordDtos.Where(x => personWorkNo.Contains(x.Number)).GroupBy(x => x.Number))
{
DateTime? workCard = null;
DateTime? offDutyCard = null;
var workCardStr = item.Where(x => x.IsOnWork).Select(x => x.CreateTime).FirstOrDefault();
var offDutyCardStr = item.Where(x => !x.IsOnWork).Select(x => x.CreateTime).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(workCardStr))
{
_ = DateTime.TryParse(workCardStr, out var time);
workCard = time;
}
if (!string.IsNullOrWhiteSpace(offDutyCardStr))
{
_ = DateTime.TryParse(offDutyCardStr, out var time);
offDutyCard = time;
}
var workCardLocationAddress = item.Where(x => x.IsOnWork).Select(x => x.LocationAddress).FirstOrDefault();
var offDutyCardLocationAddress = item.Where(x => !x.IsOnWork).Select(x => x.LocationAddress).FirstOrDefault();
var oldRecord = oldWorkRecords.Where(x => x.Number == item.Key).FirstOrDefault();
if (oldRecord == null)
{
_ = DateTime.TryParse(item.Where(x => x.IsOnWork).Select(x => x.BaseCheckTime).FirstOrDefault(), out var baseWorkCard);
_ = DateTime.TryParse(item.Where(x => !x.IsOnWork).Select(x => x.BaseCheckTime).FirstOrDefault(), out var baseOffDutyCard);
oldRecord = new WorkRecord
{
Number = item.Key,
PersonName = item.Select(x => x.PersonName).First(),
BaseWorkCard = baseWorkCard,
BaseOffDutyCard = baseOffDutyCard,
WorkCard = workCard,
OffDutyCard = offDutyCard,
WorkCardLocationAddress = workCardLocationAddress,
OffDutyCardLocationAddress = offDutyCardLocationAddress,
CreateTime = DateTime.Now,
};
addTemps.Add(oldRecord);
}
else
{
oldRecord.WorkCard = workCard;
oldRecord.OffDutyCard = offDutyCard;
oldRecord.WorkCardLocationAddress = workCardLocationAddress;
oldRecord.OffDutyCardLocationAddress = offDutyCardLocationAddress;
oldRecord.CreateTime = DateTime.Now;
updateTemps.Add(oldRecord);
}
}
_freeSql.Insert(addTemps).ExecuteAffrows();
_freeSql.Update<WorkRecord>().SetSource(updateTemps).UpdateColumns(x => new
{
x.WorkCard,
x.OffDutyCard,
x.WorkCardLocationAddress,
x.OffDutyCardLocationAddress,
x.CreateTime,
}).ExecuteAffrows();
}
_freeSql.Update<CalendarRecord>(calendar.Id)
.Set(x => x.IsSync, true)
.Set(x => x.ErrorMessage, null)
.ExecuteAffrows();
_logger.LogInformation($"[{currentDate}]考勤数据同步完成");
}
}
}
//清理历史数据
if ((DateTime.Now - _actionB).Minutes >= 5)
{
_actionB = DateTime.Now;
_freeSql.Queryable<WorkRecord>().Where(x => x.BaseOffDutyCard < DateTime.Now.AddMonths(-18)).Limit(1000).ToDelete();
}
}
catch (Exception ex)
{
_logger.LogError($"[{nameof(SystemBackgroundService)}]线程异常:{ex.Message}");
}
await Task.Delay(10000, stoppingToken);
}
}
/// <summary>
/// 生成日期记录
/// </summary>
private void GenerateCalendar()
{
try
{
var startDate = _freeSql.Queryable<CalendarRecord>().OrderByDescending(x => x.Date).First(x => x.Date);
if (startDate == default)
{
//无数据,取近三个月的数据
startDate = DateTime.Today.AddMonths(-3);
}
var totalDays = (int)(DateTime.Today - startDate).TotalDays;
var records = Enumerable.Range(1, totalDays - 1).Select(x => new CalendarRecord
{
Date = startDate.AddDays(x),
IsSync = false,
}).ToList();
_freeSql.Insert(records).ExecuteAffrows();
}
catch (Exception ex)
{
_logger.LogError($"生成日期记录出现异常:{ex.Message}");
}
}
}
}