Files
jinko.yikatong/Src/Dlhis.Basic/Organization/Services/Implements/GainfoService.cs
liguoyang f8d1997ddd Squashed commit of the following:
commit 528cdd51c05d26437f0b23f415e06311b667e9f7
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Wed Apr 17 15:37:30 2024 +0800

    feat 访客预约

commit e73a3fcd9307f86aba2c39578495c03cde1d41f9
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Tue Apr 16 16:15:16 2024 +0800

    feat 业务curd

commit b98b6e2764fea875866e11f790f388ccf3c234b5
Merge: a3dcec3 965e84b
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Tue Apr 16 14:56:30 2024 +0800

    Merge branch 'feat-visitorAppointments' of https://git.dlhis.com/liguoyang/jinko.yikatong into feat-visitorAppointments

commit a3dcec30e1289fbb09de8f85009d3931d971337a
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:57:49 2024 +0800

    fix appsettings

commit 766fbec0c45a3852a75a7a37686b885ac3b0a77a
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:37:01 2024 +0800

    add dockerfile

commit 86731d41fee97ba073065ed1b807987760a371a7
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Sun Apr 14 20:11:56 2024 +0800

    fix 测试websocket链接

commit 1301b126a9ba9a7d97cf45967cf2915e1169c505
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:57:49 2024 +0800

    fix appsettings

commit 081f3a67896c67891c3f80edde82a440b8736851
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:37:01 2024 +0800

    add dockerfile

commit 271b6c5898b5732a35ccfa0629ce89442ac49143
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:34:26 2024 +0800

    test 提交测试代码

commit 965e84b6f3b7f925f8021c9b996cce961b896dea
Merge: 578eb6a 6a6fad1
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Mon Apr 15 17:06:45 2024 +0800

    Merge branch 'feat-visitorAppointments' of https://git.dlhis.com/liguoyang/jinko.yikatong into feat-visitorAppointments

commit 578eb6afbd96f0bfe4aaf8058fd4743309c74d62
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Sun Apr 14 20:11:56 2024 +0800

    fix 测试websocket链接

commit 114511f1daea64b7dbf9c3c38b73e28b6d0301e6
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:57:49 2024 +0800

    fix appsettings

commit 5eacfa8af8087eade8553266a12a2cf42305716b
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:37:01 2024 +0800

    add dockerfile

commit b2ffff1f099be343d89690014d05cb859776acbb
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:34:26 2024 +0800

    test 提交测试代码

commit 6a6fad1d1b8772eebf5df12cd74cfd5c955ff560
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Sun Apr 14 20:11:56 2024 +0800

    fix 测试websocket链接

commit 9ce3c4d6f63957c175d65370d9a6b80e10f4254f
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:57:49 2024 +0800

    fix appsettings

commit c637fd89850cf289d7da457c6c6f47354b5beed3
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:37:01 2024 +0800

    add dockerfile

commit 58c39815b1c45a99aea0caf503fcb1365c957f03
Author: liguoyang <Ligy.97@foxmail.com>
Date:   Fri Apr 12 17:34:26 2024 +0800

    test 提交测试代码
2024-04-20 15:29:52 +08:00

519 lines
18 KiB
C#

