Merge branch 'development'

This commit is contained in:
2024-03-08 11:31:56 +08:00
226 changed files with 5698 additions and 1610 deletions

View File

@@ -0,0 +1,172 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.Sys.Api;
using Dlhis.Sys.Api.Response;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Entity;
using Kurisu.SqlSugar.Services;
using Newtonsoft.Json;
using SqlSugar;
namespace Dlhis.ScheduledTask.CommonJobs;
public class CreateDefinitelyGroupJob
{
private readonly ILogger<CreateDefinitelyGroupJob> _logger;
private readonly ITenantApi _tenantApi;
private readonly IDbContext _dbContext;
public CreateDefinitelyGroupJob(ILogger<CreateDefinitelyGroupJob> logger,
ITenantApi tenantApi,
IDbContext dbContext,
ISqlSugarOptionsService sqlSugarOptionsService)
{
_logger = logger;
_tenantApi = tenantApi;
_dbContext = dbContext;
sqlSugarOptionsService.IgnoreTenant = true;
}
private static readonly string _remark = "系统自动生成";
public async Task RunAsync()
{
_dbContext.Client.QueryFilter.ClearAndBackup<ITenantId>();
try
{
//获取所有基地信息
var tenantResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantResult.Data;
_logger.LogInformation("获取基地信息:{json}", JsonConvert.SerializeObject(tenants));
//****************************************************系统人员分组**********************************************************/
await CreateGainfoGroupsAsync(tenants);
//*****************************************************考勤设备组*********************************************************/
await CreateDeviceGroupAsync(DeviceTypeEnumType.Attendance, new List<string> { "*通用考勤设备组", "*专用考勤设备组" }, tenants);
//*****************************************************门禁设备组********************************************************/
await CreateDeviceGroupAsync(DeviceTypeEnumType.Door, new List<string> { "*共用区域", "*非共用区域" }, tenants);
}
catch (Exception ex)
{
_logger.LogError(ex, "自动创建系统分组失败:{message}", ex.Message);
}
finally
{
_dbContext.Client.QueryFilter.Restore();
}
}
private async Task CreateGainfoGroupsAsync(List<TenantResponse> tenants)
{
var grps = new List<string> { "*自定义人员分组", "*督查组", "*X3及以上领导组" };
var searchGrps = await _dbContext.Queryable<GainfoGroupEntity>().Where(x => grps.Contains(x.Name)).ToListAsync();
foreach (var grp in grps)
{
if (!searchGrps.Any(x => x.Name == grp))
{
await _dbContext.InsertAsync(new GainfoGroupEntity
{
PCode = null,
Code = Guid.NewGuid(),
Name = grp,
IsDefault = grp.Equals("*自定义人员分组"),
Editable = false,
Remark = _remark,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
TenantId = null
});
}
}
}
private async Task CreateDeviceGroupAsync(DeviceTypeEnumType type, List<string> topGroups, List<TenantResponse> tenants)
{
foreach (var grp in topGroups)
{
var topGrp = await _dbContext.Queryable<DeviceGroupEntity>().FirstAsync(x => x.Name == grp);
if (topGrp == null)
{
topGrp = new DeviceGroupEntity
{
PCode = null,
Code = Guid.NewGuid(),
Type = type,
Name = grp,
Editable = false,
AbleSetNext = false,
Remark = _remark,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
TenantId = null,
};
await _dbContext.InsertAsync(topGrp);
}
foreach (var workplace in tenants.Where(x => x.PCode.IsEmpty()))
{
var workplaceName = $"*{type.GetDescription()}工作地系统组({workplace.Name})";
var workplaceGrp = await _dbContext.Queryable<DeviceGroupEntity>().Where(x => x.PCode == topGrp.Code).FirstAsync(x => x.Name == workplaceName);
if (workplaceGrp == null)
{
workplaceGrp = new DeviceGroupEntity
{
PCode = topGrp.Code,
Code = Guid.NewGuid(),
Type = type,
Name = workplaceName,
Editable = false,
AbleSetNext = false,
Remark = _remark,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
TenantId = null,
};
await _dbContext.InsertAsync(workplaceGrp);
}
foreach (var factory in tenants.Where(x => x.PCode == workplace.Code))
{
var factoryName = $"*{type.GetDescription()}厂区系统组({factory.Name})";
if (!await _dbContext.Queryable<DeviceGroupEntity>().Where(x => x.PCode == workplaceGrp.Code).AnyAsync(x => x.Name == factoryName))
{
await _dbContext.InsertAsync(new DeviceGroupEntity
{
PCode = workplaceGrp.Code,
Code = Guid.NewGuid(),
Type = type,
Name = factoryName,
Editable = false,
AbleSetNext = true,
Remark = _remark,
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
TenantId = factory.Code,
});
}
}
}
}
}
}

View File

