refactor 优化代码

This commit is contained in:
2024-11-26 15:26:12 +08:00
parent a32910f0d9
commit 623a5c4e49
88 changed files with 1820 additions and 941 deletions

View File

@@ -140,8 +140,7 @@ public class BusinessPlaceShiftService : IBusinessPlaceShiftService
};
}
var tenantResult = await _tenantApi.GetTenantByCodeAsync(place.TenantId);
var tenantInfo = tenantResult.EnsureSuccessStatusCode();
var tenant = await _tenantApi.GetTenantByCodeAsync(place.TenantId);
var relationship = await _dbContext.Queryable<BusinessPlaceShiftRelationshipEntity>().Where(x => x.PlaceCode == place.Code).FirstAsync();
if (relationship == null)
@@ -150,8 +149,8 @@ public class BusinessPlaceShiftService : IBusinessPlaceShiftService
{
CustomCode = placeCustomCode,
Name = place.Name,
TenantCode = tenantInfo.Code,
TenantName = tenantInfo.Name,
TenantCode = tenant.Code,
TenantName = tenant.Name,
Shifts = new List<BusinessPlaceShiftTinyResponse>()
};
}
@@ -181,8 +180,8 @@ public class BusinessPlaceShiftService : IBusinessPlaceShiftService
{
CustomCode = placeCustomCode,
Name = place.Name,
TenantCode = tenantInfo.Code,
TenantName = tenantInfo.Name,
TenantCode = tenant.Code,
TenantName = tenant.Name,
Shifts = list.OrderBy(x => x.Sequence).ToList()
};
}

View File

@@ -33,9 +33,9 @@ public class DeviceGroupService : IDeviceGroupService
public async Task<List<DeviceGroupTreeResponse>> GetTreeAsync(DeviceTypeEnumType type)
{
var tenantResult = await _tenantApi.GetMyTenantsAsync();
var tenantIds = tenantResult.Data.Select(x => x.Code).ToList();
tenantIds.AddRange(tenantResult.Data.Select(x => x.PCode));
var tenants = await _tenantApi.GetMyTenantsAsync();
var tenantIds = tenants.Select(x => x.Code).ToList();
tenantIds.AddRange(tenants.Select(x => x.PCode));
var deviceGroups = await _dbContext.Queryable<DeviceGroupEntity>()
.Where(x => tenantIds.Contains(x.TenantId))

View File

@@ -379,8 +379,7 @@ public class DevicePermissionService : IDevicePermissionService
.Where(x => x.num == 1)
.ToListAsync();
var tenantsResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantsResult.Data;
var tenants = await _tenantApi.GetTenantsInternalAsync();
page.Data.ForEach(x =>
{

View File

@@ -246,8 +246,8 @@ public class DeviceService : IDeviceService
var factory = device.TenantId;
try
{
var tenantResult = await _tenantApi.GetTenantByCodeAsync(device.TenantId);
factory = tenantResult?.Data?.Name ?? string.Empty;
var tenant = await _tenantApi.GetTenantByCodeAsync(device.TenantId);
factory = tenant?.Name ?? string.Empty;
}
catch (Exception)
{

View File

@@ -27,7 +27,7 @@
<ItemGroup>
<ProjectReference Include="..\Dlhis.Entity\Dlhis.Entity.csproj" />
<ProjectReference Include="..\Dlhis.InfoCheck.Api\Dlhis.InfoCheck.Api.csproj" />
<ProjectReference Include="..\Dlhis.Scheduled.Api\Dlhis.Scheduled.Api.csproj" />
<ProjectReference Include="..\Dlhis.Jip.Api\Dlhis.Jip.Api.csproj" />
<ProjectReference Include="..\Dlhis.Sys.Api\Dlhis.Sys.Api.csproj" />
</ItemGroup>

View File

@@ -0,0 +1,21 @@
using System.Net.Http.Headers;
using System.Text;
using Kurisu.AspNetCore.Startup;
namespace Dlhis.Basic;
public class JinkoSapHttpClientPack : BaseAppPack
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("jinko:sap", (_, httpClient) =>
{
httpClient.BaseAddress = new Uri($"http://sappipap01.jinkosolar.cn:50100");
httpClient.Timeout = TimeSpan.FromMinutes(10);
const string credentials = "EHS_USER:y3R1hd2h*RICAC";
var headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);
});
}
}

View File

@@ -0,0 +1,70 @@
using Dlhis.Basic.Organization.Services.Implements;
using Dlhis.Jip.Api.Dto;
namespace Dlhis.Basic.Organization.Comparers;
/// <summary>
/// 人员信息比较器
/// </summary>
public class SapPersonComparer : IEqualityComparer<SapPersonItem>
{
public bool Equals(SapPersonItem x, SapPersonItem y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
return x.PERNR == y.PERNR
&& x.WERKS == y.WERKS
&& x.ORGEH == y.ORGEH
&& x.NAME == y.NAME
&& x.GBDAT == y.GBDAT
&& (x.ZZ_SFZH ?? string.Empty) == (y.ZZ_SFZH ?? string.Empty)
&& x.ZWORKCODE == y.ZWORKCODE
&& (x.ZMOBILE ?? string.Empty) == (y.ZMOBILE ?? string.Empty)
&& (x.ZSTATUS ?? string.Empty) == (y.ZSTATUS ?? string.Empty)
&& (x.KOSTL ?? string.Empty) == (y.KOSTL ?? string.Empty)
&& (x.ZZ_ZD ?? string.Empty) == (y.ZZ_ZD ?? string.Empty)
&& (x.Z_ZJ ?? string.Empty) == (y.Z_ZJ ?? string.Empty)
&& x.ZRZRQ == y.ZRZRQ
&& x.ZLZRQ == y.ZLZRQ
&& (x.STELL ?? string.Empty) == (y.STELL ?? string.Empty)
&& (x.STELL_NM ?? string.Empty) == (y.STELL_NM ?? string.Empty)
&& (x.MASSN ?? string.Empty) == (y.MASSN ?? string.Empty)
&& (x.MNTXT ?? string.Empty) == (y.MNTXT ?? string.Empty)
&& (x.ZXUELI ?? string.Empty).Trim() == (y.ZXUELI ?? string.Empty).Trim()
&& (x.ZZ_KLX ?? string.Empty) == (y.ZZ_KLX ?? string.Empty)
&& (x.ZZ_GZDJDNM ?? string.Empty) == (y.ZZ_GZDJDNM ?? string.Empty)
&& (x.ZZ_GZDCQNM ?? string.Empty) == (y.ZZ_GZDCQNM ?? string.Empty)
;
}
public int GetHashCode(SapPersonItem obj)
{
var r = obj.PERNR.SafeGetHashCode()
^ obj.WERKS.SafeGetHashCode()
^ obj.ORGEH.SafeGetHashCode()
^ obj.NAME.SafeGetHashCode()
^ obj.GBDAT.SafeGetHashCode()
^ obj.ZZ_SFZH.SafeGetHashCode()
^ obj.ZWORKCODE.SafeGetHashCode()
^ obj.ZMOBILE.SafeGetHashCode()
^ obj.ZSTATUS.SafeGetHashCode()
^ obj.KOSTL.SafeGetHashCode()
^ obj.ZZ_ZD.SafeGetHashCode()
^ obj.Z_ZJ.SafeGetHashCode()
^ obj.ZRZRQ.SafeGetHashCode()
^ obj.ZLZRQ.SafeGetHashCode()
^ obj.STELL.SafeGetHashCode()
^ obj.STELL_NM.SafeGetHashCode()
^ obj.MASSN.SafeGetHashCode()
^ obj.MNTXT.SafeGetHashCode()
^ obj.ZXUELI.SafeGetHashCode()
^ obj.ZZ_KLX.SafeGetHashCode()
^ obj.ZZ_GZDJDNM.SafeGetHashCode()
^ obj.ZZ_GZDCQNM.SafeGetHashCode()
;
return r;
}
}

View File

@@ -66,17 +66,4 @@ public class GainfoPermissionsController : ControllerBase
{
return await _gainfoPermissions.GetAssignGroupAsync(userNo);
}
/// <summary>
/// 权限下发重置
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("reset")]
[IgnoreTenant]
public async Task ResetPermissionsAsync(GainfoPermissionResetRequest request)
{
await _gainfoPermissions.ResetPermissionsAsync(request);
}
}

