Commit 2b87bee5 by ruyun.zhang@suvalue.com

Merge branch 'release/性能及BUG修复'

parents 3cc6037d cadad92f
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Api.Configurations
{
public static class AuthenticationConfig
{
public static void AddAuthenticationConfiguration(this IServiceCollection services, IConfiguration configuration)
{
if (services == null) throw new ArgumentNullException(nameof(services));
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.Secret));
//services.Configure<JwtOptions>(options =>
//{
// options.Issuer = Consts.Issuer;
// options.Audience = Consts.Audience;
// options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
//});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Consts.Issuer,
ValidateAudience = true,
ValidAudience = Consts.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/performance/allotLogHub")))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
}
}
//public class JwtOptions
//{
// /// <summary>
// /// Issuer jwt签发者
// /// </summary>
// public string Issuer { get; set; }
// /// <summary>
// /// Subject jwt所面向的用户
// /// </summary>
// public string Subject { get; set; }
// /// <summary>
// /// Audience 接收jwt的一方
// /// </summary>
// public string Audience { get; set; }
// /// <summary>
// /// Not Before 定义在什么时间之前,该jwt是不可以用的
// /// </summary>
// public DateTime NotBefore => DateTime.Now;
// /// <summary>
// /// Expiration Time jwt的过期时间,必须大于签发时间
// /// </summary>
// public DateTime Expiration => IssuedAt.Add(ValidFor);
// /// <summary>
// /// Issued At jwt的签发时间
// /// </summary>
// public DateTime IssuedAt => DateTime.Now;
// /// <summary>
// /// Set the timespan the token will be valid for (default is 10 min)
// /// </summary>
// public TimeSpan ValidFor { get; set; } = TimeSpan.FromMinutes(120);
// /// <summary>
// /// The signing key to use when generating tokens.
// /// </summary>
// public SigningCredentials SigningCredentials { get; set; }
//}
}
......@@ -10,9 +10,7 @@ public static class AutoMapperConfig
public static void AddAutoMapperConfiguration(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperConfigs>());
services.AddAutoMapper();
services.AddAutoMapper(typeof(AutoMapperConfigs));
}
}
}
......@@ -17,8 +17,14 @@ public static void AddDatabaseConfiguration(this IServiceCollection services)
services.AddDbContext<PerformanceDbContext>(options =>
{
options.UseMySQL(connection.Value.PerformanceConnectionString);
});
options.UseMySql(
connection.Value.PerformanceConnectionString,
ServerVersion.AutoDetect(connection.Value.PerformanceConnectionString),
optionBuilder =>
{
optionBuilder.EnableStringComparisonTranslations(true);
});
}, ServiceLifetime.Transient);
}
}
}
......@@ -55,17 +55,4 @@ public static void AddDependencyInjectionConfiguration(this IServiceCollection s
.AddPerformanceRepoitory();
}
}
#region hangfire 权限
public class HangfireAuthorizationFilter : Hangfire.Dashboard.IDashboardAuthorizationFilter
{
//这里需要配置权限规则
public bool Authorize(Hangfire.Dashboard.DashboardContext context)
{
return true;
}
}
#endregion hangfire 权限
}
using FluentScheduler;
using Microsoft.Extensions.DependencyInjection;
using Performance.Services;
using System;
using System.Linq;
using System.Reflection;
//using FluentScheduler;
//using Microsoft.Extensions.DependencyInjection;
//using Performance.Services;
//using System;
//using System.Linq;
//using System.Reflection;
namespace Performance.Api.Configurations
{
public static class FluentSchedulerConfig
{
public static void AddFluentSchedulerConfiguration(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
//namespace Performance.Api.Configurations
//{
// public static class FluentSchedulerConfig
// {
// public static void AddFluentSchedulerConfiguration(this IServiceCollection services)
// {
// if (services == null) throw new ArgumentNullException(nameof(services));
ServiceLocator.Instance = services.BuildServiceProvider();
JobManager.Initialize(new JobRegistry());
// ServiceLocator.Instance = services.BuildServiceProvider();
// JobManager.Initialize(new JobRegistry());
////扫描当前程序集中实现了Registry的类
//var registrys = Assembly.GetExecutingAssembly().GetTypes()
// .Where(t => !t.IsInterface && !t.IsSealed && !t.IsAbstract && typeof(Registry).IsAssignableFrom(t))
// .Select(s => s.Assembly.CreateInstance(s.FullName) as Registry)?.ToArray();
// ////扫描当前程序集中实现了Registry的类
// //var registrys = Assembly.GetExecutingAssembly().GetTypes()
// // .Where(t => !t.IsInterface && !t.IsSealed && !t.IsAbstract && typeof(Registry).IsAssignableFrom(t))
// // .Select(s => s.Assembly.CreateInstance(s.FullName) as Registry)?.ToArray();
//// 注册同步服务
//JobManager.Initialize(registrys);
}
}
}
// //// 注册同步服务
// //JobManager.Initialize(registrys);
// }
// }
//}
......@@ -373,7 +373,6 @@ public ApiResponse DeleteUser([CustomizeValidator(RuleSet = "Delete"), FromBody]
/// <summary>
/// 批量新增用户表头
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("GetBatchUserStructrue")]
[HttpPost]
......@@ -387,7 +386,6 @@ public ApiResponse GetBatchUserStructrue()
/// <summary>
/// 批量新增用户
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("BatchSaveUser")]
[HttpPost]
......
using FluentValidation.AspNetCore;
using Hangfire;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
......@@ -34,14 +27,14 @@ public class AgainAllotController : Controller
private ComputeService computeService;
private ClaimService claimService;
private AllotService allotService;
private IHostingEnvironment env;
private IWebHostEnvironment env;
private ConfigService configService;
private Application application;
public AgainAllotController(AgainAllotService againAllotService,
RoleService roleService,
ClaimService claimService,
AllotService allotService,
IHostingEnvironment env,
IWebHostEnvironment env,
ConfigService configService,
ComputeService computeService,
IOptions<Application> options)
......@@ -171,7 +164,7 @@ public ApiResponse Import([FromForm] IFormCollection form)
/// <returns></returns>
[Route("detail")]
[HttpPost]
public ApiResponse Detail([CustomizeValidator(RuleSet = "Generate"), FromBody]AgainAllotRequest request)
public ApiResponse Detail([CustomizeValidator(RuleSet = "Generate"), FromBody] AgainAllotRequest request)
{
var result = againAllotService.Detail(request);
return new ApiResponse(ResponseType.OK, new { result.AgainSituation, result.SheetExport });
......
using FluentValidation.AspNetCore;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Infrastructure;
......@@ -18,7 +19,6 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
......@@ -30,7 +30,7 @@ public class AllotController : Controller
private AllotService _allotService;
private ResultComputeService _resultComputeService;
private ConfigService _configService;
private IHostingEnvironment _evn;
private IWebHostEnvironment _evn;
private ILogger<AllotController> _logger;
private ClaimService _claim;
private LogManageService _logManageService;
......@@ -42,7 +42,7 @@ public class AllotController : Controller
ResultComputeService resultComputeService,
ConfigService configService,
ILogger<AllotController> logger,
IHostingEnvironment evn,
IWebHostEnvironment evn,
IBackgroundTaskQueue backgroundTaskQueue,
IServiceScopeFactory serviceScopeFactory,
ClaimService claim,
......@@ -247,7 +247,7 @@ public ApiResponse ImportExtraction(int allotId)
/// <returns></returns>
[Route("generate")]
[HttpPost]
public ApiResponse Generate([CustomizeValidator(RuleSet = "Delete"), FromBody] AllotRequest request)
public ApiResponse GenerateAsync([CustomizeValidator(RuleSet = "Delete"), FromBody] AllotRequest request)
{
var allot = _allotService.GetAllot(request.ID);
if (null == allot || string.IsNullOrEmpty(allot.Path))
......@@ -257,14 +257,12 @@ public ApiResponse Generate([CustomizeValidator(RuleSet = "Delete"), FromBody] A
_logManageService.WriteMsg("生成绩效准备中", $"准备生成{allot.Year}-{allot.Month.ToString().PadLeft(2, '0')}月份绩效,请稍等!", 1, allot.ID, "ReceiveMessage", true);
_allotService.UpdateAllotStates(allot.ID, (int)AllotStates.Wait, EnumHelper.GetDescription(AllotStates.Wait), allot.Generate);
if (_evn.IsEnvironment("Localhost"))
{
_allotService.Generate(allot);
}
else
{
//BackgroundJob.Schedule(() => _allotService.Generate(allot, email), TimeSpan.FromSeconds(1));
//if (_evn.IsEnvironment("Localhost"))
//{
// _allotService.Generate(allot);
//}
//else
//{
_backgroundTaskQueue.QueueBackgroundWorkItem(async token =>
{
using (var scope = _serviceScopeFactory.CreateScope())
......@@ -274,7 +272,9 @@ public ApiResponse Generate([CustomizeValidator(RuleSet = "Delete"), FromBody] A
await Task.Delay(TimeSpan.FromSeconds(5), token);
}
});
}
//_publishEndpoint.Publish(allot).Wait();
//}
_logManageService.WriteMsg("等待绩效生成", $"等待绩效生成{allot.Year}-{allot.Month.ToString().PadLeft(2, '0')}月份绩效!", 1, allot.ID, "ReceiveMessage");
//_allotService.Generate(allot, email);
......@@ -297,15 +297,8 @@ public ApiResponse GenerateReport([CustomizeValidator(RuleSet = "Delete"), FromB
if (null == allot || !states.Contains(allot.States))
throw new PerformanceException("当前绩效暂未生成,无法统计报表数据。");
_backgroundTaskQueue.QueueBackgroundWorkItem(async token =>
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var scopedServices = scope.ServiceProvider.GetRequiredService<AllotService>();
scopedServices.GenerateReport(allot);
await Task.Delay(TimeSpan.FromSeconds(5), token);
}
});
//_publishEndpoint.Publish(allot).Wait();
return new ApiResponse(ResponseType.OK, "统计报表数据任务开始");
}
......@@ -423,12 +416,19 @@ public ApiResponse Issued([FromBody] AllotRequest request)
var allot = _allotService.GetAllot(request.ID);
if (null == allot)
throw new PerformanceException("当前绩效记录不存在");
_allotService.UpdateAllotStates(allot.ID, (int)AllotStates.GenerateSucceed, EnumHelper.GetDescription(AllotStates.GenerateSucceed));
// 科室下发
_resultComputeService.GenerateSecondAllot(allot);
//绩效划拨,下发驳回
costTransferService.RejectedApplicat(allot.ID);
return new ApiResponse(ResponseType.OK);
bool isIssued = false;
var result = _resultComputeService.IssuedPrompt(allot, request, ref isIssued);
//绩效状态修改;绩效划拨,下发驳回
if (request.isIssued == 1 && isIssued)
{
_allotService.UpdateAllotStates(allot.ID, (int)AllotStates.GenerateSucceed, EnumHelper.GetDescription(AllotStates.GenerateSucceed));
costTransferService.RejectedApplicat(allot.ID);
}
return new ApiResponse(ResponseType.OK, result);
}
/// <summary>
......
......@@ -834,7 +834,6 @@ public ApiResponse LoadTheLastTime([FromBody] CopyRequest request)
/// <summary>
/// 下拉
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("copydropdown")]
public ApiResponse CopyDropDown()
......@@ -846,11 +845,63 @@ public ApiResponse CopyDropDown()
new CopyDrop{Label="收入费用类别",Value="drugTypes"},
new CopyDrop{Label="支出费用类别",Value="drugTypeDisburses"},
new CopyDrop{Label="费用类别系数",Value="drugTypeFactors"},
new CopyDrop{Label="科室类型",Value="deptTypes"},
/* new CopyDrop{Label="科室类型",Value="deptTypes"},*/
new CopyDrop{Label="二次绩效配置",Value="agains"},
new CopyDrop{Label="核算单元及组别",Value="accountings"},
}; ;
return new ApiResponse(ResponseType.OK, result);
}
/// <summary>
/// 自定义表Heads表头
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("customheads")]
public ApiResponse CustomHeads([FromBody] CustomPagingRequest request)
{
if (string.IsNullOrEmpty(request.TableName))
return new ApiResponse(ResponseType.ParameterError, "表名为空");
var result = _configService.QueryHandsCustom(request);
if (result == null)
return new ApiResponse(ResponseType.ParameterError, "表不符合规范,请补全注释或修改重复注释");
else
return new ApiResponse(ResponseType.OK, result);
}
/// <summary>
/// 自定义表显示
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("getcustomlist")]
public ApiResponse GetCustomList([FromBody] CustomPagingRequest request)
{
var allot = _allotService.GetAllot(request.AllotId);
if (allot == null)
return new ApiResponse(ResponseType.ParameterError, "AllotID错误");
return _configService.QueryCustom(request);
}
/// <summary>
/// 保存自定义表数据
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("savecustom")]
[HttpPost]
public ApiResponse BatchSaveCustom([FromBody] SaveCustomData request)
{
var allot = _allotService.GetAllot(request.AllotId);
if (allot == null)
return new ApiResponse(ResponseType.ParameterError, "AllotID错误");
else if (string.IsNullOrEmpty(request.TableName))
return new ApiResponse(ResponseType.ParameterError, "表名为空");
return _configService.SaveCustomTable(request);
}
}
}
\ No newline at end of file
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Performance.DtoModels;
using Performance.EntityModels;
......@@ -21,12 +20,12 @@ public class EmployeeController : Controller
private EmployeeService employeeService;
private AllotService allotService;
private ClaimService claim;
private IHostingEnvironment evn;
private IWebHostEnvironment evn;
private readonly RoleService roleService;
private readonly UserService userService;
public EmployeeController(EmployeeService employeeService, AllotService allotService,
ClaimService claim, IHostingEnvironment evn, RoleService roleService,
ClaimService claim, IWebHostEnvironment evn, RoleService roleService,
UserService userService)
{
this.employeeService = employeeService;
......@@ -719,5 +718,24 @@ public ApiResponse AprHideOverview(int allotId)
return new ApiResponse(ResponseType.OK, relust);
}
#endregion
/// <summary>
/// 实发绩效比对
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("getComparison")]
[HttpPost]
public ApiResponse GetDeptComparison([FromBody] ComparisonPagingRequest request)
{
var allot = allotService.GetAllot(request.AllotId);
if (allot == null)
return new ApiResponse(ResponseType.ParameterError, "allotId无效");
var relust = employeeService.GetComparison(request);
return new ApiResponse(ResponseType.OK, relust);
}
}
}
diff a/performance/Performance.Api/Controllers/EmployeeController.cs b/performance/Performance.Api/Controllers/EmployeeController.cs (rejected hunks)
@@ -824,6 +824,7 @@
if (allotId <= 0)
return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
+ var result = employeeService.GetGatherTotal(allotId, request);
return new ApiResponse(ResponseType.OK, result);
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Performance.DtoModels;
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.IO;
using System.Linq;
namespace Performance.Api.Controllers
{
......@@ -20,11 +17,11 @@ public class HistoryController : ControllerBase
{
private readonly HistoryService historyService;
private readonly ClaimService claim;
private readonly IHostingEnvironment evn;
private readonly IWebHostEnvironment evn;
public HistoryController(
HistoryService historyService,
ClaimService claim,
IHostingEnvironment evn)
IWebHostEnvironment evn)
{
this.historyService = historyService;
this.claim = claim;
......
......@@ -21,22 +21,19 @@ public class ModExtractController : Controller
private readonly CustomExtractService _extractService;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IHubNotificationQueue _notificationQueue;
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
public ModExtractController(
ClaimService claim,
AllotService allotService,
CustomExtractService extractService,
IServiceScopeFactory serviceScopeFactory,
IHubNotificationQueue notificationQueue,
IBackgroundTaskQueue backgroundTaskQueue)
IHubNotificationQueue notificationQueue)
{
_claim = claim;
_allotService = allotService;
_extractService = extractService;
_serviceScopeFactory = serviceScopeFactory;
_notificationQueue = notificationQueue;
_backgroundTaskQueue = backgroundTaskQueue;
}
[HttpPost("custom/{allotId}")]
......@@ -46,27 +43,27 @@ public ApiResponse CustomExtract(int allotId)
if (!_extractService.CheckConfigScript(userId, allotId))
return new ApiResponse(ResponseType.Fail, "未配置自定义抽取,请联系绩效管理人员。");
_backgroundTaskQueue.QueueBackgroundWorkItem(async token =>
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var scopedServices = scope.ServiceProvider.GetRequiredService<CustomExtractService>();
var scopedAllotService = scope.ServiceProvider.GetRequiredService<AllotService>();
var scopedQueue = scope.ServiceProvider.GetRequiredService<IHubNotificationQueue>();
//_backgroundTaskQueue.QueueBackgroundWorkItem(async token =>
//{
// using (var scope = _serviceScopeFactory.CreateScope())
// {
// var scopedServices = scope.ServiceProvider.GetRequiredService<CustomExtractService>();
// var scopedAllotService = scope.ServiceProvider.GetRequiredService<AllotService>();
// var scopedQueue = scope.ServiceProvider.GetRequiredService<IHubNotificationQueue>();
if (scopedServices.ExtractData(userId, allotId, out string resultFilePath))
{
scopedAllotService.UpdateAllotCustomExtractPath(allotId, resultFilePath);
scopedQueue.Send(new Notification(allotId, "CustomDowoload", new CustomDownloadContent("自定义数据提取数据成功,是否立即下载", allotId)));
}
else
{
scopedQueue.Send(new Notification(allotId, "Notification", new TextContent("自定义数据提取数据失败", NotificationLevel.ERR)));
}
// if (scopedServices.ExtractData(userId, allotId, out string resultFilePath))
// {
// scopedAllotService.UpdateAllotCustomExtractPath(allotId, resultFilePath);
// scopedQueue.Send(new Notification(allotId, "CustomDowoload", new CustomDownloadContent("自定义数据提取数据成功,是否立即下载", allotId)));
// }
// else
// {
// scopedQueue.Send(new Notification(allotId, "Notification", new TextContent("自定义数据提取数据失败", NotificationLevel.ERR)));
// }
await Task.Delay(TimeSpan.FromSeconds(5), token);
}
});
// await Task.Delay(TimeSpan.FromSeconds(5), token);
// }
//});
_notificationQueue.Send(new Notification(allotId, "Notification", new TextContent("自定义数据提取任务开始执行")));
......
......@@ -218,7 +218,7 @@ public ApiResponse MenuReport([CustomizeValidator(RuleSet = "Menu"), FromBody] R
var list = reportService.MenuReport(request);
return new ApiResponse(ResponseType.OK, "", list);
}
/// <summary>
/// 菜单报表
/// </summary>
/// <param name="request"></param>
......
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Performance.DtoModels;
using Performance.EntityModels;
......@@ -8,10 +7,8 @@
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Api.Controllers
{
......@@ -19,12 +16,12 @@ namespace Performance.Api.Controllers
[Route("api/{hospitalId}/report/global")]
public class ReportGlobalController : Controller
{
private readonly IHostingEnvironment env;
private readonly IWebHostEnvironment env;
private readonly AllotService allotService;
private readonly ReportGlobalService reportGlobalService;
public ReportGlobalController(
IHostingEnvironment env,
IWebHostEnvironment env,
AllotService allotService,
ReportGlobalService reportGlobalService
)
......
......@@ -102,33 +102,33 @@ public ApiResponse SaveValue(int secondid, [FromBody] List<ag_fixatitem> request
return new ApiResponse(ResponseType.OK);
}
/// <summary>
/// 提交二次绩效分配结果
/// </summary>
/// <returns></returns>
[Route("api/second/savecompute")]
[HttpPost]
public ApiResponse SaveCompute([FromBody] List<ag_compute> request)
{
var allotCount = request.Where(t => t.AllotId > 0).Select(t => t.AllotId).Distinct().Count();
if (allotCount != 1 || request.Any(t => t.AllotId == 0))
throw new PerformanceException("一次绩效ID错误");
///// <summary>
///// 提交二次绩效分配结果
///// </summary>
///// <returns></returns>
//[Route("api/second/savecompute")]
//[HttpPost]
//public ApiResponse SaveCompute([FromBody] List<ag_compute> request)
//{
// var allotCount = request.Where(t => t.AllotId > 0).Select(t => t.AllotId).Distinct().Count();
// if (allotCount != 1 || request.Any(t => t.AllotId == 0))
// throw new PerformanceException("一次绩效ID错误");
var secondCount = request.Where(t => t.SecondId > 0).Select(t => t.SecondId).Distinct().Count();
if (secondCount != 1 || request.Any(t => t.SecondId == 0))
throw new PerformanceException("二次绩效ID错误");
// var secondCount = request.Where(t => t.SecondId > 0).Select(t => t.SecondId).Distinct().Count();
// if (secondCount != 1 || request.Any(t => t.SecondId == 0))
// throw new PerformanceException("二次绩效ID错误");
var departmentCount = request.Where(t => !string.IsNullOrEmpty(t.Department)).Select(t => t.Department).Distinct().Count();
if (departmentCount != 1 || request.Any(t => string.IsNullOrEmpty(t.Department)))
throw new PerformanceException("科室名称错误");
// var departmentCount = request.Where(t => !string.IsNullOrEmpty(t.Department)).Select(t => t.Department).Distinct().Count();
// if (departmentCount != 1 || request.Any(t => string.IsNullOrEmpty(t.Department)))
// throw new PerformanceException("科室名称错误");
var personNameCount = request.Where(t => !string.IsNullOrEmpty(t.PersonName)).Select(t => t.PersonName).Distinct().Count();
if (personNameCount != 1 || request.Any(t => string.IsNullOrEmpty(t.PersonName)))
throw new PerformanceException("人员名称错误");
// var personNameCount = request.Where(t => !string.IsNullOrEmpty(t.PersonName)).Select(t => t.PersonName).Distinct().Count();
// if (personNameCount != 1 || request.Any(t => string.IsNullOrEmpty(t.PersonName)))
// throw new PerformanceException("人员名称错误");
var result = secondAllotService.SaveCompute(request);
return new ApiResponse(ResponseType.OK);
}
// var result = secondAllotService.SaveCompute(request);
// return new ApiResponse(ResponseType.OK);
//}
/// <summary>
/// 二次绩效录入页面配置信息
......@@ -613,9 +613,10 @@ public ApiResponse RedistributionCheck([FromBody] SecondComputeDto request)
throw new PerformanceException("绩效记录不存在!");
// 年资职称绩效占比与工作量绩效占比 校验
var loads = _redistributionService.GetWorkLoads(allot.HospitalId, second.UnitType, second.Department);
var workloadGroups = _redistributionService.GetTopWorkloadBodyGroups(loads);
if ((ComputeMode)request.ComputeMode != ComputeMode.NotCalculate)
{
var workloadGroups = _redistributionService.GetTopWorkloadBodyGroups(loads);
var workloadRatio = workloadGroups.Select(w => request.Head.GetValue($"Workload_Ratio_{w.Name}", 0m));
if (workloadRatio.Any(w => w > 1 || w < 0))
throw new PerformanceException("工作量绩效占比存在异常值!");
......@@ -629,8 +630,20 @@ public ApiResponse RedistributionCheck([FromBody] SecondComputeDto request)
else if (seniorityTitlesAccountedPerformance + workloadRatio.Sum() < 1)
throw new PerformanceException("年资职称绩效占比与工作量绩效占比总和,不足100%!");
}
List<SecondComputeCheckResultDto> result = new List<SecondComputeCheckResultDto>();
// 二次分配人员信息 校验
var result = _redistributionService.CheckData(second, (ComputeMode)request.ComputeMode, request.Body, loads);
var checkData = _redistributionService.CheckData(second, (ComputeMode)request.ComputeMode, request.Body, loads);
if (checkData != null && checkData.Count > 0)
result.AddRange(checkData);
// 二次分配提交数据格式 校验
var dic = _redistributionService.GetTableHeaderDictionary((ComputeMode)request.ComputeMode, allot, second, loads, workloadGroups);
var checkFormat = _redistributionService.CheckFormat(request.Head, request.Body, dic);
if (checkFormat != null && checkFormat.Count > 0)
result.AddRange(checkFormat);
return new ApiResponse(ResponseType.OK, result);
}
catch (PerformanceException ex)
......@@ -737,10 +750,16 @@ public ApiResponse RedistributionSave([FromBody] SecondComputeDto request)
throw new PerformanceException("绩效记录不存在!");
var loads = _redistributionService.GetWorkLoads(allot.HospitalId, second.UnitType, second.Department);
var workloadGroups = _redistributionService.GetTopWorkloadBodyGroups(loads);
// 二次分配人员信息 校验
var checkDatas = _redistributionService.CheckData(second, (ComputeMode)request.ComputeMode, request.Body, loads);
if (checkDatas != null && checkDatas.Any(w => w.Level == ResponseType.Error.ToString()))
return new ApiResponse(ResponseType.Fail, "数据验证未通过,请修复后查看计算结果!", checkDatas.Where(w => w.Level == ResponseType.Error.ToString()));
// 二次分配提交数据格式 校验
var dic = _redistributionService.GetTableHeaderDictionary((ComputeMode)request.ComputeMode, allot, second, loads, workloadGroups);
var checkFormat = _redistributionService.CheckFormat(request.Head, request.Body, dic);
if (checkFormat != null && checkFormat.Any(w => w.Level == ResponseType.Error.ToString()))
return new ApiResponse(ResponseType.Fail, "数据验证未通过,请修复后查看计算结果!", checkFormat.Where(w => w.Level == ResponseType.Error.ToString()));
// 清理无效数据 没有Tab标签的数据才是要计算的数据
var cleanDatas = request.Body.Where(w => w.Count > 0 && w.GetValue(nameof(ResponseType), "") == ResponseType.OK.ToString()).ToList();
......@@ -786,11 +805,19 @@ public ApiResponse RedistributionSubmit([FromBody] SecondComputeDto request)
throw new PerformanceException("绩效未下发,无法提交!");
var loads = _redistributionService.GetWorkLoads(allot.HospitalId, second.UnitType, second.Department);
var workloadGroups = _redistributionService.GetTopWorkloadBodyGroups(loads);
// 二次分配人员信息 校验
var checkDatas = _redistributionService.CheckData(second, (ComputeMode)request.ComputeMode, request.Body, loads);
if (checkDatas != null && checkDatas.Any(w => w.Level == ResponseType.Error.ToString()))
return new ApiResponse(ResponseType.Fail, "数据验证未通过,请修复后查看计算结果!", checkDatas.Where(w => w.Level == ResponseType.Error.ToString()));
// 二次分配提交数据格式 校验
var dic = _redistributionService.GetTableHeaderDictionary((ComputeMode)request.ComputeMode, allot, second, loads, workloadGroups);
var checkFormat = _redistributionService.CheckFormat(request.Head, request.Body, dic);
if (checkFormat != null && checkFormat.Any(w => w.Level == ResponseType.Error.ToString()))
return new ApiResponse(ResponseType.Fail, "数据验证未通过,请修复后查看计算结果!", checkFormat.Where(w => w.Level == ResponseType.Error.ToString()));
// 清理无效数据 没有Tab标签的数据才是要计算的数据
var cleanDatas = request.Body.Where(w => w.Count > 0 && w.GetValue(nameof(ResponseType), "") == ResponseType.OK.ToString()).ToList();
if (cleanDatas == null || cleanDatas.Count == 0)
......
......@@ -2,7 +2,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
......@@ -27,7 +26,7 @@ namespace Performance.Api.Controllers
public class TemplateController : Controller
{
private readonly ILogger logger;
private readonly IHostingEnvironment env;
private readonly IWebHostEnvironment env;
private readonly ClaimService claim;
private readonly WebapiUrl url;
private readonly Application application;
......@@ -41,7 +40,7 @@ public class TemplateController : Controller
public TemplateController(
ILogger<ExceptionsFilter> logger,
IHostingEnvironment env,
IWebHostEnvironment env,
ClaimService claim,
IOptions<WebapiUrl> url,
IOptions<Application> options,
......@@ -296,7 +295,7 @@ public ApiResponse PrejudgeLog([FromRoute] int allotId)
var allot = allotService.GetAllot(allotId);
if (allot == null)
return new ApiResponse(ResponseType.ParameterError, "AllotID错误");
var result=logService.GetLogDbug(allotId);
var result = logService.GetLogDbug(allotId);
return new ApiResponse(ResponseType.OK, result);
}
......
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Api
......@@ -21,9 +16,9 @@ public class ActionsFilter : IAsyncActionFilter
{
private readonly ILogger<ActionsFilter> _logger;
private readonly IMemoryCache _cache;
private readonly IHostingEnvironment _env;
private readonly IWebHostEnvironment _env;
public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IHostingEnvironment env)
public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IWebHostEnvironment env)
{
this._logger = factory.CreateLogger<ActionsFilter>();
this._cache = cache;
......@@ -38,7 +33,7 @@ public ActionsFilter(ILoggerFactory factory, IMemoryCache cache, IHostingEnviron
var req = new { request.Path, request.Method, context.ActionArguments, Token = authorization.Count > 0 ? authorization.First() : "" };
_logger.LogInformation($"请求内容 {JsonHelper.Serialize(req)}");
//启用body倒带功能
request.EnableRewind();
request.EnableBuffering();
//接口禁用
if (context.Filters.Any(item => item is ApiDisableAttribute))
......
......@@ -37,8 +37,8 @@ public Task OnExceptionAsync(ExceptionContext context)
}
else
{
_logger.LogError($"接口异常:{context.Exception.ToString()}");
var response = new ApiResponse(ResponseType.Error, "接口内部异常", context.Exception.Message);
_logger.LogError($"接口异常:{context.Exception}");
var response = new ApiResponse(ResponseType.Error, "服务器繁忙,请稍后再试...", context.Exception.Message);
context.Result = new ObjectResult(response);
_logger.LogError("接口内部异常" + JsonHelper.Serialize(response));
}
......
using FluentScheduler;
using Microsoft.Extensions.DependencyInjection;
using Performance.Services;
using Performance.Services.ExtractExcelService;
namespace Performance.Api
{
public class ExtractDataJob : IJob
{
private readonly ExtractJobService extractJobService;
{
public ExtractDataJob()
private readonly ExtractJobService _extractJobService;
public ExtractDataJob(ExtractJobService extractJobService)
{
this.extractJobService = ServiceLocator.Instance.GetService<ExtractJobService>();
_extractJobService = extractJobService;
}
public void Execute()
{
extractJobService.Execute();
_extractJobService.Execute();
}
}
}
using FluentScheduler;
using Microsoft.Extensions.DependencyInjection;
using Performance.Services;
using Performance.Services.ExtractExcelService;
namespace Performance.Api
{
public class ExtractGenerateJob : IJob
{
private readonly ExtractJobService extractJobService;
private readonly ExtractJobService _extractJobService;
public ExtractGenerateJob()
public ExtractGenerateJob(ExtractJobService extractJobService)
{
this.extractJobService = ServiceLocator.Instance.GetService<ExtractJobService>();
_extractJobService = extractJobService;
}
public void Execute()
{
extractJobService.ExportFile();
_extractJobService.ExportFile();
}
}
}
using FluentScheduler;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Performance.Repository;
using Performance.DtoModels;
using Performance.Services;
namespace Performance.Api
{
public class JobRegistry : Registry
{
public JobRegistry()
public JobRegistry(IServiceProvider provider)
{
//Schedule<ExtractDataJob>().ToRunNow().AndEvery(1).Days().At(23, 0);
//Schedule<ExtractDataJob>().ToRunEvery(1).Days().At(23, 0);
Schedule<ExtractGenerateJob>().ToRunEvery(1).Days().At(23, 00);
Schedule(() => provider.GetService<ExtractGenerateJob>()).ToRunEvery(1).Days().At(23, 00);
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<OutputPath />
<DocumentationFile>..\Performance.Api\wwwroot\Performance.Api.xml</DocumentationFile>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<OutputPath />
<DocumentationFile>..\Performance.Api\wwwroot\Performance.Api.xml</DocumentationFile>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Remove="aaa\**" />
<Compile Remove="Files\**" />
<Compile Remove="Hubs\**" />
<Content Remove="aaa\**" />
<Content Remove="Files\**" />
<Content Remove="Hubs\**" />
<EmbeddedResource Remove="aaa\**" />
<EmbeddedResource Remove="Files\**" />
<EmbeddedResource Remove="Hubs\**" />
<None Remove="aaa\**" />
<None Remove="Files\**" />
<None Remove="Hubs\**" />
</ItemGroup>
<PropertyGroup>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
<UserSecretsId>e732666b-5531-4cd8-b713-2fe3db31126c</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<None Remove="Template\~%24医院绩效模板.xlsx" />
</ItemGroup>
<PropertyGroup>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
<UserSecretsId>e732666b-5531-4cd8-b713-2fe3db31126c</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />
<PackageReference Include="CSRedisCore" Version="3.0.45" />
<PackageReference Include="FluentScheduler" Version="5.5.1" />
<PackageReference Include="FluentValidation.AspNetCore" Version="8.1.3" />
<PackageReference Include="GraphQL" Version="2.4.0" />
<PackageReference Include="Hangfire" Version="1.6.22" />
<PackageReference Include="Hangfire.MySql.Core" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.4" />
<PackageReference Include="MySql.Data" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="NLog" Version="4.5.11" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.4.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.4" />
<PackageReference Include="Microsoft.AspNet.SignalR" Version="2.4.1" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Files\**" />
<Content Remove="Files\**" />
<EmbeddedResource Remove="Files\**" />
<None Remove="Files\**" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
<Content Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Performance.Api.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Performance.EntityModels.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
<Content Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Performance.Api.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="wwwroot\Performance.EntityModels.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Update="Template\东方医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院人员绩效模板.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板%28无执行科室%29.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Update="Template\东方医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院人员绩效模板.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板%28无执行科室%29.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xls">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Update="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\导入数据模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Update="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\导入数据模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JSONSchema="" /></VisualStudio></ProjectExtensions>
<ProjectExtensions>
<VisualStudio>
<UserProperties appsettings_1json__JSONSchema="" />
</VisualStudio>
</ProjectExtensions>
</Project>
......@@ -13,7 +13,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishUrl>D:\publish\jx.suvalue.com2</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
<ProjectGuid>3ae00ff5-f0ba-4d72-a23b-770186309327</ProjectGuid>
<SelfContained>false</SelfContained>
</PropertyGroup>
......
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<DeleteExistingFiles>False</DeleteExistingFiles>
<ExcludeApp_Data>False</ExcludeApp_Data>
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>D:\publish</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
</PropertyGroup>
</Project>
\ No newline at end of file
using FluentValidation;
using FluentScheduler;
using FluentValidation;
using FluentValidation.AspNetCore;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Performance.Api.Configurations;
using Performance.Infrastructure;
using Performance.Services;
......@@ -40,19 +45,20 @@ public void ConfigureServices(IServiceCollection services)
#region json & fluentvalidation & filter
services
.AddMvc(option =>
.AddControllers(option =>
{
//筛选器配置
option.Filters.Add<AuthenticationFilter>();
// 控制器访问添加认证
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
option.Filters.Add(new AuthorizeFilter(policy));
option.Filters.Add<ActionsFilter>();
option.Filters.Add<ExceptionsFilter>();
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(JsonOptions) //json格式配置
.AddNewtonsoftJson(JsonOptions) //json格式配置
.AddFluentValidation(fv =>
{
// model验证,禁用其他以使FluentValidation是唯一执行的验证库
fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
//// model验证,禁用其他以使FluentValidation是唯一执行的验证库
//fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
var assembly = Assembly.Load("Performance.DtoModels");
var types = ReflectionHelper.GetInstances<IValidator>(assembly);
......@@ -64,6 +70,8 @@ public void ConfigureServices(IServiceCollection services)
#endregion json & fluentvalidation & filter
services.AddAuthenticationConfiguration(Configuration);
// dbcontext
services.AddDatabaseConfiguration();
......@@ -88,12 +96,13 @@ public void ConfigureServices(IServiceCollection services)
});
});
// fluentscheduler
services.AddFluentSchedulerConfiguration();
services.AddTransient<ExtractGenerateJob>();
services.AddTransient<ExtractDataJob>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
......@@ -103,19 +112,28 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/error/{0}");
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<RequestRateLimitingMiddleware>();
app.UseCors("SignalrCore");
app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/performance/allotLogHub"));
app.UseMvc();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<AllotLogHub>("/performance/allotLogHub");
endpoints.MapControllers();
});
app.UseSwaggerSetup(Configuration);
JobManager.Initialize(new JobRegistry(app.ApplicationServices));
}
private void JsonOptions(MvcJsonOptions json)
private void JsonOptions(MvcNewtonsoftJsonOptions json)
{
json.SerializerSettings.Converters.Add(new IsoDateTimeConverterContent() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
......
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Api
{
......
......@@ -8,7 +8,7 @@
},
"AppConnection": {
//"PerformanceConnectionString": "server=112.124.13.17;database=db_performance;uid=suvalue;pwd=suvalue2016;pooling=true;charset=utf8;convert zero datetime=true;port=3306;connection timeout=120;max pool size=512;allow user variables=true;",
"PerformanceConnectionString": "server=192.168.18.166;database=db_test_zhangye;uid=root;pwd=1234qwer;pooling=true;charset=utf8;convert zero datetime=true;port=3306;connection timeout=120;max pool size=512;allow user variables=true;",
"PerformanceConnectionString": "server=192.168.18.166;database=db_test_srfy;uid=root;pwd=1234qwer;pooling=true;charset=utf8;convert zero datetime=true;port=3306;connection timeout=120;max pool size=512;allow user variables=true;",
"HangfireConnectionString": "server=192.168.18.166;database=db_hangfire;uid=root;pwd=1234qwer;port=3306;allow user variables=true;",
"RedisConnectionString": "116.62.245.55:6379,defaultDatabase=2"
},
......
......@@ -141,14 +141,12 @@
<summary>
批量新增用户表头
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.AccountController.BatchSaveUser(Performance.DtoModels.UserCollectData)">
<summary>
批量新增用户
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="T:Performance.Api.Controllers.AgainAllotController">
......@@ -225,7 +223,7 @@
<param name="allotId"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.AllotController.Generate(Performance.DtoModels.AllotRequest)">
<member name="M:Performance.Api.Controllers.AllotController.GenerateAsync(Performance.DtoModels.AllotRequest)">
<summary>
绩效生成
</summary>
......@@ -854,6 +852,26 @@
<summary>
下拉
</summary>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ConfigController.CustomHeads(Performance.DtoModels.CustomPagingRequest)">
<summary>
自定义表Heads表头
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ConfigController.GetCustomList(Performance.DtoModels.CustomPagingRequest)">
<summary>
自定义表显示
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ConfigController.BatchSaveCustom(Performance.DtoModels.SaveCustomData)">
<summary>
保存自定义表数据
</summary>
<param name="request"></param>
<returns></returns>
</member>
......@@ -1165,6 +1183,13 @@
<param name="allotId"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.EmployeeController.GetDeptComparison(Performance.DtoModels.ComparisonPagingRequest)">
<summary>
实发绩效比对
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ExConfigController.Extract(Performance.DtoModels.ModModuleRequest)">
<summary>
绩效数据抽取模板
......@@ -1564,7 +1589,13 @@
<param name="request"></param>
<returns></returns>
</member>
<!-- Badly formed XML comment ignored for member "M:Performance.Api.Controllers.ReportController.Operation(Performance.DtoModels.ReportRequest)" -->
<member name="M:Performance.Api.Controllers.ReportController.Operation(Performance.DtoModels.ReportRequest)">
<summary>
菜单报表
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.TableNormal(Performance.DtoModels.ConditionRequest)">
<summary>
绩效汇报表
......@@ -1662,12 +1693,6 @@
</summary>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.SecondAllotController.SaveCompute(System.Collections.Generic.List{Performance.EntityModels.ag_compute})">
<summary>
提交二次绩效分配结果
</summary>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.SecondAllotController.SecondDetail(Performance.DtoModels.UseTempRequest)">
<summary>
二次绩效录入页面配置信息
......
......@@ -131,7 +131,7 @@
<summary> 绩效库 </summary>
</member>
<member name="F:Performance.DtoModels.AllotStates.NoData">
<summary> 用户状态 </summary>
<summary> 数据未上传 </summary>
</member>
<member name="F:Performance.DtoModels.AllotStates.FileUploaded">
<summary> 数据已上传 </summary>
......@@ -163,6 +163,11 @@
<member name="F:Performance.DtoModels.AllotStates.GenerateAccomplish">
<summary> 绩效结果解析成功 </summary>
</member>
<member name="F:Performance.DtoModels.AgWorkloadType.PreAccountingReward">
<summary>
核算前奖励
</summary>
</member>
<member name="F:Performance.DtoModels.AgWorkloadType.SingleAwards">
<summary>
单项奖励
......@@ -2562,7 +2567,7 @@
自定义工作量类型Id(不包括默认工作量绩效类型、单项奖励)
</summary>
</member>
<member name="P:Performance.DtoModels.WorkloadRequest.IsSingleAwards">
<member name="P:Performance.DtoModels.WorkloadRequest.AgWorkloadType">
<summary>
是否是单项奖励
</summary>
......@@ -3492,6 +3497,11 @@
有效收入占比
</summary>
</member>
<member name="P:Performance.DtoModels.IssuedPromptResponse.IssueStatus">
<summary>
1 删除 2 驳回 3 修改 4 新增
</summary>
</member>
<member name="P:Performance.DtoModels.MenuResponse.MenuName">
<summary>
菜单名称
......@@ -3517,21 +3527,11 @@
菜单状态 1 启用 2禁用
</summary>
</member>
<member name="P:Performance.DtoModels.OwnerPerformanceDto.ShouldGiveFee">
<summary>
应发绩效
</summary>
</member>
<member name="P:Performance.DtoModels.OwnerPerformanceDto.ReservedRatio">
<summary>
预留比例
</summary>
</member>
<member name="P:Performance.DtoModels.OwnerPerformanceDto.ReservedRatioFee">
<summary>
预留金额
</summary>
</member>
<member name="P:Performance.DtoModels.OwnerPerformanceDto.RealGiveFee">
<summary>
实发绩效
......@@ -4103,6 +4103,11 @@
颜色class名称
</summary>
</member>
<member name="P:Performance.DtoModels.SecondColumnDictionary.IsNumber">
<summary>
格式
</summary>
</member>
<member name="P:Performance.DtoModels.SecondEmployeeDto.ComputeMode">
<summary>
计算方式:11 不计算 12 横向计算 13 纵向计算
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />
<PackageReference Include="CSRedisCore" Version="3.0.45" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="MySql.Data" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
</Project>
......@@ -247,6 +247,9 @@ public AutoMapperConfigs()
CreateMap<view_allot_result, OwnerPerformanceDto>()
.ReverseMap();
CreateMap<ag_secondallot, IssuedPromptResponse>()
.ReverseMap();
}
}
}
......@@ -47,7 +47,7 @@ public enum DbSrouceType
public enum AllotStates
{
/// <summary> 用户状态 </summary>
/// <summary> 数据未上传 </summary>
[Description("数据未上传")]
NoData = 0,
/// <summary> 数据已上传 </summary>
......@@ -85,6 +85,10 @@ public enum AllotStates
public enum AgWorkloadType
{
/// <summary>
/// 核算前奖励
/// </summary>
PreAccountingReward = -2,
/// <summary>
/// 单项奖励
/// </summary>
SingleAwards = -1,
......
......@@ -130,5 +130,6 @@ public class PerDataClinicEmployee : IPerData
/// 行号
/// </summary>
public int RowNumber { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -120,5 +120,6 @@ public class PerDataEmployee : IPerData
/// 行号
/// </summary>
public int RowNumber { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -75,6 +75,8 @@ public class PerDataLogisticsEmployee : IPerData
/// 行号
/// </summary>
public int RowNumber { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -72,5 +72,6 @@ public class PerDataSpecialUnit : IPerData
/// 管理绩效发放系数
/// </summary>
public Nullable<decimal> Management { get; set; }
public decimal? RealGiveFee { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
......@@ -12,11 +12,7 @@
<ItemGroup>
<Compile Remove="PerExcel\PerComputeData.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="8.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
......
......@@ -33,6 +33,12 @@ public class AllotRequest
/// 路径
/// </summary>
public string Path { get; set; }
public int isIssued { get; set; }
public string SearchQuery { get; set; }
public int? QueryStatus { get; set; }
}
public class AllotRequestValidator : AbstractValidator<AllotRequest>
......
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class CustomRequest
{
public int AllotId { get; set; }
public string TableName { get; set; }
public string QuerySearch{ get; set; }
}
public class CustomPagingRequest : CustomRequest
{
public int PageIndex { get; set; } = 1;
public int PageSize { get; set; } = 20;
}
public class CustonPagingData
{
public List<dynamic> DataList { get; set; }
public int TotalCount { get; set; }
}
public class CustomResponse
{
public List<Heads> Heads { get; set; }
public CustonPagingData Datas { get; set; }
}
}
......@@ -50,7 +50,7 @@ public class WorkloadRequest
/// <summary>
/// 是否是单项奖励
/// </summary>
public bool IsSingleAwards { get; set; }
public AgWorkloadType AgWorkloadType { get; set; }
/// <summary>
/// 工作量带出HIS来源
......
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class ComparisonResponse
{
public List<Heads> Heads { get; set; }
public Comparison Datas { get; set; }
}
public class Heads
{
public string Column { get; set; }
public string Name { get; set; }
}
public class Comparison
{
public List<view_check_emp> Datas { get; set; }
public int TotalCount { get; set; }
}
public class ComparisonPagingRequest
{
public int AllotId { get; set; }
public string ViewName { get; set; }
public string SearchQuery { get; set; }
public int PageIndex { get; set; } = 1;
public int PageSize { get; set; } = 20;
}
}
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class IssuedPromptResponse : ag_secondallot
{
public string StatusRemake { get; set; }
/// <summary>
/// 1 删除 2 驳回 3 修改 4 新增
/// </summary>
public int IssueStatus { get; set; }
}
}
......@@ -8,18 +8,10 @@ public class OwnerPerformanceDto : view_allot_result
{
public IEnumerable<OwnerPerformanceDto> Detail { get; set; }
/// <summary>
/// 应发绩效
/// </summary>
public decimal? ShouldGiveFee { get; set; }
/// <summary>
/// 预留比例
/// </summary>
public decimal? ReservedRatio { get; set; }
/// <summary>
/// 预留金额
/// </summary>
public decimal? ReservedRatioFee { get; set; }
/// <summary>
/// 实发绩效
/// </summary>
public decimal RealGiveFee { get; set; }
......
......@@ -19,8 +19,14 @@ public class UserCollectData
public int HospitalId { get; set; }
public int? CreateUser { get; set; }
public string[] ColHeaders { get; set; }
public new string[][] Data { get; set; }
public string[][] Data { get; set; }
}
public class SaveCustomData
{
public int AllotId { get; set; }
public string TableName { get; set; }
public string[] ColHeaders { get; set; }
public string[][] Data { get; set; }
}
}
......@@ -34,12 +34,16 @@ public class SecondColumnDictionary
/// 颜色class名称
/// </summary>
public string Color { get; set; }
/// <summary>
/// 格式
/// </summary>
public bool IsNumber { get; set; }
public SecondColumnDictionary()
{
}
public SecondColumnDictionary(string label, string key, bool isTrue, int sort, string site = "Table", string type = "", string color = "", int? width = null)
public SecondColumnDictionary(string label, string key, bool isTrue, int sort, string site = "Table", string type = "", string color = "", int? width = null, bool isNumber = true)
{
Label = label;
Key = key;
......@@ -49,6 +53,7 @@ public SecondColumnDictionary(string label, string key, bool isTrue, int sort, s
Type = type;
Color = color;
Width = width.HasValue ? width.ToString() : ((label ?? "").Length * 20 + 10).ToString();
IsNumber = isNumber;
}
}
}
......@@ -15,8 +15,8 @@ public PerformanceDbContext(DbContextOptions<PerformanceDbContext> options)
public virtual DbSet<ag_againsituation> ag_againsituation { get; set; }
/// <summary> 二次绩效保存数据 </summary>
public virtual DbSet<ag_bodysource> ag_bodysource { get; set; }
/// <summary> 二次绩效结果表 </summary>
public virtual DbSet<ag_compute> ag_compute { get; set; }
///// <summary> 二次绩效结果表 </summary>
//public virtual DbSet<ag_compute> ag_compute { get; set; }
/// <summary> 二次分配不固定数据 </summary>
public virtual DbSet<ag_data> ag_data { get; set; }
/// <summary> 二次分配人员名单 </summary>
......
......@@ -112,6 +112,11 @@ public class ag_bodysource
public Nullable<decimal> DeptReward { get; set; }
/// <summary>
/// 科室考核前奖励
/// </summary>
public Nullable<decimal> PreDeptReward { get; set; }
/// <summary>
/// 主任基础绩效
/// </summary>
public Nullable<decimal> BasisPerformance { get; set; }
......
//-----------------------------------------------------------------------
// <copyright file=" ag_compute.cs">
// * FileName: 二次绩效结果表.cs
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
////-----------------------------------------------------------------------
//// <copyright file=" ag_compute.cs">
//// * FileName: 二次绩效结果表.cs
//// </copyright>
////-----------------------------------------------------------------------
//using System;
//using System.ComponentModel.DataAnnotations;
//using System.ComponentModel.DataAnnotations.Schema;
namespace Performance.EntityModels
{
/// <summary>
/// 二次绩效结果表
/// </summary>
[Table("ag_compute")]
public class ag_compute
{
/// <summary>
///
/// </summary>
[Key]
public int Id { get; set; }
//namespace Performance.EntityModels
//{
// /// <summary>
// /// 二次绩效结果表
// /// </summary>
// [Table("ag_compute")]
// public class ag_compute
// {
// /// <summary>
// ///
// /// </summary>
// [Key]
// public int Id { get; set; }
/// <summary>
/// 绩效ID
/// </summary>
public Nullable<int> AllotId { get; set; }
// /// <summary>
// /// 绩效ID
// /// </summary>
// public Nullable<int> AllotId { get; set; }
/// <summary>
/// 二次绩效ID
/// </summary>
public Nullable<int> SecondId { get; set; }
// /// <summary>
// /// 二次绩效ID
// /// </summary>
// public Nullable<int> SecondId { get; set; }
/// <summary>
/// 科室类型
/// </summary>
public string UnitType { get; set; }
// /// <summary>
// /// 科室类型
// /// </summary>
// public string UnitType { get; set; }
/// <summary>
/// 科室
/// </summary>
public string Department { get; set; }
// /// <summary>
// /// 科室
// /// </summary>
// public string Department { get; set; }
/// <summary>
/// 职称
/// </summary>
public string WorkPost { get; set; }
// /// <summary>
// /// 职称
// /// </summary>
// public string WorkPost { get; set; }
/// <summary>
/// 工号
/// </summary>
public string JobNumber { get; set; }
// /// <summary>
// /// 工号
// /// </summary>
// public string JobNumber { get; set; }
/// <summary>
/// 人员名称
/// </summary>
public string PersonName { get; set; }
// /// <summary>
// /// 人员名称
// /// </summary>
// public string PersonName { get; set; }
/// <summary>
/// 可分配绩效
/// </summary>
public Nullable<decimal> PerforSumFee { get; set; }
// /// <summary>
// /// 可分配绩效
// /// </summary>
// public Nullable<decimal> PerforSumFee { get; set; }
/// <summary>
/// 管理绩效
/// </summary>
public Nullable<decimal> PerforManagementFee { get; set; }
// /// <summary>
// /// 管理绩效
// /// </summary>
// public Nullable<decimal> PerforManagementFee { get; set; }
/// <summary>
/// 医院其他绩效
/// </summary>
public Nullable<decimal> OthePerfor { get; set; }
// /// <summary>
// /// 医院其他绩效
// /// </summary>
// public Nullable<decimal> OthePerfor { get; set; }
/// <summary>
/// 夜班工作量绩效
/// </summary>
public Nullable<decimal> NightWorkPerfor { get; set; }
// /// <summary>
// /// 夜班工作量绩效
// /// </summary>
// public Nullable<decimal> NightWorkPerfor { get; set; }
/// <summary>
/// 实发金额
/// </summary>
public Nullable<decimal> RealGiveFee { get; set; }
}
}
// /// <summary>
// /// 实发金额
// /// </summary>
// public Nullable<decimal> RealGiveFee { get; set; }
// }
//}
......@@ -61,6 +61,11 @@ public class ag_headsource
/// </summary>
public Nullable<decimal> TotalDeptReward { get; set; }
/// <summary>
/// 科室考核前奖励
/// </summary>
public Nullable<decimal> TotalPreAccountingReward { get; set; }
///// <summary>
///// 业绩分配绩效总额
///// </summary>
......
......@@ -57,6 +57,10 @@ public class ag_secondallot
public Nullable<decimal> RealGiveFee { get; set; }
/// <summary>
/// 预发金额
/// </summary>
public Nullable<decimal> PreRealGiveFee { get; set; }
/// <summary>
/// 效率绩效
/// </summary>
public Nullable<decimal> Efficiency { get; set; }
......
......@@ -57,6 +57,11 @@ public class ex_result
public string Source { get; set; }
/// <summary>
///
/// </summary>
public Nullable<int> TypeId { get; set; }
/// <summary>
/// 数据库类型1、Sql Server 2、Orcale
/// </summary>
public int DatabaseType { get; set; }
......
......@@ -26,11 +26,6 @@ public class ex_script
public string ExecScript { get; set; }
/// <summary>
/// 数据库类型1、Sql Server 2、Orcale
/// </summary>
public int DatabaseType { get; set; }
/// <summary>
/// ExTypeId
/// </summary>
public int TypeId { get; set; }
......
......@@ -230,5 +230,6 @@ public class im_accountbasic
/// 调节后其他绩效
/// </summary>
public Nullable<decimal> AdjustLaterOtherFee { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -175,5 +175,6 @@ public class im_employee
/// 调节后其他绩效
/// </summary>
public Nullable<decimal> AdjustLaterOtherFee { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -175,5 +175,6 @@ public class im_employee_clinic
/// 调节后其他绩效
/// </summary>
public Nullable<decimal> AdjustLaterOtherFee { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -130,5 +130,6 @@ public class im_employee_logistics
/// 是否需要二次分配
/// </summary>
public string NeedSecondAllot { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
......@@ -90,5 +90,6 @@ public class im_specialunit
///
/// </summary>
public Nullable<int> UpdateUser { get; set; }
public Nullable<decimal> RealGiveFee { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Performance.EntityModels
{
public class view_check_dept
{
public int HospitalId { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int AllotID { get; set; }
public string UnitType { get; set; }
public string AccountingUnit { get; set; }
public decimal? RealGiveFeeExecl { get; set; }
public decimal? RealGiveFeeCompute { get; set; }
public decimal? Diff { get; set; }
}
public class view_check_emp : view_check_dept
{
public string JobNumber { get; set; }
public string EmployeeName { get; set; }
}
}
namespace Performance.EntityModels
{
public class view_second_compute_collect
{
public int HospitalId { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int AllotId { get; set; }
public int SecondId { get; set; }
public int UseTempId { get; set; }
public string UnitType { get; set; }
public string Department { get; set; }
public string Status { get; set; }
public string JobNumber { get; set; }
public string WorkPost { get; set; }
public string PersonName { get; set; }
public decimal PerforSumFee { get; set; }
public decimal NightWorkPerfor { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>..\Performance.Api\wwwroot\Performance.EntityModels.xml</DocumentationFile>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Remove="T4Template\**" />
<EmbeddedResource Remove="T4Template\**" />
<None Remove="T4Template\**" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Entity\dis_drugatc.Generated.cs" />
<Compile Remove="Entity\dis_drug_tree.Generated.cs" />
<Compile Remove="Entity\dis_drug_type.Generated.cs" />
<Compile Remove="Entity\dis_drug_useinfo_fee.Generated.cs" />
<Compile Remove="Entity\dis_ip_fee.Generated.cs" />
<Compile Remove="Entity\dis_use_drugs.Generated.cs" />
<Compile Remove="Entity\drug_department_useinfo.Generated.cs" />
<Compile Remove="Entity\drug_dosage.Generated.cs" />
<Compile Remove="Entity\drug_first_use.Generated.cs" />
<Compile Remove="Entity\drug_hosinfo.Generated.cs" />
<Compile Remove="Entity\drug_p_info.Generated.cs" />
<Compile Remove="Entity\drug_p_mi.Generated.cs" />
<Compile Remove="Entity\drug_p_userinfo.Generated.cs" />
<Compile Remove="Entity\drug_som.Generated.cs" />
<Compile Remove="Entity\hos_department_coc.Generated.cs" />
<Compile Remove="Entity\hos_department_fee.Generated.cs" />
<Compile Remove="Entity\hos_disease_person.Generated.cs" />
<Compile Remove="Entity\hos_drugatc.Generated.cs" />
<Compile Remove="Entity\hos_drug_fee.Generated.cs" />
<Compile Remove="Entity\hos_drug_type.Generated.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Compile Update="T4\AutoContext.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoContext.tt</DependentUpon>
</Compile>
<Compile Update="T4\AutoEntity.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoEntity.tt</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="T4\AutoContext.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoContext.cs</LastGenOutput>
</None>
<None Update="T4\AutoEntity.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoEntity.cs</LastGenOutput>
</None>
</ItemGroup>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>..\Performance.Api\wwwroot\Performance.EntityModels.xml</DocumentationFile>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="MySql.Data" Version="8.0.27" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.1" />
<PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="5.2.15" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Compile Update="T4\AutoContext.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoContext.tt</DependentUpon>
</Compile>
<Compile Update="T4\AutoEntity.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoEntity.tt</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Update="T4\AutoContext.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoContext.cs</LastGenOutput>
</None>
<None Update="T4\AutoEntity.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoEntity.cs</LastGenOutput>
</None>
</ItemGroup>
</Project>
......@@ -16,13 +16,13 @@ namespace Performance.Extract.Api.Controllers
[Route("api/[controller]")]
public class ExtractController : Controller
{
private readonly IHostingEnvironment evn;
private readonly IWebHostEnvironment evn;
private readonly ILogger logger;
private readonly WebapiUrl options;
private readonly ExtractService extractService1;
public ExtractController(
IHostingEnvironment evn,
IWebHostEnvironment evn,
ILogger<ExtractController> logger,
IOptions<WebapiUrl> options,
ExtractService extractService1)
......
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<UserSecretsId>3af57781-f816-4c0e-ab66-9b69387e7d35</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Files\**" />
<Content Remove="Files\**" />
<EmbeddedResource Remove="Files\**" />
<None Remove="Files\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.5.1" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\Performance.Api\Template\医院二次分配绩效模板.xlsx" Link="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="..\Performance.Api\Template\医院绩效模板.xlsx" Link="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Update="Template\东方医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JSONSchema="" /></VisualStudio></ProjectExtensions>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<UserSecretsId>3af57781-f816-4c0e-ab66-9b69387e7d35</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\Performance.Api\Template\医院二次分配绩效模板.xlsx" Link="Template\医院二次分配绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="..\Performance.Api\Template\医院绩效模板.xlsx" Link="Template\医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="CSRedisCore" Version="3.6.6" />
</ItemGroup>
<ItemGroup>
<None Update="Template\东方医院绩效模板.xlsx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties appsettings_1json__JSONSchema="" />
</VisualStudio>
</ProjectExtensions>
</Project>
......@@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace Performance.Extract.Api
{
......@@ -14,11 +15,37 @@ public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
.ConfigureAppConfiguration((context, config) =>
{
var env = context.HostingEnvironment;
config.AddJsonFile("appsettings.json", true, true);
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);
})
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
}
using AutoMapper;
using CSRedis;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
......@@ -7,6 +8,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog.Extensions.Logging;
......@@ -16,21 +18,16 @@
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Extract.Api
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
public Startup(IConfiguration configuration)
{
env.ConfigureNLog("nlog.config");
Configuration = configuration;
}
......@@ -55,13 +52,11 @@ public void ConfigureServices(IServiceCollection services)
#region json & fluentvalidation & filter
services
//筛选器配置
.AddMvc(option =>
.AddControllers(option =>
{
option.Filters.Add<ExceptionsFilter>();
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
//json格式配置
.AddJsonOptions(json =>
.AddNewtonsoftJson(json =>
{
json.SerializerSettings.Converters.Add(new IsoDateTimeConverterContent() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
......@@ -94,15 +89,8 @@ public void ConfigureServices(IServiceCollection services)
.AddPerformanceRepoitory();
#endregion
#region automapper
Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperConfigs>());
services.AddAutoMapper();
#endregion
#region redis
var csredis = new CSRedis.CSRedisClient(connection.Value.RedisConnectionString);
RedisHelper.Initialization(csredis);
#endregion
services.AddAutoMapper(typeof(AutoMapperConfigs));
RedisHelper.Initialization(new CSRedisClient(connection.Value.RedisConnectionString));
#region email
......@@ -118,13 +106,10 @@ public void ConfigureServices(IServiceCollection services)
#endregion
#region //ef配置
services.AddDbContext<PerformanceDbContext>(options =>
{
options.UseMySQL(connection.Value.PerformanceConnectionString);
options.UseMySql(connection.Value.PerformanceConnectionString, ServerVersion.AutoDetect(connection.Value.PerformanceConnectionString));
});
#endregion
services.AddSignalR();
services.AddCors(options =>
{
......@@ -136,20 +121,21 @@ public void ConfigureServices(IServiceCollection services)
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("SignalrCore");
app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/allotLogHub"));
loggerFactory.CreateLogger<Startup>().LogDebug(env.EnvironmentName);
app.UseMvc();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<AllotLogHub>("/allotLogHub");
});
}
}
}
......@@ -170,7 +170,7 @@ public static bool CreateFile(string filePath, byte[] buffer)
fs.Close();
}
}
catch (Exception ex)
catch (Exception)
{
return false;
}
......
......@@ -60,9 +60,9 @@ public static string HttpPost(string Url, string postDataStr, string encoding =
return retString;
}
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
finally
{
......@@ -149,9 +149,9 @@ public static void HttpPostNoRequest(string Url, string postDataStr, bool IsJson
request.GetResponseAsync();
Thread.Sleep(1000);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
finally
{
......@@ -188,9 +188,9 @@ public static string HttpClient(string url, string file, bool IsAsync = false)
client.UploadFileAsync(new Uri(url), "POST", file);
return "";
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
......@@ -219,9 +219,9 @@ public static string HttpPost(string url, int timeout = -1, Dictionary<string, s
IRestResponse response = client.Execute(request);
return response.Content;
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.DynamicLinq" Version="2.2.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="CSRedisCore" Version="3.0.45" />
<PackageReference Include="RestSharp" Version="106.11.4" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="MySql.Data" Version="8.0.27" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.1" />
<PackageReference Include="RestSharp" Version="106.13.0" />
<PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="5.2.15" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="FluentValidation.AspNetCore" Version="10.3.3" />
<PackageReference Include="EPPlus" Version="4.5.3.2" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
<PackageReference Include="NPOI" Version="2.5.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.2.2" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Features">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.features\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Mvc.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Features">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.features\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Mvc.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
......@@ -92,7 +92,7 @@ public bool RemoveRange(params TEntity[] entities)
public bool RemoveRange(Expression<Func<TEntity, bool>> exp)
{
var query = CompileQuery(exp);
var query = context.Set<TEntity>().AsQueryable().Where(exp);
var entities = query == null || query.Count() == 0 ? null : query.ToList();
if (entities != null)
context.Set<TEntity>().RemoveRange(entities);
......@@ -142,30 +142,17 @@ public List<TEntity> GetEntities()
public List<TEntity> GetEntities(Expression<Func<TEntity, bool>> exp)
{
var query = CompileQuery(exp);
return query == null || query.Count() == 0 ? null : query.ToList();
return context.Set<TEntity>().AsQueryable().Where(exp).ToList();
}
public List<TEntity> GetEntitiesForPaging(int Page, int pageSize, Expression<Func<TEntity, bool>> exp)
{
return CompileQuery(exp).Skip((Page - 1) * pageSize).Take(pageSize).ToList();
return context.Set<TEntity>().AsQueryable().Where(exp).Skip((Page - 1) * pageSize).Take(pageSize).ToList();
}
public TEntity GetEntity(Expression<Func<TEntity, bool>> exp)
{
return CompileQuerySingle(exp);
}
private IEnumerable<TEntity> CompileQuery(Expression<Func<TEntity, bool>> exp)
{
var func = EF.CompileQuery((DbContext context, Expression<Func<TEntity, bool>> exps) => context.Set<TEntity>().Where(exp));
return func(context, exp);
}
private TEntity CompileQuerySingle(Expression<Func<TEntity, bool>> exp)
{
var func = EF.CompileQuery((DbContext context, Expression<Func<TEntity, bool>> exps) => context.Set<TEntity>().FirstOrDefault(exp));
return func(context, exp);
return context.Set<TEntity>().AsQueryable().FirstOrDefault(exp);
}
#region Bulk
......@@ -204,5 +191,26 @@ public void BulkDelete(IEnumerable<TEntity> entities)
}
#endregion Bulk
public int InsertExecute(IEnumerable<TEntity> data)
{
if (data == null || !data.Any()) return 0;
try
{
string tableName = typeof(TEntity).Name.ToLower();
string database = context.Database.GetDbConnection().Database;
var query = $"select distinct lower(column_name) from information_schema.columns where table_schema = '{database}' and lower(table_name) = '{tableName}' and lower(column_name) <> 'id'";
var columns = DapperQuery<string>(query, new { });
if (columns == null || !columns.Any()) return 0;
var exec = $"insert into {tableName}({string.Join(", ", columns)}) values({string.Join(", ", columns.Select(t => "@" + t))});";
return Execute(exec, data, commandTimeout: 1000 * 60 * 60);
}
catch
{
return 0;
}
}
}
}
using MySql.Data.MySqlClient;
using Microsoft.Data.SqlClient;
using MySql.Data.MySqlClient;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Data.SqlClient;
namespace Performance.Repository
{
......
using Performance.EntityModels;
using System.Collections.Generic;
using System.Linq;
namespace Performance.Repository
{
public partial class PerforAgsecondallotRepository : PerforRepository<ag_secondallot>
{
/// <summary>
/// 删除已提交的历史记录(ag_compute)
/// </summary>
/// <param name="secondId"></param>
/// <returns></returns>
public int DeleteComputeHistory(int secondId)
{
return Execute("DELETE FROM ag_compute WHERE SecondId = @secondId", new { secondId });
}
/// <summary>
/// 查询二次分配结果 根据AllotId
/// </summary>
/// <param name="secondId"></param>
/// <returns></returns>
public List<view_second_compute_collect> GetComputeByAllot(int allotId)
{
var datas = DapperQuery<view_second_compute_collect>("SELECT * FROM view_second_compute_collect WHERE AllotId = @allotId", new { allotId });
if (datas != null)
return datas.ToList();
return new List<view_second_compute_collect>();
}
/// <summary>
/// 查询二次分配结果 根据SecondId
/// </summary>
/// <param name="secondId"></param>
/// <returns></returns>
public List<view_second_compute_collect> GetComputeBySecond(int secondId)
{
var datas = DapperQuery<view_second_compute_collect>("SELECT * FROM view_second_compute_collect WHERE SecondId = @secondId", new { secondId });
if (datas != null)
return datas.ToList();
return new List<view_second_compute_collect>();
}
}
}
......@@ -92,10 +92,10 @@ public bool ImportData(rep_importconfig import, Dictionary<string, object> pairs
transaction.Commit();
}
catch (Exception ex)
catch (Exception)
{
transaction.Rollback();
throw ex;
throw;
}
}
}
......@@ -129,9 +129,9 @@ public void ClearResultData(int allotid)
string clear = "delete from ex_result where allotid = @allotid and isdelete = 1 and createtime < (select min(createtime) from (select distinct createtime from ex_result where allotid = @allotid and isdelete = 1 order by createtime desc limit 4) t);";
connection.Execute(clear, new { allotid }, commandTimeout: 60 * 60);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......@@ -159,10 +159,10 @@ public void ImportWorkloadData(per_allot allot, object parameters)
transaction.Commit();
}
catch (Exception ex)
catch (Exception)
{
transaction.Rollback();
throw ex;
throw;
}
}
}
......@@ -187,9 +187,9 @@ FROM view_second_report_workload
ORDER BY doctorname,Category;";
return connection.Query<report_original_workload>(clear, new { allotid, accountingunit, unittypes = unittypes.Union(new string[] { "通用工作量" }), hospitalid }, commandTimeout: 60 * 60);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......@@ -217,9 +217,9 @@ public IEnumerable<ex_result> QueryIncomeData(int allotid, string source, string
return connection.Query<ex_result>(clear, new { allotid, accountingunit, unittypes, hospitalid }, commandTimeout: 60 * 60);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......@@ -246,9 +246,9 @@ public IEnumerable<view_second_workload_result> GetSecondWorkload(int allotid, s
GROUP BY TAB1.HospitalId,AllotId,TAB1.UnitType,AccountingUnit,HISDeptName,ItemId,ItemName,FactorValue,DoctorName,PersonnelNumber,Category";
return connection.Query<view_second_workload_result>(query, new { allotid, unittype, accountingunit }, commandTimeout: 60 * 60);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......@@ -275,9 +275,9 @@ public IEnumerable<string> GetSecondWorkloadMaps(int hospitalId)
WHERE IFNULL(Category,'')<>''";
return connection.Query<string>(query, new { hospitalId }, commandTimeout: 60 * 60);
}
catch (Exception ex)
catch (Exception)
{
throw ex;
throw;
}
}
}
......
......@@ -3,9 +3,13 @@
// * FileName: per_employee.cs
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.EntityFrameworkCore;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure.Models;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
......@@ -16,11 +20,104 @@ namespace Performance.Repository
/// </summary>
public partial class PerforPeremployeeRepository : PerforRepository<per_employee>
{
public new PageList<per_employee> GetEntitiesForPaging(int pageNumber, int pageSize, Expression<Func<per_employee, bool>> exp)
{
IQueryable<per_employee> queryableAuthors = context.Set<per_employee>().Where(exp).OrderBy(w => w.IsVerify).ThenBy(t => t.Id);
return PageList<per_employee>.Create(queryableAuthors, pageNumber, pageSize);
}
//public Comparison GetComparison(ComparisonPagingRequest request)
//{
// var search = "";
// if (string.IsNullOrEmpty(request.SearchQuery))
// search = " 1=1 ";
// else
// {
// if (request.ViewName == "view_check_dept")
// search = $" ( AccountingUnit like '%{request.SearchQuery}%' )";
// else
// search = $" ( AccountingUnit like '%{request.SearchQuery}%' or JobNumber like '%{request.SearchQuery}%' or EmployeeName like '%{request.SearchQuery}%') ";
// }
// var result = new Comparison();
// var sql = $@"SELECT COUNT(*) FROM {request.ViewName} WHERE AllotId = @AllotId and {search}";
// result.TotalCount = DapperQuery<int>(sql, new { request.AllotId })?.FirstOrDefault() ?? 0;
// sql = $@"SELECT * FROM {request.ViewName} WHERE AllotId = @AllotId and {search} ORDER BY HospitalId,Year,Month,ABS(DIFF) DESC LIMIT {(request.PageIndex - 1) * request.PageSize},{request.PageSize}; ";
// result.Datas = DapperQuery<view_check_emp>(sql, new { request.AllotId })?.ToList();
// return result;
//}
/// <summary>
/// 人员实发绩效比对
/// </summary>
/// <param name="allotId"></param>
/// <param name="searchQuery"></param>
/// <returns></returns>
public Comparison CheckEmployeeRealGiveFeeDiff(int allotId, string searchQuery)
{
var queryData = @"
SELECT
HospitalId,Year,Month,AllotID,UnitType,AccountingUnit,JobNumber,MAX(EmployeeName) AS EmployeeName,
SUM(RealGiveFeeExecl) AS RealGiveFeeExecl,SUM(RealGiveFeeCompute) AS RealGiveFeeCompute,SUM(RealGiveFeeExecl) - SUM(RealGiveFeeCompute) AS Diff
FROM (
SELECT * FROM view_check_emp_clinic WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_emp_employee WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_emp_logistics WHERE AllotId = @allotId
) TAB
WHERE if(@searchQuery='','',AccountingUnit) LIKE @parm OR if(@searchQuery='','',JobNumber) LIKE @parm OR if(@searchQuery='','',EmployeeName) LIKE @parm
GROUP BY HospitalId,Year,Month,AllotID,UnitType,AccountingUnit,JobNumber
ORDER BY HospitalId,Year,Month,ABS(SUM(RealGiveFeeExecl) - SUM(RealGiveFeeCompute)) DESC
";
var queryCount = @"
SELECT COUNT(DISTINCT HospitalId,Year,Month,AllotID,UnitType,AccountingUnit,JobNumber) FROM (
SELECT * FROM view_check_emp_clinic WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_emp_employee WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_emp_logistics WHERE AllotId = @allotId
) TAB
WHERE if(@searchQuery='','',AccountingUnit) LIKE @parm OR if(@searchQuery='','',JobNumber) LIKE @parm OR if(@searchQuery='','',EmployeeName) LIKE @parm
";
return new Comparison()
{
Datas = DapperQuery<view_check_emp>(queryData, new { allotId, searchQuery, parm = $"%{searchQuery}%" })?.ToList() ?? new List<view_check_emp>(),
TotalCount = DapperQuery<int>(queryCount, new { allotId, searchQuery, parm = $"%{searchQuery}%" })?.FirstOrDefault() ?? 0,
};
}
/// <summary>
/// 科室实发绩效比对
/// </summary>
public Comparison CheckAccountingUnitRealGiveFeeDiff(int allotId, string searchQuery)
{
var queryData = @"
SELECT *,IFNULL(RealGiveFeeExecl,0) - IFNULL(RealGiveFeeCompute,0) AS Diff FROM (
SELECT * FROM view_check_dept_account WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_dept_specialunit WHERE AllotId = @allotId
) TAB
WHERE if(@searchQuery='','',AccountingUnit) LIKE @parm
ORDER BY HospitalId,Year,Month,ABS(DIFF) DESC
";
var queryCount = @"
SELECT count(0) FROM (
SELECT * FROM view_check_dept_account WHERE AllotId = @allotId UNION ALL
SELECT * FROM view_check_dept_specialunit WHERE AllotId = @allotId
) TAB
WHERE if(@searchQuery='','',AccountingUnit) LIKE @parm
";
return new Comparison()
{
Datas = DapperQuery<view_check_emp>(queryData, new { allotId, searchQuery, parm = $"%{searchQuery}%" })?.ToList() ?? new List<view_check_emp>(),
TotalCount = DapperQuery<int>(queryCount, new { allotId, searchQuery, parm = $"%{searchQuery}%" })?.FirstOrDefault() ?? 0,
};
}
}
}
using Performance.DtoModels;
using Microsoft.EntityFrameworkCore;
using Performance.DtoModels;
using Performance.EntityModels;
using System.Collections.Generic;
using System.Linq;
......@@ -385,7 +386,7 @@ public List<EmployeeReservedDto> GetEmployeeReserved(int hospitalId, int year)
public List<view_allot_result> GetOwnerPerformance(List<int> hospitalId, string jobNumber)
{
string sql = "SELECT * FROM view_allot_result WHERE HospitalID IN @HospitalID AND JobNumber=@JobNumber";
string sql = "SELECT * FROM view_allot_result WHERE States = 8 AND HospitalID IN @HospitalID AND JobNumber=@JobNumber";
return DapperQuery<view_allot_result>(sql, new { HospitalID = hospitalId, JobNumber = jobNumber })?.ToList();
}
......@@ -395,5 +396,80 @@ public List<dynamic> QueryCompute(int allotId, string viewName)
return DapperQuery<dynamic>(sql, new { allotId })?.ToList();
}
public CustonPagingData QueryCustom(CustomPagingRequest request, bool IsHead)
{
var result = new CustonPagingData();
string sql, Query;
if (string.IsNullOrEmpty(request.QuerySearch))
Query = " and 1=1 ";
else
Query = $@" and (AccountingUnit like '%{request.QuerySearch}%' or UnitType like '%{request.QuerySearch}%') ";
if (IsHead)
sql = $@"SELECT * FROM {request.TableName} WHERE AllotId = @AllotId ";
else
sql = $@"SELECT * FROM {request.TableName} WHERE AllotId = @AllotId {Query} order by UnitType,AccountingUnit LIMIT {(request.PageIndex - 1) * request.PageSize},{request.PageSize} ";
result.DataList = DapperQuery<dynamic>(sql, new { request.AllotId })?.ToList();
sql = $@"SELECT COUNT(*) FROM {request.TableName} WHERE AllotId = @AllotId {Query} ";
result.TotalCount = DapperQuery<int>(sql, new { request.AllotId })?.FirstOrDefault() ?? 0;
return result;
}
public bool QueryIsAllotId(string tableName)
{
var database = context.Database.GetDbConnection().Database;
var sql = $@"SELECT column_name FROM information_schema.COLUMNS s
WHERE table_name = @table_name AND TABLE_SCHEMA = @database AND (column_name='allotId' or column_name='AccountingUnit' or column_name='UnitType');";
var result = DapperQuery<string>(sql, new { database = database, table_name = tableName });
var isExist=result ?.Count() == 3;
return isExist;
}
public List<dynamic> QueryCustomColumn(string tableName)
{
var database = context.Database.GetDbConnection().Database;
var sql = $@"SELECT column_name,column_comment FROM information_schema.`COLUMNS` WHERE table_schema = @table_schema AND table_name = @table_name AND COLUMN_KEY <> 'PRI' ";
var result = DapperQuery<dynamic>(sql, new { table_schema = database, table_name = tableName })?.ToList();
return result;
}
public bool CreatCustom(int AllotId, string tableName, List<dynamic> datas)
{
var sql = $@"DELETE FROM {tableName} WHERE allotId=@AllotId ";
Execute(sql, new { AllotId });
if (datas == null)
return true;
var database = context.Database.GetDbConnection().Database;
sql = $@"SELECT column_name FROM information_schema.COLUMNS s
WHERE table_name = @table_name AND TABLE_SCHEMA = @database AND COLUMN_KEY <> 'PRI';";
var columns = DapperQuery<string>(sql, new { database = database, table_name = tableName })?.ToList();
sql = $"INSERT INTO {tableName}({string.Join(",", columns.ToArray())}) VALUES({string.Join(",", columns.Select(t => "@" + t))});";
var success = Execute(sql, datas);
if (success > 0)
return true;
else
return false;
}
public List<dynamic> QueryType(string tableName)
{
var database = context.Database.GetDbConnection().Database;
var sql = $@"select column_name,data_type from information_schema.columns where table_name=@table_name and table_schema=@table_schema AND (data_type like '%int%' or data_type like '%decimal%' or data_type like '%date%') AND COLUMN_KEY <> 'PRI' ";
var result = DapperQuery<dynamic>(sql, new { table_schema = database, table_name = tableName })?.ToList();
return result;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="1.60.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="MySql.Data" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.19.60" />
<PackageReference Include="Z.EntityFramework.Extensions.EFCore" Version="2.8.40" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="4.0.0" />
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="3.21.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="T4\AutoRepository.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoRepository.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Update="T4\AutoRepository.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AutoRepository.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Compile Update="T4\AutoRepository.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoRepository.tt</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Update="T4\AutoRepository.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>AutoRepository.tt</DependentUpon>
</Compile>
</ItemGroup>
</Project>
......@@ -7,13 +7,13 @@
namespace Performance.Repository
{
/// <summary>
/// ag_compute Repository
/// </summary>
public partial class PerforAgcomputeRepository : PerforRepository<ag_compute>
{
public PerforAgcomputeRepository(PerformanceDbContext context) : base(context)
{
}
}
///// <summary>
///// ag_compute Repository
///// </summary>
//public partial class PerforAgcomputeRepository : PerforRepository<ag_compute>
//{
// public PerforAgcomputeRepository(PerformanceDbContext context) : base(context)
// {
// }
//}
}
......@@ -14,6 +14,7 @@ namespace Performance.Services
public class AgainAllotService : IAutoInjection
{
private Application application;
private readonly IMapper _mapper;
private AgainService againService;
private RoleService roleService;
private ConfigService configService;
......@@ -30,7 +31,10 @@ public class AgainAllotService : IAutoInjection
private PerforAgemployeeRepository perforAgemployeeRepository;
private PerforAgheaderRepository perforAgheaderRepository;
public AgainAllotService(IOptions<Application> options, AgainService againService,
public AgainAllotService(
IOptions<Application> options,
IMapper mapper,
AgainService againService,
RoleService roleService,
PerforCofagainRepository perforCofagainRepository,
PerforPeragainallotRepository perforPeragainallotRepository,
......@@ -46,6 +50,7 @@ public class AgainAllotService : IAutoInjection
ConfigService configService)
{
this.application = options.Value;
_mapper = mapper;
this.againService = againService;
this.roleService = roleService;
this.perforCofagainRepository = perforCofagainRepository;
......@@ -197,24 +202,24 @@ public class AgainAllotService : IAutoInjection
// #region 保存
// var againsituation = Mapper.Map<ag_againsituation>(situation);
// var againsituation = _mapper.Map<ag_againsituation>(situation);
// againsituation.AllotID = againAllot.AllotID;
// againsituation.AgainAllotID = againAllot.ID;
// perforAgagainsituationRepository.Add(againsituation);
// var employeeList = Mapper.Map<List<ag_employee>>(perAgainExcel.AgainEmployee);
// var employeeList = _mapper.Map<List<ag_employee>>(perAgainExcel.AgainEmployee);
// employeeList.ForEach(item => { item.AllotID = againAllot.AllotID; item.AgainAllotID = againAllot.ID; });
// perforAgemployeeRepository.AddRange(employeeList.ToArray());
// var pHeader = Mapper.Map<ag_header>(perAgainExcel.Header);
// var pHeader = _mapper.Map<ag_header>(perAgainExcel.Header);
// pHeader.AllotID = againAllot.AllotID;
// pHeader.AgainAllotID = againAllot.ID;
// var cHeaderList = Mapper.Map<List<ag_header>>(perAgainExcel.Header.Children);
// var cHeaderList = _mapper.Map<List<ag_header>>(perAgainExcel.Header.Children);
// cHeaderList.ForEach(item => { item.AllotID = againAllot.AllotID; item.AgainAllotID = againAllot.ID; });
// perforAgheaderRepository.Add(pHeader);
// perforAgheaderRepository.AddRange(cHeaderList.ToArray());
// var dataList = Mapper.Map<List<ag_data>>(perAgainExcel.AgainData);
// var dataList = _mapper.Map<List<ag_data>>(perAgainExcel.AgainData);
// dataList.ForEach(item => { item.AllotID = againAllot.AllotID; item.AgainAllotID = againAllot.ID; });
// perforAgdataRepository.AddRange(dataList.ToArray());
......@@ -314,27 +319,27 @@ public class AgainAllotService : IAutoInjection
throw new PerformanceException("绩效二次分配不存在");
var situation = perforAgagainsituationRepository.GetEntity(t => t.AgainAllotID == againAllot.ID);
var againsituation = Mapper.Map<PerAgainSituation>(situation);
var againsituation = _mapper.Map<PerAgainSituation>(situation);
var againEmployee = perforAgemployeeRepository.GetEntities(t => t.AgainAllotID == againAllot.ID);
//var employeeList = Mapper.Map<List<PerAgainEmployee>>(againEmployee);
//var employeeList = _mapper.Map<List<PerAgainEmployee>>(againEmployee);
var header = perforAgheaderRepository.GetEntities(t => t.AgainAllotID == againAllot.ID);
//var headerList = Mapper.Map<List<PerHeader>>(header);
//var headerList = _mapper.Map<List<PerHeader>>(header);
var data = perforAgdataRepository.GetEntities(t => t.AgainAllotID == againAllot.ID);
//var dataList = Mapper.Map<List<PerAgainData>>(data);
//var dataList = _mapper.Map<List<PerAgainData>>(data);
var pHead = header.FirstOrDefault(t => t.CellValue == "工作量绩效工资");
var head = Mapper.Map<PerHeader>(pHead);
var cHead = Mapper.Map<List<PerHeader>>(header.Where(t => t.CellValue != "工作量绩效工资"));
var head = _mapper.Map<PerHeader>(pHead);
var cHead = _mapper.Map<List<PerHeader>>(header.Where(t => t.CellValue != "工作量绩效工资"));
head.Children = cHead;
var perAgainExcel = new PerAgainExcel
{
Header = head,
AgainData = Mapper.Map<List<PerAgainData>>(data),
AgainEmployee = Mapper.Map<List<PerAgainEmployee>>(againEmployee)
AgainData = _mapper.Map<List<PerAgainData>>(data),
AgainEmployee = _mapper.Map<List<PerAgainEmployee>>(againEmployee)
};
return SheetFormat(perAgainExcel, againsituation);
......@@ -395,7 +400,7 @@ public List<AgainAllotResponse> GetAllotList(int userid)
}
again = perforPeragainallotRepository.GetEntities(t => allotId.Contains(t.AllotID.Value) && t.CreateUser == userid);
List<AgainAllotResponse> list = Mapper.Map<List<AgainAllotResponse>>(again);
List<AgainAllotResponse> list = _mapper.Map<List<AgainAllotResponse>>(again);
list.ForEach(t =>
{
var data = allot.Where(p => p.ID == t.AllotID).FirstOrDefault();
......
......@@ -16,6 +16,7 @@ namespace Performance.Services.AllotCompute
/// </summary>
public class ProcessComputService : IAutoInjection
{
private readonly IMapper _mapper;
private readonly BudgetService _budgetService;
private PerforCofincomeRepository perforCofincomeRepository;
private PerforPersheetRepository perforPerSheetRepository;
......@@ -33,6 +34,7 @@ public class ProcessComputService : IAutoInjection
private readonly PerforPerallotRepository perallotRepository;
public ProcessComputService(
IMapper mapper,
BudgetService budgetService,
PerforCofincomeRepository perforCofincomeRepository,
PerforPersheetRepository perforPerSheetRepository,
......@@ -49,6 +51,7 @@ public class ProcessComputService : IAutoInjection
PerforHospitalRepository hospitalRepository,
PerforPerallotRepository perallotRepository)
{
_mapper = mapper;
_budgetService = budgetService;
this.perforCofincomeRepository = perforCofincomeRepository;
this.perforPerSheetRepository = perforPerSheetRepository;
......@@ -101,7 +104,7 @@ private void SaveComputeAccount(PerSheet sheet, int allotId)
List<res_account> addList = new List<res_account>();
foreach (var data in dataList)
{
var imdata = Mapper.Map<res_account>(data);
var imdata = _mapper.Map<res_account>(data);
imdata.SheetID = imsheet.ID;
imdata.AllotID = allotId;
addList.Add(imdata);
......@@ -123,7 +126,7 @@ private void SaveCommon(PerSheet sheet, int allotId)
List<im_header> addHeadList = new List<im_header>();
foreach (var header in sheet.PerHeader)
{
var imheader = Mapper.Map<im_header>(header);
var imheader = _mapper.Map<im_header>(header);
imheader.SheetID = imsheet.ID;
imheader.AllotID = allotId;
perforImHeaderRepository.Add(imheader);
......@@ -131,7 +134,7 @@ private void SaveCommon(PerSheet sheet, int allotId)
{
foreach (var child in header.Children)
{
var imheaderChild = Mapper.Map<im_header>(child);
var imheaderChild = _mapper.Map<im_header>(child);
imheaderChild.SheetID = imsheet.ID;
imheaderChild.ParentID = imheader.ID;
imheaderChild.AllotID = allotId;
......@@ -145,7 +148,7 @@ private void SaveCommon(PerSheet sheet, int allotId)
var dataList = sheet.PerData.Select(t => (PerData)t);
foreach (var data in dataList)
{
var imdata = Mapper.Map<im_data>(data);
var imdata = _mapper.Map<im_data>(data);
imdata.SheetID = imsheet.ID;
imdata.AllotID = allotId;
addDataList.Add(imdata);
......@@ -429,7 +432,7 @@ public void ComputeOffice(per_allot allot, PerExcel excel)
List<res_account> addList = new List<res_account>();
foreach (var data in perDatas)
{
var imdata = Mapper.Map<res_account>(data);
var imdata = _mapper.Map<res_account>(data);
imdata.AllotID = allot.ID;
addList.Add(imdata);
}
......
......@@ -12,6 +12,7 @@ namespace Performance.Services.AllotCompute
{
public class QueryDataService : IAutoInjection
{
private readonly IMapper _mapper;
private readonly LogManageService logManageService;
private readonly PerforPersheetRepository persheetRepository;
private readonly PerforImemployeeRepository imemployeeRepository;
......@@ -21,7 +22,9 @@ public class QueryDataService : IAutoInjection
private readonly PerforImdataRepository imdataRepository;
private readonly PerforImheaderRepository imheaderRepository;
public QueryDataService(LogManageService logManageService,
public QueryDataService(
IMapper mapper,
LogManageService logManageService,
PerforPersheetRepository persheetRepository,
PerforImemployeeRepository imemployeeRepository,
PerforImemployeeclinicRepository imemployeeclinicRepository,
......@@ -30,6 +33,7 @@ public class QueryDataService : IAutoInjection
PerforImdataRepository imdataRepository,
PerforImheaderRepository imheaderRepository)
{
_mapper = mapper;
this.logManageService = logManageService;
this.persheetRepository = persheetRepository;
this.imemployeeRepository = imemployeeRepository;
......@@ -121,7 +125,7 @@ private PerExcel Query(List<per_sheet> sheets, int allotId)
private void QueryEmployee(int allotId, int sheetId, PerSheet sheet)
{
var data = imemployeeRepository.GetEntities(t => t.AllotID == allotId && t.SheetID == sheetId);
var sheetData = Mapper.Map<List<PerDataEmployee>>(data);
var sheetData = _mapper.Map<List<PerDataEmployee>>(data);
if (sheetData != null && sheetData.Any())
sheet.PerData.AddRange(sheetData);
}
......@@ -129,7 +133,7 @@ private void QueryEmployee(int allotId, int sheetId, PerSheet sheet)
private void QueryClinicEmployee(int allotId, int sheetId, PerSheet sheet)
{
var data = imemployeeclinicRepository.GetEntities(t => t.AllotID == allotId && t.SheetID == sheetId);
var sheetData = Mapper.Map<List<PerDataClinicEmployee>>(data);
var sheetData = _mapper.Map<List<PerDataClinicEmployee>>(data);
if (sheetData != null && sheetData.Any())
sheet.PerData.AddRange(sheetData);
}
......@@ -137,7 +141,7 @@ private void QueryClinicEmployee(int allotId, int sheetId, PerSheet sheet)
private void QueryAccountBasic(int allotId, int sheetId, PerSheet sheet)
{
var data = imaccountbasicRepository.GetEntities(t => t.AllotID == allotId && t.SheetID == sheetId);
var sheetData = Mapper.Map<List<PerDataAccountBaisc>>(data);
var sheetData = _mapper.Map<List<PerDataAccountBaisc>>(data);
if (sheetData != null && sheetData.Any())
sheet.PerData.AddRange(sheetData);
}
......@@ -145,7 +149,7 @@ private void QueryAccountBasic(int allotId, int sheetId, PerSheet sheet)
private void QuerySpecialUnit(int allotId, int sheetId, PerSheet sheet)
{
var data = imspecialunitRepository.GetEntities(t => t.AllotID == allotId && t.SheetID == sheetId);
var sheetData = Mapper.Map<List<PerDataSpecialUnit>>(data);
var sheetData = _mapper.Map<List<PerDataSpecialUnit>>(data);
if (sheetData != null && sheetData.Any())
sheet.PerData.AddRange(sheetData);
}
......@@ -153,7 +157,7 @@ private void QuerySpecialUnit(int allotId, int sheetId, PerSheet sheet)
private void QueryCommon(int allotId, int sheetId, PerSheet sheet)
{
var data = imdataRepository.GetEntities(t => t.AllotID == allotId && t.SheetID == sheetId);
var sheetData = Mapper.Map<List<PerData>>(data);
var sheetData = _mapper.Map<List<PerData>>(data);
if (sheetData != null && sheetData.Any())
sheet.PerData.AddRange(sheetData);
}
......@@ -169,7 +173,7 @@ private List<PerHeader> GetHeaderAndChild(List<im_header> headers, List<im_heade
{
foreach (var header in headers)
{
var perHeader = Mapper.Map<PerHeader>(header);
var perHeader = _mapper.Map<PerHeader>(header);
var children = allheaders.Where(t => t.ParentID == header.ID);
if (children != null && children.Any())
{
......
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
......@@ -12,9 +14,13 @@
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Caching.Memory;
namespace Performance.Services
{
......@@ -27,11 +33,13 @@ public class AllotService : IAutoInjection
private ResultComputeService resultComputeService;
private PerforLogdbugRepository logdbug;
private ConfigService configService;
private IHostingEnvironment _evn;
private IWebHostEnvironment _evn;
private ILogger<AllotService> _logger;
private readonly IMapper _mapper;
private PerforPerallotRepository _allotRepository;
private IEmailService emailService;
private readonly IOptions<Application> options;
private readonly IOptions<AppConnection> _appConnection;
private readonly ComputeDirector _computeDirector;
private readonly PerforRescomputeRepository _perforRescomputeRepository;
private readonly PerforImemployeeRepository _perforImEmployeeRepository;
......@@ -53,6 +61,7 @@ public class AllotService : IAutoInjection
private readonly QueryDataService queryDataService;
public AllotService(
IMapper mapper,
PerforPerallotRepository allotRepository,
BaiscNormService baiscNormService,
CheckDataService checkDataService,
......@@ -61,9 +70,10 @@ public class AllotService : IAutoInjection
ResultComputeService resultComputeService,
ConfigService configService,
PerforLogdbugRepository logdbug,
IHostingEnvironment evn, ILogger<AllotService> logger,
IWebHostEnvironment evn, ILogger<AllotService> logger,
IEmailService emailService,
IOptions<Application> options,
IOptions<AppConnection> appConnection,
ComputeDirector computeDirector,
PerforRescomputeRepository perforRescomputeRepository,
PerforImemployeeRepository perforImEmployeeRepository,
......@@ -82,6 +92,7 @@ public class AllotService : IAutoInjection
PerforPeremployeeRepository perforPeremployeeRepository,
QueryDataService queryDataService)
{
_mapper = mapper;
_allotRepository = allotRepository;
_againallotRepository = againallotRepository;
_logger = logger;
......@@ -93,6 +104,7 @@ public class AllotService : IAutoInjection
this.resultComputeService = resultComputeService;
this.emailService = emailService;
this.options = options;
_appConnection = appConnection;
_computeDirector = computeDirector;
_perforRescomputeRepository = perforRescomputeRepository;
_perforImEmployeeRepository = perforImEmployeeRepository;
......@@ -127,7 +139,7 @@ public List<AllotResponse> GetAllotList(int? hospitalId)
var allotList = _allotRepository.GetEntities(t => t.HospitalId == hospitalId);
allotList = allotList == null ? allotList : allotList.OrderByDescending(t => t.ID).ToList();
var isconfig = perforHospitalconfigRepository.GetEntity(t => t.HospitalId == hospitalId) == null ? false : true;
var result = Mapper.Map<List<AllotResponse>>(allotList);
var result = _mapper.Map<List<AllotResponse>>(allotList);
result?.ForEach(t =>
{
t.IsDown = !string.IsNullOrEmpty(t.ExtractPath);
......@@ -156,7 +168,7 @@ public List<AllotResponse> GetSuccAllotList(int? hospitalId)
&& new List<int> { (int)AllotStates.Archive, (int)AllotStates.GenerateSucceed }.Contains(t.States));
allotList = allotList == null ? allotList : allotList.OrderByDescending(t => t.ID).ToList();
var isconfig = perforHospitalconfigRepository.GetEntity(t => t.HospitalId == hospitalId) == null ? false : true;
var reuslt = Mapper.Map<List<AllotResponse>>(allotList);
var reuslt = _mapper.Map<List<AllotResponse>>(allotList);
reuslt?.ForEach(t =>
{
t.IsDown = !string.IsNullOrEmpty(t.ExtractPath);
......@@ -179,7 +191,7 @@ public per_allot InsertAllot(AllotRequest request, int userID)
if (repAllot != null && repAllot.Count() > 0)
throw new PerformanceException("当前绩效记录已存在");
var allot = Mapper.Map<per_allot>(request);
var allot = _mapper.Map<per_allot>(request);
allot.CreateDate = DateTime.Now;
allot.CreateUser = userID;
allot.States = (int)AllotStates.NoData;
......@@ -212,7 +224,7 @@ public AllotResponse UpdateAllot(AllotRequest request)
if (!_allotRepository.Update(allot))
throw new PerformanceException("保存失败");
return Mapper.Map<AllotResponse>(allot);
return _mapper.Map<AllotResponse>(allot);
}
/// <summary>
......@@ -309,7 +321,6 @@ public per_allot UpdateAllotShowFormula(int allotId)
/// <param name="user"></param>
public void Generate(per_allot allot)
{
DateTime time = DateTime.Now;
try
{
logManageService.WriteMsg("绩效开始执行", $"正在生成{allot.Year}-{allot.Month.ToString().PadLeft(2, '0')}月份绩效!", 1, allot.ID, "ReceiveMessage", true);
......@@ -464,7 +475,6 @@ public void Generate(per_allot allot)
catch (Exception ex)
{
logManageService.WriteMsg("绩效生成失败", ex.Message, 4, allot.ID, "ReceiveMessage");
logdbug.Add(allot.ID, "绩效生成失败", ex.ToString(), 4, 1);
UpdateAllotStates(allot.ID, (int)AllotStates.GenerateFail, EnumHelper.GetDescription(AllotStates.GenerateFail));
//SendEmail(allot, mail, 2, time);
//throw ex;
......@@ -486,7 +496,10 @@ public void GenerateReport(per_allot allot)
/// <param name="allot"></param>
public void AccoungtingVerify(int allotId)
{
reportService.ExecProc("call proc_verify_accoungingunit_unittype(@allotId);", new { allotId });
using (IDbConnection connection = new MySqlConnection(_appConnection.Value.PerformanceConnectionString))
{
connection.Execute("call proc_verify_accoungingunit_unittype(@allotId);", new { allotId });
}
}
/// <summary>
......@@ -502,7 +515,7 @@ public void Recalculation(int allotId, decimal money)
if (empolyeeList == null) return;
var computeEmployees = Mapper.Map<List<ComputeEmployee>>(empolyeeList);
var computeEmployees = _mapper.Map<List<ComputeEmployee>>(empolyeeList);
computeEmployees.ForEach(w => w.FitPeopleValue = money);
List<res_baiscnorm> baiscnormList = new List<res_baiscnorm>();
......@@ -517,7 +530,7 @@ public void Recalculation(int allotId, decimal money)
if (historyRescompute != null && historyRescompute.Any())
_perforRescomputeRepository.RemoveRange(historyRescompute.ToArray());
var computes = Mapper.Map<List<res_compute>>(computResult);
var computes = _mapper.Map<List<res_compute>>(computResult);
computes.ForEach(t => t.AllotID = allot.ID);
_perforRescomputeRepository.AddRange(computes.ToArray());
......@@ -525,7 +538,7 @@ public void Recalculation(int allotId, decimal money)
var historyResbaiscnorm = perforResbaiscnormRepository.GetEntities(w => w.AllotID == allotId && names.Contains(w.PositionName));
if (historyResbaiscnorm != null && historyResbaiscnorm.Any())
perforResbaiscnormRepository.RemoveRange(historyResbaiscnorm.ToArray());
perforResbaiscnormRepository.AddRange(Mapper.Map<res_baiscnorm[]>(baiscnormList));
perforResbaiscnormRepository.AddRange(_mapper.Map<res_baiscnorm[]>(baiscnormList));
}
/// <summary>
......@@ -595,7 +608,7 @@ public void Pigeonhole(per_allot allot)
public List<AgainAllotResponse> GetAgainAllotNotSucceed(per_allot allot)
{
var again = _againallotRepository.GetEntities(t => t.AllotID == allot.ID && (!t.States.HasValue || t.States.Value != 3));
List<AgainAllotResponse> result = Mapper.Map<List<AgainAllotResponse>>(again);
List<AgainAllotResponse> result = _mapper.Map<List<AgainAllotResponse>>(again);
if (result != null && result.Count > 0)
{
result.ForEach(t => { t.Year = allot.Year; t.Month = allot.Month; });
......@@ -711,7 +724,7 @@ public List<OwnerPerformanceDto> GetOwnerPerformance(int userid)
.Where(p => p.Year == w.Key.Year && p.Month == w.Key.Month && p.JobNumber == w.Key.JobNumber)
.Select(detial =>
{
var dto = Mapper.Map<OwnerPerformanceDto>(detial);
var dto = _mapper.Map<OwnerPerformanceDto>(detial);
dto.Source = string.IsNullOrEmpty(detial.SourceItem) ? detial.Source : $"{detial.Source}-{detial.SourceItem}";
// 应发绩效
dto.ShouldGiveFee = Math.Round((dto.RealPerformance ?? 0) + (dto.OtherPerfor ?? 0) + (dto.HideOtherPerfor ?? 0) + (dto.NightWorkPerfor ?? 0), 2, MidpointRounding.AwayFromZero);
......
......@@ -14,18 +14,22 @@ namespace Performance.Services
{
public class BudgetService : IAutoInjection
{
private readonly IMapper _mapper;
private readonly PerforPerbudgetamountRepository perbudgetamountRepository;
private readonly PerforPerbudgetratioRepository perbudgetratioRepository;
private readonly PerforPerbudgetresultRepository perbudgetresultRepository;
private readonly PerforPerallotRepository perallotRepository;
private readonly ILogger logger;
public BudgetService(PerforPerbudgetamountRepository perbudgetamountRepository,
public BudgetService(
IMapper mapper,
PerforPerbudgetamountRepository perbudgetamountRepository,
PerforPerbudgetratioRepository perbudgetratioRepository,
PerforPerbudgetresultRepository perbudgetresultRepository,
PerforPerallotRepository perallotRepository,
ILogger<BudgetService> logger)
{
_mapper = mapper;
this.perbudgetamountRepository = perbudgetamountRepository;
this.perbudgetratioRepository = perbudgetratioRepository;
this.perbudgetresultRepository = perbudgetresultRepository;
......@@ -43,12 +47,12 @@ public List<BudgetResponse> QueryBudgetByYear(int hospitalid, int year)
{
var amounts = perbudgetamountRepository.GetEntities(t => t.HospitalId == hospitalid && t.MainYear == year);
var ratios = perbudgetratioRepository.GetEntities(t => t.HospitalId == hospitalid && t.MainYear == year);
var result = Mapper.Map<List<BudgetResponse>>(amounts);
var result = _mapper.Map<List<BudgetResponse>>(amounts);
if (result == null)
return Mapper.Map<List<BudgetResponse>>(ratios);
return _mapper.Map<List<BudgetResponse>>(ratios);
else if (ratios != null && ratios.Any())
{
result.AddRange(Mapper.Map<List<BudgetResponse>>(ratios));
result.AddRange(_mapper.Map<List<BudgetResponse>>(ratios));
}
return result.OrderBy(t => t.Year).ToList();
}
......@@ -68,7 +72,7 @@ public bool SaveBudgetData(int mainYear, List<BudgetResponse> request, int userI
if (entity != null && entity.Any())
throw new PerformanceException($"{mainYear}年数据已存在");
var amounts = Mapper.Map<List<per_budget_amount>>(request.Where(t => t.Type == 1));
var amounts = _mapper.Map<List<per_budget_amount>>(request.Where(t => t.Type == 1));
amounts.ForEach(t =>
{
t.MainYear = mainYear;
......@@ -77,7 +81,7 @@ public bool SaveBudgetData(int mainYear, List<BudgetResponse> request, int userI
});
if (amounts != null && perbudgetamountRepository.AddRange(amounts.ToArray()))
{
var ratios = Mapper.Map<List<per_budget_ratio>>(request.Where(t => t.Type == 2));
var ratios = _mapper.Map<List<per_budget_ratio>>(request.Where(t => t.Type == 2));
var budgetData = request.FirstOrDefault(t => t.Type == 2);
ratios.ForEach(t =>
{
......
......@@ -18,6 +18,7 @@ namespace Performance.Services
{
public class CostTransferService : IAutoInjection
{
private readonly IMapper _mapper;
private readonly ILogger<CostTransferService> logger;
private readonly Application application;
private readonly PerforCosttransferRepository costtransferRepository;
......@@ -32,6 +33,7 @@ public class CostTransferService : IAutoInjection
private readonly PerforExmoduleRepository perforExmodule;
public CostTransferService(
IMapper mapper,
ILogger<CostTransferService> logger,
IOptions<Application> application,
PerforCosttransferRepository costtransferRepository,
......@@ -46,6 +48,7 @@ public class CostTransferService : IAutoInjection
PerforExmoduleRepository perforExmodule
)
{
_mapper = mapper;
this.logger = logger;
this.application = application.Value;
this.costtransferRepository = costtransferRepository;
......@@ -115,7 +118,7 @@ public List<CostTransferResponse> GetAuditList(int allotId, int menuType, int ro
foreach (var item in costTransfers)
{
var result = new CostTransferResponse();
result = Mapper.Map<CostTransferResponse>(item);
result = _mapper.Map<CostTransferResponse>(item);
result.Items = costItem?.Where(t => t.TransferId == item.Id)?.Select(t => new Option
{
Id = t.Id,
......@@ -271,8 +274,8 @@ public bool Applicat(CostTransferRequest request)
if (request.Adopted.Department == request.Applicant.Department && request.Adopted.UnitType == request.Applicant.UnitType)
throw new PerformanceException("参数错误,提交科室相同");
var item=request.Items.Where(t => string.IsNullOrEmpty(t.Source) || string.IsNullOrEmpty(t.Category));
if(item.Count()>0) throw new PerformanceException("参数错误,申请信息填写不完整");
var item = request.Items.Where(t => string.IsNullOrEmpty(t.Source) || string.IsNullOrEmpty(t.Category));
if (item.Count() > 0) throw new PerformanceException("参数错误,申请信息填写不完整");
var allot = perallotRepository.GetEntity(t => t.ID == request.AllotId);
var allotStatus = new[] { (int)AllotStates.GenerateSucceed, (int)AllotStates.Archive };
......@@ -546,7 +549,7 @@ public void IntoLastTiemData(int hospitalId, int allotId)
foreach (var item in transferLast)
{
var newTransfers = new cost_transfer();
newTransfers = Mapper.Map<cost_transfer>(item);
newTransfers = _mapper.Map<cost_transfer>(item);
newTransfers.AllotId = allotId;
newTransfers.Status = 0;
newTransfers.AdminStatus = 0;
......
......@@ -21,7 +21,7 @@
// {
// #region
// private readonly ILogger<ExtractService> logger;
// private readonly IHostingEnvironment environment;
// private readonly IWebHostEnvironment environment;
// private readonly IEmailService emailService;
// private readonly PerSheetService perSheetService;
// private readonly PerforHospitalRepository perforHospitalRepository;
......@@ -44,7 +44,7 @@
// private per_allot Allot;
// public DFExtractService(ILogger<ExtractService> logger,
// IHostingEnvironment environment,
// IWebHostEnvironment environment,
// IEmailService emailService,
// PerSheetService perSheetService,
// PerforHospitalRepository perforHospitalRepository,
......
......@@ -28,7 +28,7 @@ public class DownloadService : IAutoInjection
private readonly PerforCofaliasRepository perforCofalias;
private readonly ConfigService configService;
private readonly ComputeService _computeService;
private readonly IHostingEnvironment evn;
private readonly IWebHostEnvironment evn;
public DownloadService(ILogger<DownloadService> logger,
PerforPerallotRepository perallotRepository,
......@@ -36,7 +36,7 @@ public class DownloadService : IAutoInjection
PerforCofaliasRepository perforCofalias,
ConfigService configService,
ComputeService computeService,
IHostingEnvironment evn)
IWebHostEnvironment evn)
{
this.logger = logger;
this.perallotRepository = perallotRepository;
......@@ -194,17 +194,13 @@ public string AllComputerViewReport(int allotId, List<dynamic> dynamics, string
using (ExcelPackage package = new ExcelPackage(fs))
{
var worksheet = package.Workbook.Worksheets.Add(name);
worksheet.View.FreezePanes(2, 1);
if (dynamics != null && dynamics.Count() > 0)
{
var headers = ((IDictionary<string, object>)dynamics.ElementAt(0)).Keys;
for (int col = 0; col < headList.Count; col++)
{
worksheet.SetValue(1, col + 1, headList[col].Alias);
worksheet.Cells[1, col + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
worksheet.Cells[1, col + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[1, col + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[1, col + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
}
for (int col = 0; col < headList.Count; col++)
......@@ -216,33 +212,23 @@ public string AllComputerViewReport(int allotId, List<dynamic> dynamics, string
var value = temp[headList[col].Name];
worksheet.Cells[row + 2, col + 1].Value = value;
worksheet.Cells[row + 2, col + 1].Style.Numberformat.Format = "#,##0.00";//这是保留两位小数
worksheet.Cells[row + 2, col + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
worksheet.Cells[row + 2, col + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[row + 2, col + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[row + 2, col + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
}
if (col == 0)
{
worksheet.SetValue(dynamics.Count() + 2, col + 1, "合计");
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
}
else
{
string address = new ExcelAddress(2, col + 1, dynamics.Count() + 1, col + 1).Address;
worksheet.Cells[dynamics.Count() + 2, col + 1].Formula = string.Format("SUM({0})", address);
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Numberformat.Format = "#,##0.00";//这是保留两位小数
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[dynamics.Count() + 2, col + 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
}
worksheet.Cells[dynamics.Count() + 2, col + 1].Formula = string.Format("SUM({0})", new ExcelAddress(2, col + 1, dynamics.Count() + 1, col + 1).Address);
}
}
worksheet.View.FreezePanes(2, 1);
for (int row = worksheet.Dimension.Start.Row; row <= worksheet.Dimension.End.Row; row++)
{
for (int col = worksheet.Dimension.Start.Column; col <= worksheet.Dimension.End.Column; col++)
{
worksheet.Cells[row, col].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.00";
}
}
package.Save();
}
return filepath;
......
......@@ -14,11 +14,13 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
namespace Performance.Services
{
public class EmployeeService : IAutoInjection
{
private readonly IMapper _mapper;
private PerforImemployeeRepository perforImemployeeRepository;
private PerforPersheetRepository perforPersheetRepository;
private PerforImdataRepository perforImdataRepository;
......@@ -36,6 +38,7 @@ public class EmployeeService : IAutoInjection
private ILogger<EmployeeService> logger;
public EmployeeService(
IMapper mapper,
PerforImemployeeRepository perforImemployeeRepository,
PerforPersheetRepository perforPersheetRepository,
PerforImdataRepository perforImdataRepository,
......@@ -52,6 +55,7 @@ public class EmployeeService : IAutoInjection
PerforPerapramounthideRepository hideRepository,
ILogger<EmployeeService> logger)
{
_mapper = mapper;
this.perforImemployeeRepository = perforImemployeeRepository;
this.perforPersheetRepository = perforPersheetRepository;
this.perforImdataRepository = perforImdataRepository;
......@@ -126,7 +130,7 @@ public im_employee Insert(EmployeeRequest request)
perforPersheetRepository.Add(sheet);
}
var employee = Mapper.Map<im_employee>(request);
var employee = _mapper.Map<im_employee>(request);
employee.WorkTime = ConvertHelper.To<DateTime?>(request.WorkTime);
employee.SheetID = sheet.ID;
perforImemployeeRepository.Add(employee);
......@@ -1097,5 +1101,51 @@ public List<TitleValue> GetPerforTypeDictHide(int allotId)
return others;
}
#endregion
public ComparisonResponse GetComparison(ComparisonPagingRequest request)
{
var result = new ComparisonResponse();
if (request.ViewName == "view_check_dept")
{
result.Heads = ComparisonConfig.DeptHeads;
result.Datas = peremployeeRepository.CheckAccountingUnitRealGiveFeeDiff(request.AllotId, request.SearchQuery);
}
else if (request.ViewName == "view_check_emp")
{
result.Heads = ComparisonConfig.EmpHeads;
result.Datas = peremployeeRepository.CheckEmployeeRealGiveFeeDiff(request.AllotId, request.SearchQuery);
}
else
{
result.Datas = new Comparison { Datas = new List<view_check_emp>(), TotalCount = 0 };
}
//result.Datas = peremployeeRepository.GetComparison(request);
return result;
}
}
public class ComparisonConfig
{
public static List<Heads> DeptHeads { get; } = new List<Heads>
{
new Heads{Column="核算单元组别",Name=nameof(view_check_dept.UnitType)},
new Heads{Column="核算单元",Name=nameof(view_check_dept.AccountingUnit)},
new Heads{Column="测算表实发",Name=nameof(view_check_dept.RealGiveFeeExecl)},
new Heads{Column="软件实发",Name=nameof(view_check_dept.RealGiveFeeCompute)},
new Heads{Column="差额",Name=nameof(view_check_dept.Diff)},
};
public static List<Heads> EmpHeads { get; } = new List<Heads>
{
new Heads{Column="核算单元组别",Name=nameof(view_check_emp.UnitType)},
new Heads{Column="核算单元",Name=nameof(view_check_emp.AccountingUnit)},
new Heads{Column="人员工号",Name=nameof(view_check_emp.JobNumber)},
new Heads{Column="姓名",Name=nameof(view_check_emp.EmployeeName)},
new Heads{Column="测算表实发",Name=nameof(view_check_emp.RealGiveFeeExecl)},
new Heads{Column="软件实发",Name=nameof(view_check_emp.RealGiveFeeCompute)},
new Heads{Column="差额",Name=nameof(view_check_emp.Diff)},
};
}
}
......@@ -99,10 +99,10 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
HisData(allot, configs.FirstOrDefault(t => t.Id == item.ConfigId), item);
}
}
catch (Exception ex)
catch (Exception)
{
logger.LogError("获取数据时发生异常");
throw ex;
throw;
}
}
......@@ -134,7 +134,7 @@ private void Employee(per_allot allot, List<sys_hospitalconfig> configs, IEnumer
{
data = data.GroupJoin(hrpDepartments, outer => new { department = outer.Department }, inner => new { department = inner.HRPDepartment }, (outer, inner) => new { outer, inner }).Select(t =>
{
t.outer.AccountingUnit = t.inner?.FirstOrDefault()?.AccountingUnit;
t.outer.AccountingUnit = t.inner?.FirstOrDefault()?.AccountingUnit ?? t.outer.AccountingUnit;
return t.outer;
}).ToList();
}
......@@ -191,7 +191,8 @@ private void JudgeDataEqual(List<string> columns, List<per_employee> emps, List<
{ nameof(per_employee.BankCard), (t) => t.BankCard },
};
if (columns.Contains(nameof(per_employee.PersonnelNumber))) columns.Remove(nameof(per_employee.PersonnelNumber));
if (columns.Contains(nameof(per_employee.PersonnelNumber).ToLower())) columns.Remove(nameof(per_employee.PersonnelNumber).ToLower());
if (!columns.Contains(nameof(per_employee.AccountingUnit).ToLower())) columns.Add(nameof(per_employee.AccountingUnit).ToLower());
List<per_employee> updateData = new List<per_employee>();
foreach (var emp in emps)
......
......@@ -40,6 +40,12 @@ public class ExtractTransDto
public string SheetName { get; set; }
/// <summary>
/// ex_type >> ename
/// 根据ename中的关键字门诊、住院取对应的核算单元
/// </summary>
public string EName { get; set; }
/// <summary>
/// 核算单元(门诊医生)
/// </summary>
public string OutDoctorAccounting { get; set; }
......
......@@ -197,8 +197,17 @@ public static void WriteSheetData(ISheet sheet, PerSheetPoint point, SheetType s
{
var departments = data.Select(s => s.Department ?? "")/*.Where(w => !string.IsNullOrEmpty(w))*/.Distinct().ToList();
var filed = sheet.SheetName.Contains("住院") ? fieldInpat : fieldOut;
if (sheet.SheetName.Contains("工作量"))
var filed = new Dictionary<string, Func<ExtractTransDto, string>>();
if (sheetType == SheetType.Income)
{
if (sheet.SheetName.Contains("住院") || sheet.SheetName.Contains("门诊"))
filed = sheet.SheetName.Contains("住院") ? fieldInpat : fieldOut;
var ename = data.Where(w => w.SheetName == sheet.SheetName)?.FirstOrDefault(w => !string.IsNullOrEmpty(w.EName))?.EName;
if (ename.Contains("住院") || ename.Contains("门诊"))
filed = ename.Contains("住院") ? fieldInpatOut : fieldOutInpat;
}
else if (sheet.SheetName.Contains("工作量"))
{
filed = sheet.SheetName.Contains("医生") ? fieldDoctor : fieldNurse;
}
......@@ -255,8 +264,8 @@ public static void WriteSheetData(ISheet sheet, PerSheetPoint point, SheetType s
var deptContents = new Dictionary<int, string>
{
{ 1, item.Department },
{ 2, (sheet.SheetName.Contains("门诊")
? deptData.FirstOrDefault(t => !string.IsNullOrEmpty(t.OutNurseAccounting))?.OutNurseAccounting
{ 2, (sheet.SheetName.Contains("门诊")
? deptData.FirstOrDefault(t => !string.IsNullOrEmpty(t.OutNurseAccounting))?.OutNurseAccounting
: deptData.FirstOrDefault(t => !string.IsNullOrEmpty(t.InpatNurseAccounting))?.InpatNurseAccounting) ?? item.NurseAccount },
{ 3, (sheet.SheetName.Contains("门诊")
? deptData.FirstOrDefault(t => !string.IsNullOrEmpty(t.OutDoctorAccounting))?.OutDoctorAccounting
......@@ -316,6 +325,24 @@ public static string HasValue(params string[] list)
{ "核算单元(医技组)", (dto) => dto.OutTechnicAccounting },
};
/// <summary> 住院核算单元 </summary>
private static readonly Dictionary<string, Func<ExtractTransDto, string>> fieldInpatOut = new Dictionary<string, Func<ExtractTransDto, string>>
{
{ "科室名称", (dto) => dto.Department },
{ "核算单元(医生组)", (dto) => new string[]{ dto.InpatDoctorAccounting, dto.OutDoctorAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
{ "核算单元(护理组)", (dto) => new string[]{ dto.InpatNurseAccounting, dto.OutNurseAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
{ "核算单元(医技组)", (dto) => new string[]{ dto.InpatTechnicAccounting, dto.OutTechnicAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
};
/// <summary> 门诊核算单元 </summary>
private static readonly Dictionary<string, Func<ExtractTransDto, string>> fieldOutInpat = new Dictionary<string, Func<ExtractTransDto, string>>
{
{ "科室名称", (dto) => dto.Department },
{ "核算单元(医生组)", (dto) => new string[]{ dto.OutDoctorAccounting, dto.InpatDoctorAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
{ "核算单元(护理组)", (dto) => new string[]{ dto.OutNurseAccounting, dto.InpatNurseAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
{ "核算单元(医技组)", (dto) => new string[]{ dto.OutTechnicAccounting, dto.InpatTechnicAccounting }.FirstOrDefault(w=>!string.IsNullOrEmpty(w)) },
};
/// <summary> 医生工作量 </summary>
private static readonly Dictionary<string, Func<ExtractTransDto, string>> fieldDoctor = new Dictionary<string, Func<ExtractTransDto, string>>
{
......
......@@ -14,7 +14,7 @@ namespace Performance.Services.ExtractExcelService
public class ExtractJobService : IAutoInjection
{
private readonly ILogger logger;
private readonly IHostingEnvironment env;
private readonly IWebHostEnvironment env;
private readonly AllotService allotService;
private readonly ConfigService configService;
private readonly DictionaryService dictionaryService;
......@@ -26,7 +26,7 @@ public class ExtractJobService : IAutoInjection
public ExtractJobService(
ILogger<ExtractJobService> logger,
IHostingEnvironment env,
IWebHostEnvironment env,
AllotService allotService,
ConfigService configService,
DictionaryService dictionaryService,
......
......@@ -24,6 +24,7 @@ public class ExtractService : IAutoInjection
private readonly CustomDataWrite customDataWrite;
private readonly PerforPerallotRepository perallotRepository;
private readonly PerforCollectdataRepository collectdataRepository;
private readonly PerforExtypeRepository extypeRepository;
private readonly PerforPeremployeeRepository peremployeeRepository;
private readonly PerforPerdeptdicRepository perdeptdicRepository;
private readonly PerforCofdrugtypefactorRepository drugtypefactorRepository;
......@@ -39,6 +40,7 @@ public class ExtractService : IAutoInjection
CustomDataWrite customDataWrite,
PerforPerallotRepository perallotRepository,
PerforCollectdataRepository collectdataRepository,
PerforExtypeRepository extypeRepository,
PerforPeremployeeRepository peremployeeRepository,
PerforPerdeptdicRepository perdeptdicRepository,
PerforCofdrugtypefactorRepository drugtypefactorRepository
......@@ -54,6 +56,7 @@ PerforCofdrugtypefactorRepository drugtypefactorRepository
this.customDataWrite = customDataWrite;
this.perallotRepository = perallotRepository;
this.collectdataRepository = collectdataRepository;
this.extypeRepository = extypeRepository;
this.peremployeeRepository = peremployeeRepository;
this.perdeptdicRepository = perdeptdicRepository;
this.drugtypefactorRepository = drugtypefactorRepository;
......@@ -268,15 +271,20 @@ private List<ExtractTransDto> StandDataFormat(int hospitalId, List<ex_result> re
t.Department = string.IsNullOrEmpty(t.Department) ? "(空白)" : t.Department;
});
var types = extypeRepository.GetEntities(w => w.HospitalId == hospitalId) ?? new List<ex_type>();
var dict = personService.GetDepartments(hospitalId)?.ToList();
if (dict == null || !dict.Any())
{
return results.GroupBy(t => new { t.Department, t.Category, t.Source }).Select(t => new ExtractTransDto
{
SheetName = t.Key.Source,
Department = t.Key.Department,
Category = t.Key.Category,
Value = t.Sum(group => group.Fee) == 0 ? null : t.Sum(group => group.Fee),
EName = types.FirstOrDefault(w => w.Id == t.FirstOrDefault().TypeId)?.EName
}).ToList();
}
dict.ForEach(t =>
{
......@@ -302,6 +310,7 @@ private List<ExtractTransDto> StandDataFormat(int hospitalId, List<ex_result> re
InpatNurseAccounting = t.inner.FirstOrDefault(f => f.Department == dept)?.InpatNurseAccounting?.AccountingUnit,
InpatTechnicAccounting = t.inner.FirstOrDefault(f => f.Department == dept)?.InpatTechnicAccounting?.AccountingUnit,
SpecialAccounting = t.inner.FirstOrDefault(f => f.Department == dept)?.SpecialAccounting?.AccountingUnit ?? dept,
EName = types.FirstOrDefault(w => w.Id == t.outer.TypeId)?.EName,
};
});
......@@ -317,7 +326,8 @@ private List<ExtractTransDto> StandDataFormat(int hospitalId, List<ex_result> re
InpatDoctorAccounting = t.First().InpatDoctorAccounting,
InpatNurseAccounting = t.First().InpatNurseAccounting,
InpatTechnicAccounting = t.First().InpatTechnicAccounting,
SpecialAccounting = t.First().SpecialAccounting
SpecialAccounting = t.First().SpecialAccounting,
EName = t.FirstOrDefault(w => !string.IsNullOrEmpty(w.EName)).EName
});
return groupdata.ToList();
......
......@@ -110,10 +110,10 @@ public List<ex_result> Handler(int hospitalId, per_allot allot, string groupName
}
return data;
}
catch (Exception ex)
catch (Exception)
{
logger.LogError("获取数据时发生异常");
throw ex;
throw;
}
}
......@@ -198,13 +198,20 @@ private List<ex_result> ExtractModuleData(per_allot allot, string groupName, boo
foreach (var script in scripts.Where(t => t.TypeId == typeId))
{
var config = configs.FirstOrDefault(t => t.Id == script.ConfigId) ?? configs.FirstOrDefault(t => t.DataBaseType == script.DatabaseType);
var config = configs.FirstOrDefault(t => t.Id == script.ConfigId);
if (config == null) continue;
try
{
if(!pools.ContainsKey(config.Id))
pools.Add(config.Id, ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword));
try
{
if (!pools.ContainsKey(config.Id))
pools.Add(config.Id, ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword));
}
catch
{
logService.ReturnTheLog(allot.ID, groupName, 2, "数据库连接", $"数据库“{config.DbName}”连接失败", 3, isSingle);
}
IDbConnection connection = pools[config.Id];
......@@ -223,12 +230,13 @@ private List<ex_result> ExtractModuleData(per_allot allot, string groupName, boo
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = f.ModuleName,
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.AddRange(result.ToArray());
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
}
......@@ -237,8 +245,7 @@ private List<ex_result> ExtractModuleData(per_allot allot, string groupName, boo
}
catch (Exception ex)
{
logger.LogError($"数据库“{config.DbName}”连接失败: {ex}; {Infrastructure.JsonHelper.Serialize(script)}");
logService.ReturnTheLog(allot.ID, groupName, 2, "数据库连接", $"数据库“{config.DbName}”连接失败", 3, isSingle);
logger.LogError($"typeId: {typeId}提取数据异常{ex}{Infrastructure.JsonHelper.Serialize(script)}");
}
}
}
......@@ -294,12 +301,13 @@ private List<ex_result> ExtractItemData(per_allot allot, string groupName, bool
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = modulename,
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.AddRange(result.ToArray());
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
}
......@@ -356,12 +364,13 @@ private List<ex_result> ExtractSpecialData(per_allot allot, string groupName, bo
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = "4.2 特殊核算单元绩效测算表",
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.AddRange(result.ToArray());
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
}
......
......@@ -27,7 +27,7 @@
// public class ExtractService : IAutoInjection
// {
// private readonly ILogger<ExtractService> logger;
// private readonly IHostingEnvironment environment;
// private readonly IWebHostEnvironment environment;
// private readonly IEmailService emailService;
// private readonly PerSheetService perSheetService;
// private readonly PerHeaderService perHeaderService;
......@@ -43,7 +43,7 @@
// private readonly PerforHospitalconfigRepository perforHospitalconfigRepository;
// public ExtractService(ILogger<ExtractService> logger,
// IHostingEnvironment environment,
// IWebHostEnvironment environment,
// IEmailService emailService,
// PerSheetService perSheetService,
// PerHeaderService perHeaderService,
......@@ -540,12 +540,12 @@
// ModuleName = EnumHelper.GetDescription((SheetType)sheet.SheetType),
// };
// var perHeadList = perforImheaderRepository.GetEntities(t => t.SheetID == sheet.ID);
// perSheet.PerHeader = AutoMapper.Mapper.Map<List<PerHeader>>(perHeadList);
// perSheet.PerHeader = AutoMapper._mapper.Map<List<PerHeader>>(perHeadList);
// if (SheetType.Employee == (SheetType)sheet.SheetType)
// {
// perSheet.PerHeader = GetHeader((SheetType)sheet.SheetType);
// var employeeList = perforImemployeeRepository.GetEntities(t => t.AllotID == sheet.AllotID);
// var perEmployeeList = AutoMapper.Mapper.Map<List<PerDataEmployee>>(employeeList);
// var perEmployeeList = AutoMapper._mapper.Map<List<PerDataEmployee>>(employeeList);
// perSheet.PerData = perEmployeeList?.ConvertAll(new Converter<PerDataEmployee, IPerData>(m => m));
// }
// else if (SheetType.SpecialUnit == (SheetType)sheet.SheetType)
......@@ -556,7 +556,7 @@
// {
// perSheet.PerHeader = GetHeader((SheetType)sheet.SheetType);
// var basicList = perforImaccountbasicRepository.GetEntities(t => t.AllotID == sheet.AllotID);
// var perBasicList = AutoMapper.Mapper.Map<List<PerDataAccountBaisc>>(basicList);
// var perBasicList = AutoMapper._mapper.Map<List<PerDataAccountBaisc>>(basicList);
// perSheet.PerData = perBasicList?.ConvertAll(new Converter<PerDataAccountBaisc, IPerData>(m => m));
// }
// sheetList.Add(perSheet);
......
using Microsoft.Extensions.Logging;
using AutoMapper;
using Microsoft.Extensions.Logging;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
......@@ -16,6 +17,7 @@ namespace Performance.Services
{
public class HistoryService : IAutoInjection
{
private readonly IMapper _mapper;
private readonly ILogger<EmployeeService> logger;
private readonly PerforReportoriginalsurgeryRepository reportoriginalsurgeryRepository;
private readonly PerforReportoriginalstaysRepository reportoriginalstaysRepository;
......@@ -23,12 +25,14 @@ public class HistoryService : IAutoInjection
private readonly PerforPerdeptdicRepository perdeptdicRepository;
public HistoryService(
IMapper mapper,
ILogger<EmployeeService> logger,
PerforReportoriginalsurgeryRepository reportoriginalsurgeryRepository,
PerforReportoriginalstaysRepository reportoriginalstaysRepository,
PerforReportoriginalpersontimeRepository reportoriginalpersontimeRepository,
PerforPerdeptdicRepository perdeptdicRepository)
{
_mapper = mapper;
this.logger = logger;
this.reportoriginalsurgeryRepository = reportoriginalsurgeryRepository;
this.reportoriginalstaysRepository = reportoriginalstaysRepository;
......@@ -48,7 +52,7 @@ public void ImportHistoryData(int hospitalid, string path)
var months = @data1.Select(s => s.Month).Distinct().ToList();
reportoriginalpersontimeRepository.RemoveRange(w => w.HospitalID == hospitalid && years.Contains(w.Year) && months.Contains(w.Month));
var @data = AutoMapper.Mapper.Map<List<report_original_persontime>>(@data1);
var @data = _mapper.Map<List<report_original_persontime>>(@data1);
reportoriginalpersontimeRepository.AddRange(@data.ToArray());
}
var @data2 = entities.Where(w => w.SheetName == "手术量");
......@@ -58,7 +62,7 @@ public void ImportHistoryData(int hospitalid, string path)
var months = @data2.Select(s => s.Month).Distinct().ToList();
reportoriginalsurgeryRepository.RemoveRange(w => w.HospitalID == hospitalid && years.Contains(w.Year) && months.Contains(w.Month));
var @data = AutoMapper.Mapper.Map<List<report_original_surgery>>(@data2);
var @data = _mapper.Map<List<report_original_surgery>>(@data2);
reportoriginalsurgeryRepository.AddRange(@data.ToArray());
}
var @data3 = entities.Where(w => w.SheetName == "住院天数");
......@@ -68,7 +72,7 @@ public void ImportHistoryData(int hospitalid, string path)
var months = @data3.Select(s => s.Month).Distinct().ToList();
reportoriginalstaysRepository.RemoveRange(w => w.HospitalID == hospitalid && years.Contains(w.Year) && months.Contains(w.Month));
var @data = AutoMapper.Mapper.Map<List<report_original_stays>>(@data3);
var @data = _mapper.Map<List<report_original_stays>>(@data3);
reportoriginalstaysRepository.AddRange(@data.ToArray());
}
}
......
......@@ -11,17 +11,21 @@ namespace Performance.Services
{
public class HospitalService : IAutoInjection
{
private readonly IMapper _mapper;
private PerforHospitalRepository _hospitalRepository;
private PerforUserhospitalRepository _joinRepository;
private PerforHospitalconfigRepository _hospitalconfigRepository;
private PerforPerfirstRepository _perfirstRepository;
private PerforPerallotRepository _perallotRepository;
public HospitalService(PerforHospitalRepository hospitalRepository,
public HospitalService(
IMapper mapper,
PerforHospitalRepository hospitalRepository,
PerforUserhospitalRepository joinRepository,
PerforHospitalconfigRepository hospitalconfigRepository,
PerforPerfirstRepository perfirstRepository,
PerforPerallotRepository perallotRepository)
{
_mapper = mapper;
this._hospitalRepository = hospitalRepository;
this._joinRepository = joinRepository;
this._hospitalconfigRepository = hospitalconfigRepository;
......@@ -50,7 +54,7 @@ public List<HospitalResponse> GetUserHopital(int userid)
//获取已经上传过模板的hospital
var firstId = _perfirstRepository.GetEntities(t => hosId.Contains(t.HospitalId.Value))?.Select(t => t.HospitalId.Value).ToList();
var list = Mapper.Map<List<sys_hospital>, List<HospitalResponse>>(hosList);
var list = _mapper.Map<List<sys_hospital>, List<HospitalResponse>>(hosList);
list.ForEach(t =>
{
if (hosId != null && hosId.Contains(t.HosID))
......@@ -103,7 +107,7 @@ public HospitalResponse Insert(HospitalRequest request, int userid)
{
if (null != _hospitalRepository.GetEntity(t => t.HosName == request.HosName))
throw new PerformanceException("医院名称重复");
var hospital = Mapper.Map<sys_hospital>(request);
var hospital = _mapper.Map<sys_hospital>(request);
hospital.CreateDate = DateTime.Now;
hospital.CreateUser = userid;
hospital.States = (int)States.Enabled;
......@@ -111,7 +115,7 @@ public HospitalResponse Insert(HospitalRequest request, int userid)
if (!_hospitalRepository.Add(hospital))
throw new PerformanceException("保存失败");
return Mapper.Map<HospitalResponse>(hospital);
return _mapper.Map<HospitalResponse>(hospital);
}
/// <summary>
......@@ -141,7 +145,7 @@ public HospitalResponse Update(HospitalRequest request)
if (!_hospitalRepository.Update(hospital))
throw new PerformanceException("保存失败");
return Mapper.Map<HospitalResponse>(hospital);
return _mapper.Map<HospitalResponse>(hospital);
}
/// <summary>
......
......@@ -3,75 +3,74 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Services
{
public class HubGroupInfo
{
public DateTime AddTime { get; set; }
public string ConnectionId { get; set; }
}
public class AllotLogHub : Hub
{
private readonly ILogger<AllotLogHub> logger;
private readonly IMemoryCache cache;
private static ConcurrentDictionary<int, List<ConnectionUser>> _pairs
= new ConcurrentDictionary<int, List<ConnectionUser>>();
public AllotLogHub(
ILogger<AllotLogHub> logger,
IMemoryCache cache)
public AllotLogHub(ILogger<AllotLogHub> logger)
{
this.logger = logger;
this.cache = cache;
}
public override Task OnConnectedAsync()
{
logger.LogDebug($"日志推送 连接{Context.ConnectionId}");
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
var connectionId = Context.ConnectionId;
logger.LogDebug($"日志推送 断开连接{connectionId}");
var userId = Context.User?.Claims.FirstOrDefault(w => w.Type == "id").Value ?? "";
string key = $"AllotLogGroup_{connectionId}";
//1 查询用户分组信息
var groupName = "";
//2 删除数据库中用户分组数据
if (cache.TryGetValue(key, out string value))
if (!string.IsNullOrEmpty(userId))
{
cache.Remove(key);
foreach (var item in _pairs)
{
var conn = item.Value.FirstOrDefault(w => w.ConnectionId == connectionId);
if (conn != null)
{
Groups.RemoveFromGroupAsync(connectionId, item.Key.ToString()).Wait();
logger.LogDebug($"日志推送 断开连接{connectionId}-{item.Key}-{userId}");
}
}
}
logger.LogDebug($"日志推送 断开连接{connectionId}-{groupName}");
//3 分组中删除用户
Groups.RemoveFromGroupAsync(connectionId, groupName);
return base.OnDisconnectedAsync(exception);
}
public async Task AddGroup(string token, string groupName)
public async Task AddGroup(string token, int groupName)
{
var connectionId = Context.ConnectionId;
string key = $"AllotLogGroup_{connectionId}";
if (cache.TryGetValue(key, out string value))
var userId = Context.User?.Claims.FirstOrDefault(w => w.Type == "id").Value ?? "";
if (!string.IsNullOrEmpty(userId))
{
cache.Remove(key);
if (_pairs.ContainsKey(groupName))
_pairs[groupName].Add(new ConnectionUser { ConnectionId = connectionId, UserId = userId });
else
_pairs[groupName] = new List<ConnectionUser> { new ConnectionUser { ConnectionId = connectionId, UserId = userId } };
await Groups.AddToGroupAsync(connectionId, groupName.ToString());
}
cache.Set(key, groupName, new TimeSpan(1, 0, 0));
logger.LogDebug($"日志推送 添加用户组{connectionId}-{groupName}");
logger.LogDebug($"日志推送 添加用户组{connectionId}-{groupName}-{userId}");
//2 将用户插入分组
await Groups.AddToGroupAsync(connectionId, groupName);
}
public async Task SendMessage(string groupName, string message)
class ConnectionUser
{
await Clients.Group(groupName).SendAsync("ReceiveMessage", "测试", message);
public string ConnectionId { get; set; }
public string UserId { get; set; }
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment