Commit ab9c8f84 by ruyun.zhang@suvalue.com

Merge branch 'release/柳铁12.21.1'

parents 2b87bee5 f4e5cafe
......@@ -736,6 +736,92 @@ public ApiResponse GetDeptComparison([FromBody] ComparisonPagingRequest request)
return new ApiResponse(ResponseType.OK, relust);
}
#region 手工录入
/// <summary>
/// 手工录入 - 下拉列表
/// </summary>
/// <param name="allotId"></param>
/// <returns></returns>
[Route("getgatherdrop/{allotId}")]
[HttpPost]
public ApiResponse GetGatherDrop([FromRoute] int allotId)
{
if (allotId <= 0)
return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
var relust = employeeService.GetGatherDrop(allotId);
return new ApiResponse(ResponseType.OK, relust);
}
/// <summary>
/// 手工录入 - 录入界面
/// </summary>
/// <param name="allotId"></param>
/// <param name="request"></param>
/// <returns></returns>
[Route("getgatherhands/{allotId}")]
[HttpPost]
public ApiResponse GetGatherHands([FromRoute] int allotId, [FromBody] GatherRequest request)
{
if (allotId <= 0)
return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
var relust = employeeService.GetGatherHands(allotId, request);
return new ApiResponse(ResponseType.OK, relust);
}
/// <summary>
/// 保存手工录入
/// </summary>
/// <param name="allotId"></param>
/// <param name="request"></param>
/// <returns></returns>
[Route("savegatherhands/{allotId}")]
[HttpPost]
public ApiResponse SaveGatherHands(int allotId, [FromBody] SaveGatherData request)
{
if (allotId <= 0)
return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
if (string.IsNullOrEmpty(request.Source) || string.IsNullOrEmpty(request.Category))
return new ApiResponse(ResponseType.OK);
employeeService.SaveGatherHands(allotId, request);
return new ApiResponse(ResponseType.OK);
}
/// <summary>
/// 手工录入列表 - 明细
/// </summary>
/// <param name="allotId"></param>
/// <param name="request"></param>
/// <returns></returns>
[Route("getgather/{allotId}")]
[HttpPost]
public ApiResponse GetGather([FromRoute] int allotId, [FromBody] PersonParamsRequest request)
{
if (allotId <= 0)
return new ApiResponse(ResponseType.Fail, "参数错误", "allotid无效");
var result = employeeService.GetGather(allotId, request);
return new ApiResponse(ResponseType.OK, result);
}
/// <summary>
/// 手工录入列表 - 汇总
/// </summary>
/// <param name="allotId"></param>
/// <param name="request"></param>
/// <returns></returns>
[Route("getgathertotal/{allotId}")]
[HttpPost]
public ApiResponse GetGatherTotal([FromRoute] int allotId, [FromBody] PersonParamsRequest request)
{
return new ApiResponse(ResponseType.OK);
}
#endregion
}
}
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Performance.DtoModels;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
......@@ -16,19 +19,25 @@ namespace Performance.Api.Controllers
public class ReportController : Controller
{
private AllotService allotService;
private ComputeService _computeService;
private ReportService reportService;
private ReportDataService reportDataService;
private ClaimService claimService;
private readonly DownloadService downloadService;
public ReportController(
ClaimService claimService,
AllotService allotService,
ReportService reportService,
ReportDataService reportDataService)
ReportDataService reportDataService,
ComputeService computeService,
DownloadService downloadService)
{
this.allotService = allotService;
this.reportService = reportService;
this.reportDataService = reportDataService;
this.claimService = claimService;
this._computeService = computeService;
this.downloadService = downloadService;
}
[Route("rank")]
......@@ -265,5 +274,216 @@ public ApiResponse TableSpecial([FromBody] ConditionRequest request)
var list = reportService.TableSpecial(request);
return new ApiResponse(ResponseType.OK, "", list);
}
#region 发放表视图、下载
/// <summary>
/// 全院绩效发放(视图)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("getAllComputeView")]
[HttpPost]
public ApiResponse GetAllComputeView([FromBody] BeginEndTime request)
{
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var datas = _computeService.GetAllComputeViewByDate("view_allot_sign_emp", bdate, edate.AddMonths(1));
if (null == datas)
throw new PerformanceException("当前绩效记录不存在");
var list = new QueryComputeByDateGetPage
{
Data = datas.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize).ToList(),
TotalData = _computeService.SumDatas(datas),
TotalCount = datas.Count(),
TotalPages = (int)Math.Ceiling((double)datas.Count() / request.PageSize),
CurrentPage = request.CurrentPage,
PageSize = request.PageSize
};
return new ApiResponse(ResponseType.OK, "ok", list);
}
/// <summary>
/// 全院绩效发放(视图)下载
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("getAllComputeViewDown/download")]
[HttpPost]
public IActionResult AllComputeViewDownload([FromBody] BeginEndTimeDown request)
{
if (request.HospitalId == 0)
throw new PerformanceException("医院ID不能为空");
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var list = _computeService.GetAllComputeViewByDate("view_allot_sign_emp", bdate, edate.AddMonths(1));
if (null == list)
throw new PerformanceException("当前绩效记录不存在");
var filepath = downloadService.AllComputerViewReportByDate(request.HospitalId, list, "/report/wholehospital_grant", "全院绩效发放", bdate, edate.AddMonths(1));
var memoryStream = new MemoryStream();
using (var stream = new FileStream(filepath, FileMode.Open))
{
stream.CopyToAsync(memoryStream).Wait();
}
memoryStream.Seek(0, SeekOrigin.Begin);
var provider = new FileExtensionContentTypeProvider();
FileInfo fileInfo = new FileInfo(filepath);
var memi = provider.Mappings[".xlsx"];
return File(memoryStream, memi, Path.GetFileName(fileInfo.Name));
}
/// <summary>
/// 全院核算绩效发放(视图)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("gethosdataView")]
[HttpPost]
public ApiResponse GethosdataView([FromBody] BeginEndTime request)
{
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var datas = _computeService.GetAllComputeViewByDate("view_allot_sign_dept", bdate, edate.AddMonths(1));
if (null == datas)
throw new PerformanceException("当前绩效记录不存在");
var list = new QueryComputeByDateGetPage
{
Data = datas.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize).ToList(),
TotalData = _computeService.SumDatas(datas),
TotalCount = datas.Count(),
TotalPages = (int)Math.Ceiling((double)datas.Count() / request.PageSize),
CurrentPage = request.CurrentPage,
PageSize = request.PageSize
};
return new ApiResponse(ResponseType.OK, "ok", list);
}
/// <summary>
/// 全院核算绩效发放(视图) 下载
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("gethosdataView/download")]
[HttpPost]
public IActionResult GethosdataView([FromBody] BeginEndTimeDown request)
{
if (request.HospitalId == 0)
throw new PerformanceException("医院ID不能为空");
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var list = _computeService.GetAllComputeViewByDate("view_allot_sign_dept", bdate, edate.AddMonths(1));
if (null == list)
throw new PerformanceException("当前绩效记录不存在");
var filepath = downloadService.AllComputerViewReportByDate(request.HospitalId, list, "/report/wholehospital_accounting_grant", "全院核算绩效发放", bdate, edate.AddMonths(1));
var memoryStream = new MemoryStream();
using (var stream = new FileStream(filepath, FileMode.Open))
{
stream.CopyToAsync(memoryStream).Wait();
}
memoryStream.Seek(0, SeekOrigin.Begin);
var provider = new FileExtensionContentTypeProvider();
FileInfo fileInfo = new FileInfo(filepath);
var memi = provider.Mappings[".xlsx"];
return File(memoryStream, memi, Path.GetFileName(fileInfo.Name));
}
/// <summary>
/// 获取财务全院绩效列表(视图)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("allcomputeView/personnel")]
[HttpPost]
public ApiResponse AllComputeViewByPM([FromBody] BeginEndTime request)
{
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var datas = _computeService.GetAllComputeViewByDate("view_allot_sign_emp_finance", bdate, edate.AddMonths(1));
if (null == datas)
throw new PerformanceException("当前绩效记录不存在");
var list = new QueryComputeByDateGetPage
{
Data = datas.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize).ToList(),
TotalData = _computeService.SumDatas(datas),
TotalCount = datas.Count(),
TotalPages = (int)Math.Ceiling((double)datas.Count() / request.PageSize),
CurrentPage = request.CurrentPage,
PageSize = request.PageSize
};
return new ApiResponse(ResponseType.OK, "ok", list);
}
/// <summary>
/// 获取财务全院绩效列表(视图)下载
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[Route("allcomputeView/personnel/download")]
[HttpPost]
public IActionResult AllComputeByPMViewDownLoad([FromBody] BeginEndTimeDown request)
{
if (request.HospitalId == 0)
throw new PerformanceException("医院ID不能为空");
DateTime bdate = DateTime.Now;
DateTime edate = DateTime.Now;
if (string.IsNullOrEmpty(request.BeginTime) || !DateTime.TryParse(request.BeginTime, out bdate) ||
string.IsNullOrEmpty(request.EndTime) || !DateTime.TryParse(request.EndTime, out edate))
throw new PerformanceException("请输入正确的时间");
var list = _computeService.GetAllComputeViewByDate("view_allot_sign_emp_finance", bdate, edate.AddMonths(1));
if (null == list)
throw new PerformanceException("当前绩效记录不存在");
var filepath = downloadService.AllComputerViewReportByDate(request.HospitalId, list, "/report/wholehospital_finance_grant", "财务全院绩效发放", bdate, edate.AddMonths(1));
var memoryStream = new MemoryStream();
using (var stream = new FileStream(filepath, FileMode.Open))
{
stream.CopyToAsync(memoryStream).Wait();
}
memoryStream.Seek(0, SeekOrigin.Begin);
var provider = new FileExtensionContentTypeProvider();
FileInfo fileInfo = new FileInfo(filepath);
var memi = provider.Mappings[".xlsx"];
return File(memoryStream, memi, Path.GetFileName(fileInfo.Name));
}
#endregion
}
}
\ No newline at end of file
......@@ -13,6 +13,7 @@
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using Performance.Services.Queues;
using System;
using System.Collections.Generic;
using System.IO;
......@@ -37,6 +38,7 @@ public class TemplateController : Controller
private readonly AllotService allotService;
private readonly LogManageService logService;
private readonly IServiceScopeFactory serviceScopeFactory;
private readonly ExtractService extractService;
public TemplateController(
ILogger<ExceptionsFilter> logger,
......@@ -50,7 +52,8 @@ public class TemplateController : Controller
HospitalService hospitalService,
AllotService allotService,
LogManageService logService,
IServiceScopeFactory serviceScopeFactory)
IServiceScopeFactory serviceScopeFactory,
ExtractService extractService)
{
this.logger = logger;
this.env = env;
......@@ -64,6 +67,7 @@ public class TemplateController : Controller
this.allotService = allotService;
this.logService = logService;
this.serviceScopeFactory = serviceScopeFactory;
this.extractService = extractService;
}
/// <summary>
......@@ -226,22 +230,23 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest
allot.IsExtracting = 1;
allot.ExtractTime = DateTime.Now;
allotService.Update(allot);
string email = claim.GetUserClaim(JwtClaimTypes.Mail);
// string email = claim.GetUserClaim(JwtClaimTypes.Mail);
string email = "";
if (isSingle)
{
logger.LogInformation("同一项目中进行提取");
Task.Run(() =>
{
Thread.Sleep(1000);
using (var scope = serviceScopeFactory.CreateScope())
{
var scopedServices = scope.ServiceProvider.GetRequiredService<ExtractService>();
logger.LogInformation("提取绩效数据参数:" + JsonHelper.Serialize(new { allotId = allot.ID, hospitalId = allot.HospitalId, userId = claim.GetUserId() }));
string extractFilePath = scopedServices.Main(allot.ID, allot.HospitalId, email, "User" + claim.GetUserId(), filePath, isSingle);
logger.LogInformation("提取绩效数据参数:" + JsonHelper.Serialize(new { allotId = allot.ID, hospitalId = allot.HospitalId }));
string extractFilePath = scopedServices.Main(allot.ID, allot.HospitalId, email, allot.ID.ToString(), filePath, isSingle);
}
});
Thread.Sleep(1000);
}
else
{
......@@ -252,8 +257,7 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest
{
AllotId = request.AllotId,
HospitalId = request.HospitalId,
Email = email,
UserId = claim.GetUserId()
Email = email
};
string json = JsonHelper.Serialize(obj);
......@@ -284,6 +288,12 @@ public ApiResponse NewExtractData([CustomizeValidator, FromBody] ExtractRequest
// B 使用配置作为模板
}
[HttpPost("extract/allot/file")]
public ApiResponse ExtractAllotFile(ExtractRequest request)
{
extractService.Main(request.AllotId, request.HospitalId, request.Email, request.AllotId.ToString(), "", true);
return new ApiResponse(ResponseType.OK);
}
/// <summary>
/// 提取日志
......
......@@ -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_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;",
"PerformanceConnectionString": "server=192.168.18.166;database=db_performance_screen;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"
},
......
......@@ -1190,6 +1190,37 @@
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.EmployeeController.GetGatherDrop(System.Int32)">
<summary>
手工录入 - 下拉列表
</summary>
<param name="allotId"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.EmployeeController.GetGatherHands(System.Int32,Performance.DtoModels.GatherRequest)">
<summary>
手工录入
</summary>
<param name="allotId"></param>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.EmployeeController.SaveGatherHands(System.Int32,Performance.DtoModels.SaveGatherData)">
<summary>
保存手工录入
</summary>
<param name="allotId"></param>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.EmployeeController.GetGather(System.Int32,Performance.DtoModels.PersonParamsRequest)">
<summary>
手工录入列表
</summary>
<param name="allotId"></param>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ExConfigController.Extract(Performance.DtoModels.ModModuleRequest)">
<summary>
绩效数据抽取模板
......@@ -1610,6 +1641,48 @@
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.GetAllComputeView(Performance.DtoModels.BeginEndTime)">
<summary>
全院绩效发放(视图)
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.AllComputeViewDownload(Performance.DtoModels.BeginEndTimeDown)">
<summary>
全院绩效发放(视图)下载
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.GethosdataView(Performance.DtoModels.BeginEndTime)">
<summary>
全院核算绩效发放(视图)
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.GethosdataView(Performance.DtoModels.BeginEndTimeDown)">
<summary>
全院核算绩效发放(视图) 下载
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.AllComputeViewByPM(Performance.DtoModels.BeginEndTime)">
<summary>
获取财务全院绩效列表(视图)
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportController.AllComputeByPMViewDownLoad(Performance.DtoModels.BeginEndTimeDown)">
<summary>
获取财务全院绩效列表(视图)下载
</summary>
<param name="request"></param>
<returns></returns>
</member>
<member name="M:Performance.Api.Controllers.ReportGlobalController.GetAllReportGlobal(System.Int32)">
<summary>
获取报表配置信息
......
......@@ -157,6 +157,9 @@
<member name="P:Performance.EntityModels.PerformanceDbContext.ex_type">
<summary> </summary>
</member>
<member name="P:Performance.EntityModels.PerformanceDbContext.ex_result_gather">
<summary> </summary>
</member>
<member name="P:Performance.EntityModels.PerformanceDbContext.his_data">
<summary> </summary>
</member>
......@@ -3571,6 +3574,51 @@
1 删除 0 未删除
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.Id">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.AllotId">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.Department">
<summary>
科室
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.DoctorName">
<summary>
医生姓名
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.PersonnelNumber">
<summary>
人员工号
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.Category">
<summary>
费用类型
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.Fee">
<summary>
费用
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.Source">
<summary>
来源
</summary>
</member>
<member name="P:Performance.EntityModels.ex_result_gather.CreateTime">
<summary>
创建时间
</summary>
</member>
<member name="T:Performance.EntityModels.ex_script">
<summary>
......
......@@ -250,6 +250,9 @@ public AutoMapperConfigs()
CreateMap<ag_secondallot, IssuedPromptResponse>()
.ReverseMap();
CreateMap<ex_result, ex_result_gather>()
.ReverseMap();
}
}
}
......@@ -89,4 +89,18 @@ public class PerSheetHeader
//("调节系数", (t) => Math.Round(t.Adjust.Value * 100, 2), 1, 1, false, true, true, "Adjust"),
};
}
public class ColumnHeadsConfig
{
public static List<Heads> GatherHeads { get; } = new List<Heads>
{
new Heads{Column="科室",Name=nameof(ex_result_gather.Department)},
new Heads{Column="医生姓名",Name=nameof(ex_result_gather.DoctorName)},
new Heads{Column="人员工号",Name=nameof(ex_result_gather.PersonnelNumber)},
new Heads{Column="费用类型",Name=nameof(ex_result_gather.Category)},
new Heads{Column="费用",Name=nameof(ex_result_gather.Fee)},
new Heads{Column="来源",Name=nameof(ex_result_gather.Source)}
};
}
}
......@@ -52,4 +52,28 @@ public class ComputerAliasRequest
public string Route { get; set; }
}
public class BeginEndTime
{
public string BeginTime { get; set; } // 2021-01
public string EndTime { get; set; } // 2021-08
public int CurrentPage { get; set; }
public int PageSize { get; set; }
}
public class BeginEndTimeDown
{
public string BeginTime { get; set; } // 2021-01
public string EndTime { get; set; } // 2021-08
public int HospitalId { get; set; }
}
public class QueryComputeByDateGetPage
{
public List<dynamic> Data { get; set; }
public Dictionary<string, decimal> TotalData { get; set; }
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
}
}
using Performance.EntityModels;
using System;
using Performance.Infrastructure.Models;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
......@@ -17,7 +16,7 @@ public class Heads
public string Name { get; set; }
}
public class Comparison
public class Comparison
{
public List<view_check_emp> Datas { get; set; }
public int TotalCount { get; set; }
......
using Performance.EntityModels;
using Performance.Infrastructure.Models;
using System.Collections.Generic;
namespace Performance.DtoModels
{
public class GatherResponse
{
public List<Heads> Heads { get; set; }
public PageList<ex_result_gather> Datas { get; set; }
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
}
public class GatherDropResponse
{
public string Label { get; set; }
public string Value { get; set; }
public List<GatherDropResponse> Children { get; set; }
}
public class GatherRequest
{
public string Source { get; set; }
public string Category { get; set; }
}
}
......@@ -29,4 +29,12 @@ public class SaveCustomData
public string[] ColHeaders { get; set; }
public string[][] Data { get; set; }
}
public class SaveGatherData
{
public string Source { get; set; }
public string Category { get; set; }
public string[] ColHeaders { get; set; }
public new string[][] Data { get; set; }
}
}
......@@ -116,6 +116,8 @@ public PerformanceDbContext(DbContextOptions<PerformanceDbContext> options)
/// <summary> </summary>
public virtual DbSet<ex_type> ex_type { get; set; }
/// <summary> </summary>
public virtual DbSet<ex_result_gather> ex_result_gather { get; set; }
/// <summary> </summary>
public virtual DbSet<his_data> his_data { get; set; }
/// <summary> </summary>
public virtual DbSet<his_import_account> his_import_account { get; set; }
......
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class ex_result_gather
{
/// <summary>
///
/// </summary>
public int Id { get; set; }
/// <summary>
///
/// </summary>
public int AllotId { get; set; }
/// <summary>
/// 科室
/// </summary>
public string Department { get; set; }
/// <summary>
/// 医生姓名
/// </summary>
public string DoctorName { get; set; }
/// <summary>
/// 人员工号
/// </summary>
public string PersonnelNumber { get; set; }
/// <summary>
/// 费用类型
/// </summary>
public string Category { get; set; }
/// <summary>
/// 费用
/// </summary>
public decimal Fee { get; set; }
/// <summary>
/// 来源
/// </summary>
public string Source { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 1 未通过 2 通过
/// </summary>
public int States { get; set; }
}
}
using Microsoft.Data.SqlClient;
using MySql.Data.MySqlClient;
using MySql.Data.MySqlClient;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Data.SqlClient;
namespace Performance.Repository
{
......
......@@ -10,6 +10,7 @@
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
......@@ -29,6 +30,13 @@ public new PageList<per_employee> GetEntitiesForPaging(int pageNumber, int pageS
}
public PageList<ex_result_gather> GetGatherForPaging(int pageNumber, int pageSize, Expression<Func<ex_result_gather, bool>> exp)
{
IQueryable<ex_result_gather> queryableAuthors = context.Set<ex_result_gather>().Where(exp).OrderBy(w => w.Department).ThenBy(t => t.PersonnelNumber);
return PageList<ex_result_gather>.Create(queryableAuthors, pageNumber, pageSize);
}
//public Comparison GetComparison(ComparisonPagingRequest request)
//{
// var search = "";
......@@ -117,7 +125,10 @@ public Comparison CheckAccountingUnitRealGiveFeeDiff(int allotId, string searchQ
TotalCount = DapperQuery<int>(queryCount, new { allotId, searchQuery, parm = $"%{searchQuery}%" })?.FirstOrDefault() ?? 0,
};
}
}
public IDbConnection GetDbConnection()
{
return context.Database.GetDbConnection();
}
}
}
using Microsoft.EntityFrameworkCore;
using Performance.DtoModels;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Linq;
......@@ -396,6 +397,14 @@ public List<dynamic> QueryCompute(int allotId, string viewName)
return DapperQuery<dynamic>(sql, new { allotId })?.ToList();
}
public List<dynamic> QueryComputeByDate(string viewName, DateTime beginTime, DateTime endTime)
{
var sql = $@"SELECT * FROM {viewName}
where STR_TO_DATE(concat(Year,'-',Month,'-01'),'%Y-%m-%d') >= @beginTime
and STR_TO_DATE(concat(Year,'-',Month,'-01'),'%Y-%m-%d') < @endTime";
return DapperQuery<dynamic>(sql, new { beginTime = beginTime.ToString("yyyy-MM-dd"), endTime = endTime.ToString("yyyy-MM-dd") }).ToList();
}
public CustonPagingData QueryCustom(CustomPagingRequest request, bool IsHead)
{
......@@ -412,7 +421,7 @@ public CustonPagingData QueryCustom(CustomPagingRequest request, bool IsHead)
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} ";
......@@ -426,7 +435,7 @@ public bool QueryIsAllotId(string tableName)
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;
var isExist = result?.Count() == 3;
return isExist;
......
......@@ -5,8 +5,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="4.0.0" />
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="3.21.4" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
</ItemGroup>
......
using Performance.EntityModels;
namespace Performance.Repository
{
public partial class PerforExresultgatherRepository : PerforRepository<ex_result_gather>
{
public PerforExresultgatherRepository(PerformanceDbContext context) : base(context)
{
}
}
}
......@@ -673,7 +673,7 @@ public List<IssuedPromptResponse> IssuedPrompt(per_allot allot, AllotRequest req
{
var second = secondList?.FirstOrDefault(f => f.UnitType == item.UnitType && f.Department == item.Department);
var isDiffer = (item.RealGiveFee ?? 0) > 0 && (item.PreRealGiveFee ?? 0) > 0 && ((item.RealGiveFee ?? 0) != (item.PreRealGiveFee ?? 0));
var isDiffer = (item.RealGiveFee ?? 0) != (item.PreRealGiveFee ?? 0);
if ((item.RealGiveFee ?? 0) == 0 && (item.PreRealGiveFee ?? 0) > 0)
{
......@@ -729,7 +729,15 @@ public List<IssuedPromptResponse> IssuedPrompt(per_allot allot, AllotRequest req
{
var updSecondQuery = promptSeconds.Where(t => t.IssueStatus != 1);
var updSeconds = secondList.Where(w => updSecondQuery.Select(t => t.Id).Contains(w.Id)) ?? new List<ag_secondallot>();
updSeconds.ToList().ForEach(t => t.RealGiveFee = t.PreRealGiveFee);
updSeconds.ToList().ForEach(t =>
{
var second = updSecondQuery.FirstOrDefault(c => c.Id == t.Id);
t.RealGiveFee = t.PreRealGiveFee;
t.Status = second.Status;
t.Remark = second.Remark;
t.NursingDeptStatus = second.NursingDeptStatus;
t.NursingDeptRemark = second.NursingDeptRemark;
});
perforAgsecondallotRepository.UpdateRange(updSeconds.ToArray());
}
if (promptSeconds.Any(t => t.IssueStatus == 1))
......
......@@ -2001,20 +2001,23 @@ private decimal GetDecimal(decimal? value, decimal _ = 0)
/// <returns></returns>
public List<cof_alias> CustomColumnHeaders(int hospitalId, string route)
{
var alias = cofaliasRepository.GetEntities(t => t.HospitalId == hospitalId && t.Route.Equals(route, StringComparison.OrdinalIgnoreCase));
var init = new List<cof_alias>();
var alias = cofaliasRepository.GetEntities(t => t.HospitalId == hospitalId) ?? new List<cof_alias>();
alias = alias.Where(t => t.Route.Equals(route, StringComparison.OrdinalIgnoreCase)).OrderBy(w => w.Id).ToList() ?? new List<cof_alias>();
var pairs = new Dictionary<string, List<cof_alias>>
if (alias == null || alias.Count == 0)
{
{ "/result/compute" , ComputeConfig.AllComputeView },
{ "/result/wholehospital" , ComputeConfig.AllComputePersonView },
{ "/result/print/compute" , ComputeConfig.AllComputeDepartmentView },
};
var init = pairs.ContainsKey(route.ToLower()) ? pairs[route.ToLower()] : new List<cof_alias>();
foreach (var item in init)
{
item.HospitalId = hospitalId;
item.Route = route;
item.OriginalName = item.Alias;
var pairs = new Dictionary<string, List<cof_alias>>
{
{ "/result/compute" , ComputeConfig.AllComputeView },
{ "/result/wholehospital" , ComputeConfig.AllComputePersonView },
{ "/result/print/compute" , ComputeConfig.AllComputeDepartmentView },
{ "/report/wholehospital_grant" , ComputeConfig.AllComputeViewByDate },
{ "/report/wholehospital_accounting_grant" , ComputeConfig.AllComputeDepartmentViewByDate },
{ "/report/wholehospital_finance_grant" , ComputeConfig.AllComputePersonViewByDate },
};
init = pairs.ContainsKey(route.ToLower()) ? pairs[route.ToLower()] : new List<cof_alias>();
}
if (alias != null && alias.Count > 0)
......@@ -2066,6 +2069,48 @@ public List<dynamic> GetAllComputeView(int hospitalId, int AllotId, string viewN
{
return reportRepository.QueryCompute(AllotId, viewName);
}
public List<dynamic> GetAllComputeViewByDate(string viewName, DateTime beginTime, DateTime endTime)
{
return reportRepository.QueryComputeByDate(viewName, beginTime, endTime);
}
/// <summary>
///
/// </summary>
/// <param name="datas"></param>
/// <returns></returns>
public Dictionary<string, decimal> SumDatas(List<dynamic> datas)
{
string[] notSum = new string[] { "hospitalid", "allotid", "year", "month", "jobnumber", "bankcard", "jobtitle", "secondid", "states", "isshowmanage", "batch" };
Dictionary<string, decimal> pairs = new Dictionary<string, decimal>();
foreach (var dt in datas)
{
var row = (IDictionary<string, object>)dt;
foreach (var item in row)
{
if (notSum.Contains(item.Key.ToLower())) continue;
if (decimal.TryParse(item.Value?.ToString(), out decimal v))
{
if (pairs.TryGetValue(item.Key, out decimal sum))
{
sum += v;
pairs[item.Key] = sum;
}
else
{
pairs[item.Key] = v;
}
}
}
}
foreach (var item in pairs)
{
pairs[item.Key] = Math.Round(item.Value, 2, MidpointRounding.AwayFromZero);
}
return pairs;
}
}
public class ComputeConfig
......@@ -2082,7 +2127,7 @@ public class ComputeConfig
new cof_alias{ Alias = "批次", Name = nameof(view_allot_sign_emp.Batch), States = 1},
new cof_alias{ Alias = "银行卡号", Name = nameof(view_allot_sign_emp.BankCard), States = 1},
new cof_alias{ Alias = "正式/临聘", Name = nameof(view_allot_sign_emp.JobCategory), States = 1},
new cof_alias{ Alias = "职务", Name = nameof(view_allot_sign_emp.Duty), States = 1},
//new cof_alias{ Alias = "职务", Name = nameof(view_allot_sign_emp.Duty), States = 1},
new cof_alias{ Alias = "职称", Name = nameof(view_allot_sign_emp.TitlePosition), States = 1},
new cof_alias{ Alias = "调节后业绩绩效", Name = nameof(view_allot_sign_emp.PerforSumFee), States = 1},
......@@ -2096,6 +2141,22 @@ public class ComputeConfig
new cof_alias{ Alias = "实发绩效", Name = nameof(view_allot_sign_emp.RealGiveFee), States = 1},
};
private static List<cof_alias> _allComputeViewByDate = new List<cof_alias>();
public static List<cof_alias> AllComputeViewByDate
{
get
{
if (_allComputeViewByDate == null || _allComputeViewByDate.Count == 0)
{
_allComputeViewByDate.Add(new cof_alias { Alias = "年份", Name = nameof(view_allot_sign_emp.Year), States = 1 });
_allComputeViewByDate.Add(new cof_alias { Alias = "月份", Name = nameof(view_allot_sign_emp.Month), States = 1 });
_allComputeViewByDate.AddRange(AllComputeView);
}
return _allComputeViewByDate;
}
}
public static List<cof_alias> AllComputePersonView { get; } = new List<cof_alias>
{
new cof_alias{ Alias = "科室类别", Name = nameof(view_allot_sign_emp.UnitType), States = 1},
......@@ -2112,6 +2173,21 @@ public class ComputeConfig
new cof_alias{ Alias = "预留绩效", Name = nameof(view_allot_sign_emp.ReservedRatioFee), States = 1},
new cof_alias{ Alias = "实发绩效", Name = nameof(view_allot_sign_emp.RealGiveFee), States = 1},
};
private static List<cof_alias> _allComputePersonViewByDate = new List<cof_alias>();
public static List<cof_alias> AllComputePersonViewByDate
{
get
{
if (_allComputePersonViewByDate == null || _allComputePersonViewByDate.Count == 0)
{
_allComputePersonViewByDate.Add(new cof_alias { Alias = "年份", Name = nameof(view_allot_sign_emp.Year), States = 1 });
_allComputePersonViewByDate.Add(new cof_alias { Alias = "月份", Name = nameof(view_allot_sign_emp.Month), States = 1 });
_allComputePersonViewByDate.AddRange(AllComputePersonView);
}
return _allComputePersonViewByDate;
}
}
public static List<cof_alias> AllComputeDepartmentView { get; } = new List<cof_alias>
{
new cof_alias{ Alias = "核算群体", Name = nameof(view_allot_sign_dept.UnitName), States = 1},
......@@ -2133,5 +2209,19 @@ public class ComputeConfig
new cof_alias{ Alias = "不公示其他绩效", Name = nameof(view_allot_sign_dept.HideAprOtherPerforAmount), States = 1},
new cof_alias{ Alias = "实发绩效", Name = nameof(view_allot_sign_dept.RealGiveFee), States = 1},
};
private static List<cof_alias> _allComputeDepartmentViewByDate = new List<cof_alias>();
public static List<cof_alias> AllComputeDepartmentViewByDate
{
get
{
if (_allComputeDepartmentViewByDate == null || _allComputeDepartmentViewByDate.Count == 0)
{
_allComputeDepartmentViewByDate.Add(new cof_alias { Alias = "年份", Name = nameof(view_allot_sign_emp.Year), States = 1 });
_allComputeDepartmentViewByDate.Add(new cof_alias { Alias = "月份", Name = nameof(view_allot_sign_emp.Month), States = 1 });
_allComputeDepartmentViewByDate.AddRange(AllComputeDepartmentView);
}
return _allComputeDepartmentViewByDate;
}
}
}
}
......@@ -181,15 +181,34 @@ public string AllComputerViewReport(int allotId, List<dynamic> dynamics, string
{
var allot = perallotRepository.GetEntity(t => t.ID == allotId);
var hospital = perforHospital.GetEntity(t => t.ID == allot.HospitalId);
var alias = perforCofalias.GetEntities(t => t.HospitalId == hospital.ID);
var title = $"{allot.Year}{allot.Month}{hospital.HosName}医院 --- {name}";
return AllComputerDown(hospital, dynamics, route, title, name);
}
/// <summary>
/// 财务、全院绩效发放下载(时间段)
/// </summary>
/// <param name="allotId"></param>
/// <param name="allData"></param>
/// <param name="isAll"></param>
/// <returns></returns>
public string AllComputerViewReportByDate(int hospitalId, List<dynamic> dynamics, string route, string name, DateTime beginTime, DateTime endTime)
{
var hospital = perforHospital.GetEntity(t => t.ID == hospitalId);
var title = (beginTime.AddMonths(1).Date == endTime.Date)
? $"{beginTime.ToString("yyyy年MM月")}{hospital.HosName}医院 --- {name}"
: $"{beginTime.ToString("yyyy年MM月")}{endTime.ToString("yyyy年MM月")}{hospital.HosName}医院 --- {name}";
return AllComputerDown(hospital, dynamics, route, title, name);
}
public string AllComputerDown(sys_hospital hospital, List<dynamic> dynamics, string route, string title, string name)
{
var headList = _computeService.CustomColumnHeaders(hospital.ID, route).Where(w => w.States == 1).ToList();
var dpath = Path.Combine(evn.ContentRootPath, "Files", "PerformanceRelease", $"{allot.HospitalId}");
var dpath = Path.Combine(evn.ContentRootPath, "Files", "PerformanceRelease", $"{hospital.ID}");
FileHelper.CreateDirectory(dpath);
string filepath = Path.Combine(dpath, $"{hospital.HosName}-{name}-{DateTime.Now:yyyyMMdd}");
FileHelper.DeleteFile(filepath);
string[] notSum = new string[] { "year", "month" };
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
using (ExcelPackage package = new ExcelPackage(fs))
{
......@@ -197,11 +216,12 @@ public string AllComputerViewReport(int allotId, List<dynamic> dynamics, string
if (dynamics != null && dynamics.Count() > 0)
{
worksheet.SetValue(1, 1, title);
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.SetValue(2, col + 1, headList[col].Alias);
}
for (int col = 0; col < headList.Count; col++)
{
......@@ -211,23 +231,41 @@ public string AllComputerViewReport(int allotId, List<dynamic> dynamics, string
var temp = (IDictionary<string, object>)data;
var value = temp[headList[col].Name];
worksheet.Cells[row + 2, col + 1].Value = value;
worksheet.Cells[row + 3, col + 1].Value = value;
}
if (col == 0)
worksheet.SetValue(dynamics.Count() + 2, col + 1, "合计");
else
worksheet.Cells[dynamics.Count() + 2, col + 1].Formula = string.Format("SUM({0})", new ExcelAddress(2, col + 1, dynamics.Count() + 1, col + 1).Address);
worksheet.SetValue(dynamics.Count() + 3, col + 1, "合计");
else if (!notSum.Contains(headList[col].Name.ToLower()))
worksheet.Cells[dynamics.Count() + 3, col + 1].Formula = string.Format("SUM({0})", new ExcelAddress(3, col + 1, dynamics.Count() + 2, col + 1).Address);
}
}
worksheet.View.FreezePanes(2, 1);
for (int row = worksheet.Dimension.Start.Row; row <= worksheet.Dimension.End.Row; row++)
{
#region 样式设置
for (int row = worksheet.Dimension.Start.Row; row <= worksheet.Dimension.End.Row; row++)
{
worksheet.Row(row).Height = 20;
for (int col = worksheet.Dimension.Start.Column; col <= worksheet.Dimension.End.Column; col++)
{
if (headList.Count < col && !notSum.Contains(headList[col - 1].Name.ToLower()))
worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.00";
worksheet.Cells[row, col].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheet.Cells[row, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
}
worksheet.Cells[1, 1, 1, headList.Count].Merge = true;
worksheet.Cells[1, 1, 1, headList.Count].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
worksheet.Cells[1, 1, 1, headList.Count].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells[1, 1, 1, headList.Count].Style.Font.Bold = true;
worksheet.Cells[1, 1, 1, headList.Count].Style.Font.Size = 16;
worksheet.Row(1).Height = 24;
worksheet.Cells[2, 1, 2, headList.Count].Style.Font.Bold = true;
worksheet.View.FreezePanes(3, 1);
worksheet.Cells.AutoFitColumns();
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";
worksheet.Column(col).Width = worksheet.Column(col).Width > 20 ? 20 : worksheet.Column(col).Width;
}
#endregion
}
package.Save();
}
......
......@@ -35,6 +35,13 @@ public class EmployeeService : IAutoInjection
private PerforUserRepository userRepository;
private readonly PerforRoleRepository _roleRepository;
private readonly PerforPerapramounthideRepository _hideRepository;
private readonly PerforExresultgatherRepository exresultgatherRepository;
private readonly PerforImheaderRepository imheaderRepository;
private readonly PerforPerdeptdicRepository perdeptdicRepository;
private readonly PerforExmoduleRepository exmoduleRepository;
private readonly PerforExitemRepository exitemRepository;
private readonly PerforExspecialRepository exspecialRepository;
private readonly PerforExresultRepository exresultRepository;
private ILogger<EmployeeService> logger;
public EmployeeService(
......@@ -53,6 +60,13 @@ public class EmployeeService : IAutoInjection
PerforUserRepository userRepository,
PerforRoleRepository roleRepository,
PerforPerapramounthideRepository hideRepository,
PerforExresultgatherRepository exresultgatherRepository,
PerforImheaderRepository imheaderRepository,
PerforPerdeptdicRepository perdeptdicRepository,
PerforExmoduleRepository exmoduleRepository,
PerforExitemRepository exitemRepository,
PerforExspecialRepository exspecialRepository,
PerforExresultRepository exresultRepository,
ILogger<EmployeeService> logger)
{
_mapper = mapper;
......@@ -70,6 +84,13 @@ public class EmployeeService : IAutoInjection
this.userRepository = userRepository;
_roleRepository = roleRepository;
_hideRepository = hideRepository;
this.exresultgatherRepository = exresultgatherRepository;
this.imheaderRepository = imheaderRepository;
this.perdeptdicRepository = perdeptdicRepository;
this.exmoduleRepository = exmoduleRepository;
this.exitemRepository = exitemRepository;
this.exspecialRepository = exspecialRepository;
this.exresultRepository = exresultRepository;
this.logger = logger;
}
......@@ -1124,6 +1145,328 @@ public ComparisonResponse GetComparison(ComparisonPagingRequest request)
return result;
}
#region 手工数据录入
public List<GatherDropResponse> GetGatherDrop(int allotId)
{
again:
var perSheets = perforPersheetRepository.GetEntities(t => t.AllotID == allotId && new[] { 3, 4, 7 }.Contains(t.SheetType.Value));
if (perSheets == null || !perSheets.Any())
{
var allot = perallotRepository.GetEntity(t => t.ID == allotId);
var list = perallotRepository.GetEntities(t => t.HospitalId == allot.HospitalId);
if (list == null || !list.Any(t => t.ID == allot.ID)) return new List<GatherDropResponse>();
list = list.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).ToList();
var index = list.IndexOf(list.First(t => t.ID == allot.ID));
// 先取上一个月的绩效Id,若没有取最后一个月的绩效Id,若都不存在则获取allotId为-1的数据
allotId = index + 1 < list.Count ? list[index + 1].ID : list.First().ID;
if (allotId == allot.ID) return new List<GatherDropResponse>();
goto again;
}
//var sheets = perSheets.Select(t => new GatherDropResponse() { Label = t.SheetName, Value = t.SheetName });
var imHeaders = imheaderRepository.GetEntities(t => t.AllotID == allotId);
var result = new List<GatherDropResponse>();
var cellValue = new[] { "核算单元(医技组)", "核算单元(医生组)", "核算单元(护理组)", "科室名称" };
foreach (var sheet in perSheets)
{
var drop = new GatherDropResponse();
var header = imHeaders.Where(t => t.SheetID == sheet.ID && !cellValue.Contains(t.CellValue)).Select(t => t.CellValue).Distinct();
drop.Label = sheet.SheetName.Split(' ')[1];
drop.Value = sheet.SheetName.Split(' ')[1];
drop.Children = header.Select(t => new GatherDropResponse() { Label = t, Value = t }).ToList();
result.Add(drop);
}
return result;
}
public HandsonTable GetGatherHands(int AllotId, GatherRequest request)
{
var result = new HandsonTable((int)SheetType.Unidentifiable, Gather.Select(t => t.Value).ToArray(), Gather.Select(t => new collect_permission
{
HeadName = t.Value,
Visible = 1
}).ToList());
if (result.Columns != null && result.Columns.Any())
{
foreach (var column in result.Columns)
{
if (column.Data == "数值")
{
column.Type = "numeric";
column.NumericFormat = new NumericFormat { Pattern = "0,00.00" };
}
else
column.Type = "text";
}
}
var data = exresultgatherRepository.GetEntities(t => t.AllotId == AllotId && t.Source.Contains(request.Source) && t.Category.Contains(request.Category));
if (data == null)
return result;
List<HandsonRowData> rowDatas = new List<HandsonRowData>();
int i = 1;
foreach (var item in data)
{
var json = JsonHelper.Serialize(item);
var firstDic = JsonHelper.Deserialize<Dictionary<string, string>>(json);
var cells = (from conf in Gather join fst in firstDic on conf.Key.ToUpper() equals fst.Key.ToUpper() select new HandsonCellData(conf.Value, fst.Value)).ToList();
rowDatas.Add(new HandsonRowData(i, cells));
i++;
}
result.SetRowData(rowDatas, rowDatas != null);
return result;
}
public void SaveGatherHands(int allotId, SaveGatherData request)
{
var dicData = CreateDataRow(0, allotId, request, Gather);
List<ex_result_gather> depts = new List<ex_result_gather>();
DateTime timeNow = DateTime.Now;
foreach (var item in dicData)
{
var json = JsonHelper.Serialize(item);
var data = JsonHelper.Deserialize<ex_result_gather>(json);
if (!string.IsNullOrEmpty(data.Department) && !string.IsNullOrEmpty(data.Fee.ToString()))
{
data.Source = request.Source;
data.Category = request.Category;
data.AllotId = allotId;
data.CreateTime = timeNow;
depts.Add(data);
}
}
exresultgatherRepository.Execute($@"delete from ex_result_gather where allotid = @allotid and source like '%{request.Source}%' and category = '{request.Category}' ", new { allotId });
exresultgatherRepository.AddRange(depts.ToArray());
}
public GatherResponse GetGather(int allotId, PersonParamsRequest request)
{
var head = ColumnHeadsConfig.GatherHeads;
head.ForEach(t =>
{
t.Name = t.Name.ToLower();
});
Expression<Func<ex_result_gather, bool>> exp = t => t.AllotId == allotId;
if (request != null && !string.IsNullOrEmpty(request.SearchQuery))
exp = exp.And(t => t.Department.Contains(request.SearchQuery) || t.DoctorName.Contains(request.SearchQuery) || t.PersonnelNumber.Contains(request.SearchQuery) || t.Category.Contains(request.SearchQuery) || t.Source.Contains(request.SearchQuery));
var data = peremployeeRepository.GetGatherForPaging(request.PageNumber, request.PageSize, exp);
return new GatherResponse()
{
Heads = head,
Datas = data,
CurrentPage = data.CurrentPage,
TotalCount = data.TotalCount,
PageSize = data.PageSize,
TotalPages = data.TotalPages
};
}
public static Dictionary<string, string> Gather { get; } = new Dictionary<string, string>
{
{nameof(ex_result_gather.Department), "科室"},
{nameof(ex_result_gather.DoctorName), "医生姓名"},
{nameof(ex_result_gather.PersonnelNumber), "人员工号"},
//{nameof(ex_result_gather.Category), "费用类型"},
{nameof(ex_result_gather.Fee), "数值"},
//{nameof(ex_result_gather.Source), "来源"}
};
private List<Dictionary<string, string>> CreateDataRow(int hospitalId, int allotId, SaveGatherData request, Dictionary<string, string> config)
{
List<Dictionary<string, string>> allData = new List<Dictionary<string, string>>();
for (int r = 0; r < request.Data.Length; r++)
{
// 创建固定数据列
Dictionary<string, string> baseData = CreateBaseData(request, config, r);
baseData.Add(nameof(cof_hrp_department.AllotId), hospitalId.ToString());
allData.Add(baseData);
}
return allData;
}
private Dictionary<string, string> CreateBaseData(SaveGatherData request, Dictionary<string, string> config, int rownumber)
{
Dictionary<string, string> result = new Dictionary<string, string>();
for (int c = 0; c < request.ColHeaders.Length; c++)
{
var header = request.ColHeaders[c];
var first = config.FirstOrDefault(w => w.Value == header);
if (!default(KeyValuePair<string, string>).Equals(first)
&& !result.ContainsKey(header)
&& request.Data[rownumber].Length > c)
{
result.Add(first.Key, request.Data[rownumber][c]);
}
}
return result;
}
#endregion
#region 录入校验
public bool CheckGatherData(int allotId)
{
try
{
var allot = perallotRepository.GetEntity(w => w.ID == allotId);
if (allot == null) throw new PerformanceException("绩效记录不存在");
var data = exresultgatherRepository.GetEntities(w => w.AllotId == allotId);
if (data == null || !data.Any()) throw new PerformanceException("录入数据为空");
SetDataStatesAndRemark(data, 2, string.Empty);
var departments = perdeptdicRepository.GetEntities(w => w.HospitalId == allot.HospitalId);
if (departments != null && departments.Any())
{
var notExistsDeptData = data.Where(w => !departments.Select(t => t.Department).Contains(w.Department));
if (notExistsDeptData != null && notExistsDeptData.Any())
SetDataStatesAndRemark(notExistsDeptData, 1, "科室字典中不存在科室[{0}]", t => t.Department);
}
var employees = peremployeeRepository.GetEntities(w => w.AllotId == allotId);
if (employees != null && employees.Any())
{
var notExistNameData = data.Where(w => !employees.Select(t => t.DoctorName).Contains(w.DoctorName) && !string.IsNullOrEmpty(w.DoctorName));
if (notExistNameData != null && notExistNameData.Any())
SetDataStatesAndRemark(notExistNameData, 1, "人员字典中不存在医生名称[{0}]", t => t.DoctorName);
var notExistNumberData = data.Where(w => !employees.Select(t => t.PersonnelNumber).Contains(w.PersonnelNumber) && !string.IsNullOrEmpty(w.PersonnelNumber));
if (notExistNumberData != null && notExistNumberData.Any())
SetDataStatesAndRemark(notExistNumberData, 1, "人员字典中不存在工号[{0}]", t => t.PersonnelNumber);
}
var sheets = perforPersheetRepository.GetEntities(w => w.AllotID == allotId);
if (sheets != null && sheets.Any())
{
var notExistsSourceData = data.Where(w => !sheets.Select(t => t.SheetName).Contains(w.Source));
if (notExistsSourceData != null && notExistsSourceData.Any())
SetDataStatesAndRemark(notExistsSourceData, 1, "来源中不存在名称[{0}]", t => t.Source);
}
exresultgatherRepository.UpdateRange(data.ToArray());
AddCategoryToConfig(data, allot.HospitalId);
return data.Any(w => w.States == 1);
}
catch (Exception ex)
{
logger.LogError(ex.Message);
throw new PerformanceException("校验失败");
}
}
private static void SetDataStatesAndRemark(IEnumerable<ex_result_gather> data, int states, string remark, Func<ex_result_gather, string> func = null)
{
if (new int[] { 1, 2 }.Contains(states)) return;
if (data == null || !data.Any()) return;
foreach (var item in data)
{
if (func != null)
remark = string.Format(remark, func.Invoke(item));
item.States = states;
item.Remark = (!string.IsNullOrEmpty(item.Remark) && item.Remark.Length > 0) ? item.Remark + ", " + remark : remark;
}
}
private void AddCategoryToConfig(List<ex_result_gather> data, int hospitalId)
{
if (data == null || !data.Any(w => w.States == 2)) return;
data = data.Where(w => w.States == 2).ToList();
var modules = exmoduleRepository.GetEntities(w => w.HospitalId == hospitalId && w.SheetType != (int)SheetType.Income);
if (modules == null || !modules.Any()) return;
var items = exitemRepository.GetEntities(w => modules.Select(t => t.Id).Distinct().Contains(w.ModuleId ?? 0));
if (items == null || !items.Any()) return;
try
{
var insertList = new List<ex_item>();
foreach (var module in modules)
{
var categories = data.Where(t => t.Source == module.ModuleName)?.Select(t => t.Category).Distinct();
if (categories == null || !categories.Any()) continue;
var moduleItems = items.Where(w => w.ModuleId == module.Id)?.Select(t => t.ItemName).Distinct();
if (moduleItems == null || !moduleItems.Any()) continue;
var exceptCategories = categories.Except(moduleItems);
if (exceptCategories == null || !exceptCategories.Any()) continue;
insertList.AddRange(exceptCategories.Select(t => new ex_item
{
ModuleId = module.Id,
ItemName = t,
ReadOnly = 0
}));
}
if (insertList != null && insertList.Any())
{
exitemRepository.AddRange(insertList.ToArray());
}
var speacialCategories = data.Where(t => t.Source.Contains("特殊核算单元"))?.Select(t => new { t.Category, t.Department }).Distinct();
if (speacialCategories == null || !speacialCategories.Any()) return;
var specials = exspecialRepository.GetEntities(w => w.HospitalId == hospitalId);
if (specials == null || !specials.Any()) return;
var list = speacialCategories.Where(w => !specials.Select(t => t.Target + t.Department).Contains(w.Category + w.Department));
if (list == null || !list.Any()) return;
exspecialRepository.AddRange(list.Select(t => new ex_special
{
HospitalId = hospitalId,
Department = t.Department,
Target = t.Category
}).ToArray());
}
catch (Exception ex)
{
logger.LogError(ex.Message);
}
}
public void SyncDataToResult(int allotId)
{
var data = exresultgatherRepository.GetEntities(w => w.AllotId == allotId);
if (data == null || !data.Any() || data.Any(w => w.States == 1)) return;
var syncData = _mapper.Map<List<ex_result>>(data);
exresultRepository.AddRange(syncData.ToArray());
}
#endregion
}
public class ComparisonConfig
......
......@@ -624,7 +624,7 @@ public string LastAllotFilePath(int allotId)
var statesArray = new int[] { (int)AllotStates.GenerateSucceed, (int)AllotStates.Archive };
var allotList = perallotRepository.GetEntities(t => t.HospitalId == allot.HospitalId && statesArray.Contains(t.States));
var allotLast = allotList?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).First();
var allotLast = allotList?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).FirstOrDefault();
if (allotLast != null)
return allotLast.Path;
......@@ -659,7 +659,7 @@ public string Judge(int allotId, int hospitalId, int useTemplate, ref bool isSin
// 获取最近一次绩效
var statesArray = new int[] { (int)AllotStates.GenerateSucceed, (int)AllotStates.Archive };
var allotList = perallotRepository.GetEntities(t => t.HospitalId == hospitalId && statesArray.Contains(t.States));
var allotLast = allotList?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).First();
var allotLast = allotList?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).FirstOrDefault();
if (allotLast != null)
filePath = allotLast.Path;
// 获取当前医院模版信息
......@@ -775,7 +775,7 @@ public string Judge(int allotId, int hospitalId, int useTemplate, ref bool isSin
if (conf == null)
continue;
var data = queryService.QueryData(conf, allot, scr.ExecScript);
var data = queryService.QueryData<ExtractDto>(conf, scr.ExecScript, allot, false);
if (data == null || !data.Any()) continue;
foreach (var module in moduleSheet.Where(t => t.CheckScriptId == scr.Id))
......
......@@ -71,7 +71,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
var typeIds = types.Where(t => t.Source == (int)SheetType.Employee).Select(t => t.Id);
var script = scripts.Where(t => typeIds.Contains(t.TypeId));
if (script != null)
Employee(allot, configs, scripts);
Employee(allot, configs, scripts, isSingle);
}
if (types.Any(t => t.Source == (int)SheetType.OnlyExtract)) //不写入Excel的提取数据
{
......@@ -84,7 +84,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
foreach (var script in thisTypeScripts)
{
logger.LogInformation($"提取sql: {script.ExecScript}");
ExResult(allot, configs.FirstOrDefault(t => t.Id == script.ConfigId), script.ExecScript, type.EName);
ExResult(allot, configs.FirstOrDefault(t => t.Id == script.ConfigId), script.ExecScript, type.EName, isSingle);
}
}
}
......@@ -96,7 +96,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
foreach (var item in hisScrips)
{
logService.ReturnTheLog(allot.ID, groupName, 2, "提取数据", $"提取{item.SourceType} - {item.Category}数据", isSingle: isSingle);
HisData(allot, configs.FirstOrDefault(t => t.Id == item.ConfigId), item);
HisData(allot, configs.FirstOrDefault(t => t.Id == item.ConfigId), item, isSingle);
}
}
catch (Exception)
......@@ -106,7 +106,7 @@ public void Handler(int hospitalId, per_allot allot, string groupName, bool isSi
}
}
private void Employee(per_allot allot, List<sys_hospitalconfig> configs, IEnumerable<ex_script> scripts)
private void Employee(per_allot allot, List<sys_hospitalconfig> configs, IEnumerable<ex_script> scripts, bool isSingle)
{
try
{
......@@ -116,12 +116,12 @@ private void Employee(per_allot allot, List<sys_hospitalconfig> configs, IEnumer
var sql = script.ExecScript;
if (config == null || string.IsNullOrEmpty(sql)) return;
var limitData = queryService.QueryData<dynamic>(config, allot, sql);
var limitData = queryService.QueryData<dynamic>(config, sql, allot, isSingle);
if (limitData == null || !limitData.Any()) return;
var columns = ((IDictionary<string, object>)limitData.ElementAt(0)).Select(t => t.Key.ToLower()).ToList();
var data = queryService.QueryData<per_employee>(config, allot, sql).ToList();
var data = queryService.QueryData<per_employee>(config, sql, allot, isSingle).ToList();
data.ForEach(t =>
{
t.AllotId = allot.ID;
......@@ -223,13 +223,13 @@ private void JudgeDataEqual(List<string> columns, List<per_employee> emps, List<
}
}
private void HisData(per_allot allot, sys_hospitalconfig config, his_script script)
private void HisData(per_allot allot, sys_hospitalconfig config, his_script script, bool isSingle)
{
try
{
if (config == null || string.IsNullOrEmpty(script.ExecScript)) return;
var data = queryService.QueryData<HisData>(config, allot, script.ExecScript);
var data = queryService.QueryData<HisData>(config, script.ExecScript, allot, isSingle);
if (data == null || !data.Any()) return;
var hisdata = hisdataRepository.GetEntities(t => t.AllotId == allot.ID && t.SourceType == script.SourceType && t.Category == script.Category);
......@@ -265,13 +265,13 @@ private void Department()
{
}
private void ExResult(per_allot allot, sys_hospitalconfig config, string sql, string enmae)
private void ExResult(per_allot allot, sys_hospitalconfig config, string sql, string enmae, bool isSingle)
{
try
{
if (config == null || string.IsNullOrEmpty(sql)) return;
var data = queryService.QueryData(config, allot, sql);
var data = queryService.QueryData<ExtractDto>(config, sql, allot, isSingle);
if (data == null || !data.Any()) return;
var createTime = DateTime.Now;
......
......@@ -52,40 +52,43 @@ public static void CreateNotExistSheet(List<ex_module> modulesList, IWorkbook wo
pairs.Add(workbook.GetSheetAt(i).SheetName, i);
}
foreach (var module in modulesList.Where(t => t.SheetType == (int)SheetType.Income)?.OrderBy(t => t.ModuleName))
try
{
var sheet = workbook.GetSheet(module.ModuleName) ?? workbook.GetSheet(module.ModuleName.NoBlank());
if (sheet == null)
foreach (var module in modulesList.Where(t => t.SheetType == (int)SheetType.Income)?.OrderBy(t => t.ModuleName))
{
var sheet = workbook.GetSheet(module.ModuleName) ?? workbook.GetSheet(module.ModuleName.NoBlank());
if (sheet == null)
{
string[] keyArray = new string[] { "开单", "就诊", "执行" };
if (keyArray.Any(key => module.ModuleName.Contains(key)))
{
var item = pairs.Where(t => t.Key.ToString().NoBlank().StartsWith("1.")).OrderByDescending(t => t.Key).First();
var copysheet = workbook.GetSheet(item.Key);
if (copysheet == null) continue;
var newSheet = copysheet.CopySheet(module.ModuleName, true);
workbook.SetSheetOrder(newSheet.SheetName, workbook.NumberOfSheets - 1);
}
}
}
foreach (var module in modulesList.Where(t => new int[] { (int)SheetType.OtherWorkload, (int)SheetType.Assess }.Contains(t.SheetType.Value))?.OrderBy(t => t.ModuleName))
{
string[] keyArray = new string[] { "开单", "就诊", "执行" };
if (keyArray.Any(key => module.ModuleName.Contains(key)))
var sheet = workbook.GetSheet(module.ModuleName) ?? workbook.GetSheet(module.ModuleName.NoBlank());
if (sheet == null)
{
var item = pairs.Where(t => t.Key.StartsWith("1.")).OrderByDescending(t => t.Key).First();
var item = pairs.Where(t => t.Key.ToString().NoBlank().StartsWith("3.")).OrderByDescending(t => t.Key).First();
var copysheet = workbook.GetSheet(item.Key);
if (copysheet == null) continue;
var newSheet = copysheet.CopySheet(module.ModuleName, true);
workbook.SetSheetOrder(newSheet.SheetName, workbook.NumberOfSheets - 1);
var point = PerSheetDataFactory.GetDataRead(SheetType.Workload)?.Point;
ClearSheetTemplate(newSheet, point, (SheetType)module.SheetType);
}
}
}
foreach (var module in modulesList.Where(t => new int[] { (int)SheetType.OtherWorkload, (int)SheetType.Assess }
.Contains(t.SheetType.Value))?.OrderBy(t => t.ModuleName))
catch
{
var sheet = workbook.GetSheet(module.ModuleName) ?? workbook.GetSheet(module.ModuleName.NoBlank());
if (sheet == null)
{
//string key = "工作量";
//if (module.ModuleName.Contains(key))
//{
var item = pairs.Where(t => t.Key.StartsWith("3.")).OrderByDescending(t => t.Key).First();
var copysheet = workbook.GetSheet(item.Key);
var newSheet = copysheet.CopySheet(module.ModuleName, true);
workbook.SetSheetOrder(newSheet.SheetName, workbook.NumberOfSheets - 1);
var point = PerSheetDataFactory.GetDataRead(SheetType.Workload)?.Point;
ClearSheetTemplate(newSheet, point, (SheetType)module.SheetType);
//}
}
}
}
......
......@@ -197,14 +197,14 @@ 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 = new Dictionary<string, Func<ExtractTransDto, string>>();
var filed = fieldOut;
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("门诊"))
if (string.IsNullOrEmpty(ename) || ename.Contains("住院") || ename.Contains("门诊"))
filed = ename.Contains("住院") ? fieldInpatOut : fieldOutInpat;
}
else if (sheet.SheetName.Contains("工作量"))
......
using Microsoft.Extensions.Logging;
using Dapper;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.EntityModels;
......@@ -7,6 +8,7 @@
using Performance.Services.ExtractExcelService.SheetDataWrite;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
......@@ -21,6 +23,7 @@ public class ExtractService : IAutoInjection
private readonly PerSheetService perSheetService;
private readonly CostTransferDataWrite costTransfer;
private readonly DictionaryService dictionaryService;
private readonly EmployeeService employeeService;
private readonly CustomDataWrite customDataWrite;
private readonly PerforPerallotRepository perallotRepository;
private readonly PerforCollectdataRepository collectdataRepository;
......@@ -28,6 +31,7 @@ public class ExtractService : IAutoInjection
private readonly PerforPeremployeeRepository peremployeeRepository;
private readonly PerforPerdeptdicRepository perdeptdicRepository;
private readonly PerforCofdrugtypefactorRepository drugtypefactorRepository;
private readonly PerforExresultRepository exresultRepository;
public ExtractService(
ILogger<ExtractService> logger,
......@@ -37,13 +41,15 @@ public class ExtractService : IAutoInjection
PerSheetService perSheetService,
CostTransferDataWrite costTransfer,
DictionaryService dictionaryService,
EmployeeService employeeService,
CustomDataWrite customDataWrite,
PerforPerallotRepository perallotRepository,
PerforCollectdataRepository collectdataRepository,
PerforExtypeRepository extypeRepository,
PerforPeremployeeRepository peremployeeRepository,
PerforPerdeptdicRepository perdeptdicRepository,
PerforCofdrugtypefactorRepository drugtypefactorRepository
PerforCofdrugtypefactorRepository drugtypefactorRepository,
PerforExresultRepository exresultRepository
)
{
this.logger = logger;
......@@ -53,6 +59,7 @@ PerforCofdrugtypefactorRepository drugtypefactorRepository
this.perSheetService = perSheetService;
this.costTransfer = costTransfer;
this.dictionaryService = dictionaryService;
this.employeeService = employeeService;
this.customDataWrite = customDataWrite;
this.perallotRepository = perallotRepository;
this.collectdataRepository = collectdataRepository;
......@@ -60,6 +67,7 @@ PerforCofdrugtypefactorRepository drugtypefactorRepository
this.peremployeeRepository = peremployeeRepository;
this.perdeptdicRepository = perdeptdicRepository;
this.drugtypefactorRepository = drugtypefactorRepository;
this.exresultRepository = exresultRepository;
}
/// <summary>
......@@ -73,9 +81,11 @@ PerforCofdrugtypefactorRepository drugtypefactorRepository
/// <param name="isSingle">抽取是否在同一项目</param>
public string Main(int allotId, int hospitalId, string email, string groupName, string filePath = null, bool isSingle = false)
{
groupName = allotId.ToString();
string extractFilePath = "";
per_allot allot = null;
IWorkbook workbook = null;
IDbConnection connection = peremployeeRepository.GetDbConnection();
try
{
logService.ClearExtractLog(allotId);
......@@ -92,7 +102,10 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
queryService.ClearHistoryData(allot.ID, groupName, isSingle);
var data = queryService.Handler(hospitalId, allot, groupName, isSingle, ref dict);
employeeService.SyncDataToResult(allotId);
var data = exresultRepository.GetEntities(t => t.AllotId == allotId && t.IsDelete == 0);
data.AddRange(queryService.Handler(hospitalId, allot, groupName, isSingle, ref dict));
var standData = StandDataFormat(hospitalId, data);
dictionaryService.Handler(hospitalId, allot, groupName, isSingle);
......@@ -102,18 +115,24 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
var templateFilePath = ExtractHelper.GetExtractFile(hospitalId, allot, ref extractFilePath, filePath);
logService.ReturnTheLog(allotId, groupName, 2, "创建文件", $"模板文件: {templateFilePath}", 1, isSingle);
if (!FileHelper.IsExistFile(templateFilePath)) throw new PerformanceException("抽取文件创建失败");
if (!FileHelper.IsExistFile(templateFilePath)) throw new Exception("抽取文件创建失败");
workbook = ExcelHelper.GetWorkbook(templateFilePath);
if (workbook == null) throw new PerformanceException("文件读取失败");
if (workbook == null) throw new Exception("文件读取失败");
WriteDataToFile(workbook, allot, dict, standData, groupName, isSingle);
logService.ReturnTheLog(allotId, groupName, 2, "提取完成", $"绩效数据提取成功", 5, isSingle);
allot.IsExtracting = isSingle ? 2 : 0;
allot.ExtractPath = extractFilePath;
logService.ReturnTheLog(allotId, groupName, 2, "写入数据", $"写入数据至Excel文件", 1, isSingle);
workbook.EvaluateAll();
using (FileStream file = new FileStream(extractFilePath, FileMode.OpenOrCreate))
{
workbook.Write(file);
}
workbook.Close();
}
catch (Exception ex)
{
......@@ -124,12 +143,9 @@ public string Main(int allotId, int hospitalId, string email, string groupName,
finally
{
logService.ReturnTheLog(allotId, groupName, 3, "", 100, 5, isSingle);
using (FileStream file = new FileStream(extractFilePath, FileMode.OpenOrCreate))
{
workbook.Write(file);
}
workbook.Close();
perallotRepository.Update(allot);
if (allot.IsExtracting != 3)
logService.ReturnTheLog(allotId, groupName, 2, "提取完成", $"绩效数据提取成功", 5, isSingle);
UpdateAllot(connection, allot);
}
return extractFilePath;
}
......@@ -320,19 +336,38 @@ private List<ExtractTransDto> StandDataFormat(int hospitalId, List<ex_result> re
Department = t.Key.Department,
Category = t.Key.Category,
Value = t.Sum(group => group.Value) == 0 ? null : t.Sum(group => group.Value),
OutDoctorAccounting = t.First().OutDoctorAccounting,
OutNurseAccounting = t.First().OutNurseAccounting,
OutTechnicAccounting = t.First().OutTechnicAccounting,
InpatDoctorAccounting = t.First().InpatDoctorAccounting,
InpatNurseAccounting = t.First().InpatNurseAccounting,
InpatTechnicAccounting = t.First().InpatTechnicAccounting,
SpecialAccounting = t.First().SpecialAccounting,
EName = t.FirstOrDefault(w => !string.IsNullOrEmpty(w.EName)).EName
OutDoctorAccounting = t.FirstOrDefault()?.OutDoctorAccounting,
OutNurseAccounting = t.FirstOrDefault()?.OutNurseAccounting,
OutTechnicAccounting = t.FirstOrDefault()?.OutTechnicAccounting,
InpatDoctorAccounting = t.FirstOrDefault()?.InpatDoctorAccounting,
InpatNurseAccounting = t.FirstOrDefault()?.InpatNurseAccounting,
InpatTechnicAccounting = t.FirstOrDefault()?.InpatTechnicAccounting,
SpecialAccounting = t.FirstOrDefault()?.SpecialAccounting,
EName = t.FirstOrDefault(w => !string.IsNullOrEmpty(w.EName))?.EName
});
return groupdata.ToList();
}
private void UpdateAllot(IDbConnection connection, per_allot allot)
{
try
{
string sql = "update per_allot set isextracting = @isextracting, extractpath = @extractpath where id = @id";
if (connection == null) return;
if (connection.State == ConnectionState.Closed)
connection.Open();
connection.Execute(sql, allot);
}
catch (Exception ex)
{
logger.LogError(ex.Message);
}
}
private readonly List<SheetType> OtherConfigSheet = new List<SheetType>
{
SheetType.AccountExtra,
......
......@@ -59,6 +59,7 @@ PerforPerallotRepository perallotRepository
}
private readonly DateTime CreateTime = DateTime.Now;
private static Dictionary<int, IDbConnection> pools = new Dictionary<int, IDbConnection>();
/// <summary>
/// 获取抽取数据
......@@ -194,8 +195,6 @@ private List<ex_result> ExtractModuleData(per_allot allot, string groupName, boo
logService.ReturnTheLog(allot.ID, groupName, 3, "", ratio > 20 ? 20 : ratio, 1, isSingle);
logService.ReturnTheLog(allot.ID, groupName, 2, "提取数据", $"开始提取模块“{string.Join("、", thisModules.Select(t => t.ModuleName))}”的数据", 1, isSingle);
Dictionary<int, IDbConnection> pools = new Dictionary<int, IDbConnection>();
foreach (var script in scripts.Where(t => t.TypeId == typeId))
{
var config = configs.FirstOrDefault(t => t.Id == script.ConfigId);
......@@ -203,20 +202,7 @@ private List<ex_result> ExtractModuleData(per_allot allot, string groupName, boo
try
{
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];
var parameters = GetParameters(allot);
var querydata = QueryData(connection, parameters, script.ExecScript);
var querydata = QueryData<ExtractDto>(config, script.ExecScript, allot, isSingle);
if (querydata != null && querydata.Any())
{
......@@ -286,33 +272,38 @@ private List<ex_result> ExtractItemData(per_allot allot, string groupName, bool
{
var config = configs.FirstOrDefault(t => t.Id == script.ConfigId);
if (config == null) continue;
var querydata = QueryData(config, allot, script.ExecScript);
if (querydata != null && querydata.Any())
try
{
thisItems.ForEach(f =>
var querydata = QueryData<ExtractDto>(config, script.ExecScript, allot, isSingle);
if (querydata != null && querydata.Any())
{
var modulename = modules.FirstOrDefault(t => t.Id == f.ModuleId)?.ModuleName;
var result = querydata.Select(t => new ex_result
thisItems.ForEach(f =>
{
Department = t.Department,
Category = f.ItemName,
Fee = t.Value,
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = modulename,
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
var modulename = modules.FirstOrDefault(t => t.Id == f.ModuleId)?.ModuleName;
var result = querydata.Select(t => new ex_result
{
Department = t.Department,
Category = f.ItemName,
Fee = t.Value,
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = modulename,
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
}
}
catch (Exception ex)
{
logger.LogError($"typeId: {typeId}提取数据异常{ex}{Infrastructure.JsonHelper.Serialize(script)}");
}
}
logService.ReturnTheLog(allot.ID, groupName, 2, "提取数据", $"项目“{string.Join("、", thisItems.Select(t => t.ItemName))}”的数据已完成提取", 1, isSingle);
}
}
......@@ -350,29 +341,35 @@ private List<ex_result> ExtractSpecialData(per_allot allot, string groupName, bo
{
var config = configs.FirstOrDefault(t => t.Id == script.ConfigId);
if (config == null) continue;
var querydata = QueryData(config, allot, script.ExecScript);
if (querydata != null && querydata.Any())
try
{
thisSpecials.ForEach(f =>
var querydata = QueryData<ExtractDto>(config, script.ExecScript, allot, isSingle);
if (querydata != null && querydata.Any())
{
var result = querydata.Select(t => new ex_result
thisSpecials.ForEach(f =>
{
Department = f.Department,
Category = f.Target,
Fee = t.Value,
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = "4.2 特殊核算单元绩效测算表",
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
var result = querydata.Select(t => new ex_result
{
Department = f.Department,
Category = f.Target,
Fee = t.Value,
DoctorName = t.DoctorName,
PersonnelNumber = t.PersonnelNumber,
Source = "4.2 特殊核算单元绩效测算表",
TypeId = typeId,
DatabaseType = config.DataBaseType,
ConfigId = config.Id,
AllotId = allot.ID,
CreateTime = CreateTime,
}).ToList();
exresultRepository.InsertExecute(result.ToArray());
data.AddRange(result);
});
}
}
catch (Exception ex)
{
logger.LogError($"typeId: {typeId}提取数据异常{ex}{Infrastructure.JsonHelper.Serialize(script)}");
}
}
......@@ -396,62 +393,36 @@ private List<ex_result> ExtractSpecialData(per_allot allot, string groupName, bo
/// <param name="source"></param>
/// <param name="category"></param>
/// <returns></returns>
public IEnumerable<ExtractDto> QueryData(sys_hospitalconfig config, per_allot allot, string execsql)
public IEnumerable<T> QueryData<T>(sys_hospitalconfig config, string execsql, per_allot allot, bool isSingle)
{
var parameters = GetParameters(allot);
using (var connection = ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword))
{
return QueryData(connection, parameters, execsql);
}
}
/// <summary>
/// 查询数据
/// </summary>
/// <param name="config"></param>
/// <param name="allot"></param>
/// <param name="execsql"></param>
/// <param name="source"></param>
/// <param name="category"></param>
/// <returns></returns>
public IEnumerable<ExtractDto> QueryData(IDbConnection connection, Dictionary<string, string> parameters, string execsql)
{
foreach (var item in parameters)
{
execsql = Regex.Replace(execsql, item.Key, item.Value, RegexOptions.IgnoreCase);
}
logger.LogInformation($"提取绩效数据SQL脚本{execsql}");
var result = connection.Query<ExtractDto>(execsql, commandTimeout: 20000);
logger.LogInformation($"提取绩效数据执行脚本获取数据{result?.Count() ?? 0}条记录");
IDbConnection connection = null;
try
{
if (!pools.ContainsKey(config.Id))
pools.Add(config.Id, ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword));
connection = pools[config.Id];
return result;
}
if (connection == null) return Enumerable.Empty<T>();
/// <summary>
/// 查询数据
/// </summary>
/// <param name="config"></param>
/// <param name="allot"></param>
/// <param name="execsql"></param>
/// <param name="source"></param>
/// <param name="category"></param>
/// <returns></returns>
public IEnumerable<T> QueryData<T>(sys_hospitalconfig config, per_allot allot, string execsql)
{
var parameters = GetParameters(allot);
using (var connection = ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword))
if (connection.State == ConnectionState.Closed)
connection.Open();
}
catch
{
foreach (var item in parameters)
{
execsql = Regex.Replace(execsql, item.Key, item.Value, RegexOptions.IgnoreCase);
}
logService.ReturnTheLog(allot.ID, allot.ID.ToString(), 2, "数据库连接", $"数据库“{config.DbName}”连接失败", 3, isSingle);
}
logger.LogInformation($"提取绩效数据SQL脚本{execsql}");
var result = connection.Query<T>(execsql, commandTimeout: 20000);
logger.LogInformation($"提取绩效数据执行脚本获取数据{result?.Count() ?? 0}条记录");
logger.LogInformation($"提取绩效数据SQL脚本{execsql}");
var result = connection.Query<T>(execsql, commandTimeout: 20000);
logger.LogInformation($"提取绩效数据执行脚本获取数据{result?.Count() ?? 0}条记录");
return result;
}
return result;
}
/// <summary>
......
......@@ -63,7 +63,7 @@ public void WriteDataToCustom(IWorkbook workbook, per_allot allot, ExcelStyle st
sheet = workbook.CreateSheet(module.ModuleName);
workbook.SetSheetOrder(sheet.SheetName, workbook.NumberOfSheets - 1);
}
ClearSheetData(sheet);
var exscript = exscripts.FirstOrDefault(t => t.TypeId == module.TypeId);
if (exscript == null) continue;
......@@ -116,5 +116,35 @@ public void WriteDataToCustom(IWorkbook workbook, per_allot allot, ExcelStyle st
}
}
}
private void ClearSheetData(ISheet sheet)
{
try
{
for (int i = Point.DataFirstRowNum.Value; i < sheet.LastRowNum + 1; i++)
{
var row = sheet.GetRow(i);
if (row != null)
{
row.ZeroHeight = false; //取消隐藏行
int dataFirstCellRowNum = Point.DataFirstCellNum.Value;
//跳过核算单元和科室
for (int j = dataFirstCellRowNum; j < row.LastCellNum; j++)
{
var cell = row.GetCell(j);
if (cell != null && cell.CellType != CellType.Formula)
{
cell.RemoveCellComment();
row.RemoveCell(cell);
}
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex.Message);
}
}
}
}
......@@ -49,7 +49,7 @@ public void WriteSheetData(ISheet sheet, PerSheetPoint point, SheetType sheetTyp
if (exdict.ContainsKey(ExDataDict.IncomeFactor) && exdict[ExDataDict.IncomeFactor] is List<cof_drugtype_factor> factors && factors.Any(t => t.ExModuleId == module.Id))
{
factors = factors.Where(t => t.ExModuleId == module.Id).ToList();
categories = categories.Union(factors.Select(t => t.Charge)).Distinct();
// categories = categories.Union(factors.Select(t => t.Charge)).Distinct();
headers = categories.GroupJoin(factors, inner => new { category = inner.NoBlank() }, outer => new { category = outer.Charge.NoBlank() }, (inner, outer) => new { inner, outer })
.Select(t => new ExcelHeader
{
......
......@@ -511,44 +511,50 @@ public void SaveSecondAllotHeadData(int secondId, string json)
List<ag_worktype_source> insertData = new List<ag_worktype_source>();
var worktypeSources = agworktypesourceRepository.GetEntities(t => t.SecondId == secondId);
if (worktypeSources == null || !worktypeSources.Any())
//多工作量
var workTypes = agworkloadtypeRepository.GetEntities();
var workValue = new List<int>();
foreach (var item in keys)
{
var workTypes = agworkloadtypeRepository.GetEntities();
var workValue = new List<int>();
foreach (var item in keys)
{
var value = item.Replace("workload_ratio_", "").Replace("workload_amount_", "");
if (!Regex.IsMatch(value, @"^\d")) continue;
workValue.Add(Convert.ToInt32(value));
}
if (workValue == null || !workValue.Any())
return;
var value = item.Replace("workload_ratio_", "").Replace("workload_amount_", "");
if (!Regex.IsMatch(value, @"^\d")) continue;
workValue.Add(Convert.ToInt32(value));
}
if (workValue == null || !workValue.Any())
return;
foreach (var value in workValue)
foreach (var value in workValue)
{
for (int i = 0; i < prefix.Length; i++)
{
for (int i = 0; i < prefix.Length; i++)
var fieldId = prefix[i] + $"{value}";
var typeName = workTypes?.FirstOrDefault(t => t.Id == value)?.TypeName;
var source = new ag_worktype_source
{
var fieldId = prefix[i] + $"{value}";
var typeName = workTypes?.FirstOrDefault(t => t.Id == value)?.TypeName;
var source = new ag_worktype_source
{
WorkTypeId = value,
SecondId = secondId,
FieldId = fieldId,
FieldName = i == 0 ? typeName + "占比" : typeName + "金额",
Value = prefix[i].StartsWith(prefix[0]) ? (decimal?)Convert.ToDecimal(dict[fieldId.ToLower()]) : null,
};
insertData.Add(source);
WorkTypeId = value,
SecondId = secondId,
FieldId = fieldId,
FieldName = i == 0 ? typeName + "占比" : typeName + "金额",
Value = prefix[i].StartsWith(prefix[0]) ? (decimal?)Convert.ToDecimal(dict[fieldId.ToLower()]) : null,
};
insertData.Add(source);
}
}
agworktypesourceRepository.AddRange(insertData.ToArray());
}
foreach (var k in worktypeSources.Select(t => t.FieldId))
{
var remove = insertData.FirstOrDefault(t => t.FieldId.EqualsIgnoreCase(k));
if (remove != null)
{
insertData.Remove(remove);
}
}
agworktypesourceRepository.AddRange(insertData.ToArray());
worktypeSources = agworktypesourceRepository.GetEntities(t => t.SecondId == secondId);
foreach (var key in keys)
{
var update = worktypeSources.FirstOrDefault(t => t.FieldId.EqualsIgnoreCase(key));
......
......@@ -2376,17 +2376,17 @@ public List<DeptDataDetails> DeptComputeDetailList(int userId, int allotId, out
var userrole = userroleRepository.GetEntity(t => t.UserID == userId);
var role = roleRepository.GetEntity(t => t.ID == userrole.RoleID);
Dictionary<int, string> dict = new Dictionary<int, string>
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>
{
{ application.DirectorRole, AccountUnitType.科主任.ToString() },
{ application.NurseRole, AccountUnitType.护士长.ToString() },
{ application.OfficeRole, AccountUnitType.行政中层.ToString() },
{ application.SpecialRole, AccountUnitType.科主任.ToString() },
{ application.DirectorRole, new List<string>{ AccountUnitType.科主任.ToString()} },
{ application.NurseRole, new List<string>{ AccountUnitType.护士长.ToString() } },
{ application.OfficeRole, new List<string> { AccountUnitType.行政中层.ToString() } },
{ application.SpecialRole, new List<string> { AccountUnitType.科主任.ToString() , AccountUnitType.护士长.ToString() } },
};
if (!dict.Keys.Contains(role.Type.Value)) return new List<DeptDataDetails>();
var computes = rescomputeRepository.GetEntities(t => t.AllotID == allotId && t.AccountingUnit == user.Department && t.AccountType == dict[role.Type.Value]);
var computes = rescomputeRepository.GetEntities(t => t.AllotID == allotId && t.AccountingUnit == user.Department && dict[role.Type.Value].Contains(t.AccountType));
if (computes == null || !computes.Any()) return new List<DeptDataDetails>();
foreach (var item in computes)
{
......
......@@ -782,6 +782,9 @@ public string SaveUserHandsFlat(UserCollectData request)
{
if (item == null) return "必填项为空";
var HospitalId = hospitals.FirstOrDefault(w => w.HosName == item)?.ID;
if (HospitalId == null) return "未找到分配医院";
var allot = _perallotRepository.GetEntities(t => t.HospitalId == HospitalId);
var accountingUnits = accounts?.Join(allot, t => t.AllotId, w => w.ID, (t, w) => t.AccountingUnit).Distinct().ToList();
res.Add(item, accountingUnits);
......
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