View File

@@ -0,0 +1,55 @@
using Dlhis.Basic.Organization.Request;
using Dlhis.Basic.Organization.Services;
using Dlhis.Jip.Api.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Dlhis.Basic.Organization.Controllers;
[AllowAnonymous]
[ApiController]
[Route("/api/[controller]")]
public class SyncController : ControllerBase
{
private readonly IGainfoUpdateService _gainfoUpdateService;
private readonly IJinkoSapService _jinkoSapService;
private readonly ISapBusinessTripService _sapBusinessTripService;
public SyncController(IGainfoUpdateService gainfoUpdateService, IJinkoSapService jinkoSapService, ISapBusinessTripService sapBusinessTripService)
{
_gainfoUpdateService = gainfoUpdateService;
_jinkoSapService = jinkoSapService;
_sapBusinessTripService = sapBusinessTripService;
}
[HttpPost("/api/sync/gainfo/werk")]
public async Task TodoByWerkAsync(CodeRequest request)
{
await _gainfoUpdateService.TodoByWerkAsync(request.Code);
}
[HttpPost("/api/sync/gainfo/user")]
public async Task TodoByCodeAsync(CodeRequest request)
{
await _gainfoUpdateService.TodoByCodeAsync(request.Code);
}
[HttpGet("/api/sync/orgs")]
public async Task<SapOrganizationResponse> GetOrgsSync()
{
return await _jinkoSapService.GetSapOrganizationsAsync();
}
[HttpGet("/api/sync/positions")]
public async Task<SapPositionResponse> GetPositionsAsync()
{
return await _jinkoSapService.GetPositionsAsync();
}
[HttpPost("/api/sync/businessTrips")]
public async Task GetPositionsAsync(CodeRequest request)
{
await _sapBusinessTripService.HandlerBusinessTripsByFactoryAsync(request.Code);
}
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Basic.Organization.Request;
public class CodeRequest
{
public string Code { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace Dlhis.Basic.Organization.Services;
public interface IGainfoUpdateService : IScopeDependency
{
Task TodoByWerkAsync(string werk);
Task TodoByCodeAsync(string code);
}

View File

@@ -0,0 +1,6 @@
namespace Dlhis.Basic.Organization.Services;
public interface IIdentityUserSyncService : IScopeDependency
{
Task SyncAccountAsync(string userName, string name, string idNo, string tenant);
}

View File

@@ -0,0 +1,14 @@
using Dlhis.Jip.Api.Responses;
namespace Dlhis.Basic.Organization.Services;
public interface IJinkoSapService : IScopeDependency
{
Task<SapOrganizationResponse> GetSapOrganizationsAsync();
Task<SapPositionResponse> GetPositionsAsync();
Task<SapPersonResponse> GetPersonsByWerkAsync(string werk);
Task<SapPersonResponse> GetPersonsByCodeAsync(string code);
}

View File

@@ -79,8 +79,7 @@ public class FactorySettingService : IFactorySettingService
}
else
{
var apiResult = await _tenantApi.GetMyTenantsAsync();
factories = apiResult.Data;
factories = await _tenantApi.GetMyTenantsAsync();
}
var factoryCodes = factories.Select(x => x.Code).ToList();

View File

@@ -8,8 +8,7 @@ using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Device.Enums;
using Dlhis.InfoCheck.Api;
using Dlhis.InfoCheck.Api.Requests;
using Dlhis.Scheduled.Api;
using Dlhis.Scheduled.Api.Request;
using Dlhis.Jip.Api;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.CustomClass;
using Kurisu.AspNetCore.DataAccess.Extensions;
@@ -28,11 +27,11 @@ public class GainfoFaceService : IGainfoFaceService
private readonly ILogger<GainfoFaceService> _logger;
private readonly IConfiguration _configuration;
private readonly ICurrentUser _currentUser;
private readonly IHangfireApi _hangfireApi;
private readonly IDevicePermissionService _devicePermissionService;
private readonly IFactorySettingService _factorySettingService;
private readonly IHainingApi _hainingApi;
private readonly IInfoCheckApi _infoCheckApi;
private readonly IJinkoJipApi _jinkoJipApi;
private readonly IDataProtectionProvider _dataProtectionProvider;
public GainfoFaceService(IGainfoStore gainfoStore,
@@ -40,11 +39,11 @@ public class GainfoFaceService : IGainfoFaceService
ILogger<GainfoFaceService> logger,
IConfiguration configuration,
ICurrentUser currentUser,
IHangfireApi hangfireApi,
IDevicePermissionService devicePermissionService,
IFactorySettingService factorySettingService,
IHainingApi hainingApi,
IInfoCheckApi infoCheckApi,
IJinkoJipApi jinkoJipApi,
IDataProtectionProvider dataProtectionProvider)
{
_gainfoStore = gainfoStore;
@@ -53,11 +52,11 @@ public class GainfoFaceService : IGainfoFaceService
_logger = logger;
_configuration = configuration;
_currentUser = currentUser;
_hangfireApi = hangfireApi;
_devicePermissionService = devicePermissionService;
_factorySettingService = factorySettingService;
_hainingApi = hainingApi;
_infoCheckApi = infoCheckApi;
_jinkoJipApi = jinkoJipApi;
_dataProtectionProvider = dataProtectionProvider;
}
@@ -109,7 +108,7 @@ public class GainfoFaceService : IGainfoFaceService
var gainfo = await _gainfoStore.Queryable(GainfoStatusEnumType.External)
.Where(x => x.IdNo == request.UserNo)
.SingleAsync();
gainfo ??= await _gainfoStore.Queryable(GainfoStatusEnumType.Working)
.Where(x => x.IdNo == request.UserNo)
.SingleAsync();
@@ -231,11 +230,14 @@ public class GainfoFaceService : IGainfoFaceService
try
{
await _hangfireApi.SyncFaceToSapAsync(new FaceUploadToSapRequest
var r = await _jinkoJipApi.SyncFaceToSapAsync(face.UserCode, face.Face);
if (r.OLX == "S")
{
UserCode = face.UserCode,
Base64 = face.Face
});
await _faceDbContext.Updateable<GainfoFaceEntity>()
.SetColumns(x => x.IsSync == true)
.Where(x => x.UserCode == face.UserCode)
.ExecuteCommandAsync();
}
}
catch (Exception e)
{
@@ -372,7 +374,7 @@ public class GainfoFaceService : IGainfoFaceService
Level = (int)x.Level
}).ToList()
});
r = result.Data;
r = result;
}
catch (Exception ex)
{

View File

@@ -6,8 +6,6 @@ using Dlhis.Entity.Basic.Enums;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.Entity.Visitor.Entity;
using Dlhis.Scheduled.Api;
using Dlhis.Scheduled.Api.Request;
using Dlhis.Sys.Api;
using Kurisu.AspNetCore.Authentication.Abstractions;
using Kurisu.AspNetCore.DataAccess.Dto;
@@ -26,7 +24,7 @@ public class GainfoService : IGainfoService
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly ICurrentUser _currentUser;
private readonly ITenantApi _tenantApi;
private readonly IHangfireApi _hangfireApi;
private readonly IJinkoSapService _jinkoSapService;
private readonly IDevicePermissionService _devicePermissionService;
private readonly IGainfoPermissionService _gainfoPermissionService;
private readonly ILogger<GainfoService> _logger;
@@ -36,7 +34,7 @@ public class GainfoService : IGainfoService
IDataProtectionProvider dataProtectionProvider,
ICurrentUser currentUser,
ITenantApi tenantApi,
IHangfireApi hangfireApi,
IJinkoSapService jinkoSapService,
IDevicePermissionService devicePermissionService,
IGainfoPermissionService gainfoPermissionService,
ILogger<GainfoService> logger)
@@ -46,7 +44,7 @@ public class GainfoService : IGainfoService
_dataProtectionProvider = dataProtectionProvider;
_currentUser = currentUser;
_tenantApi = tenantApi;
_hangfireApi = hangfireApi;
_jinkoSapService = jinkoSapService;
_devicePermissionService = devicePermissionService;
_gainfoPermissionService = gainfoPermissionService;
_logger = logger;
@@ -166,8 +164,7 @@ public class GainfoService : IGainfoService
.Select<GainfoAllPageResponse>()
.ToPageListAsync(new PageDto { PageIndex = 1, PageSize = 1 });
var tenantsResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantsResult.Data;
var tenants = await _tenantApi.GetTenantsInternalAsync();
page.Data.ForEach(x =>
{
@@ -191,8 +188,9 @@ public class GainfoService : IGainfoService
if (gainfo == null)
{
//开启同步处理
await _hangfireApi.SyncSapPersonAsync(new SapNoRequest { Code = code });
return null;
await _jinkoSapService.GetPersonsByCodeAsync(code);
gainfo = await _gainfoStore.Queryable().Where(x => x.Code == code).SingleAsync();
if (gainfo == null) return null;
}
var info = await _gainfoStore.Queryable(GainfoStatusEnumType.Working)
@@ -217,11 +215,8 @@ public class GainfoService : IGainfoService
{
try
{
var tenantResult = await _tenantApi.GetTenantByCodeAsync(info.Factory);
if (tenantResult is { Data: not null })
{
info.FactoryName = tenantResult.Data.Name;
}
var tenant = await _tenantApi.GetTenantByCodeAsync(info.Factory);
info.FactoryName = tenant?.Name;
}
catch (Exception)
{
@@ -408,8 +403,7 @@ public class GainfoService : IGainfoService
try
{
var tenantsResult = await _tenantApi.GetTenantsInternalAsync();
var tenants = tenantsResult.Data;
var tenants = await _tenantApi.GetTenantsInternalAsync();
info.Workplace = tenants.FirstOrDefault(x => x.Code == info.Workplace)?.Name;
info.Factory = tenants.FirstOrDefault(x => x.Code == info.Factory)?.Name;

View File

@@ -0,0 +1,506 @@
using Dlhis.Basic.Device.Services;
using Dlhis.Basic.Organization.Comparers;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums;
using Dlhis.Jip.Api.Dto;
using Dlhis.Sys.Api;
using Dlhis.Sys.Api.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
namespace Dlhis.Basic.Organization.Services.Implements;
public class GainfoUpdateService : IGainfoUpdateService
{
private readonly IDbContext _dbContext;
private readonly ILogger<GainfoUpdateService> _logger;
private readonly ITenantApi _tenantApi;
private readonly IJinkoSapService _jinkoSapService;
private readonly IDevicePermissionService _devicePermissionService;
private readonly IIdentityUserSyncService _identityUserSyncService;
private List<TenantResponse> _tenants;
public GainfoUpdateService(IDbContext dbContext,
ILogger<GainfoUpdateService> logger,
ITenantApi tenantApi,
IJinkoSapService jinkoSapService,
IDevicePermissionService devicePermissionService,
IIdentityUserSyncService identityUserSyncService)
{
_dbContext = dbContext;
_dbContext.Client.QueryFilter.Clear();
_logger = logger;
_tenantApi = tenantApi;
_jinkoSapService = jinkoSapService;
_devicePermissionService = devicePermissionService;
_identityUserSyncService = identityUserSyncService;
}
public async Task TodoByWerkAsync(string werk)
{
var werkInfo = await _dbContext.Queryable<WerkEntity>().Where(x => x.Werk == werk).SingleAsync();
werkInfo.LastSyncStartTime = DateTime.Now;
werkInfo.HandleMessage = "任务执行中";
await _dbContext.UpdateAsync(werkInfo);
try
{
var personResp = await _jinkoSapService.GetPersonsByWerkAsync(werk);
var persons = personResp.Person.Items;
werkInfo.HandleMessage = "SAP人员数量" + persons.Count;
werkInfo.Total = persons.Count;
await _dbContext.UpdateAsync(werkInfo);
if (persons.Count > 0)
{
var modifiedPersons = await GetModifiedPersonAsync(persons.OrderByDescending(x => x.ZSTATUS).ThenBy(x => x.ZRZRQ).ToList());
werkInfo.HandleMessage = "SAP人员差异数量" + modifiedPersons.Count;
werkInfo.DiffNumber = modifiedPersons.Count;
await _dbContext.UpdateAsync(werkInfo);
if (modifiedPersons.Count > 0)
{
await SavePersonAsync(modifiedPersons);
}
}
werkInfo.HandleMessage = "同步结束";
werkInfo.LastSyncEndTime = DateTime.Now;
werkInfo.BackgroundJobKey = string.Empty;
await _dbContext.UpdateAsync(werkInfo);
}
catch (Exception ex)
{
_logger.LogError(ex, "{werk}同步处理异常:{message}", werk, ex.Message);
werkInfo.HandleMessage = ex.Message;
werkInfo.LastSyncEndTime = DateTime.Now;
werkInfo.BackgroundJobKey = string.Empty;
await _dbContext.UpdateAsync(werkInfo);
}
}
public async Task TodoByCodeAsync(string code)
{
_logger.LogInformation("SAP根据学工号同步开始:{code}", code);
var personResp = await _jinkoSapService.GetPersonsByCodeAsync(code);
var persons = personResp.Person.Items;
_logger.LogInformation("获取SAP人员数量为:{count}", persons.Count);
if (persons.Count > 0)
{
var modifiedPersons = await GetModifiedPersonAsync(persons.OrderByDescending(x => x.ZSTATUS).ThenBy(x => x.ZRZRQ).ToList());
_logger.LogInformation("SAP人员差异数量为:{count}", modifiedPersons.Count);
if (modifiedPersons.Count > 0)
{
await SavePersonAsync(modifiedPersons);
}
}
_logger.LogInformation("SAP根据学工号同步结束:{code}", code);
}
private async Task SavePersonAsync(List<SapPersonItem> persons)
{
_tenants = await _tenantApi.GetTenantsInternalAsync();
var workCodes = persons.Select(x => x.ZWORKCODE).ToList();
var chunks = workCodes.Chunk(4000).ToList();
foreach (var searchCodes in chunks)
{
_logger.LogWarning("SAP分批处理Chunk数量:{count}", searchCodes.Length);
var existsWorkCodes = await _dbContext.Queryable<GainfoSapEntity>()
.Where(x => searchCodes.Contains(x.ename))
.Select(x => x.ename)
.ToListAsync();
var originUpdates = persons.Where(x => existsWorkCodes.Contains(x.ZWORKCODE)).ToList();
var existsUpdateWorkCodes = originUpdates.Select(x => x.ZWORKCODE).ToList();
var originInserts = persons.Where(x => searchCodes.Contains(x.ZWORKCODE)).Where(x => !existsUpdateWorkCodes.Contains(x.ZWORKCODE)).ToList();
var updates = ToGainfoSap(originUpdates);
var inserts = ToGainfoSap(originInserts);
foreach (var item in inserts)
{
try
{
await InsertPersonAsync(item);
}
catch (Exception ex)
{
_logger.LogError(ex, "执行新增失败:{message}", ex.Message);
}
}
foreach (var item in updates)
{
try
{
var no = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == item.ename).Select(x => x.No).SingleAsync();
if (no.IsEmpty())
{
await InsertPersonAsync(item);
}
else
{
await UpdatePersonAsync(item);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "执行更新失败:{message}", ex.Message);
}
}
}
}
private async Task InsertPersonAsync(GainfoSapEntity item)
{
await _dbContext.InsertAsync(item);
var info = GainfoSapToGainfo(item);
if (item.isowner == "T")
{
await _devicePermissionService.GenerateDeviceTasksAsync(async () =>
{
await _dbContext.InsertAsync(info);
await _identityUserSyncService.SyncAccountAsync(info.Code, info.Name, info.IdNo, info.Factory);
}, new List<string> { info.No });
}
else
{
if (!await _dbContext.Queryable<GainfoLeaveEntity>().AnyAsync(x => x.Code == item.ename))
{
await _dbContext.Client.Insertable(info).AS("GainfoLeave").ExecuteCommandAsync();
}
}
}
private GainfoEntity GainfoSapToGainfo(GainfoSapEntity item)
{
var info = new GainfoEntity
{
No = Guid.NewGuid().ToString(),
InternalNo = item.PERNR,
Type = GainfoUserTypeEnumType.Normal,
Name = item.gname,
Code = item.ename,
CountryNo = item.country,
IdClass = item.idcls,
IdNo = item.idno,
Native = item.native,
Gender = item.sex == "F" ? GenderEnumType.Female : GenderEnumType.Male,
Birthday = item.birthday,
Address = item.address,
DepartmentNo = item.appellation,
Nation = item.nation,
Phone = item.phone,
Degree = item.email,
Grade = item.ZZ_ZD,
Title = item.Z_ZJ,
PositionNo = item.STELL,
Remark = item.remark,
Werks = item.WERKS,
CostId = item.KOSTL,
EntryDate = item.createdate,
ResignationDate = item.ZLZRQ,
CardType = SafeParseCardType(item.ZZ_KLX),
Workplace = _tenants.LastOrDefault(x => x.Name == item.ZZ_GZDJDNM)?.Code ?? item.ZZ_GZDJDNM,
Factory = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDCQNM)?.Code ?? item.ZZ_GZDCQNM,
};
return info;
}
private async Task UpdatePersonAsync(GainfoSapEntity item)
{
var info = GainfoSapToGainfo(item);
await _dbContext.Updateable<GainfoSapEntity>().SetColumns(g => new GainfoSapEntity
{
PERNR = item.PERNR,
gname = item.gname,
phone = item.phone,
appellation = item.appellation,
isowner = item.isowner,
remark = item.remark,
email = item.email,
WERKS = item.WERKS,
KOSTL = item.KOSTL,
STELL = item.STELL,
Z_ZJ = item.Z_ZJ,
ZZ_ZD = item.ZZ_ZD,
MNTXT = item.MNTXT,
MASSN = item.MASSN,
ZSTATUS = item.ZSTATUS,
ZLZRQ = item.ZLZRQ,
STELL_NM = item.STELL_NM,
ZZ_KLX = item.ZZ_KLX,
createdate = item.createdate,
ZZ_GZDJDNM = item.ZZ_GZDJDNM,
ZZ_GZDCQNM = item.ZZ_GZDCQNM,
}).Where(x => x.ename == item.ename).ExecuteCommandAsync();
//获取当前在职人员
var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == item.ename).SingleAsync();
var workplace = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDJDNM)?.Code ?? item.ZZ_GZDJDNM;
var factory = _tenants.LastOrDefault(x => x.Name == item.ZZ_GZDCQNM)?.Code ?? item.ZZ_GZDCQNM;
if (gainfo != null)
{
if (item.isowner == "T")
{
await _devicePermissionService.GenerateDeviceTasksAsync(async () =>
{
await _dbContext.Updateable<GainfoEntity>().SetColumns(g => new GainfoEntity
{
InternalNo = item.PERNR,
Name = item.gname,
PositionNo = item.STELL,
Grade = item.ZZ_ZD,
Title = item.Z_ZJ,
Phone = item.phone,
DepartmentNo = item.appellation,
Remark = item.remark,
Degree = item.email,
Werks = item.WERKS,
CostId = item.KOSTL,
EntryDate = item.createdate,
ResignationDate = item.ZLZRQ,
Workplace = workplace,
Factory = factory,
CardType = SafeParseCardType(item.ZZ_KLX)
}).Where(x => x.Code == item.ename).ExecuteCommandAsync();
await _identityUserSyncService.SyncAccountAsync(gainfo.Code, gainfo.Name, gainfo.IdNo, factory);
}, new List<string> { gainfo.No });
}
else
{
await _devicePermissionService.GenerateDeviceTasksAsync(async () =>
{
await _dbContext.Updateable<GainfoEntity>().SetColumns(g => new GainfoEntity
{
InternalNo = item.PERNR,
Name = item.gname,
PositionNo = item.STELL,
Grade = item.ZZ_ZD,
Title = item.Z_ZJ,
Phone = item.phone,
DepartmentNo = item.appellation,
Remark = item.remark,
Degree = item.email,
Werks = item.WERKS,
CostId = item.KOSTL,
EntryDate = item.createdate,
ResignationDate = item.ZLZRQ,
Workplace = workplace,
Factory = factory,
CardType = SafeParseCardType(item.ZZ_KLX)
}).Where(x => x.Code == item.ename).ExecuteCommandAsync();
await _identityUserSyncService.SyncAccountAsync(gainfo.Code, gainfo.Name, gainfo.IdNo, factory);
}, new List<string> { gainfo.No });
try
{
//先写入离职表
gainfo.IdentityUserId = (int)gainfo.Id; //记录原始id
gainfo.Id = 0;
gainfo.ResignationDate = item.ZLZRQ;
if (!await _dbContext.Queryable<GainfoLeaveEntity>().AnyAsync(x => x.Code == item.ename))
{
await _dbContext.Client.Insertable(gainfo).AS("GainfoLeave").ExecuteCommandAsync();
}
gainfo.Id = gainfo.IdentityUserId;
await _dbContext.DeleteReallyAsync(gainfo);
}
catch (Exception ex)
{
_logger.LogError(ex, "离职任务生成失败:{message}", ex.Message);
}
}
}
else
{
if (item.isowner == "T")
{
await _dbContext.InsertAsync(info);
await _identityUserSyncService.SyncAccountAsync(info.Code, info.Name, info.IdNo, factory);
}
else
{
if (!await _dbContext.Queryable<GainfoLeaveEntity>().AnyAsync(x => x.Code == item.ename))
{
await _dbContext.Client.Insertable(info).AS("GainfoLeave").ExecuteCommandAsync();
}
else
{
await _dbContext.Updateable<GainfoLeaveEntity>().SetColumns(g => new GainfoLeaveEntity
{
InternalNo = item.PERNR,
Name = item.gname,
PositionNo = item.STELL,
Grade = item.ZZ_ZD,
Title = item.Z_ZJ,
Phone = item.phone,
DepartmentNo = item.appellation,
Remark = item.remark,
Degree = item.email,
Werks = item.WERKS,
CostId = item.KOSTL,
EntryDate = item.createdate,
ResignationDate = item.ZLZRQ,
Workplace = workplace,
Factory = factory,
CardType = SafeParseCardType(item.ZZ_KLX)
}).Where(x => x.Code == item.ename).ExecuteCommandAsync();
}
}
}
}
private async Task<List<SapPersonItem>> GetModifiedPersonAsync(List<SapPersonItem> sapList)
{
var last = await LoadDataAsync();
if (last.Count <= 0)
{
return sapList;
}
var needRemove = sapList.Intersect(last, new SapPersonComparer()).ToList();
return sapList.Except(needRemove, new SapPersonComparer()).ToList();
}
private async Task<List<SapPersonItem>> LoadDataAsync()
{
//var pJson = "{\"id\":0,\"ano\":null,\"class\":\"C\",\"passwd\":null,\"question\":null,\"answer\":null,\"gname\":\"岳文超\",\"ename\":\"098250\",\"country\":null,\"idcls\":\"ID\",\"idno\":\"\\\"140105200112051318\n\",\"native\":\"14010\",\"sex\":\"M\",\"birthday\":\"2001-12-05T00:00:00\",\"address\":\"\",\"postcode\":null,\"occupation\":\"99\",\"appellation\":\"00210591\",\"nation\":\"01\",\"phone\":\"13773151205\",\"fax\":null,\"mobile\":null,\"email\":\"高中/中专【失效】\",\"web\":\"\",\"vip\":null,\"sec\":null,\"cropsno\":null,\"cropname\":null,\"fancy\":null,\"remark\":\"入职时间:2023-05-05 离职时间:2023-10-30 变更原因:自离【失效】\",\"amount\":0,\"days\":0,\"consume01\":0.0000,\"consume02\":0.0000,\"consume03\":0.0000,\"consume04\":0.0000,\"log_id\":\"XX\",\"log_shift\":\"1\",\"log_date\":null,\"log_ip\":\"127.0.0.1\",\"times\":0,\"logmark\":0,\"rmcode\":null,\"mkt\":null,\"src\":null,\"isowner\":\"F\",\"createdate\":\"2023-05-05T00:00:00\",\"PERNR\":\"00281800\",\"WERKS\":\"1560\",\"ZSTATUS\":\"5\",\"KOSTL\":\"156020336\",\"ZZ_ZD\":\"3\",\"Z_ZJ\":\"T0\",\"STELL\":null,\"STELL_NM\":null,\"ZLZRQ\":\"2023-10-30T00:00:00\",\"MASSN\":\"ZD\",\"MNTXT\":\"离职\",\"MASSG\":null,\"MGTXT\":null,\"logdate\":\"2024-03-14T00:02:34\",\"updatelogdate\":null,\"guestno\":null,\"ZZ_KLX\":\"3\",\"DAT01\":null,\"ZZ_COUNNM\":null,\"ZZ_GZDJDNM\":\"海宁基地\",\"ZZ_GZDCQNM\":\"海宁尖山\"}";
//var gainfos = new List<GainfoSapEntity>() { pJson.ToObject<GainfoSapEntity>() };
var gainfos = await _dbContext.Queryable<GainfoSapEntity>().ToListAsync();
return gainfos.Select(x => new SapPersonItem
{
NAME = x.gname,
ZWORKCODE = x.ename,
ZZ_SFZH = x.idno,
GBDAT = x.birthday,
ZZ_KLX = x.ZZ_KLX,
ZXUELI = x.email,
ORGEH = x.appellation,
ZMOBILE = x.phone,
ZSTATUS = x.ZSTATUS,
ZRZRQ = x.createdate,
PERNR = x.PERNR,
WERKS = x.WERKS,
KOSTL = x.KOSTL,
ZZ_ZD = x.ZZ_ZD,
Z_ZJ = x.Z_ZJ,
STELL = x.STELL,
STELL_NM = x.STELL_NM,
ZLZRQ = x.ZLZRQ,
MASSN = x.MASSN,
MNTXT = x.MNTXT,
ZZ_COUNNM = x.ZZ_COUNNM,
ZZ_GZDJDNM = x.ZZ_GZDJDNM,
ZZ_GZDCQNM = x.ZZ_GZDCQNM
}).ToList();
}
private static List<GainfoSapEntity> ToGainfoSap(List<SapPersonItem> data)
{
return data.Select(person =>
{
//var position = _positions.FirstOrDefault(x => x.No == person.PLANS);
var rzrq = person.ZRZRQ;
var lzrq = person.ZLZRQ;
var rmk = $"入职时间:{rzrq.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)} ";
if (lzrq != null && lzrq.Value.ToString("yyyy-MM-dd") != "1900-01-01")
rmk += $"离职时间:{lzrq.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)} ";
if (!string.IsNullOrWhiteSpace(person.MGTXT))
rmk += $"变更原因:{person.MGTXT}";
var native = GetNative(person.ZZ_SFZH);
var sex = person.GESCH == "2" ? "F" : "M";
person.ZZ_SFZH = person.ZZ_SFZH?.TrimStart();
GainfoSapEntity o = new()
{
gname = person.NAME,
ename = person.ZWORKCODE,
idno = person.ZZ_SFZH,
birthday = person.GBDAT,
ZZ_KLX = person.ZZ_KLX,
email = person.ZXUELI,
appellation = person.ORGEH,
phone = person.ZMOBILE,
ZSTATUS = person.ZSTATUS,
createdate = person.ZRZRQ,
PERNR = person.PERNR,
WERKS = person.WERKS,
KOSTL = person.KOSTL,
ZZ_ZD = person.ZZ_ZD,
Z_ZJ = person.Z_ZJ,
STELL = person.STELL,
STELL_NM = person.STELL_NM,
ZLZRQ = person.ZLZRQ,
MASSN = person.MASSN,
MNTXT = person.MNTXT,
remark = rmk,
native = native,
sex = sex,
logdate = DateTime.Now,
isowner = int.Parse(person.ZSTATUS) < 5 ? "T" : "F",
@class = "C",
country = person.ZZ_COUNNM,
log_ip = "127.0.0.1",
log_shift = "1",
log_id = "XX",
address = "",
occupation = "99",
nation = "01",
idcls = "ID",
ZZ_COUNNM = person.ZZ_COUNNM,
ZZ_GZDJDNM = person.ZZ_GZDJDNM,
ZZ_GZDCQNM = person.ZZ_GZDCQNM,
};
return o;
}).ToList();
}
private static string GetNative(string idNo)
{
if (string.IsNullOrWhiteSpace(idNo) || idNo.Length < 6) return null;
idNo = idNo.TrimStart();
return idNo[..6];
}
private static int? SafeParseCardType(string ZZ_KLX)
{
if (int.TryParse(ZZ_KLX, out var cardType))
{
return cardType;
}
return null;
}
}

View File

@@ -0,0 +1,11 @@
namespace Dlhis.Basic.Organization.Services.Implements;
internal static class GetHashCodeExtensions
{
public static int SafeGetHashCode(this object o)
{
if (o == null) return 0;
if(string.IsNullOrEmpty(o.ToString())) return 0;
return o.GetHashCode();
}
}

View File

@@ -0,0 +1,96 @@
using Dlhis.Entity.Sys.Entities;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.AspNetCore.Identity;
namespace Dlhis.Basic.Organization.Services.Implements;
public class IdentityUserSyncService : IIdentityUserSyncService
{
private readonly IDbContext _identityDbContext;
public IdentityUserSyncService(IDbContext dbContext)
{
_identityDbContext = dbContext.ChangeDb("identity");
}
/// <inheritdoc />
public async Task SyncAccountAsync(string userName, string name, string idNo, string tenant)
{
if (tenant.IsEmpty()) return;
try
{
var password = idNo.TakeLast(6).Join("");
var user = await _identityDbContext.Queryable<UserEntity>().SingleAsync(x => x.UserName == userName);
if (user == null)
{
var hasher = new PasswordHasher<UserEntity>();
user = new UserEntity
{
UserName = userName,
NormalizedUserName = userName.ToUpper(),
ConcurrencyStamp = Guid.NewGuid().ToString(),
SecurityStamp = Guid.NewGuid().ToString(),
};
password = hasher.HashPassword(user, password);
user.PasswordHash = password;
var id = (int)await _identityDbContext.InsertReturnIdentityAsync(user);
user.Id = id;
await AddUserClaim(_identityDbContext, id, "jinko-code", userName);
await AddUserClaim(_identityDbContext, id, "name", name);
}
//todo 考虑角色?
var userTenants = await _identityDbContext.Queryable<UserTenantEntity>().Where(x => x.UserId == user.Id).ToListAsync();
if (userTenants.Count is 0 or 1)
{
var userTenant = userTenants.FirstOrDefault();
if (userTenant == null)
{
userTenant = new UserTenantEntity
{
UserId = user.Id,
TenantCode = tenant
};
await _identityDbContext.InsertAsync(userTenant);
}
else
{
userTenant.TenantCode = tenant;
await _identityDbContext.UpdateAsync(userTenant);
}
}
}
catch (Exception)
{
//ignore
}
}
//************************************************************************** help method **************************************************************************************
private async Task AddUserClaim(IDbContext dbContext, int userId, string type, string value)
{
var claim = await _identityDbContext.Queryable<UserClaimEntity>().Where(x => x.UserId == userId).FirstAsync(x => x.ClaimType == type);
if (claim == null)
{
claim = new UserClaimEntity()
{
UserId = userId,
ClaimType = type,
ClaimValue = value
};
await dbContext.InsertAsync(claim);
}
else
{
claim.ClaimValue = value;
await dbContext.UpdateAsync(claim);
}
}
}

View File

@@ -0,0 +1,149 @@
using System.Net;
using System.Text;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Jip.Api.Dto;
using Dlhis.Jip.Api.Responses;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Newtonsoft.Json;
namespace Dlhis.Basic.Organization.Services.Implements;
public class JinkoSapService : IJinkoSapService
{
private readonly IDbContext _dbContext;
private readonly ILogger<JinkoSapService> _logger;
private readonly IHttpClientFactory _httpClientFactory;
public JinkoSapService(IHttpClientFactory httpClientFactory, IDbContext dbContext, ILogger<JinkoSapService> logger)
{
_dbContext = dbContext;
_logger = logger;
_httpClientFactory = httpClientFactory;
}
public async Task<SapOrganizationResponse> GetSapOrganizationsAsync()
{
const string apiUrl = "/RESTAdapter/Rest/EHR_ORGANIZATION/";
var response = await _httpClientFactory.CreateClient("jinko:sap").PostAsync(apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SapOrganizationResponse>(responseJson);
return result;
}
public async Task<SapPositionResponse> GetPositionsAsync()
{
const string apiUrl = "/RESTAdapter/Rest/EHR_POSITION/";
var response = await _httpClientFactory.CreateClient("jinko:sap").PostAsync(apiUrl, new StringContent("{}", Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SapPositionResponse>(responseJson);
return result;
}
public async Task<SapPersonResponse> GetPersonsByWerkAsync(string werk)
{
const string apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/";
var werkInfo = await _dbContext.Queryable<WerkEntity>()
.Where(x => x.Enable)
.Where(x => x.Werk == werk)
.SingleAsync();
var body = new
{
//I_ALLINFO = "X",
T_WERKS = new
{
item = new List<object>
{
new
{
WERKS = werkInfo.Werk
}
}
},
T_PERSON = Array.Empty<string>(),
T_PNO = Array.Empty<string>(),
};
var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
var response = await _httpClientFactory.CreateClient("jinko:sap").PostAsync(apiUrl, content);
if (response.StatusCode != HttpStatusCode.OK)
{
_logger.LogError("获取{Werk}人事范围数据异常:{error}", werk, await response.Content.ReadAsStringAsync());
response.EnsureSuccessStatusCode();
}
var jsonResponse = await response.Content.ReadAsStringAsync();
var personResp = JsonConvert.DeserializeObject<SapPersonResponse>(jsonResponse);
List<SapPersonItem> persons = new();
if (personResp?.Person?.Items?.Any() == true)
{
persons.AddRange(personResp.Person.Items);
}
return new SapPersonResponse()
{
Person = new SapPerson<SapPersonItem>
{
Items = persons
}
};
}
public async Task<SapPersonResponse> GetPersonsByCodeAsync(string code)
{
const string apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/";
var body = new
{
//I_ALLINFO = "X",
T_WERKS = Array.Empty<string>(),
T_PERSON = Array.Empty<string>(),
T_PNO = new
{
item = new List<object>
{
new
{
ZWORKCODE = code
}
}
},
};
var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
var response = await _httpClientFactory.CreateClient("jinko:sap").PostAsync(apiUrl, content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
var personResp = JsonConvert.DeserializeObject<SapPersonResponse>(jsonResponse);
List<SapPersonItem> persons = new();
if (personResp?.Person?.Items?.Any() == true)
{
persons.AddRange(personResp.Person.Items);
}
return new SapPersonResponse
{
Person = new SapPerson<SapPersonItem>
{
Items = persons
}
};
}
}

View File

@@ -1,139 +1,147 @@
// using Dlhis.Entity.Basic.Entity;
// using Dlhis.Entity.Device.Entities;
// using Dlhis.Entity.Device.Enums;
// using Dlhis.Entity.Sys.Entities;
// using Dlhis.Entity.Sys.Enums;
// using Dlhis.Entity.Visitor.Entity;
// using Dlhis.Entity.Visitor.Enums;
// using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
// using SqlSugar;
//
// namespace Dlhis.Basic.Organization.Services.Implements;
//
// public class SapBusinessTripService : ISapBusinessTripService
// {
// private readonly IJinkoJipService _jinkoJipService;
// private readonly IDbContext _dbContext;
// private readonly ILogger<SapBusinessTripService> _logger;
//
// public SapBusinessTripService(IJinkoJipService jinkoJipService, IDbContext dbContext , ILogger<SapBusinessTripService> logger)
// {
// _jinkoJipService = jinkoJipService;
// _dbContext = dbContext;
// _logger = logger;
// }
//
// /// <inheritdoc />
// public async Task HandlerBusinessTripsByFactoryAsync(string factory)
// {
// var today = DateTime.Today;
// var yesterday = today.AddDays(-1);
//
// try
// {
// var tripResponse = await _jinkoJipService.GetTravelInfosByFactoryAsync(today, today, factory);
// if (!tripResponse.Items.Any())
// {
// return;
// }
//
// foreach (var tripInfoItem in tripResponse.Items.Where(x => x.Destination.IsPresent()))
// {
// if (await _dbContext.Queryable<BusinessTripEntity>().Where(x => x.Code == tripInfoItem.Code
// && x.BeginDate == tripInfoItem.BeginDate
// && x.EndDate == tripInfoItem.EndDate
// && x.Destination == factory).AnyAsync())
// {
// continue;
// }
//
// var entity = tripInfoItem.Adapt<BusinessTripEntity>();
// entity.Status = BusinessTripStatusEnumType.Wait;
// await _dbContext.InsertAsync(entity);
// }
//
// //获取今天和昨天的出差数据
// var tripInfos = await _dbContext.Queryable<BusinessTripEntity>()
// .Where(x => (SqlFunc.DateIsSame(x.BeginDate, today) && SqlFunc.DateIsSame(x.BeginDate, today))
// || (SqlFunc.DateIsSame(x.BeginDate, yesterday) && SqlFunc.DateIsSame(x.BeginDate, yesterday)))
// .Where(x => !SqlFunc.IsNullOrEmpty(x.Destination))
// .Where(x => x.Destination == factory)
// .ToListAsync();
//
// //获取分组信息
// var tripGroup = await _dbContext.Queryable<DeviceGroupEntity>()
// .Where(x => x.Type == DeviceTypeEnumType.Door)
// .Where(x => x.TenantId == factory)
// .Where(x => x.IsBusinessTrip)
// .SingleAsync();
//
// var userCodes = tripInfos.Select(x => x.Code).Distinct().ToList();
// var gainfos = await _dbContext.Queryable<GainfoEntity>().Where(x => userCodes.Contains(x.Code)).ToListAsync();
//
// foreach (var gainfo in gainfos)
// {
// try
// {
// var myTripInfos = tripInfos.Where(x => x.Code == gainfo.Code).ToList();
//
// var yesterdayTripInfo = myTripInfos.FirstOrDefault(x => x.BeginDate == yesterday && x.EndDate == yesterday); //昨天出差数据
// var todayTripInfo = myTripInfos.FirstOrDefault(x => x.BeginDate == today && x.EndDate == today); //今天出差数据
//
// //都为空不处理
// if (yesterdayTripInfo == null && todayTripInfo == null) continue;
//
// //都不为空则更新数据状态
// if (yesterdayTripInfo != null && todayTripInfo != null)
// {
// todayTripInfo.Status = BusinessTripStatusEnumType.Generated;
// await _dbContext.UpdateAsync(todayTripInfo);
// continue;
// }
//
// var beforeResult = await _devicePermissionApi.GetPermissionUsersInfoAsync(new List<string> { gainfo.Code });
//
// if (yesterdayTripInfo != null)
// {
// yesterdayTripInfo.Status = BusinessTripStatusEnumType.Deleted;
// await _dbContext.Updateable<DevicePermissionEntity>()
// .SetColumns(x => x.IsDeleted == true)
// .Where(x => x.AssignType == AssignTypeEnumType.User)
// .Where(x => x.AssignValue == gainfo.No)
// .Where(x => x.UniqueType == DeviceAssignmentTypeEnumType.Group)
// .Where(x => x.UniqueValue == tripGroup.Code)
// .Where(x => x.Type == tripGroup.Type)
// .Where(x => x.TenantId == factory)
// .ExecuteCommandAsync();
// await _dbContext.UpdateAsync(yesterdayTripInfo);
// }
//
// if (yesterdayTripInfo == null)
// {
// todayTripInfo.Status = BusinessTripStatusEnumType.Generated;
// await _dbContext.InsertAsync(new DevicePermissionEntity
// {
// AssignType = AssignTypeEnumType.User,
// AssignValue = gainfo.No,
// UniqueType = DeviceAssignmentTypeEnumType.Group,
// UniqueValue = tripGroup.Code,
// TenantId = factory,
// Type = tripGroup.Type,
// IsDeleted = false
// });
// await _dbContext.UpdateAsync(todayTripInfo);
// }
//
// await _devicePermissionApi.RePermissionUsersInfoAsync(beforeResult.Data);
// }
// catch (Exception e)
// {
// _logger.LogError(e, "出差自动下发任务失败:{message}", e.Message);
// }
// }
// }
// catch (Exception e)
// {
// _logger.LogError(e, "处理{factory}出差数据失败:{message}", factory, e.Message);
// }
// }
// }
using Dlhis.Basic.Device.Services;
using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Device.Entities;
using Dlhis.Entity.Device.Enums;
using Dlhis.Entity.Sys.Entities;
using Dlhis.Entity.Sys.Enums;
using Dlhis.Entity.Visitor.Entity;
using Dlhis.Entity.Visitor.Enums;
using Dlhis.Jip.Api;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.Utils.Extensions;
using Mapster;
using SqlSugar;
namespace Dlhis.Basic.Organization.Services.Implements;
public class SapBusinessTripService : ISapBusinessTripService
{
private readonly IJinkoJipApi _jinkoJipApi;
private readonly IDbContext _dbContext;
private readonly IDevicePermissionService _devicePermissionService;
private readonly ILogger<SapBusinessTripService> _logger;
public SapBusinessTripService(IJinkoJipApi jinkoJipApi,
IDbContext dbContext,
IDevicePermissionService devicePermissionService,
ILogger<SapBusinessTripService> logger)
{
_jinkoJipApi = jinkoJipApi;
_dbContext = dbContext;
_devicePermissionService = devicePermissionService;
_logger = logger;
}
/// <inheritdoc />
public async Task HandlerBusinessTripsByFactoryAsync(string factory)
{
var today = DateTime.Today;
var yesterday = today.AddDays(-1);
try
{
var tripResponse = await _jinkoJipApi.GetBusinessTripInfosByFactoryAsync(factory, today, today);
if (!tripResponse.Items.Any())
{
return;
}
foreach (var tripInfoItem in tripResponse.Items.Where(x => x.Destination.IsPresent()))
{
if (await _dbContext.Queryable<BusinessTripEntity>().Where(x => x.Code == tripInfoItem.Code
&& x.BeginDate == tripInfoItem.BeginDate
&& x.EndDate == tripInfoItem.EndDate
&& x.Destination == factory).AnyAsync())
{
continue;
}
var entity = tripInfoItem.Adapt<BusinessTripEntity>();
entity.Status = BusinessTripStatusEnumType.Wait;
await _dbContext.InsertAsync(entity);
}
//获取今天和昨天的出差数据
var tripInfos = await _dbContext.Queryable<BusinessTripEntity>()
.Where(x => (SqlFunc.DateIsSame(x.BeginDate, today) && SqlFunc.DateIsSame(x.BeginDate, today))
|| (SqlFunc.DateIsSame(x.BeginDate, yesterday) && SqlFunc.DateIsSame(x.BeginDate, yesterday)))
.Where(x => !SqlFunc.IsNullOrEmpty(x.Destination))
.Where(x => x.Destination == factory)
.ToListAsync();
//获取分组信息
var tripGroup = await _dbContext.Queryable<DeviceGroupEntity>()
.Where(x => x.Type == DeviceTypeEnumType.Door)
.Where(x => x.TenantId == factory)
.Where(x => x.IsBusinessTrip)
.SingleAsync();
var userCodes = tripInfos.Select(x => x.Code).Distinct().ToList();
var gainfos = await _dbContext.Queryable<GainfoEntity>().Where(x => userCodes.Contains(x.Code)).Select(x => new { x.No, x.Code }).ToListAsync();
foreach (var gainfo in gainfos)
{
try
{
var myTripInfos = tripInfos.Where(x => x.Code == gainfo.Code).ToList();
var yesterdayTripInfo = myTripInfos.FirstOrDefault(x => x.BeginDate == yesterday && x.EndDate == yesterday); //昨天出差数据
var todayTripInfo = myTripInfos.FirstOrDefault(x => x.BeginDate == today && x.EndDate == today); //今天出差数据
//都为空不处理
if (yesterdayTripInfo == null && todayTripInfo == null) continue;
//都不为空则更新数据状态
if (yesterdayTripInfo != null && todayTripInfo != null)
{
todayTripInfo.Status = BusinessTripStatusEnumType.Generated;
await _dbContext.UpdateAsync(todayTripInfo);
continue;
}
await _devicePermissionService.GenerateDeviceTasksAsync(async () =>
{
if (yesterdayTripInfo != null)
{
yesterdayTripInfo.Status = BusinessTripStatusEnumType.Deleted;
await _dbContext.Updateable<DevicePermissionEntity>()
.SetColumns(x => x.IsDeleted == true)
.Where(x => x.AssignType == AssignTypeEnumType.User)
.Where(x => x.AssignValue == gainfo.No)
.Where(x => x.UniqueType == DeviceAssignmentTypeEnumType.Group)
.Where(x => x.UniqueValue == tripGroup.Code)
.Where(x => x.Type == tripGroup.Type)
.Where(x => x.TenantId == factory)
.ExecuteCommandAsync();
await _dbContext.UpdateAsync(yesterdayTripInfo);
}
if (yesterdayTripInfo == null)
{
todayTripInfo.Status = BusinessTripStatusEnumType.Generated;
await _dbContext.InsertAsync(new DevicePermissionEntity
{
AssignType = AssignTypeEnumType.User,
AssignValue = gainfo.No,
UniqueType = DeviceAssignmentTypeEnumType.Group,
UniqueValue = tripGroup.Code,
TenantId = factory,
Type = tripGroup.Type,
IsDeleted = false
});
await _dbContext.UpdateAsync(todayTripInfo);
}
}, new List<string> { gainfo.No });
}
catch (Exception e)
{
_logger.LogError(e, "出差自动下发任务失败:{message}", e.Message);
}
}
}
catch (Exception e)
{
_logger.LogError(e, "处理{factory}出差数据失败:{message}", factory, e.Message);
}
}
}

View File

@@ -35,8 +35,7 @@ public class BusinessPlacePermissionsService : IBusinessPlacePermissionsService
})
.ToPageListAsync(request);
var usersResult = await _userApi.GetUserByIdsAsync(page.Data.Select(x => x.UserId).Distinct().ToList());
var users = usersResult.Data;
var users = await _userApi.GetUserByIdsAsync(page.Data.Select(x => x.UserId).Distinct().ToList());
page.Data.ForEach(item => { item.UserName = users.FirstOrDefault(x => x.Id == item.UserId)?.UserName; });
@@ -98,9 +97,7 @@ public class BusinessPlacePermissionsService : IBusinessPlacePermissionsService
})
.ToListAsync();
var userResult = await _userApi.GetUserByIdAsync(id);
var user = userResult.Data;
var user = await _userApi.GetUserByIdAsync(id);
infos.ForEach(item => { item.UserName = user?.UserName; });
return infos;

View File

@@ -22,7 +22,7 @@
"Timeout": 30,
"SlowSqlTime": 1,
"EnableSqlLog": true,
"Generate": true
"Generate": false
},
"SwaggerOptions": {
"Enable": true,