using Dlhis.Basic.Organization.Request; using Dlhis.Basic.Organization.Response; using Dlhis.Entity.Basic.Entity; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.Utils; using Kurisu.AspNetCore.Utils.Extensions; using Mapster; using SqlSugar; namespace Dlhis.Basic.Organization.Services.Implements; public class GainfoOutsourceService : IGainfoOutsourceService { private readonly IDbContext _dbContext; private readonly RedisCache _redisCache; public GainfoOutsourceService(IDbContext dbContext, RedisCache redisCache) { _dbContext = dbContext; _redisCache = redisCache; } public async Task SaveAsync(GainfoOutsourceRequest request) { await CheckIdNoDuplicate(request.IdNo); if (!request.Id.HasValue) { var entity = request.Adapt(); entity.No = Guid.NewGuid().ToString(); entity.Code = await GetOutSourceCodeAsync(); await _dbContext.InsertAsync(entity); await _dbContext.InsertAsync(new OutsourceEntity { Code = entity.Code, Supplier = request.ExternalInfo.Supplier, SapCode = request.ExternalInfo.SapCode, SapPhone = request.ExternalInfo.SapPhone }); } else { var entity = await _dbContext.Queryable().FirstAsync(x => x.Id == request.Id); entity.ThrowIfNull("档案数据不存在"); var outsource = await _dbContext.Queryable().FirstAsync(x => x.Code == entity.Code); (outsource == null).ThrowIfTrue("不可编辑非外包人员档案数据"); request.Adapt(entity); request.ExternalInfo.Adapt(outsource); await _dbContext.UpdateAsync(entity); await _dbContext.UpdateAsync(outsource); } } public async Task GetExternalInfoAsync(string userNo) { return await _dbContext.Queryable() .LeftJoin((a, b) => a.Code == b.Code) .LeftJoin((a, b, c) => a.SapCode == c.Code) .Where((a, b, c) => b.No == userNo) .Select((a, b, c) => new GainfoOutSourceExternalInfoResponse { Supplier = a.Supplier, SapCode = a.SapCode, SapPhone = a.SapPhone, Name = c.Name, EntryDate = b.EntryDate, ResignationDate = b.ResignationDate }) .SingleAsync(); } //********************************************************************** help methods *********************************************************************************** private async Task GetOutSourceCodeAsync() { await using var handler = await _redisCache.LockAsync("gainfo:outsource:code-generate", expiry: TimeSpan.FromSeconds(3), retryInterval: TimeSpan.FromSeconds(1), retryCount: 3); handler.Acquired.ThrowIfFalse("生成虚拟工号失败"); int code; var entity = await _dbContext.Queryable().OrderBy(x => x.Id, OrderByType.Desc).FirstAsync(); if (entity == null) { code = 1; } else { code = int.Parse(entity.Code.Replace("LS", "").TrimStart('0')) + 1; } return "LS" + code.ToString().PadLeft(6, '0'); } /// /// 检查证件号重复 /// /// private async Task CheckIdNoDuplicate(string idNo) { var exists = await _dbContext.Queryable().Where(x => x.IdNo == idNo).AnyAsync(); exists.ThrowIfTrue($"证件号{idNo}重复"); } }