feat 设备任务领取

This commit is contained in:
2024-01-13 20:53:04 +08:00
parent 24b026aa04
commit 79bc32c959
24 changed files with 477 additions and 25 deletions

View File

@@ -18,7 +18,7 @@
<ItemGroup>
<PackageReference Include="Kurisu.AspNetCore" Version="0.4.8" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.26" />
</ItemGroup>
<ItemGroup>

View File

@@ -45,7 +45,7 @@ public class MealUserService : IMealUserService
UserNo = request.UserNo,
UserType = request.UserType,
UserCode = gainfoEntity.Code,
CarNo = gainfoEntity.CarNo,
CarNo = gainfoEntity.CardNo,
Balance = 0,
BalanceOfRecharge = 0,
BalanceOfSubsidies = 0,

View File

@@ -1,4 +1,6 @@
using Dlhis.Basic.Organization.Request;
using System.ComponentModel.DataAnnotations;
using Dlhis.Basic.Organization.Filters;
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Response;
using Dlhis.Basic.Organization.Services;
using Kurisu.AspNetCore.MVC;
@@ -96,7 +98,20 @@ public class GainfosController : ControllerBase
[HttpPost("face")]
public async Task UploadFaceAsync(GainfoUploadFaceRequest request)
{
await _gainfoService.UploadFaceAsync(request);
await _gainfoService.UploadFaceAsync(request);
}
/// <summary>
/// 获取人脸照片
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[NotFound]
[AllowAnonymous]
[HttpGet("face")]
public async Task<IActionResult> GetFaceAsync(string token)
{
return await _gainfoService.GetFaceAsync(token);
}
}

View File

@@ -0,0 +1,30 @@
using Kurisu.Core.Result;
using Kurisu.Core.Result.Abstractions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Dlhis.Basic.Organization.Filters;
[AttributeUsage(AttributeTargets.Method)]
public class NotFoundAttribute : Attribute, IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if (context.Result is ObjectResult result)
{
var type = result.Value?.GetType();
if (type.IsGenericType && type.IsAssignableTo(typeof(IApiResult)))
{
var apiResult = result.Value as DefaultApiResult<object>;
if (apiResult.Data is ProblemDetails _)
{
context.Result = new NotFoundResult();
//context.HttpContext.Response
}
}
}
await next();
}
}

View File

@@ -1,6 +1,7 @@
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Response;
using Kurisu.Core.DataAccess.Dto;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Basic.Organization.Services;
@@ -8,7 +9,6 @@ public interface IGainfoService : IScopeDependency
{
Task<Pagination<GainfoPageResponse>> GetPageAsync(GainfoPageRequest request);
Task SaveAsync(List<GainfoSaveRequest> requests);
Task UpdateAsync(GainfoSaveRequest request);
@@ -19,6 +19,7 @@ public interface IGainfoService : IScopeDependency
Task<GainfoCurrentResponse> CurrentUserInfoAsync();
Task UploadFaceAsync(GainfoUploadFaceRequest request);
Task<IActionResult> GetFaceAsync(string token);
}

View File

@@ -1,5 +1,4 @@
using System.Configuration;
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
@@ -12,6 +11,8 @@ using Kurisu.SqlSugar.Attributes;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Services;
using Mapster;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Basic.Organization.Services.Implements;
@@ -225,4 +226,44 @@ public class GainfoService : IGainfoService
}
});
}
public async Task<IActionResult> GetFaceAsync(string token)
{
return await Scoped.Request.Value.CreateAsync<IActionResult>(async (sp) =>
{
var timeLimitedDataProtector = sp.GetService<IDataProtectionProvider>()
.CreateProtector("down:face")
.ToTimeLimitedDataProtector();
try
{
var password = timeLimitedDataProtector.Unprotect(token);
var userCode = password.Split(':')[1];
var configuration = sp.GetService<IConfiguration>();
var faceConnectionString = configuration.GetSection("SqlSugarOptions:FaceConnectionString").Value;
if (faceConnectionString.IsEmpty())
{
throw new UserFriendlyException("暂不支持获取人脸");
}
var dbContext = sp.GetService<IDbContext>();
//todo 切换连接字符串
dbContext.Client.CurrentConnectionConfig.ConnectionString = faceConnectionString;
var face = await dbContext.Queryable<GainfoFaceEntity>().Where(x => x.UserCode == userCode).SingleAsync();
if (face == null)
{
return new NotFoundResult();
}
return new FileContentResult(Convert.FromBase64String(face.Face), "image/png");
}
catch (Exception)
{
return new NotFoundResult();
}
});
}
}