@@ -0,0 +1,54 @@
using System.Net;
using System.Net.Sockets;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Kurisu.Core.DataAccess.Entity;
using Kurisu.SqlSugar.Services;
using Newtonsoft.Json;
namespace Dlhis.ScheduledTask.CommonJobs;
public class HeartbeatJob
{
private readonly IDbContext _dbContext;
private readonly ILogger<HeartbeatJob> _logger;
public HeartbeatJob(IDbContext dbContext, ILogger<HeartbeatJob> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task RunAsync()
{
_dbContext.Client.QueryFilter.ClearAndBackup<ITenantId>();
try
{
var devices = await _dbContext.Queryable<DeviceEntity>().Where(x => x.Enable).Where(x => x.HeartbeatInterval > 0).ToListAsync();
foreach (var device in devices)
{
try
{
var ipInfo = JsonConvert.DeserializeObject<IPPortDto>(device.ConnectionInfo);
//超时时间
var CancellationTokenSource = new CancellationTokenSource(300);
await new TcpClient().ConnectAsync(IPAddress.Parse(ipInfo.IP), ipInfo.Port, CancellationTokenSource.Token);
await _dbContext.Updateable<DeviceRegistryEntity>().SetColumns(x => x.LastHeartbeatTime == DateTime.Now)
.Where(x => x.DeviceUniqueNo == device.UniqueNo).ExecuteCommandAsync();
// _logger.LogInformation("心跳设备成功:{no}", device.UniqueNo);
}
catch (Exception)
{
//_logger.LogError(ex, "心跳设备失败:{no}. {message}", device.UniqueNo, ex.Message);
}
}
}
finally
{
_dbContext.Client.QueryFilter.Restore();
}
}
}

View File

@@ -1,6 +1,7 @@
using Dlhis.ScheduledTask.DeviceUploadLog.Request;
using Dlhis.ScheduledTask.DeviceUploadLog.Response;
using Dlhis.ScheduledTask.DeviceUploadLog.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Kurisu.Core.DataAccess.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -33,25 +34,27 @@ public class DeviceUploadLogsController : ControllerBase
return await _deviceUploadLogService.GetPageAsync(request);
}
/// <summary>
/// 上传记录
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("record")]
public async Task UploadLogAsync(DeviceUploadLogUploadRequest request)
{
await _deviceUploadLogService.UploadLogAsync(request);
}
/// <summary>
/// 批量上传记录
/// </summary>
/// <param name="requests"></param>
/// <returns></returns>
[HttpPost("records")]
[IgnoreTenant]
public async Task UploadLogsAsync(List<DeviceUploadLogUploadRequest> requests)
{
await _deviceUploadLogService.UploadLogsAsync(requests);
}
/// <summary>
/// 设置设备获取记录开始时间
/// </summary>
/// <param name="requests"></param>
/// <returns></returns>
[HttpPost("reset-begintime")]
[Transactional]
public async Task SetUploadLogsBeginDateTime(List<SetUploadLogsBeginDateTimeRequest> requests)
{
await _deviceUploadLogService.SetUploadLogsBeginDateTimeAsync(requests);
}
}

View File

@@ -20,7 +20,7 @@ public class DeviceUploadLogPageRequest : PageDto, IValidatableObject
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var now = DateTime.Now;
var today = DateTime.Today;
if (SearchDateTimeDimension.HasValue)
{
//重新赋值
@@ -28,37 +28,37 @@ public class DeviceUploadLogPageRequest : PageDto, IValidatableObject
if (SearchDateTimeDimension == DateTimeSearchEnumType.Day)
{
SearchDateTimePeriod.Start = new DateTime(now.Year, now.Month, now.Day, 0, 0, 1);
SearchDateTimePeriod.End = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
SearchDateTimePeriod.Start = today;
SearchDateTimePeriod.End = today.AddDays(1).AddSeconds(-1);
}
else if (SearchDateTimeDimension == DateTimeSearchEnumType.Week)
{
SearchDateTimePeriod.Start = now.AddDays(1 - (int)now.DayOfWeek);
SearchDateTimePeriod.Start = today.AddDays(1 - (int)today.DayOfWeek);
SearchDateTimePeriod.End = SearchDateTimePeriod.Start.Value.AddDays(6);
}
else if (SearchDateTimeDimension == DateTimeSearchEnumType.Month)
{
SearchDateTimePeriod.Start = new DateTime(now.Year, now.Month, 1);
SearchDateTimePeriod.Start = new DateTime(today.Year, today.Month, 1);
SearchDateTimePeriod.End = SearchDateTimePeriod.Start.Value.AddMonths(1).AddDays(-1);
}
else if (SearchDateTimeDimension == DateTimeSearchEnumType.Season)
{
SearchDateTimePeriod.Start = now.AddMonths(0 - ((now.Month - 1) % 3));
SearchDateTimePeriod.End = now.AddMonths(3 - ((now.Month - 1) % 3)).AddMonths(1).AddDays(-1);
SearchDateTimePeriod.Start = new DateTime(today.Year, today.Month, 1).AddMonths(2 - ((today.Month - 1) % 3));
SearchDateTimePeriod.End = SearchDateTimePeriod.Start.Value.AddMonths(2);
}
else if (SearchDateTimeDimension == DateTimeSearchEnumType.HalfOfYear)
{
SearchDateTimePeriod.Start = now.AddDays(-180);
SearchDateTimePeriod.End = now;
SearchDateTimePeriod.Start = today.AddDays(-180);
SearchDateTimePeriod.End = today;
}
else if (SearchDateTimeDimension == DateTimeSearchEnumType.Year)
{
SearchDateTimePeriod.Start = new DateTime(now.Year, 1, 1);
SearchDateTimePeriod.Start = new DateTime(today.Year, 1, 1);
SearchDateTimePeriod.End = SearchDateTimePeriod.Start.Value.AddYears(1).AddDays(-1);
}
SearchDateTimePeriod.Start = SearchDateTimePeriod.Start.Value.Date;
SearchDateTimePeriod.End = SearchDateTimePeriod.End.Value.Date;
SearchDateTimePeriod.Start = SearchDateTimePeriod.Start.Value;
SearchDateTimePeriod.End = SearchDateTimePeriod.End.Value;
}
yield break;

