fix sap人员同步拆分

This commit is contained in:
2024-04-03 15:29:03 +08:00
parent 77ec9c9fc9
commit 28a347e04a
11 changed files with 184 additions and 70 deletions

View File

@@ -11,13 +11,12 @@ public interface IDevicePermissionApi
[Get("/api/devicepermissions/canteen/uniqueNos")] [Get("/api/devicepermissions/canteen/uniqueNos")]
Task<DefaultApiResult<List<string>>> GetCanteenDeviceUniqueNosByUserNoAsync(string userNo); Task<DefaultApiResult<List<string>>> GetCanteenDeviceUniqueNosByUserNoAsync(string userNo);
/// <summary> /// <summary>
/// 获取所有人的权限信息 /// 获取所有人的权限信息
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Get("/api/devicepermissions/all-permission")] [Post("/api/devicepermissions/all-permission")]
Task<DefaultApiResult<PermissionUsersInfoDto>> GetPermissionUsersInfoAsync(); Task<DefaultApiResult<PermissionUsersInfoDto>> GetPermissionUsersInfoAsync(List<string> userNos);
/// <summary> /// <summary>
/// 重新生成权限 /// 重新生成权限

View File

@@ -74,11 +74,11 @@ public class DevicePermissionsController : ControllerBase
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpGet("all-permission")] [HttpPost("all-permission")]
[IgnoreTenant] [IgnoreTenant]
public async Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync() public async Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync(List<string> userNos)
{ {
return await _devicePermissionService.GetPermissionUsersInfoAsync(); return await _devicePermissionService.GetPermissionUsersInfoAsync(userNos);
} }
/// <summary> /// <summary>

View File

@@ -68,7 +68,7 @@ public interface IDevicePermissionService : IScopeDependency
Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync(); Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync(List<string> userNos);
Task<int> ReGeneratePermissionUsersInfoAsync(PermissionUsersInfoDto beforeDto); Task<int> ReGeneratePermissionUsersInfoAsync(PermissionUsersInfoDto beforeDto);

View File

@@ -162,10 +162,11 @@ public class DevicePermissionService : IDevicePermissionService
} }
} }
public async Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync() public async Task<PermissionUsersInfoDto> GetPermissionUsersInfoAsync(List<string> userNos)
{ {
//获取所有人的权限 if (userNos.IsEmpty())
var userNos = await GetPermissionUserNosAsync(); userNos = await GetPermissionUserNosAsync();
var permissions = await GetAssignDeviceCodesInternalAsync(userNos); var permissions = await GetAssignDeviceCodesInternalAsync(userNos);
return new PermissionUsersInfoDto return new PermissionUsersInfoDto
@@ -489,7 +490,7 @@ public class DevicePermissionService : IDevicePermissionService
return result; return result;
} }
private static List<UserTenantDeviceCodeDto> GetAssignDeviceCodesInternal( private static List<UserTenantDeviceCodeDto> GetAssignDeviceCodesInternal(
GainfoEntity gainfo, GainfoEntity gainfo,
List<GainfoGroupRelationshipEntity> gainfoGroupRelationships, List<GainfoGroupRelationshipEntity> gainfoGroupRelationships,
List<DevicePermissionEntity> devicePermissions, List<DevicePermissionEntity> devicePermissions,

View File

@@ -17,8 +17,51 @@ public class WerkEntity : SugarBaseEntity
/// <summary> /// <summary>
/// 名称 /// 名称
/// </summary> /// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "名称")]
public string Name { get; set; } public string Name { get; set; }
/// <summary>
/// 后台任务key
/// </summary>
[SugarColumn(IsNullable = true, ColumnDescription = "后台任务key")]
public string BackgroundJobKey { get; set; }
/// <summary>
/// 获取总人数
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "获取总人数")]
public int Total { get; set; }
/// <summary>
/// 差异数
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "差异数")]
public int DiffNumber { get; set; }
/// <summary>
/// 权限变更数
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "权限变更数")]
public int PermissionChangeNumber { get; set; }
/// <summary>
/// 最近同步时间
/// </summary>
[SugarColumn(IsNullable = true, ColumnDescription = "最近同步时间")]
public DateTime? LastSyncStartTime { get; set; }
/// <summary>
/// 最近同步时间
/// </summary>
[SugarColumn(IsNullable = true, ColumnDescription = "最近同步时间")]
public DateTime? LastSyncEndTime { get; set; }
/// <summary>
/// 结果
/// </summary>
[SugarColumn(IsNullable = false, ColumnDescription = "结果")]
public string HandleMessage { get; set; }
/// <summary> /// <summary>
/// 是否启用 /// 是否启用
/// </summary> /// </summary>