View File

@@ -1,10 +1,9 @@
using Dlhis.Entity.Basic.Entity;
using Kurisu.AspNetCore;
using Kurisu.AspNetCore;
using Kurisu.AspNetCore.Startup;
using Kurisu.SqlSugar.Extensions;
using SqlSugar;
namespace Dlhis.Canteen;
namespace Dlhis.Basic.Packs;
public class SqlSugarPack : BaseAppPack
{

View File

@@ -1,6 +1,7 @@
using Kurisu.AspNetCore.Startup;
using Kurisu.Startup;
using Microsoft.IdentityModel.Logging;
using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;
class Program
{
@@ -14,6 +15,17 @@ public class Startup : DefaultStartup
{
public Startup(IConfiguration configuration) : base(configuration)
{
IdentityModelEventSource.ShowPII = true;
}
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
//todo
var redis = ConnectionMultiplexer.Connect($"192.168.199.30:30115,defaultDatabase:1,password=zxc111");
services.AddDataProtection()
.SetApplicationName("basic")
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
}
}

View File

@@ -0,0 +1,14 @@
//using Microsoft.AspNetCore.Mvc.Filters;
//namespace Dlhis.Canteen.Order.Filters;
///// <summary>
///// 检查用户设备消费
///// </summary>
//public class CheckUserDeviceConsumeAttribute : IAsyncActionFilter
//{
// public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
// {
// }
//}

View File

@@ -129,7 +129,7 @@ public class GainfoEntity : SugarBaseEntity
/// 卡号
/// </summary>
[SugarColumn(ColumnDescription = "卡号")]
public string CarNo { get; set; }
public string CardNo { get; set; }
/// <summary>
/// 备注

View File

@@ -10,7 +10,7 @@ namespace Dlhis.Entity.Device.Entities;
/// 设备任务表
/// </summary>
[SugarTable(TableName = "DeviceTask")]
public class DeviceTaskEntity : SugarBaseEntity, ITenantId
public class DeviceTaskEntity : SugarBaseEntity, ITenantId, IVersion
{
/// <summary>
/// 任务类型
@@ -28,11 +28,6 @@ public class DeviceTaskEntity : SugarBaseEntity, ITenantId
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 设备唯一号
/// </summary>
@@ -49,6 +44,12 @@ public class DeviceTaskEntity : SugarBaseEntity, ITenantId
[SugarColumn(ColumnDataType = "varchar(50)", SqlParameterDbType = typeof(EnumToStringConvert))]
public DeviceTaskStatusEnumType Status { get; set; }
/// <summary>
/// 数据版本
/// </summary>
public int Version { get; set; }
/// <summary>
/// 处理结果
/// </summary>

View File

@@ -21,6 +21,7 @@
<PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
<PackageReference Include="Hangfire.MySqlStorage" Version="2.0.3" />
<PackageReference Include="Kurisu.AspNetCore" Version="0.4.8" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.26" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,6 +1,7 @@
using Kurisu.AspNetCore.Startup;
using Kurisu.Startup;
using Microsoft.AspNetCore.DataProtection;
using StackExchange.Redis;
class Program
{
@@ -15,4 +16,15 @@ public class Startup : DefaultStartup
public Startup(IConfiguration configuration) : base(configuration)
{
}
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
//todo
var redis = ConnectionMultiplexer.Connect($"192.168.199.30:30115,defaultDatabase:1,password=zxc111");
services.AddDataProtection()
.SetApplicationName("basic")
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
}
}

View File

@@ -32,4 +32,14 @@ public class DeviceTaskAssignmentsController : ControllerBase
{
return await _deviceTaskAssignmentService.GetPageAsync(request);
}
/// <summary>
/// 获取设备任务(按设备)
/// </summary>
/// <returns></returns>
[HttpGet("device-tasks")]
public async Task<List<DeviceTaskToDeviceByDeviceResponse>> DeviceGetTasksAsync([FromQuery] DeviceTaskGetRequest request)
{
return await _deviceTaskAssignmentService.DeviceGetTasksAsync(request);
}
}

