自定义抽取

parent a6201a51
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Services; using Performance.Services;
namespace Performance.Api.Controllers namespace Performance.Api.Controllers
{ {
[Route("api/[controller]")] [Route("api/extract")]
public class ModExtractController : Controller public class ModExtractController : Controller
{ {
private readonly ILogger<ModExtractController> _logger; private readonly ClaimService _claim;
private readonly CustomExtractService _service; private readonly CustomExtractService _service;
public ModExtractController( public ModExtractController(
ILogger<ModExtractController> logger, ClaimService claim,
CustomExtractService service) CustomExtractService service)
{ {
_logger = logger; _claim = claim;
_service = service; _service = service;
} }
[HttpPost("custom/{allotId}")]
public ApiResponse CustomExtract(int allotId)
{
if (_service.ExtractData(_claim.GetUserId(), allotId, out string resultFilePath))
{
return new ApiResponse(ResponseType.OK, new { path = resultFilePath });
}
return new ApiResponse(ResponseType.Fail, new { path = "" });
}
} }
} }
\ No newline at end of file
...@@ -1668,6 +1668,41 @@ ...@@ -1668,6 +1668,41 @@
0 可见 1 不可见 0 可见 1 不可见
</summary> </summary>
</member> </member>
<member name="T:Performance.EntityModels.cust_script">
<summary>
自定义导出
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.ID">
<summary>
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.HospitalId">
<summary>
医院ID
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.IsOnceAllot">
<summary>
是否允许一次分配下载 1 允许 2 禁止
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.IsSecondAllot">
<summary>
是否允许二次分配下载 1 允许 2 禁止
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.ConfigId">
<summary>
配置Id
</summary>
</member>
<member name="P:Performance.EntityModels.cust_script.IsEnable">
<summary>
是否可用 1 可用 2 不可用
</summary>
</member>
<member name="T:Performance.EntityModels.ex_item"> <member name="T:Performance.EntityModels.ex_item">
<summary> <summary>
......
//-----------------------------------------------------------------------
// <copyright file="cust_script.cs">
// * FileName: cust_script.cs
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Performance.EntityModels
{
/// <summary>
/// 自定义导出
/// </summary>
[Table("cust_script")]
public class cust_script
{
/// <summary>
///
/// </summary>
[Key]
public int ID { get; set; }
/// <summary>
/// 医院ID
/// </summary>
public int HospitalId { get; set; }
/// <summary>
/// 是否允许一次分配下载 1 允许 2 禁止
/// </summary>
public int IsOnceAllot { get; set; }
/// <summary>
/// 是否允许二次分配下载 1 允许 2 禁止
/// </summary>
public int IsSecondAllot { get; set; }
public string Name { get; set; }
public string Script { get; set; }
/// <summary>
/// 配置Id
/// </summary>
public int ConfigId { get; set; }
/// <summary>
/// 是否可用 1 可用 2 不可用
/// </summary>
public int IsEnable { get; set; }
}
}
//-----------------------------------------------------------------------
// <copyright file=" ag_againsituation.cs">
// * FileName: ag_againsituation.cs
// </copyright>
//-----------------------------------------------------------------------
using Performance.EntityModels;
using System;
namespace Performance.Repository
{
/// <summary>
/// collect_data Repository
/// </summary>
public partial class PerforcustscriptRepository : PerforRepository<cust_script>
{
public PerforcustscriptRepository(PerformanceDbContext context) : base(context)
{
}
}
}
using System; using Dapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Repository;
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
namespace Performance.Services namespace Performance.Services
{ {
public class CustomExtractService : IAutoInjection public class CustomExtractService : IAutoInjection
{ {
private readonly ILogger<CustomExtractService> _logger;
private readonly IOptions<Application> _options;
private readonly UserService _userService;
private readonly RoleService _roleService;
private readonly PerforPerallotRepository _perallotRepository;
private readonly PerforHospitalconfigRepository _perforHospitalconfigRepository;
private readonly PerforcustscriptRepository _perforcustscriptRepository;
public CustomExtractService(
ILogger<CustomExtractService> logger,
IOptions<Application> options,
UserService userService,
RoleService roleService,
PerforPerallotRepository perallotRepository,
PerforHospitalconfigRepository perforHospitalconfigRepository,
PerforcustscriptRepository perforcustscriptRepository)
{
_logger = logger;
_options = options;
_userService = userService;
_roleService = roleService;
_perallotRepository = perallotRepository;
_perforHospitalconfigRepository = perforHospitalconfigRepository;
_perforcustscriptRepository = perforcustscriptRepository;
}
public bool ExtractData(int userId, int allotId, out string resultFilePath)
{
bool result = true;
var allot = _perallotRepository.GetEntity(w => w.ID == allotId)
?? throw new PerformanceException("绩效ID无效");
var filePath = ExtractHelper.GetExtractFile(allot.HospitalId);
resultFilePath = filePath;
var scripts = _perforcustscriptRepository.GetEntities(w => w.HospitalId == allot.HospitalId && w.IsEnable == 1);
if (scripts != null)
{
result = false;
return result;
}
if (IsSecondAdmin(userId))
scripts = scripts.Where(w => w.IsOnceAllot == 2 && w.IsSecondAllot == 1).ToList();
else
scripts = scripts.Where(w => w.IsOnceAllot == 1 && w.IsSecondAllot == 2).ToList();
IWorkbook workbook = null;
try
{
workbook = ExcelHelper.GetWorkbook(filePath);
ExcelStyle style = new ExcelStyle(workbook);
WriteDataToFile(userId, allot, scripts, workbook);
}
catch (Exception ex)
{
allot.IsExtracting = 3;
resultFilePath = "";
result = false;
_logger.LogError("提取数据中发生异常: " + ex.ToString());
}
finally
{
using (FileStream file = new FileStream(filePath, FileMode.OpenOrCreate))
{
workbook.Write(file);
}
workbook.Close();
}
return result;
}
private void WriteDataToFile(int userId, per_allot allot, List<cust_script> scripts, IWorkbook workbook)
{
var configs = _perforHospitalconfigRepository.GetEntities(t => t.HospitalId == allot.HospitalId)
?? throw new PerformanceException("当前医院没有数据库地址配置");
var parameters = GetParameters(allot, userId);
foreach (var item in scripts)
{
var conf = configs.FirstOrDefault(w => w.Id == item.ConfigId);
if (conf != null)
{
var execsql = item.Script;
var dynamics = QueryData(conf, execsql, parameters);
try
{
var sheet = workbook.CreateSheet(item.Name);
var headers = ((IDictionary<string, object>)dynamics.ElementAt(0)).Keys;
var hrow = sheet.GetOrCreate(0);
for (int col = 0; col < headers.Count; col++)
{
var cell = hrow.CreateCell(col + 1);
cell.SetCellOValue(headers.ElementAt(col));
}
for (int col = 0; col < headers.Count; col++)
{
for (int row = 0; row < dynamics.Count(); row++)
{
var key = headers.ElementAt(col);
var data = dynamics.ElementAt(row);
var temp = (IDictionary<string, object>)data;
var value = temp[key]?.ToString() ?? "";
var srow = sheet.GetOrCreate(row + 1);
var cell = srow.CreateCell(col + 1);
cell.SetCellOValue(value);
}
}
}
catch (Exception ex)
{
_logger.LogError($"提取绩效数据写入错误:{item.Name}{ex}");
}
}
}
}
/// <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<dynamic> QueryData(sys_hospitalconfig config, string execsql, Dictionary<string, string> parameters)
{
try
{
using (var connection = ConnectionBuilder.Create((DatabaseType)config.DataBaseType, config.DbSource, config.DbName, config.DbUser, config.DbPassword))
{
foreach (var item in parameters)
{
execsql = Regex.Replace(execsql, item.Key, item.Value, RegexOptions.IgnoreCase);
}
_logger.LogInformation($"提取绩效数据SQL脚本{execsql}");
var result = connection.Query(execsql, commandTimeout: 20000);
_logger.LogInformation($"提取绩效数据执行脚本获取数据{result?.Count() ?? 0}条记录");
return result;
}
}
catch (Exception ex)
{
_logger.LogError($"提取绩效数据SQL脚本查询错误:{execsql} 错误原因:{ex}");
}
return null;
}
/// <summary>
/// 获取参数
/// </summary>
/// <param name="allot"></param>
/// <returns></returns>
private Dictionary<string, string> GetParameters(per_allot allot, int userId)
{
DateTime beginTime = new DateTime(allot.Year, allot.Month, 1);
Dictionary<string, string> pairs = new Dictionary<string, string>
{
{ "@beginTime", $"'{beginTime.ToString("yyyy-MM-dd")}'" },
{ "@endTime", $"'{beginTime.AddMonths(1).ToString("yyyy-MM-dd")}'"},
{ "@department", GetUserDepartment(userId) },
};
return pairs;
}
/// <summary>
/// 是否是二次分配管理员 是 true 否 false
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
private bool IsSecondAdmin(int userId)
{
var role = _roleService.GetRole(userId);
int[] roleArray = new int[] { _options.Value.NurseRole, _options.Value.DirectorRole, _options.Value.SpecialRole, _options.Value.OfficeRole };
return roleArray.Contains(role?.FirstOrDefault().ID ?? 0);
}
/// <summary>
/// 返回二次分配管理科室 默认 返回 空值
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
private string GetUserDepartment(int userId)
{
var user = _userService.GetUser(userId)
?? throw new PerformanceException("当前用户信息无效");
return IsSecondAdmin(userId) ? string.Empty : user.Department;
}
} }
} }
\ No newline at end of file
...@@ -22,6 +22,13 @@ public static string GetExtractFile(int hospitalId, ref string newFilePath, stri ...@@ -22,6 +22,13 @@ public static string GetExtractFile(int hospitalId, ref string newFilePath, stri
return tempPath; return tempPath;
} }
public static string GetExtractFile(int hospitalId, string prefix = "绩效提取数据")
{
var dpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", $"{hospitalId}", "autoextract");
FileHelper.CreateDirectory(dpath);
return Path.Combine(dpath, $"{prefix}{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xls");
}
private static (string TempPath, string FilePath) CopyOriginalFile(int hospitalId, string originalPath) private static (string TempPath, string FilePath) CopyOriginalFile(int hospitalId, string originalPath)
{ {
var ext = FileHelper.GetExtension(originalPath); var ext = FileHelper.GetExtension(originalPath);
......
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