TbPunchService.cs
23.5 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
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Education.Interfaces.TbPunch;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Education.Entitys;
using NCC.Education.Entitys.Dto.TbPunch;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.System.Interfaces.System;
using NCC.System.Entitys.Permission;
using Microsoft.Extensions.Logging;
namespace NCC.Education.TbPunch
{
/// <summary>
/// 打卡记录服务
/// </summary>
[ApiDescriptionSettings(Tag = "打卡记录",Name = "TbPunch", Order = 200)]
[Route("api/Education/[controller]")]
public class TbPunchService : ITbPunchService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository<TbPunchEntity> _tbPunchRepository;
private readonly IDbLinkService _dbLinkService;
private readonly IDataBaseService _dataBaseService;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
private readonly ILogger<TbPunchEntity> _logger;
/// <summary>
/// 初始化一个<see cref="TbPunchService"/>类型的新实例
/// </summary>
public TbPunchService(
ISqlSugarRepository<TbPunchEntity> tbPunchRepository,
IDbLinkService dbLinkService,
IDataBaseService dataBaseService,
IUserManager userManager,
ILogger<TbPunchEntity> logger)
{
_tbPunchRepository = tbPunchRepository;
_db = _tbPunchRepository.Context;
_dbLinkService = dbLinkService;
_dataBaseService = dataBaseService;
_userManager = userManager;
_logger= logger;
}
/// <summary>
/// 查询用户会员到期时间
/// </summary>
/// <returns></returns>
[HttpPost("TaskSchedulerUserType")]
public async Task TaskSchedulerUserType()
{
var list = _db.Queryable<UserEntity>().Where(o => o.IsAdministrator == 0).ToList();
foreach (var item in list)
{
if (item.Type == "2" && item.MemDate.ToDate() < DateTime.Now)
{
item.Type = "1";
item.MemDate = null;
var result = _db.Updateable(item).ExecuteCommand();
_logger.LogInformation($"更改会员用户为普通用户:{result}----{item.ToJson()}");
}
}
}
/// <summary>
/// 每天凌晨过5分判断前一天的时间有那些人没打卡 进行赋值缺卡
/// </summary>
/// <returns></returns>
[HttpPost("TaskSchedulerPunch")]
public async Task TaskSchedulerPunch()
{
var userList = _db.Queryable<UserEntity>().Where(o => o.IsAdministrator == 0).ToList();
List<TbPunchEntity> list = new List<TbPunchEntity>();
foreach (var item in userList)
{
var model = _db.Queryable<TbPunchEntity>().Where(o => SqlFunc.ToDate(o.CreatorTime) == SqlFunc.ToDate(DateTime.Now.AddDays(-1)) && o.UserId == item.Id).First();
if (model == null)
{
list.Add(new TbPunchEntity()
{
Id=YitIdHelper.NextId().ToString(),
UserId=item.Id,
CreatorTime=DateTime.Now,
Type="2",
});
}
}
_logger.LogInformation($"缺卡人数时间汇总为:{list.ToJson()}");
var result = _db.Insertable(list).ExecuteCommand();
_logger.LogInformation($"是否添加了缺卡信息:{result}");
}
/// <summary>
/// 开始打卡入参
/// </summary>
public class OutPutInfo
{
/// <summary>
/// 单次打卡赠送的积分数量
/// </summary>
public int SingleNum { get; set; }
/// <summary>
/// 已连续打卡赠送的积分数量
/// </summary>
public int BothNum { get; set; }
/// <summary>
/// 已连续打卡天数
/// </summary>
public int Days { get; set; }
}
/// <summary>
/// 开始打卡
/// </summary>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPost("StartPunch")]
public async Task<dynamic> StartPunch([FromBody] TbPunchCrInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt<TbPunchEntity>();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
entity.Type = "1";
try
{
_db.BeginTran();
//1.添加打卡记录
var isOk = _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommand();
//2.判断是否有单次打卡赠送对应积分
var model = _db.Queryable<TbSingleSettingEntity>().First();
if (model != null)
{
AddInterateNumSinge(model, entity);
}
//3.判断是否有连续打卡赠送对应积分
int sum = ComputeContinuousDays(entity.UserId);
var bothModel = _db.Queryable<TbBothSettingEntity>().Where(o => o.BothNumber == sum).First();
if (bothModel != null)
{
AddInterateNumBoth(bothModel, entity);
}
_db.CommitTran();
return new OutPutInfo()
{
SingleNum = model.Num.ToInt(),
BothNum =bothModel!=null?bothModel.Num.ToInt():0,
Days = sum
};
}
catch(Exception ex)
{
_logger.LogInformation($"打卡失败:{ex.Message}");
_db.RollbackTran();
throw NCCException.Oh($"打卡失败:{ex.Message}");
}
}
/// <summary>
/// 连续打卡增加积分流程
/// </summary>
private void AddInterateNumBoth(TbBothSettingEntity model, TbPunchEntity entity)
{
//增加用户积分
var result = _db.Updateable<UserEntity>(it => new UserEntity { IntegralNum =SqlFunc.ToInt32(it.IntegralNum) + model.Num }).Where(o => o.Id == entity.UserId).ExecuteCommand();
//增加积分日志
var logResult = _db.Insertable(new TbMoneysLogEntity()
{
Id = YitIdHelper.NextId().ToString(),
UserId = entity.UserId,
Type = "1",
Num = model.Num,
CreatorTime = DateTime.Now
}).ExecuteCommand();
}
/// <summary>
/// 单次打卡增加积分流程
/// </summary>
private void AddInterateNumSinge(TbSingleSettingEntity model, TbPunchEntity entity)
{
//增加用户积分
var result = _db.Updateable<UserEntity>(it => new UserEntity { IntegralNum =SqlFunc.ToInt32(it.IntegralNum)+ model.Num }).Where(o => o.Id == entity.UserId).ExecuteCommand();
//增加积分日志
var logResult = _db.Insertable(new TbMoneysLogEntity()
{
Id = YitIdHelper.NextId().ToString(),
UserId = entity.UserId,
Type = "1",
Num = model.Num,
CreatorTime = DateTime.Now
}).ExecuteCommand();
}
public class ComputeDaysOptions
{
public string UserId { get; set; }
public string CreatorTime { get; set; }
public string date_rank { get; set; }
public string day_cha { get; set; }
}
/// <summary>
/// 判断用户连续打卡多少天
/// </summary>
/// <param name="UserId"></param>
/// <returns></returns>
private int ComputeContinuousDays(string UserId)
{
int sum = 0;
var list = _db.SqlQueryable<ComputeDaysOptions>($" select UserId,CreatorTime , date_rank,(DatePart(Day,CreatorTime)-date_rank) as day_cha from ( select F_UserId as UserId,F_CreatorTime as CreatorTime,ROW_NUMBER() over(partition by F_UserId order by F_CreatorTime) as date_rank from [Antis_Ncc_Education].[dbo].[tb_Punch] where F_Type='1' and F_UserId='{UserId}' ) as t1 order by CreatorTime desc").Select(it=>new ComputeDaysOptions {
UserId=it.UserId,
CreatorTime=it.CreatorTime,
date_rank=it.date_rank,
day_cha=it.day_cha,
}).ToList();
var model = list.First();
if (model == null)
{
return 0;
}
else
{
return list.Where(o => o.day_cha == model.day_cha).Count();
}
}
/// <summary>
/// 获取打卡记录
/// </summary>
/// <param name="id">参数</param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable<TbPunchEntity>().FirstAsync(p => p.Id == id);
var output = entity.Adapt<TbPunchInfoOutput>();
return output;
}
/// <summary>
/// 获取打卡记录列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] TbPunchListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
List<string> queryExerciseDate = input.exerciseDate != null ? input.exerciseDate.Split(',').ToObeject<List<string>>() : null;
DateTime? startExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.First()) : null;
DateTime? endExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.Last()) : null;
List<string> creatorTimeDate = input.creatorTime != null ? input.creatorTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startcreatorTimeDate = creatorTimeDate != null ? Ext.GetDateTime(creatorTimeDate.First()) : null;
DateTime? endcreatorTimeDate = creatorTimeDate != null ? Ext.GetDateTime(creatorTimeDate.Last()) : null;
var data = await _db.Queryable<TbPunchEntity>()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate >= new DateTime(startExerciseDate.ToDate().Year, startExerciseDate.ToDate().Month, startExerciseDate.ToDate().Day, 0, 0, 0))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate <= new DateTime(endExerciseDate.ToDate().Year, endExerciseDate.ToDate().Month, endExerciseDate.ToDate().Day, 23, 59, 59))
.WhereIF(creatorTimeDate != null, p => p.CreatorTime >= new DateTime(startcreatorTimeDate.ToDate().Year, startcreatorTimeDate.ToDate().Month, startcreatorTimeDate.ToDate().Day, 0, 0, 0))
.WhereIF(creatorTimeDate != null, p => p.CreatorTime <= new DateTime(endcreatorTimeDate.ToDate().Year, endcreatorTimeDate.ToDate().Month, endcreatorTimeDate.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.Select(it=> new TbPunchListOutput
{
id = it.Id,
userId=it.UserId,
exerciseDate=it.ExerciseDate,
code=it.Code,
totalTime=it.TotalTime,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
type=it.Type,
imgList=it.ImgList,
}).MergeTable().Mapper(p => {
p.user = _db.Queryable<UserEntity>().Where(o => o.Id == p.userId).First();
}).OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<TbPunchListOutput>.SqlSugarPageResult(data);
}
/// <summary>
/// 新建打卡记录
/// </summary>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] TbPunchCrInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt<TbPunchEntity>();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
/// <summary>
/// 获取打卡记录无分页列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[NonAction]
public async Task<dynamic> GetNoPagingList([FromQuery] TbPunchListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
List<string> queryExerciseDate = input.exerciseDate != null ? input.exerciseDate.Split(',').ToObeject<List<string>>() : null;
DateTime? startExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.First()) : null;
DateTime? endExerciseDate = queryExerciseDate != null ? Ext.GetDateTime(queryExerciseDate.Last()) : null;
var data = await _db.Queryable<TbPunchEntity>()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate >= new DateTime(startExerciseDate.ToDate().Year, startExerciseDate.ToDate().Month, startExerciseDate.ToDate().Day, 0, 0, 0))
.WhereIF(queryExerciseDate != null, p => p.ExerciseDate <= new DateTime(endExerciseDate.ToDate().Year, endExerciseDate.ToDate().Month, endExerciseDate.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.code), p => p.Code.Contains(input.code))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.Select(it=> new TbPunchListOutput
{
id = it.Id,
userId=it.UserId,
exerciseDate=it.ExerciseDate,
code=it.Code,
totalTime=it.TotalTime,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
type=it.Type,
}).MergeTable().OrderBy(sidx+" "+input.sort).ToListAsync();
return data;
}
/// <summary>
/// 导出打卡记录
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("Actions/Export")]
public async Task<dynamic> Export([FromQuery] TbPunchListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = new List<TbPunchListOutput>();
if (input.dataType == 0)
{
var data = Clay.Object(await this.GetList(input));
exportData = data.Solidify<PageResult<TbPunchListOutput>>().list;
}
else
{
exportData = await this.GetNoPagingList(input);
}
List<ParamsModel> paramList = "[{\"value\":\"用户\",\"field\":\"userId\"},{\"value\":\"练习日期\",\"field\":\"exerciseDate\"},{\"value\":\"编号\",\"field\":\"code\"},{\"value\":\"做题总时长\",\"field\":\"totalTime\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"修改时间\",\"field\":\"lastModifyTime\"},{\"value\":\"状态\",\"field\":\"type\"},]".ToList<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "打卡记录.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
List<string> selectKeyList = input.selectKey.Split(',').ToList();
foreach (var item in selectKeyList)
{
var isExist = paramList.Find(p => p.field == item);
if (isExist != null)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
}
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<TbPunchListOutput>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
/// <summary>
/// 批量删除打卡记录
/// </summary>
/// <param name="ids">主键数组</param>
/// <returns></returns>
[HttpPost("batchRemove")]
public async Task BatchRemove([FromBody] List<string> ids)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entitys = await _db.Queryable<TbPunchEntity>().In(it => it.Id, ids).ToListAsync();
if (entitys.Count > 0)
{
try
{
//开启事务
_db.BeginTran();
//批量删除打卡记录
await _db.Deleteable<TbPunchEntity>().In(d => d.Id,ids).ExecuteCommandAsync();
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw NCCException.Oh(ErrorCode.COM1002);
}
}
}
/// <summary>
/// 更新打卡记录
/// </summary>
/// <param name="id">主键</param>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] TbPunchUpInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = input.Adapt<TbPunchEntity>();
entity.LastModifyTime = DateTime.Now;
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
/// <summary>
/// 删除打卡记录
/// </summary>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable<TbPunchEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable<TbPunchEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
}
}
}