View File

@@ -0,0 +1,14 @@
using Kurisu.Core.ConfigurableOptions.Attributes;
namespace Dlhis.ScheduledTask.TaskAssignment;
[Configuration]
public class FaceUrlOptions
{
public string Url { get; set; }
/// <summary>
/// 过期时间:秒
/// </summary>
public int Limit { get; set; }
}

View File

@@ -0,0 +1,26 @@
using System.ComponentModel.DataAnnotations;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
namespace Dlhis.ScheduledTask.TaskAssignment.Request;
public class DeviceTaskGetRequest : PageDto, IValidatableObject
{
/// <summary>
/// 品牌
/// </summary>
public string Brand { get; set; }
/// <summary>
/// 设备号
/// </summary>
public string DeviceUniqueNo { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Brand.IsEmpty() && DeviceUniqueNo.IsEmpty())
{
yield return new ValidationResult("设备品牌和设备唯一号不能都为空", new[] { nameof(Brand), nameof(DeviceUniqueNo) });
}
}
}

View File

@@ -0,0 +1,19 @@
namespace Dlhis.ScheduledTask.TaskAssignment.Response;
public class DeviceConnectionResponse
{
/// <summary>
/// 品牌
/// </summary>
public string Brand { get; set; }
/// <summary>
/// 设备唯一号
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 连接信息
/// </summary>
public string ConnectionInfo { get; set; }
}

View File

@@ -0,0 +1,27 @@
namespace Dlhis.ScheduledTask.TaskAssignment.Response;
/// <summary>
/// 设备维度任务
/// </summary>
public class DeviceTaskToDeviceByDeviceResponse
{
/// <summary>
/// 品牌
/// </summary>
public string Brand { get; set; }
/// <summary>
/// 设备唯一号
/// </summary>
public string DeviceUniqueNo { get; set; }
/// <summary>
/// 连接信息
/// </summary>
public string DeviceConnectionInfo { get; set; }
/// <summary>
/// 任务
/// </summary>
public List<TaskCombineUserDimensionDto> Tasks { get; set; }
}

View File

@@ -0,0 +1,27 @@
using Dlhis.Entity.Device.Enums;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.ScheduledTask.TaskAssignment.Response;
public class TaskCombineUserDimensionDto
{
/// <summary>
/// 任务id
/// </summary>
public long TaskId { get; set; }
/// <summary>
/// 任务类型
/// </summary>
public DeviceTaskEnumType Type { get; set; }
/// <summary>
/// 任务类型描述
/// </summary>
public string TypeDesc => Type.GetDescription();
/// <summary>
/// 用户下发信息
/// </summary>
public UserToDeviceResponse UserInfo { get; set; }
}

View File

@@ -0,0 +1,42 @@
using Newtonsoft.Json;
namespace Dlhis.ScheduledTask.TaskAssignment.Response;
public class UserToDeviceResponse
{
/// <summary>
/// 人员档案号
/// </summary>
public string UserNo { get; set; }
/// <summary>
/// 人员学工号
/// </summary>
public string UserCode { get; set; }
/// <summary>
/// 人员名称
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 部门号
/// </summary>
public string DepartmentNo { get; set; }
/// <summary>
/// 部门名称
/// </summary>
public string DepartmentName { get; set; }
/// <summary>
/// 卡号
/// </summary>
public string CardNo { get; set; }
/// <summary>
/// 人脸
/// </summary>
public string Face { get; set; }
}

View File