View File

@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace Dlhis.ScheduledTask.DeviceUploadLog.Request;
public class SetUploadLogsBeginDateTimeRequest
{
/// <summary>
/// 设备号不能为空
/// </summary>
[Required(ErrorMessage = "设备号不能为空")]
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime Begin { get; set; }
}

View File

@@ -1,4 +1,6 @@
namespace Dlhis.ScheduledTask.DeviceUploadLog.Response;
using Newtonsoft.Json;
namespace Dlhis.ScheduledTask.DeviceUploadLog.Response;
public class DeviceUploadLogResponse
{
@@ -29,4 +31,14 @@ public class DeviceUploadLogResponse
/// 上传时间
/// </summary>
public DateTime RaiseDateTime { get; set; }
/// <summary>
/// 序列号
/// </summary>
public string SerialNo { get; set; }
[JsonIgnore]
public string OriginUserUniqueNo { get; set; }
}

View File

@@ -8,7 +8,7 @@ public interface IDeviceUploadLogService : IScopeDependency
{
Task<Pagination<DeviceUploadLogResponse>> GetPageAsync(DeviceUploadLogPageRequest request);
Task UploadLogAsync(DeviceUploadLogUploadRequest request);
Task UploadLogsAsync(List<DeviceUploadLogUploadRequest> requests);
Task SetUploadLogsBeginDateTimeAsync(List<SetUploadLogsBeginDateTimeRequest> requests);
}

View File

@@ -1,11 +1,11 @@
using System.Linq.Expressions;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.ScheduledTask.DeviceUploadLog.Request;
using Dlhis.ScheduledTask.DeviceUploadLog.Response;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
using Kurisu.SqlSugar.Attributes;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Services;
using SqlSugar;
@@ -24,41 +24,38 @@ public class DeviceUploadLogService : IDeviceUploadLogService
public async Task<Pagination<DeviceUploadLogResponse>> GetPageAsync(DeviceUploadLogPageRequest request)
{
var page = await _dbContext.Queryable<DeviceUploadLogEntity>()
.LeftJoin<GainfoEntity>((deviceUp, ga) => deviceUp.UserUniqueNo == ga.No)
.LeftJoin<GainfoEntity>((deviceUp, ga) => deviceUp.UserUniqueNo == ga.Code)
.WhereIF(request.SearchDateTimePeriod?.Start.HasValue == true, deviceUp => deviceUp.RaiseDateTime >= request.SearchDateTimePeriod.Start)
.WhereIF(request.SearchDateTimePeriod?.End.HasValue == true, deviceUp => deviceUp.RaiseDateTime <= request.SearchDateTimePeriod.End)
.WhereIF(request.Search.IsPresent(), (deviceUp, ga) => ga.Code.Contains(request.Search) || ga.Name.Contains(request.Search) || deviceUp.DeviceUniqueNo.Contains(request.Search))
.OrderBy(deviceUp => deviceUp.CreateTime, OrderByType.Desc)
.Select((deviceUp, ga) => new DeviceUploadLogResponse
{
OriginUserUniqueNo = deviceUp.UserUniqueNo,
DeviceUniqueNo = deviceUp.DeviceUniqueNo,
Id = deviceUp.Id,
RaiseDateTime = deviceUp.RaiseDateTime,
SerialNo = deviceUp.SerialNo,
UserNo = ga.No,
UserCode = ga.Code,
UserName = ga.Name,
})
.ToPageListAsync(request);
//var gainfos = await _dbContext.Queryable<GainfoEntity>().ToListAsync();
//page.Data.ForEach(item =>
//{
// _ = int.TryParse(item.OriginUserUniqueNo, out var userId);
// var gainfo = gainfos.FirstOrDefault(x => x.No == item.OriginUserUniqueNo || x.Id == userId || x.Code == item.OriginUserUniqueNo);
// item.UserNo = gainfo?.No;
// item.UserCode = gainfo?.Code;
// item.UserName = gainfo?.Name;
//});
return page;
}
[IgnoreTenant]
public async Task UploadLogAsync(DeviceUploadLogUploadRequest request)
{
var device = await _dbContext.Queryable<DeviceEntity>().Where(x => x.UniqueNo == request.DeviceUniqueNo).SingleAsync();
device.ThrowIfNull("设备信息不存在");
var entity = new DeviceUploadLogEntity
{
DeviceUniqueNo = request.DeviceUniqueNo,
// UploadTime = request.UploadTime,
UserUniqueNo = request.UserUniqueNo,
TenantId = device.TenantId,
};
await _dbContext.InsertAsync(entity);
}
[IgnoreTenant]
public async Task UploadLogsAsync(List<DeviceUploadLogUploadRequest> requests)
{
//判断存在的记录
@@ -101,4 +98,30 @@ public class DeviceUploadLogService : IDeviceUploadLogService
await _dbContext.InsertAsync(records);
}
public async Task SetUploadLogsBeginDateTimeAsync(List<SetUploadLogsBeginDateTimeRequest> requests)
{
var uniqueNos = requests.DistinctBy(x => x.DeviceUniqueNo).Select(x => x.DeviceUniqueNo).ToList();
var devices = await _dbContext.Queryable<DeviceEntity>()
.Where(x => uniqueNos.Contains(x.UniqueNo))
.Where(x => x.Type == DeviceTypeEnumType.Attendance || x.Type == DeviceTypeEnumType.Door)
.ToListAsync();
(uniqueNos.Count != devices.Count).ThrowIfTrue("存在非考勤和门禁的设备");
var tenantId = devices.FirstOrDefault().TenantId;
var logs = new List<DeviceUploadLogEntity>(requests.Count);
foreach (var request in requests)
{
logs.Add(new DeviceUploadLogEntity
{
DeviceUniqueNo = request.DeviceUniqueNo,
Type = DeviceUploadLogTypeEnumType.Raise,
RaiseDateTime = request.Begin,
TenantId = tenantId
});
}
await _dbContext.InsertAsync(logs);
}
}