View File

@@ -2,5 +2,7 @@
public interface IGainfoUpdateService : IScopeDependency public interface IGainfoUpdateService : IScopeDependency
{ {
Task TodoAsync(string code); Task TodoByWerkAsync(string werk);
Task TodoByCodeAsync(string code);
} }

View File

@@ -8,7 +8,7 @@ public interface IJinkoSapService : IScopeDependency
Task<SapPositionResponse> GetPositionsAsync(); Task<SapPositionResponse> GetPositionsAsync();
Task<SapPersonResponse> GetPersonsAsync(); Task<SapPersonResponse> GetPersonsByWerkAsync(string werk);
Task<SapPersonResponse> GetPersonsAsync(string code); Task<SapPersonResponse> GetPersonsByCodeAsync(string code);
} }

View File

@@ -1,5 +1,4 @@
 using Dlhis.Basic.Api;
using Dlhis.Basic.Api;
using Dlhis.Entity.Basic.Entity; using Dlhis.Entity.Basic.Entity;
using Dlhis.Entity.Basic.Enums; using Dlhis.Entity.Basic.Enums;
using System.Text; using System.Text;
@@ -20,7 +19,6 @@ public class GainfoUpdateService : IGainfoUpdateService
private readonly IDevicePermissionApi _devicePermissionApi; private readonly IDevicePermissionApi _devicePermissionApi;
private readonly IJinkoSapService _jinkoSapService; private readonly IJinkoSapService _jinkoSapService;
private List<TenantResponse> _tenants; private List<TenantResponse> _tenants;
private List<SapPersonDepartmentStatus> _departmentChanges; private List<SapPersonDepartmentStatus> _departmentChanges;
private List<SapPersonJobStatus> _jobChanges; private List<SapPersonJobStatus> _jobChanges;
@@ -32,54 +30,117 @@ public class GainfoUpdateService : IGainfoUpdateService
IJinkoSapService jinkoSapService) IJinkoSapService jinkoSapService)
{ {
_dbContext = dbContext; _dbContext = dbContext;
_dbContext.Client.QueryFilter.Clear();
_logger = logger; _logger = logger;
_tenantApi = tenantApi; _tenantApi = tenantApi;
_devicePermissionApi = devicePermissionApi; _devicePermissionApi = devicePermissionApi;
_jinkoSapService = jinkoSapService; _jinkoSapService = jinkoSapService;
} }
public async Task TodoAsync(string code)
{
_logger.LogWarning("开始获取SAP人员");
_dbContext.Client.QueryFilter.ClearAndBackup();
var personResp = await _jinkoSapService.GetPersonsAsync(code); 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;
_departmentChanges = personResp.DepartmentInfo.Items;
_jobChanges = personResp.JobStatusInfo.Items;
werkInfo.HandleMessage = "SAP人员数量" + persons.Count;
werkInfo.Total = persons.Count;
await _dbContext.UpdateAsync(werkInfo);
if (persons.Count > 0)
{
var modifiedPersons = GetModifiedPerson(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)
{
var tenantResult = await _tenantApi.GetTenantsInternalAsync();
_tenants = tenantResult.Data;
var codes = modifiedPersons.Select(x => x.ZWORKCODE).ToList();
var userNos = await _dbContext.Queryable<GainfoEntity>().Where(x => codes.Contains(x.Code)).Select(x => x.No).ToListAsync();
var dtoResult = await _devicePermissionApi.GetPermissionUsersInfoAsync(userNos);
var dto = dtoResult.Data;
await SavePersonAsync(modifiedPersons);
var rResult = await _devicePermissionApi.RePermissionUsersInfoAsync(dto);
var r = rResult.Data;
werkInfo.PermissionChangeNumber = r;
await _dbContext.UpdateAsync(werkInfo);
}
}
}
finally
{
werkInfo.HandleMessage = "同步结束";
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; var persons = personResp.Person.Items;
_departmentChanges = personResp.DepartmentInfo.Items; _departmentChanges = personResp.DepartmentInfo.Items;
_jobChanges = personResp.JobStatusInfo.Items; _jobChanges = personResp.JobStatusInfo.Items;
_logger.LogWarning("获取SAP人员数量为:{count}", persons.Count); _logger.LogInformation("获取SAP人员数量为:{count}", persons.Count);
if (persons.Count > 0) if (persons.Count > 0)
{ {
var modifiedPersons = GetModifiedPerson(persons.OrderByDescending(x => x.ZSTATUS).ThenBy(x => x.ZRZRQ).ToList()); var modifiedPersons = GetModifiedPerson(persons.OrderByDescending(x => x.ZSTATUS).ThenBy(x => x.ZRZRQ).ToList());
_logger.LogWarning("SAP人员差异数量为:{count}", modifiedPersons.Count); _logger.LogInformation("SAP人员差异数量为:{count}", modifiedPersons.Count);
if (modifiedPersons.Count > 0) if (modifiedPersons.Count > 0)
{ {
var tenantResult = await _tenantApi.GetTenantsInternalAsync();
_tenants = tenantResult.Data;
var codes = modifiedPersons.Select(x => x.ZWORKCODE).ToList();
var userNos = await _dbContext.Queryable<GainfoEntity>().Where(x => codes.Contains(x.Code)).Select(x => x.No).ToListAsync();
var dtoResult = await _devicePermissionApi.GetPermissionUsersInfoAsync(userNos);
var dto = dtoResult.Data;
await SavePersonAsync(modifiedPersons); await SavePersonAsync(modifiedPersons);
var rResult = await _devicePermissionApi.RePermissionUsersInfoAsync(dto);
var r = rResult.Data;
} }
} }
_logger.LogWarning("同步SAP人员数据结束"); _logger.LogInformation("SAP根据学工号同步结束:{code}", code);
} }
private async Task SavePersonAsync(List<SapPersonItem> persons) private async Task SavePersonAsync(List<SapPersonItem> persons)
{ {
var tenantResult = await _tenantApi.GetTenantsInternalAsync();
_tenants = tenantResult.Data;
var workCodes = persons.Select(x => x.ZWORKCODE).ToList(); var workCodes = persons.Select(x => x.ZWORKCODE).ToList();
var chunks = workCodes.Chunk(4000).ToList(); var chunks = workCodes.Chunk(4000).ToList();
var dtoResult = await _devicePermissionApi.GetPermissionUsersInfoAsync();
var dto = dtoResult.Data;
foreach (var searchCodes in chunks) foreach (var searchCodes in chunks)
{ {
_logger.LogWarning("SAP分批处理Chunk数量:{count}", searchCodes.Length); _logger.LogWarning("SAP分批处理Chunk数量:{count}", searchCodes.Length);
var existsWorkCodes = _dbContext.Queryable<GainfoSapEntity>() var existsWorkCodes = await _dbContext.Queryable<GainfoSapEntity>()
.Where(x => searchCodes.Contains(x.ename)) .Where(x => searchCodes.Contains(x.ename))
.Select(x => x.ename) .Select(x => x.ename)
.ToList(); .ToListAsync();
var originUpdates = persons.Where(x => existsWorkCodes.Contains(x.ZWORKCODE)).ToList(); var originUpdates = persons.Where(x => existsWorkCodes.Contains(x.ZWORKCODE)).ToList();
var existsUpdateWorkCodes = originUpdates.Select(x => x.ZWORKCODE).ToList(); var existsUpdateWorkCodes = originUpdates.Select(x => x.ZWORKCODE).ToList();
@@ -97,14 +158,13 @@ public class GainfoUpdateService : IGainfoUpdateService
i++; i++;
try try
{ {
InsertPerson(item); await InsertPersonAsync(item);
_logger.LogWarning("执行新增成功 工号:{code},姓名:{name}", item.ename, item.gname); _logger.LogWarning("执行新增成功 工号:{code},姓名:{name}", item.ename, item.gname);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "执行新增失败:{message}", ex.Message); _logger.LogError(ex, "执行新增失败:{message}", ex.Message);
} }
} }
foreach (var item in updates) foreach (var item in updates)
@@ -112,7 +172,7 @@ public class GainfoUpdateService : IGainfoUpdateService
i++; i++;
try try
{ {
UpdatePerson(item); await UpdatePersonAsync(item);
_logger.LogWarning("执行更新成功 工号:{code},姓名:{name}", item.ename, item.gname); _logger.LogWarning("执行更新成功 工号:{code},姓名:{name}", item.ename, item.gname);
} }
catch (Exception ex) catch (Exception ex)
@@ -121,26 +181,21 @@ public class GainfoUpdateService : IGainfoUpdateService
} }
} }
} }
var rResult = await _devicePermissionApi.RePermissionUsersInfoAsync(dto);
var r = rResult.Data;
_logger.LogWarning("生成下发任务数量:{count}", r);
} }
private void InsertPerson(GainfoSapEntity item) private async Task InsertPersonAsync(GainfoSapEntity item)
{ {
_dbContext.Client.Insertable(item).ExecuteCommand(); await _dbContext.InsertAsync(item);
var info = GainfoSapToGainfo(item); var info = GainfoSapToGainfo(item);
if (item.isowner == "T") if (item.isowner == "T")
{ {
_dbContext.Client.Insertable(info).ExecuteCommand(); await _dbContext.InsertAsync(info);
} }
else else
{ {
_dbContext.Client.Insertable(info).AS("GainfoLeave").ExecuteCommand(); await _dbContext.Client.Insertable(info).AS("GainfoLeave").ExecuteCommandAsync();
} }
} }
@@ -177,10 +232,10 @@ public class GainfoUpdateService : IGainfoUpdateService
return info; return info;
} }
private void UpdatePerson(GainfoSapEntity item) private async Task UpdatePersonAsync(GainfoSapEntity item)
{ {
var gainfoSap = _dbContext.Queryable<GainfoSapEntity>().Where(x => x.ename == item.ename).First(); var gainfoSap = await _dbContext.Queryable<GainfoSapEntity>().Where(x => x.ename == item.ename).FirstAsync();
_dbContext.Updateable<GainfoSapEntity>().SetColumns(g => new GainfoSapEntity await _dbContext.Updateable<GainfoSapEntity>().SetColumns(g => new GainfoSapEntity
{ {
PERNR = item.PERNR, PERNR = item.PERNR,
gname = item.gname, gname = item.gname,
@@ -199,16 +254,16 @@ public class GainfoUpdateService : IGainfoUpdateService
ZZ_GZDCQNM = item.ZZ_GZDCQNM, ZZ_GZDCQNM = item.ZZ_GZDCQNM,
}) })
.Where(x => x.ename == item.ename) .Where(x => x.ename == item.ename)
.ExecuteCommand(); .ExecuteCommandAsync();
var gainfo = _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == item.ename).First(); var gainfo = await _dbContext.Queryable<GainfoEntity>().Where(x => x.Code == item.ename).FirstAsync();
if (item.isowner == "T") if (item.isowner == "T")
{ {
if (gainfo != null) if (gainfo != null)
{ {
var workplace = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDJDNM)?.Code ?? item.ZZ_GZDJDNM; var workplace = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDJDNM)?.Code ?? item.ZZ_GZDJDNM;
var factory = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDCQNM)?.Code ?? item.ZZ_GZDCQNM; var factory = _tenants.FirstOrDefault(x => x.Name == item.ZZ_GZDCQNM)?.Code ?? item.ZZ_GZDCQNM;
_dbContext.Updateable<GainfoEntity>().SetColumns(g => new GainfoEntity await _dbContext.Updateable<GainfoEntity>().SetColumns(g => new GainfoEntity
{ {
SapNo = item.PERNR, SapNo = item.PERNR,
Name = item.gname, Name = item.gname,
@@ -225,21 +280,21 @@ public class GainfoUpdateService : IGainfoUpdateService
Factory = factory Factory = factory
}) })
.Where(x => x.Code == item.ename) .Where(x => x.Code == item.ename)
.ExecuteCommand(); .ExecuteCommandAsync();
} }
else else
{ {
var info = GainfoSapToGainfo(item); var info = GainfoSapToGainfo(item);
_dbContext.Client.Insertable(info).ExecuteCommand(); await _dbContext.InsertAsync(info);
} }
} }
else else
{ {
if (gainfo != null) if (gainfo != null)
{ {
_dbContext.Client.Deleteable(gainfo).ExecuteCommand(); await _dbContext.DeleteReallyAsync(gainfo);
gainfo.Id = 0; gainfo.Id = 0;
_dbContext.Client.Insertable(gainfo).AS("GainfoLeave").ExecuteCommand(); await _dbContext.Client.Insertable(gainfo).AS("GainfoLeave").ExecuteCommandAsync();
} }
} }
} }
@@ -318,7 +373,7 @@ public class GainfoUpdateService : IGainfoUpdateService
} }
private List<GainfoSapEntity> ToGainfoSap(List<SapPersonItem> data) private static List<GainfoSapEntity> ToGainfoSap(List<SapPersonItem> data)
{ {
return data.Select(person => return data.Select(person =>
{ {
@@ -421,7 +476,7 @@ public class GainfoUpdateService : IGainfoUpdateService
return null; return null;
} }
private string SubString(string s, int len) private static string SubString(string s, int len)
{ {
if (string.IsNullOrWhiteSpace(s)) if (string.IsNullOrWhiteSpace(s))
{ {

View File

@@ -62,11 +62,14 @@ public class JinkoSapService : IJinkoSapService
return result; return result;
} }
public async Task<SapPersonResponse> GetPersonsAsync() public async Task<SapPersonResponse> GetPersonsByWerkAsync(string werk)
{ {
var apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/"; var apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/";
var werks = await _dbContext.Queryable<WerkEntity>().Where(x => x.Enable).ToListAsync(); var werks = await _dbContext.Queryable<WerkEntity>()
.Where(x => x.Enable)
.WhereIF(werk.IsPresent(), x => x.Werk == werk)
.ToListAsync();
List<SapPersonItem> persons = new(); List<SapPersonItem> persons = new();
List<SapPersonJobStatus> jobInfos = new(); List<SapPersonJobStatus> jobInfos = new();
@@ -139,13 +142,8 @@ public class JinkoSapService : IJinkoSapService
}; };
} }
public async Task<SapPersonResponse> GetPersonsAsync(string code) public async Task<SapPersonResponse> GetPersonsByCodeAsync(string code)
{ {
if (code.IsEmpty())
{
return await GetPersonsAsync();
}
var apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/"; var apiUrl = "/RESTAdapter/Rest/EHR_PERSONNEL/";
List<SapPersonItem> persons = new(); List<SapPersonItem> persons = new();

View File

@@ -1,11 +1,14 @@
using Dlhis.ScheduledTask.Common.Services; using Dlhis.Entity.Basic.Entity;
using Dlhis.ScheduledTask.Common.Services;
using Hangfire;
using Kurisu.AspNetCore.Utils.Extensions;
using Kurisu.Scheduled; using Kurisu.Scheduled;
using Kurisu.Scheduled.Attributes; using Kurisu.Scheduled.Attributes;
namespace Dlhis.ScheduledTask.Jobs; namespace Dlhis.ScheduledTask.Jobs;
/// <summary> /// <summary>
/// SAP人员信息同步 /// SAP人员信息同步(按人事范围拆分)
/// </summary> /// </summary>
[RecurringJob(nameof(SyncPersonJob), "0 0 3,12,18 * * ?", Name = "SAP人员信息同步")] [RecurringJob(nameof(SyncPersonJob), "0 0 3,12,18 * * ?", Name = "SAP人员信息同步")]
public class SyncPersonJob : BaseJob public class SyncPersonJob : BaseJob
@@ -16,7 +19,20 @@ public class SyncPersonJob : BaseJob
public override async Task RunAsync(IServiceProvider serviceProvider) public override async Task RunAsync(IServiceProvider serviceProvider)
{ {
var gainfoUpdate = serviceProvider.GetService<IGainfoUpdateService>(); var werks = await DbContext.Queryable<WerkEntity>()
await gainfoUpdate.TodoAsync(null); .Where(x => x.Enable)
.ToListAsync();
foreach (var werk in werks)
{
if (werk.BackgroundJobKey.IsEmpty())
{
var jobKey = BackgroundJob.Enqueue<IGainfoUpdateService>(x => x.TodoByWerkAsync(werk.Werk));
werk.BackgroundJobKey = jobKey;
await DbContext.UpdateAsync(werk);
Logger.LogInformation("SAP创建人事范围{werk}后台调度任务", werk.Werk);
}
}
} }
} }

View File

@@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Kurisu.RemoteCall" Version="0.1.0" /> <PackageReference Include="Kurisu.RemoteCall" Version="0.2.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>