@@ -7,4 +7,11 @@ namespace Dlhis.ScheduledTask.TaskAssignment.Services;
public interface IDeviceTaskAssignmentService : IScopeDependency
{
Task<Pagination<DeviceTaskAssignmentResponse>> GetPageAsync(DeviceTaskAssignmentRequest request);
/// <summary>
/// 设备获取任务
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
Task<List<DeviceTaskToDeviceByDeviceResponse>> DeviceGetTasksAsync(DeviceTaskGetRequest request);
}

View File

@@ -1,32 +1,44 @@
using Dlhis.Entity.Device.Entities;
using System.Linq.Expressions;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.ScheduledTask.TaskAssignment.Request;
using Dlhis.ScheduledTask.TaskAssignment.Response;
using Kurisu.AspNetCore.Scope;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Services;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
using SqlSugar;
namespace Dlhis.ScheduledTask.TaskAssignment.Services.Implements;
public class DeviceTaskAssignmentService : IDeviceTaskAssignmentService
{
private readonly IDbContext _dbContext;
private readonly ILogger<DeviceTaskAssignmentService> _logger;
public DeviceTaskAssignmentService(IDbContext dbContext)
public DeviceTaskAssignmentService(IDbContext dbContext, ILogger<DeviceTaskAssignmentService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<Pagination<DeviceTaskAssignmentResponse>> GetPageAsync(DeviceTaskAssignmentRequest request)
{
var page = await _dbContext.Queryable<DeviceTaskEntity>()
.Select((deviceTask) => new DeviceTaskAssignmentResponse
.LeftJoin<GainfoEntity>((deviceTask, ga) => deviceTask.UserNo == ga.No)
.Select((deviceTask, ga) => new DeviceTaskAssignmentResponse
{
DeviceUniqueNo = deviceTask.DeviceUniqueNo,
ResultMessage = deviceTask.ResultMessage,
RetryCount = deviceTask.RetryCount,
Status = deviceTask.Status,
UserNo = deviceTask.UserNo,
UserName = deviceTask.UserName,
UserName = ga.Name,
UserCode = deviceTask.UserCode,
Type = deviceTask.Type,
LastUpdateTime = deviceTask.ModifiedTime
@@ -35,4 +47,137 @@ public class DeviceTaskAssignmentService : IDeviceTaskAssignmentService
return page;
}
public async Task<List<DeviceTaskToDeviceByDeviceResponse>> DeviceGetTasksAsync(DeviceTaskGetRequest request)
{
var data = await ContinueUpdateAsync(async () =>
{
var page = await _dbContext.Queryable<DeviceTaskEntity>()
.LeftJoin<DeviceEntity>((deviceTask, deivce) => deviceTask.DeviceUniqueNo == deivce.UniqueNo)
.LeftJoin<DeviceTemplateEntity>((deviceTask, deivce, deivceTamplate) => deivceTamplate.Code == deivce.TemplateCode)
.LeftJoin<GainfoEntity>((deviceTask, deivce, deivceTamplate, ga) => deviceTask.UserNo == ga.No)
.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)
.Where(deviceTask => deviceTask.Status != DeviceTaskStatusEnumType.Success)
.OrderBy(deviceTask => deviceTask.CreateTime)
.Select((deviceTask, deivce, deivceTamplate, ga, department) => new
{
deviceTask.Id,
deviceTask.Type,
deviceTask.DeviceUniqueNo,
DeviceConnectionInfo = deivce.ConnectionInfo,
deivce.Brand,
deviceTask.UserNo,
deviceTask.UserCode,
UserName = ga.Name,
ga.DepartmentNo,
DepartmentName = department.Name,
ga.CardNo,
deviceTask.Version
})
.ToPageListAsync(request);
var taskIdVs = page.Data.Select(x => new { x.Id, x.Version }).ToList();
Expression<Func<DeviceTaskEntity, bool>> where = LinqExpressionExtension.False<DeviceTaskEntity>();
taskIdVs.ForEach(p =>
{
where = where.Or(x => x.Id == p.Id && x.Version == p.Version && x.Status != DeviceTaskStatusEnumType.Success);
});
await _dbContext.Client.Ado.BeginTranAsync();
try
{
var effecet = await _dbContext.Updateable<DeviceTaskEntity>()
.SetColumns(x => x.Version == x.Version + 1)
.SetColumns(x => x.Status == DeviceTaskStatusEnumType.Process)
.SetColumns(x => x.ModifiedTime == DateTime.Now)
.Where(where)
.ExecuteCommandAsync();
if (taskIdVs.Count != effecet)
{
throw new VersionExceptions("更新错误");
}
await _dbContext.Client.Ado.CommitTranAsync();
}
catch
{
await _dbContext.Client.Ado.RollbackTranAsync();
throw;
}
return page.Data;
}, 5);
return Scoped.Request.Value.Create((sp) =>
{
var faceUrlOptions = sp.GetService<IOptions<FaceUrlOptions>>().Value;
var dataProtectionProvider = sp.GetService<IDataProtectionProvider>();
var timeLimitedDataProtector = dataProtectionProvider
.CreateProtector("down:face")
.ToTimeLimitedDataProtector();
return data.GroupBy(x => new { x.Brand, x.DeviceUniqueNo, x.DeviceConnectionInfo })
.Select(x =>
{
var b = x.Key.Brand;
var d = x.Key.DeviceUniqueNo;
var dc = x.Key.DeviceConnectionInfo;
return new DeviceTaskToDeviceByDeviceResponse
{
Brand = b,
DeviceUniqueNo = d,
DeviceConnectionInfo = dc,
Tasks = x.AsEnumerable().Select(item =>
{
var key = $"face:{item.UserCode}";
var token = timeLimitedDataProtector.Protect(key, TimeSpan.FromSeconds(faceUrlOptions.Limit));
return new TaskCombineUserDimensionDto
{
TaskId = item.Id,
Type = item.Type,
UserInfo = new UserToDeviceResponse
{
UserNo = item.UserNo,
UserCode = item.UserCode,
UserName = item.UserName,
DepartmentNo = item.DepartmentNo,
DepartmentName = item.DepartmentName,
CardNo = item.CardNo,
Face = faceUrlOptions.Url + token
}
};
}).ToList()
};
}).ToList();
});
}
private async Task<T> ContinueUpdateAsync<T>(Func<Task<T>> func, int retry)
{
for (int i = 0; i < retry; i++)
{
try
{
return await func();
}
catch (Exception ex) when (ex is VersionExceptions)
{
_logger.LogWarning(ex, ex.Message);
}
catch (Exception)
{
throw;
}
}
throw new UserFriendlyException("操作失败,请重试");
}
}

View File

@@ -5,6 +5,10 @@
"Microsoft.AspNetCore": "Warning"
}
},
"FaceUrlOptions": {
"Url": "http://localhost:5002/api/gainfos/face?token=",
"Limit": 7200
},
"SwaggerOptions": {
"Enable": true,
"Authority": "https://yikatong.isawesome.cn/oauth2",

View File

@@ -8,6 +8,7 @@
"SqlSugarOptions": {
"DefaultConnectionString": "server=192.168.199.124;port=3306;userid=root;password=dlhis123;database=yikatong;charset=utf8mb4;",
"SlaveConnectionString": [],
"FaceConnectionString": "server=192.168.199.124;port=3306;userid=root;password=dlhis123;database=face;charset=utf8mb4;",
"Timeout": 30,
"SlowSqlTime": 1,
"EnableSqlLog": true
@@ -15,6 +16,10 @@
"ConnectionStrings": {
"HangfireConnection": "server=192.168.199.124;port=3306;userid=root;password=dlhis123;database=HangFire;charset=utf8mb4;Allow User Variables=true;"
},
"FaceUrlOptions": {
"Url": "https://yikatong.isawesome.cn/api/basic/gainfos/face?token=",
"Limit": 7200
},
"SwaggerOptions": {
"Enable": true,
"Authority": "http://identity.oauth.svc.cluster.local",