using System.Text.RegularExpressions;
using Dlhis.Basic.Device.Services;
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Response;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Device.Enums;
using Dlhis.Scheduled.Api;
using Dlhis.Scheduled.Api.Request;
using Dlhis.Sys.Api;
using Kurisu.AspNetCore.Utils;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Core.DataAccess.Dto;
using Kurisu.Core.User.Abstractions;
using Kurisu.SqlSugar.Extensions;
using Kurisu.SqlSugar.Services;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Basic.Organization.Services.Implements;
public class GainfoService : IGainfoService
{
private readonly IGainfoStore _gainfoStore;
private readonly IDbContext _dbContext;
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly ICurrentUser _currentUser;
private readonly IDevicePermissionService _devicePermissionService;
private readonly RedisCache _redisCache;
private readonly IConfiguration _configuration;
private readonly ITenantApi _tenantApi;
private readonly IHangfireApi _hangfireApi;
private readonly ILogger<GainfoService> _logger;
public GainfoService(IGainfoStore gainfoStore,
IDbContext dbContext,
IDataProtectionProvider dataProtectionProvider,
ICurrentUser currentUser,
IDevicePermissionService devicePermissionService,
RedisCache redisCache,
IConfiguration configuration,
ITenantApi tenantApi,
IHangfireApi hangfireApi,
ILogger<GainfoService> logger)
{
_gainfoStore = gainfoStore;
_dbContext = dbContext;
_dataProtectionProvider = dataProtectionProvider;
_currentUser = currentUser;
_devicePermissionService = devicePermissionService;
_redisCache = redisCache;
_configuration = configuration;
_tenantApi = tenantApi;
_hangfireApi = hangfireApi;
_logger = logger;
}
/// <summary>
/// 档案分页
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<Pagination<GainfoPageResponse>> GetPageAsync(GainfoPageRequest request)
{
var currentTenantId = _currentUser.GetStringTenantId();
//根据组织架构搜索档案
var where = LinqExpressionExtensions.False<GainfoEntity>();
foreach (var item in request.DepartmentSelections)
{
var depts = await GetRecursionDepartmentNosAsync(item.DepartmentNos);
if (depts.Any())
where = where.Or(gainfo => gainfo.Factory == item.Tenant && depts.Contains(gainfo.DepartmentNo));
else
where = where.Or(gainfo => gainfo.Factory == item.Tenant);
}
var page = await _gainfoStore.Queryable(request.Status)
.WhereIF(request.DepartmentSelections.IsPresent(), where)
.WhereIF(request.DepartmentSelections.IsEmpty(), gainfo => gainfo.Factory == currentTenantId)
.WhereIF(request.Search.IsPresent(), gainfo =>
gainfo.Name.Contains(request.Search)
|| gainfo.Code == request.Search
|| gainfo.IdNo == request.Search)
.Select<GainfoPageResponse>()
.ToPageListAsync(request);
return page;
}
public async Task<Pagination<GainfoAllPageResponse>> GetPageByCodeAsync(string code)
{
var page = await _gainfoStore.Queryable()
.Where(x => x.Code == code)
.Select<GainfoAllPageResponse>()
.ToPageListAsync(new PageDto { PageIndex = 1, PageSize = 1 });
var tenantsResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantsResult.Data;
page.Data.ForEach(x =>
{
x.Workplace = tenants.FirstOrDefault(item => item.Code == x.Workplace)?.Name;
x.Factory = tenants.FirstOrDefault(item => item.Code == x.Factory)?.Name;
});
return page;
}
public async Task<GainfoCurrentResponse> CurrentUserInfoAsync()
{
var code = _currentUser.GetUserClaim("jinko-code");
if (code.IsEmpty())
{
_logger.LogWarning("工号为空尝试获取人员信息");
return null;
}
var gainfo = await _gainfoStore.Queryable().Where(x => x.Code == code).SingleAsync();
if (gainfo == null)
{
//开启同步处理
await _hangfireApi.SyncSapPersonAsync(new SapNoRequest { Code = code });
return null;
}
var info = await _gainfoStore.Queryable(GainfoStatusEnumType.Working)
.LeftJoin<DepartmentEntity>((ga, department) => ga.DepartmentNo == department.No)
.LeftJoin<GainfoMealEntity>((ga, department, mealUser) => ga.No == mealUser.UserNo)
.Where((ga, department) => ga.Id == gainfo.Id)
.Select((ga, department, mealUser) => new GainfoCurrentResponse
{
UserNo = ga.No,
Birthday = ga.Birthday,
DepartmentNo = department.No,
DepartmentName = department.Name,
Gender = ga.Gender,
UserCode = ga.Code,
UserName = ga.Name,
Factory = ga.Factory,
MealInfo = new GainfoCurrentMealInfoResponse
{
Balance = mealUser.Balance
}
})
.FirstAsync();
if (info != null)
{
try
{
var tenantResult = await _tenantApi.GetTenantByCodeAsync(info.Factory);
if (tenantResult != null && tenantResult.Data != null)
{
info.Factory = tenantResult.Data.Name;
}
}
catch (Exception)
{
}
}
return info;
}
public async Task<IActionResult> GetFaceAsync(string token)
{
var timeLimitedDataProtector = _dataProtectionProvider.CreateProtector("down:face").ToTimeLimitedDataProtector();
try
{
var password = timeLimitedDataProtector.Unprotect(token);
var userCode = password.Split(':')[1];
var faceCache = await _redisCache.HashGetAsync("faces", userCode);
if (faceCache.HasValue)
{
return new FileContentResult(Convert.FromBase64String(faceCache), "image/png");
}
var dbContext = _dbContext.ChangeDb("face");
var face = await dbContext.Queryable<GainfoFaceEntity>().Where(x => x.UserCode == userCode).SingleAsync();
if (face == null)
{
_logger.LogWarning("学工号:{userCode}不存在人脸照片", userCode);
return new NotFoundResult();
}
return new FileContentResult(Convert.FromBase64String(face.Face), "image/png");
}
catch (Exception ex)
{
_logger.LogError(ex, "获取人脸失败:{message}", ex.Message);
return new NotFoundResult();
}
}
public async Task UploadFaceAsync(GainfoUploadFaceRequest request)
{
var gainfo = await _gainfoStore.Queryable().Where(x => x.No == request.UserNo).FirstAsync();
gainfo.ThrowIfNull("人员档案信息不存在");
var userId = _currentUser.GetIntSubjectId();
var faceContext = _dbContext.ChangeDb("face");
var face = await faceContext.Queryable<GainfoFaceEntity>().Where(x => x.UserCode == gainfo.Code).SingleAsync();
var taskType = face == null ? DeviceTaskEnumType.Add : DeviceTaskEnumType.Update;
await _redisCache.HashSetAsync("faces", gainfo.Code, request.Face);
if (face == null)
{
face = new GainfoFaceEntity
{
UserCode = gainfo.Code,
Face = request.Face,
CreateTime = DateTime.Now,
ModifiedTime = DateTime.Now,
CreatedBy = userId,
ModifiedBy = userId
};
await faceContext.InsertAsync(face);
}
else
{
if (face.Face == request.Face)
{
_logger.LogWarning("相同的人脸照片更新忽略");
return;
}
face.Face = request.Face;
face.ModifiedBy = userId;
face.ModifiedTime = DateTime.Now;
await faceContext.UpdateAsync(face);
}
//生成任务
await _devicePermissionService.GenerateDeviceTasksAsync(gainfo.No, taskType);
}
public async Task UploadFacesAsync(List<GainfoUploadFaceRequest> requests)
{
foreach (var request in requests)
{
var gainfo = await _gainfoStore.Queryable(GainfoStatusEnumType.Working).Where(x => x.No == request.UserNo).FirstAsync();
gainfo ??= await _gainfoStore.Queryable(GainfoStatusEnumType.External).Where(x => x.No == request.UserNo).FirstAsync();
gainfo.ThrowIfNull("人员档案信息不存在");
var dbContext = _dbContext.ChangeDb("face");
var face = await dbContext.Queryable<GainfoFaceEntity>().Where(x => x.UserCode == gainfo.Code).SingleAsync();
var taskType = face == null ? DeviceTaskEnumType.Add : DeviceTaskEnumType.Update;
await _redisCache.HashSetAsync("faces", gainfo.Code, request.Face);
if (face == null)
{
face = new GainfoFaceEntity
{
UserCode = gainfo.Code,
Face = request.Face
};
await dbContext.InsertAsync(face);
}
else
{
if (face.Face == request.Face)
{
_logger.LogWarning("相同的人脸照片更新忽略");
return;
}
face.Face = request.Face;
await dbContext.UpdateAsync(face);
}
//生成任务
await _devicePermissionService.GenerateDeviceTasksAsync(gainfo.No, taskType);
}
}
public async Task<string> GetFaceByUserCodeAsync(string userCode)
{
var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == userCode).SingleAsync();
gainfo.ThrowIfNull($"{userCode}人员信息不存在");
var dbContext = _dbContext.ChangeDb("face");
var face = await dbContext.Queryable<GainfoFaceEntity>()
.Where(x => x.UserCode == userCode)
.SingleAsync();
face.ThrowIfNull("人脸照片尚未录入");
var timeLimitedDataProtector = _dataProtectionProvider.CreateProtector("down:face").ToTimeLimitedDataProtector();
var faceUrl = _configuration.GetSection("FaceUrlOptions:Url").Value;
var limit = _configuration.GetSection("FaceUrlOptions:Limit").Get<int>();
var key = $"face:{userCode}";
var token = timeLimitedDataProtector.Protect(key, TimeSpan.FromSeconds(limit));
return faceUrl + token;
}
public async Task<Dictionary<string, string>> GetFaceByUserCodesAsync(GetFaceByUserCodesRequest request)
{
var faceDictionary = new Dictionary<string, string>();
foreach (var userCode in request.UserCodes)
{
try
{
var faceUrl = await GetFaceByUserCodeAsync(userCode);
faceDictionary.Add(userCode, faceUrl);
}
catch (Exception)
{
}
}
return faceDictionary;
}
public async Task<string> CheckIdNoAndNameMatchAsync(GainfoCheckIdNoAndNameRequest request)
{
var match = await _gainfoStore.Queryable(GainfoStatusEnumType.External).AnyAsync(x => x.IdNo == request.IdNo && x.Name == request.Name);
if (!match)
{
match = await _gainfoStore.Queryable(GainfoStatusEnumType.Working).AnyAsync(x => x.IdNo == request.IdNo && x.Name == request.Name);
}
match.ThrowIfFalse("验证失败!");
return request.IdNo;
}
/// <summary>
/// 档案列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<Pagination<GainfoListResponse>> GetGainfoListAsync(GainfoListRequest request)
{
var page = await _gainfoStore.Queryable(request.Status)
.LeftJoin<DepartmentEntity>((ga, de) => ga.DepartmentNo == de.No)
.WhereIF(!request.Name.IsEmpty(), ga => ga.Name == request.Name)
.WhereIF(!request.IdNo.IsEmpty(), ga => ga.IdNo == request.IdNo)
.WhereIF(!request.DepartmentNo.IsEmpty(), ga => ga.DepartmentNo == request.DepartmentNo)
.WhereIF(!request.Code.IsEmpty(), ga => ga.Code == request.Code)
.Select((ga, de) => new GainfoListResponse
{
No = ga.No,
Name = ga.Name,
Code = ga.Code,
IdNo = ga.IdNo,
Gender = ga.Gender,
Phone = ga.Phone,
DepartmentNo = de.No,
DepartmentName = de.Name,
Address = ga.Address,
}).ToPageListAsync(request);
return page;
}
/// <summary>
/// 档案详情
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<GainfoDetailResponse> GetGainfoDetailAsync(GainfoDetailRequest request)
{
var info = await _gainfoStore.Queryable(request.Status)
.LeftJoin<DepartmentEntity>((ga, de) => ga.DepartmentNo == de.No)
.LeftJoin<PositionEntity>((ga, de, pos) => ga.PositionNo == pos.No)
.Where(ga => ga.No == request.No)
.Select((ga, de, pos) => new GainfoDetailResponse
{
No = ga.No,
SapNo = ga.SapNo,
Name = ga.Name,
Code = ga.Code,
IdClass = ga.IdClass,
IdNo = ga.IdNo,
Gender = ga.Gender,
Address = ga.Address,
Birthday = ga.Birthday,
Phone = ga.Phone,
Grade = ga.Grade,
Title = ga.Title,
Degree = ga.Degree,
Werks = ga.Werks,
CostId = ga.CostId,
NativeName = ga.Native,
CountryName = ga.CountryNo,
NationName = ga.Nation,
ClassName = ga.IdClass,
EntryDate = ga.EntryDate,
Workplace = ga.Workplace,
Factory = ga.Factory,
DepartmentName = de.Name,
Position = pos.Name,
})
.SingleAsync();
if (info != null)
{
var searchTypes = new List<string>() { "native", "country", "nation", "cls" };
var types = await _dbContext.Queryable<BasicTypeEntity>().Where(x => searchTypes.Contains(x.Type)).ToListAsync();
info.NativeName = types.Where(x => x.Type == "native").FirstOrDefault(x => x.Code == info.NativeName)?.Display;
info.CountryName = types.Where(x => x.Type == "country").FirstOrDefault(x => x.Code == info.CountryName)?.Display ?? "中国";
info.NationName = types.Where(x => x.Type == "nation").FirstOrDefault(x => x.Code == info.NationName)?.Display;
info.ClassName = types.Where(x => x.Type == "cls").FirstOrDefault(x => x.Code == info.ClassName)?.Display ?? "身份证";
if (request.WithFace)
{
info.Face = await _dbContext.ChangeDb("face").Queryable<GainfoFaceEntity>().Where(x => x.UserCode == info.Code).Select(x => x.Face).SingleAsync();
}
try
{
var tenantsResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantsResult.Data;
info.Workplace = tenants.FirstOrDefault(x => x.Code == info.Workplace)?.Name;
info.Factory = tenants.FirstOrDefault(x => x.Code == info.Factory)?.Name;
}
catch (Exception)
{
}
}
return info;
}
public async Task MigrationAsync(MigrationRequest request)
{
//档案数据
var gainfo = await _gainfoStore.Queryable().Where(x => x.Code == request.Code).FirstAsync();
if (gainfo == null)
{
return;
}
//卡号为空则更新
if (gainfo.CardNo.IsEmpty())
{
gainfo.CardNo = request.CardNo;
await _gainfoStore.UpdateAsync(gainfo);
}
//外部传入人脸
if (request.Face.IsPresent())
{
var faceDbContext = _dbContext.ChangeDb("face");
var exists = await faceDbContext.Queryable<GainfoFaceEntity>().AnyAsync(x => x.UserCode == gainfo.Code);
//人脸不存在则写入
if (!exists)
{
await faceDbContext.InsertAsync(new GainfoFaceEntity
{
CreatedBy = 1,
CreateTime = DateTime.Now,
ModifiedBy = 1,
ModifiedTime = DateTime.Now,
UserCode = gainfo.Code,
Face = request.Face,
});
}
}
}
//-------------------------------------------help methods ------------------------------------------------
/// <summary>
/// 递归获取部门No
/// </summary>
/// <param name="departmentNos"></param>
/// <returns></returns>
private async Task<List<string>> GetRecursionDepartmentNosAsync(List<string> departmentNos)
{
if (departmentNos.IsEmpty())
{
return new List<string>();
}
var departments = await _dbContext.Queryable<DepartmentEntity>().ToListAsync();
var currentNos = departments.Where(x => departmentNos.Contains(x.No)).ToList();
foreach (var item in currentNos)
{
RecursionGetNext(item.No, departments, departmentNos);
}
return departmentNos.Distinct().ToList();
//local method
void RecursionGetNext(string currentNo, List<DepartmentEntity> departments, List<string> result)
{
var next = departments.Where(x => x.PNo == currentNo).ToList();
foreach (var item in next)
{
result.Add(item.No);
RecursionGetNext(item.No, departments, result);
}
}
}
}