View File

@@ -20,8 +20,7 @@
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.7" />
<PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.9.3" />
<PackageReference Include="Kurisu.AspNetCore" Version="0.5.2" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.26" />
<PackageReference Include="Kurisu.AspNetCore" Version="0.7.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,8 @@
namespace Dlhis.ScheduledTask
{
public class IPPortDto
{
public string IP { get; set; }
public int Port { get; set; }
}
}

View File

@@ -48,7 +48,7 @@ public class HangfirePack : BaseAppPack
new BasicAuthAuthorizationUser
{
Login ="admin",
PasswordClear = "admin"
PasswordClear = "dlhis123"
}
}
})

View File

@@ -1,4 +1,5 @@
using Dlhis.ScheduledTask.SyncSapInfo.Job;
using Dlhis.ScheduledTask.CommonJobs;
using Dlhis.ScheduledTask.SyncSapInfo.Job;
using Dlhis.ScheduledTask.TaskAssignment.Job;
using Hangfire;
using Kurisu.AspNetCore.Startup;
@@ -23,12 +24,26 @@ public class JobPack : BaseAppPack
TimeZone = TimeZoneInfo.Local
});
//创建设备同步时间任务
RecurringJob.AddOrUpdate<CreateSyncServerDateTimeJob>("SyncServerDateTime", s => s.RunAsync(), "0 0 0/1 * * ?", new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});
RecurringJob.AddOrUpdate<CreateGetAttendanceJob>("CreateGetAttendance", s => s.RunAsync(), "0 0/1 * * * ?", new RecurringJobOptions
//创建设备获取的任务
RecurringJob.AddOrUpdate<CreateGetUploadRecordJob>("CreateGetUploadRecord", s => s.RunAsync(), "0 0/1 * * * ?", new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});
//创建系统默认分组
RecurringJob.AddOrUpdate<CreateDefinitelyGroupJob>("CreateDefinitelyGroup", s => s.RunAsync(), "0 0 5 * * ?", new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});
//心跳
RecurringJob.AddOrUpdate<HeartbeatJob>("Heartbeat", s => s.RunAsync(), "0/10 * * * * ?", new RecurringJobOptions
{
TimeZone = TimeZoneInfo.Local
});

View File

@@ -1,4 +1,6 @@
using Kurisu.AspNetCore.Startup;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Startup;
using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;
@@ -20,16 +22,11 @@ public class Startup : DefaultStartup
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
services.AddRedis();
}
services.AddSingleton<IConnectionMultiplexer>(sp =>
{
return ConnectionMultiplexer.Connect("10.27.21.15:30050,defaultDatabase:1,password=dlhis123");
});
//todo
var redis = ConnectionMultiplexer.Connect($"10.27.21.15:30050,defaultDatabase:1,password=dlhis123");
services.AddDataProtection()
.SetApplicationName("basic")
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
base.Configure(app, env);
}
}

View File

@@ -5,7 +5,7 @@
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://*:5010"
"applicationUrl": "http://localhost:5010"
}
}
}

View File

@@ -1,33 +0,0 @@
using Dlhis.ScheduledTask.SyncSapInfo.Dto;
namespace Dlhis.ScheduledTask.SyncSapInfo.Comparers;
/// <summary>
/// 机构数据比较器
/// </summary>
public class SapOrganizationComparer : IEqualityComparer<SapOrganizationItem>
{
public bool Equals(SapOrganizationItem x, SapOrganizationItem y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.BEGDA == y.BEGDA
&& x.ENDDA == y.ENDDA
&& x.LANGU == y.LANGU
&& x.OBJID == y.OBJID
&& x.STEXT == y.STEXT
&& x.SOBID == y.SOBID
&& x.ORGID01 == y.ORGID01
&& x.ORGID02 == y.ORGID02;
}
public int GetHashCode(SapOrganizationItem obj)
{
return obj.BEGDA.SafeGetHashCode() ^ obj.ENDDA.SafeGetHashCode()
^ obj.LANGU.SafeGetHashCode() ^ obj.OBJID.SafeGetHashCode()
^ obj.STEXT.SafeGetHashCode() ^ obj.SOBID.SafeGetHashCode()
^ obj.ORGID01.SafeGetHashCode() ^ obj.ORGID02.SafeGetHashCode();
}
}

View File

@@ -1,32 +0,0 @@
using Dlhis.ScheduledTask.SyncSapInfo.Dto;
namespace Dlhis.ScheduledTask.SyncSapInfo.Comparers;
/// <summary>
/// 岗位信息比较器
/// </summary>
public class SapPositionComparer : IEqualityComparer<SapPositionItem>
{
public bool Equals(SapPositionItem x, SapPositionItem y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.BEGDA == y.BEGDA
&& x.ENDDA == y.ENDDA
&& x.LANGU == y.LANGU
&& x.ZJOBID == y.ZJOBID
&& x.ZJOBNAME == y.ZJOBNAME
&& x.ZZWID == y.ZZWID
&& x.ZDEPID == y.ZDEPID;
}
public int GetHashCode(SapPositionItem obj)
{
return obj.BEGDA.SafeGetHashCode() ^ obj.ENDDA.SafeGetHashCode()
^ obj.LANGU.SafeGetHashCode() ^ obj.ZJOBID.SafeGetHashCode()
^ obj.ZJOBNAME.SafeGetHashCode() ^ obj.ZZWID.SafeGetHashCode()
^ obj.ZDEPID.SafeGetHashCode();
}
}

View File

@@ -137,7 +137,6 @@ public class SyncPersonJob
Position = item.web,
Remark = item.remark,
Werks = item.WERKS,
Employed = item.isowner,
};
if (item.isowner == "T")
@@ -150,6 +149,7 @@ public class SyncPersonJob
}
}
private void UpdatePerson(IDbContext db, GainfoSapEntity item)
{
var gainfoSap = db.Queryable<GainfoSapEntity>().Where(x => x.ename == item.ename).First();

View File

@@ -1,6 +1,7 @@
using Dlhis.ScheduledTask.TaskAssignment.Request;
using Dlhis.ScheduledTask.TaskAssignment.Response;
using Dlhis.ScheduledTask.TaskAssignment.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -25,6 +26,7 @@ public class AssignmentsController : ControllerBase
/// 获取设备任务(按设备)
/// </summary>
/// <returns></returns>
[IgnoreTenant]
[HttpGet("devicetasks")]
public async Task<List<DeviceTaskToDeviceByDeviceResponse>> DeviceGetTasksGetAsync([FromQuery] DeviceTaskGetRequest request)
{
@@ -36,6 +38,7 @@ public class AssignmentsController : ControllerBase
/// </summary>
/// <returns></returns>
[HttpPost("devicetasks")]
[IgnoreTenant]
public async Task<List<DeviceTaskToDeviceByDeviceResponse>> DeviceGetTasksPostAsync(DeviceTaskGetRequest request)
{
return await _assignmentService.DeviceGetTasksAsync(request);
@@ -47,6 +50,7 @@ public class AssignmentsController : ControllerBase
/// <param name="requests"></param>
/// <returns></returns>
[HttpPost("taskstatus")]
[IgnoreTenant]
public async Task UpdateDeviceTaskStatusAsync(List<UpdateDeviceTaskStatusRequest> requests)
{
await _assignmentService.UpdateDeviceTaskStatusAsync(requests);
@@ -58,6 +62,7 @@ public class AssignmentsController : ControllerBase
/// <param name="taskId"></param>
/// <returns></returns>
[HttpGet("renewfaceurl")]
[IgnoreTenant]
public async Task<string> RenewFaceUrlAsync(long taskId)
{
return await _assignmentService.RenewFaceUrlAsync(taskId);

View File

@@ -1,6 +1,7 @@
using Dlhis.ScheduledTask.TaskAssignment.Request;
using Dlhis.ScheduledTask.TaskAssignment.Response;
using Dlhis.ScheduledTask.TaskAssignment.Services;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Aop;
using Kurisu.Core.DataAccess.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -28,9 +29,19 @@ public class DeviceTaskAssignmentsController : ControllerBase
/// <param name="request"></param>
/// <returns></returns>
[HttpGet("page")]
[DataPermission]
public async Task<Pagination<DeviceTaskAssignmentResponse>> GetPageAsync([FromQuery] DeviceTaskAssignmentRequest request)
{
return await _deviceTaskAssignmentService.GetPageAsync(request);
}
/// <summary>
/// 重置任务
/// </summary>
/// <returns></returns>
[HttpPost("reset")]
public async Task ResetAsync(DeviceTaskResetRequest request)
{
await _deviceTaskAssignmentService.ResetAsync(request);
}
}

View File

@@ -7,12 +7,12 @@ using Kurisu.SqlSugar.Services;
namespace Dlhis.ScheduledTask.TaskAssignment.Job;
public class CreateGetAttendanceJob
public class CreateGetUploadRecordJob
{
private readonly IDbContext _dbContext;
private readonly ILogger<CreateSyncServerDateTimeJob> _logger;
public CreateGetAttendanceJob(IDbContext dbContext, ILogger<CreateSyncServerDateTimeJob> logger)
public CreateGetUploadRecordJob(IDbContext dbContext, ILogger<CreateSyncServerDateTimeJob> logger)
{
_logger = logger;
_dbContext = dbContext;
@@ -23,30 +23,25 @@ public class CreateGetAttendanceJob
_dbContext.Client.QueryFilter.ClearAndBackup<ITenantId>();
try
{
var devices = await _dbContext.Queryable<DeviceEntity>().Where(x => x.Enable).ToListAsync();
devices = devices.Where(x => x.Funcs.Contains(DeviceFuncEnumType.Attendance)).ToList();
var devices = await _dbContext.Queryable<DeviceEntity>()
.Where(x => x.Enable)
.Where(x => x.Type == DeviceTypeEnumType.Attendance || x.Type == DeviceTypeEnumType.Door)
.ToListAsync();
var ds = devices.Select(x => x.UniqueNo).ToList();
//过滤处理中的任务
var currentUniqueNos = await _dbContext.Queryable<DeviceTaskEntity>()
.Where(x => x.Type == DeviceTaskEnumType.UploadRecord)
.Where(x => x.Status == DeviceTaskStatusEnumType.Process || x.Status == DeviceTaskStatusEnumType.Wait)
.Select(x => x.DeviceUniqueNo)
.ToListAsync();
var b = await _dbContext.Queryable<DeviceTaskEntity>()
.Where(x => ds.Contains(x.DeviceUniqueNo))
.Where(x => x.Type == DeviceTaskEnumType.UploadRecord)
.Where(x => x.Status == DeviceTaskStatusEnumType.Process)
.AnyAsync();
if (b)
{
return;
}
var tasks = devices.Select(x => new DeviceTaskEntity
var tasks = devices.Where(x => !currentUniqueNos.Contains(x.UniqueNo)).Select(x => new DeviceTaskEntity
{
DeviceUniqueNo = x.UniqueNo,
Status = DeviceTaskStatusEnumType.Wait,
TenantId = x.TenantId,
Version = 0,
UserNo = string.Empty,
UserCode = string.Empty,
Type = DeviceTaskEnumType.UploadRecord,
CreatedBy = 1,
@@ -54,7 +49,8 @@ public class CreateGetAttendanceJob
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
}).ToList();
})
.ToList();
await _dbContext.InsertAsync(tasks);
}

View File

@@ -1,6 +1,7 @@
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Kurisu.Core.DataAccess.Entity;
using Kurisu.SqlSugar.Services;
namespace Dlhis.ScheduledTask.TaskAssignment.Job
@@ -19,20 +20,29 @@ namespace Dlhis.ScheduledTask.TaskAssignment.Job
public async Task RunAsync()
{
_dbContext.Client.QueryFilter.ClearAndBackup();
_dbContext.Client.QueryFilter.ClearAndBackup<ITenantId>();
try
{
var devices = await _dbContext.Queryable<DeviceEntity>().Where(x => x.Enable).ToListAsync();
var deviceUniqueNos = await _dbContext.Queryable<DeviceTaskEntity>()
.Where(x => x.Status == DeviceTaskStatusEnumType.Wait || x.Status == DeviceTaskStatusEnumType.Process)
.Where(x => x.Type == DeviceTaskEnumType.SyncDateTime)
.Select(x => x.DeviceUniqueNo)
.Distinct()
.ToListAsync();
var devices = await _dbContext.Queryable<DeviceEntity>()
.Where(x => !deviceUniqueNos.Contains(x.UniqueNo))
.Where(x => x.Enable)
.ToListAsync();
var tasks = devices.Select(x => new DeviceTaskEntity
{
DeviceUniqueNo = x.UniqueNo,
Status = DeviceTaskStatusEnumType.Wait,
TenantId = x.TenantId,
Version = 0,
UserNo = string.Empty,
UserCode = string.Empty,
Type = DeviceTaskEnumType.SyncDateTime,
CreatedBy = 1,
@@ -46,7 +56,7 @@ namespace Dlhis.ScheduledTask.TaskAssignment.Job
}
catch (Exception ex)
{
_logger.LogError(ex, "生成同步时间任务失败:" + ex.Message);
_logger.LogError(ex, "生成同步时间任务失败:{message}", ex.Message);
}
finally
{

View File

@@ -1,7 +1,27 @@
using Kurisu.Core.DataAccess.Dto;
using System.ComponentModel.DataAnnotations;
using Dlhis.Entity.Device.Enums;
using Kurisu.Core.DataAccess.Dto;
namespace Dlhis.ScheduledTask.TaskAssignment.Request;
public class DeviceTaskAssignmentRequest : PageDto
{
/// <summary>
/// 设备类型
/// </summary>
[EnumDataType(typeof(DeviceTypeEnumType))]
public DeviceTypeEnumType? Type { get; set; }
/// <summary>
/// 任务类型
/// </summary>
[EnumDataType(typeof(DeviceTaskEnumType))]
public DeviceTaskEnumType? TaskType { get; set; }
/// <summary>
/// 任务下发状态
/// </summary>
[EnumDataType(typeof(DeviceTaskStatusEnumType))]
public DeviceTaskStatusEnumType? Status { get; set; }
}

View File

@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations;
using Dlhis.Entity.Device.Enums;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
@@ -16,6 +17,11 @@ public class DeviceTaskGetRequest : PageDto, IValidatableObject
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 任务类型
/// </summary>
public List<DeviceTaskEnumType> Types { get; set; }
/// <summary>
/// 获取处理中的任务
/// </summary>

View File

@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace Dlhis.ScheduledTask.TaskAssignment.Request;
public class DeviceTaskResetRequest
{
/// <summary>
/// 任务ids
/// </summary>
[MinLength(1, ErrorMessage = "请选择任务进行重置")]
public List<long> Ids { get; set; }
/// <summary>
/// 是否强制重置
/// </summary>
public bool Force { get; set; }
}

View File

@@ -1,10 +1,13 @@
using Dlhis.Entity.Device.Enums;
using Kurisu.AspNetCore.Utils.Extensions;
using SqlSugar;
namespace Dlhis.ScheduledTask.TaskAssignment.Response;
public class DeviceTaskAssignmentResponse
{
public long Id { get; set; }
/// <summary>
/// 任务类型
/// </summary>
@@ -55,8 +58,34 @@ public class DeviceTaskAssignmentResponse
/// </summary>
public string ResultMessage { get; set; }
/// <summary>
/// 任务创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 数据状态最新修改时间
/// </summary>
public DateTime LastUpdateTime { get; set; }
/// <summary>
/// 厂区id
/// </summary>
public string TenantId { get; set; }
/// <summary>
/// 厂区名称
/// </summary>
public string TenantName { get; set; }
/// <summary>
/// 部署点
/// </summary>
public string DeployPlace { get; set; }
/// <summary>
/// 连接信息
/// </summary>
public string ConnectionInfo { get; set; }
}

View File

@@ -8,4 +8,6 @@ public interface IDeviceTaskAssignmentService : IScopeDependency
{
Task<Pagination<DeviceTaskAssignmentResponse>> GetPageAsync(DeviceTaskAssignmentRequest request);
Task ResetAsync(DeviceTaskResetRequest request);
}

View File

@@ -12,13 +12,12 @@ using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
using SqlSugar;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Attributes;
using Newtonsoft.Json.Linq;
using Kurisu.Core.CustomClass;
using Kurisu.AspNetCore;
namespace Dlhis.ScheduledTask.TaskAssignment.Services.Implements;
[IgnoreTenant]
public class AssignmentService : IAssignmentService
{
private readonly IDbContext _dbContext;
@@ -41,6 +40,7 @@ public class AssignmentService : IAssignmentService
.LeftJoin<DepartmentEntity>((deviceTask, deivce, deivceTamplate, ga, department) => department.No == ga.DepartmentNo)
.WhereIF(request.Brand.IsPresent(), (deviceTask, deivce, deivceTamplate) => deivceTamplate.Brand == request.Brand)
.WhereIF(request.DeviceUniqueNo.IsPresent(), (deviceTask, deivce) => deviceTask.DeviceUniqueNo == request.DeviceUniqueNo)
.WhereIF(request.Types.IsPresent(), deviceTask => request.Types.Contains(deviceTask.Type))
.WhereIF(!request.IsProcess, deviceTask => deviceTask.Status == DeviceTaskStatusEnumType.Wait)
.WhereIF(request.IsProcess, deviceTask => deviceTask.Status == DeviceTaskStatusEnumType.Process)
.OrderBy(deviceTask => deviceTask.CreateTime)
@@ -54,7 +54,7 @@ public class AssignmentService : IAssignmentService
deivceTamplate.Brand,
FuncStr = deivce.Funcs.ToString(),
deviceTask.UserNo,
deviceTask.UserCode,
UserCode = ga.Code,
UserName = ga.Name,
ga.DepartmentNo,
DepartmentName = department.Name,
@@ -99,6 +99,7 @@ public class AssignmentService : IAssignmentService
}
return page.Data;
}, 5);
if (!data.Any())
@@ -284,25 +285,21 @@ public class AssignmentService : IAssignmentService
{
var task = await _dbContext.Queryable<DeviceTaskEntity>().Where(x => x.Id == taskId).FirstAsync();
task.ThrowIfNull("该任务不存在");
(task.Status != DeviceTaskStatusEnumType.Process).ThrowIfTrue($"设备任务下发状态需为{DeviceTaskStatusEnumType.Process.GetDescription()}");
return Scoped.Request.Value.Create((sp) =>
{
var faceUrlOptions = sp.GetService<IOptions<FaceUrlOptions>>().Value;
var dataProtectionProvider = sp.GetService<IDataProtectionProvider>();
var faceUrlOptions = App.GetServiceProvider(true).GetService<IOptions<FaceUrlOptions>>().Value;
var dataProtectionProvider = App.GetServiceProvider(true).GetService<IDataProtectionProvider>();
var timeLimitedDataProtector = dataProtectionProvider
.CreateProtector("down:face")
.ToTimeLimitedDataProtector();
var timeLimitedDataProtector = dataProtectionProvider
.CreateProtector("down:face")
.ToTimeLimitedDataProtector();
var userCode = task.UserCode;
var userCode = await _dbContext.Queryable<GainfoEntity>().Where(x => x.No == task.UserNo).Select(x => x.Code).SingleAsync();
var key = $"face:{userCode}";
var token = timeLimitedDataProtector.Protect(key, TimeSpan.FromSeconds(faceUrlOptions.Limit));
var key = $"face:{userCode}";
var token = timeLimitedDataProtector.Protect(key, TimeSpan.FromSeconds(faceUrlOptions.Limit));
return faceUrlOptions.Url + token;
});
return faceUrlOptions.Url + token;
}
@@ -318,11 +315,6 @@ public class AssignmentService : IAssignmentService
requests = requests.Where(x => taskIds.Contains(x.TaskId)).ToList();
deviceTasks.ForEach(x =>
{
});
var now = DateTime.Now;
var tasks = new List<DeviceTaskEntity>(requests.Count);
foreach (var request in requests)
@@ -359,7 +351,7 @@ public class AssignmentService : IAssignmentService
}
catch (Exception ex) when (ex is VersionExceptions)
{
_logger.LogWarning(ex, ex.Message);
_logger.LogWarning(ex, "并发更新失败:{message},", ex.Message);
}
catch (Exception)
{

View File

@@ -3,44 +3,101 @@ using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.ScheduledTask.TaskAssignment.Request;
using Dlhis.ScheduledTask.TaskAssignment.Response;
using Dlhis.Sys.Api;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Services;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using SqlSugar;
namespace Dlhis.ScheduledTask.TaskAssignment.Services.Implements;
public class DeviceTaskAssignmentService : IDeviceTaskAssignmentService
{
private readonly IDbContext _dbContext;
private readonly ITenantApi _tenantApi;
public DeviceTaskAssignmentService(IDbContext dbContext)
public DeviceTaskAssignmentService(IDbContext dbContext, ITenantApi tenantApi)
{
_dbContext = dbContext;
_tenantApi = tenantApi;
}
public async Task<Pagination<DeviceTaskAssignmentResponse>> GetPageAsync(DeviceTaskAssignmentRequest request)
{
var page = await _dbContext.Queryable<DeviceTaskEntity>()
.LeftJoin<GainfoEntity>((deviceTask, ga) => deviceTask.UserNo == ga.No)
.Select((deviceTask, ga) => new DeviceTaskAssignmentResponse
{
DeviceUniqueNo = deviceTask.DeviceUniqueNo,
ResultMessage = deviceTask.ResultMessage,
RetryCount = deviceTask.Version,
Status = deviceTask.Status,
UserNo = deviceTask.UserNo,
UserName = ga.Name,
UserCode = deviceTask.UserCode,
Type = deviceTask.Type,
LastUpdateTime = deviceTask.ModifiedTime
})
.ToPageListAsync(request);
.LeftJoin<DeviceEntity>((deviceTask, ga, device) => deviceTask.DeviceUniqueNo == device.UniqueNo)
.WhereIF(!request.Search.IsEmpty(), (deviceTask, ga, device) =>
deviceTask.UserNo == request.Search
|| ga.Name.Contains(request.Search)
|| ga.Code == request.Search
|| deviceTask.DeviceUniqueNo == request.Search
)
.WhereIF(request.TaskType.HasValue, deviceTask => deviceTask.Type == request.TaskType)
.WhereIF(request.Type.HasValue, (deviceTask, ga, device) => device.Type == request.Type)
.WhereIF(request.Status.HasValue, deviceTask => deviceTask.Status == request.Status)
.Where(deviceTask => 1 == 1)
.OrderBy(deviceTask => deviceTask.CreateTime, OrderByType.Desc)
.Select((deviceTask, ga, device) => new DeviceTaskAssignmentResponse
{
Id = deviceTask.Id,
DeviceUniqueNo = deviceTask.DeviceUniqueNo,
ResultMessage = deviceTask.ResultMessage,
RetryCount = deviceTask.Version,
Status = deviceTask.Status,
UserNo = deviceTask.UserNo,
UserName = ga.Name,
UserCode = ga.Code,
Type = deviceTask.Type,
CreateTime = deviceTask.CreateTime,
LastUpdateTime = deviceTask.ModifiedTime,
TenantId = deviceTask.TenantId,
DeployPlace = device.DeployPlace,
ConnectionInfo = device.ConnectionInfo
})
.ToPageListAsync(request);
try
{
var tenantResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantResult.Data;
page.Data.ForEach(item =>
{
item.TenantName = tenants.FirstOrDefault(x => x.Code == item.TenantId)?.Name;
});
}
catch (Exception)
{
}
return page;
}
public async Task ResetAsync(DeviceTaskResetRequest request)
{
var tasks = await _dbContext.Queryable<DeviceTaskEntity>()
.Where(x => request.Ids.Contains(x.Id))
.Where(x => x.Status == DeviceTaskStatusEnumType.Process || x.Status == DeviceTaskStatusEnumType.Error)
.ToListAsync();
//判断process任务时间
if (!request.Force)
{
var now = DateTime.Now;
tasks.Any(x => x.ModifiedTime.AddMinutes(10) < now && x.Status == DeviceTaskStatusEnumType.Process).ThrowIfTrue("请等待任务处理完成");
}
//更新任务状态
await _dbContext.Updateable<DeviceTaskEntity>()
.SetColumns(x => x.Status == DeviceTaskStatusEnumType.Wait)
.Where(x => request.Ids.Contains(x.Id))
.Where(x => x.Status == DeviceTaskStatusEnumType.Process || x.Status == DeviceTaskStatusEnumType.Error)
.ExecuteCommandAsync();
}
}

View File

@@ -5,6 +5,9 @@
"Microsoft.AspNetCore": "Warning"
}
},
"InternalRequest": {
"SysRequestUrl": "http://localhost:5003"
},
"FaceUrlOptions": {
"Url": "http://localhost:5002/api/gainfos/face?token=",
"Limit": 7200

View File

@@ -8,6 +8,10 @@
"InternalRequest": {
"SysRequestUrl": "http://sys"
},
"DataProtectionOptions": {
"Enable": true,
"AppName": "yiliantong"
},
"SqlSugarOptions": {
"DefaultConnectionString": "server=10.27.21.22;port=3306;userid=root;password=dlhis123;database=yikatong;charset=utf8mb4;",
"SlaveConnectionString": [],
@@ -54,6 +58,9 @@
"AttendanceUploadInterval": "30",
"BeginSyncDate": "2020-5-1"
},
"RedisOptions": {
"ConnectionString": "192.168.199.30:30115,defaultDatabase:1,password=dlhis123"
},
"AllowedHosts": "*",
"Serilog": {
"MinimumLevel": {