Compare commits

..

59 Commits

Author SHA1 Message Date
hang b0ef2dc8ab 修改审核时间修改
continuous-integration/drone/push Build is passing
2024-08-02 15:41:29 +08:00
hang ccf4bbdff9 CRC 上传导表
continuous-integration/drone/push Build is passing
2024-08-02 11:48:09 +08:00
hang c3e36991b8 质控增加字段
continuous-integration/drone/push Build is passing
2024-08-02 11:29:41 +08:00
hang 81f6c10f23 QCAgreeUpload 才允许修改
continuous-integration/drone/push Build is passing
2024-08-01 17:22:10 +08:00
hang 719ca071e1 crc 重传允许修改部位编辑
continuous-integration/drone/push Build is passing
2024-08-01 17:06:17 +08:00
hang dad420a7e8 Merge branch 'Uat_IRC_Net8' of http://192.168.3.68:2000/XCKJ/irc-netcore-api into Uat_IRC_Net8
continuous-integration/drone/push Build is passing
2024-07-31 14:34:30 +08:00
hang d84aedf135 邮件昵称修改 2024-07-31 14:34:29 +08:00
hang 34f3b1607e 修改隐藏邮箱的算法
continuous-integration/drone/push Build is passing
2024-07-31 10:04:58 +08:00
hang 7fa73e0054 修改us配置文件
continuous-integration/drone/push Build is passing
2024-07-29 11:47:02 +08:00
hang c146c2bfd2 修改uat 美国配置文件
continuous-integration/drone/push Build is passing
2024-07-29 11:27:02 +08:00
hang 2a1220899e 重阅自动失效,错误消息位置改变
continuous-integration/drone/push Build is passing
2024-07-25 14:22:19 +08:00
hang 874d36de28 同意重阅,成功,但是给出自动失效的提示
continuous-integration/drone/push Build is passing
2024-07-25 13:54:57 +08:00
hang 0283052555 修改,无序重阅 和审批
continuous-integration/drone/push Build is passing
2024-07-25 10:13:26 +08:00
hang effef5ad65 修改IR 无序阅片申请bug
continuous-integration/drone/push Build is passing
2024-07-24 16:25:53 +08:00
hang 43d260e036 修改美国环境配置,使用AWS
continuous-integration/drone/push Build is passing
2024-07-19 17:17:53 +08:00
hang 19708240b2 oss 下载走内网地址
continuous-integration/drone/push Build is passing
2024-07-19 16:13:33 +08:00
hang 0999bae749 修改非dicom 监控上传
continuous-integration/drone/push Build is passing
2024-07-19 09:04:55 +08:00
hang e6bd35ae04 url 解码下载修改
continuous-integration/drone/push Build is passing
2024-07-17 18:00:17 +08:00
he 102e193ae8 修改
continuous-integration/drone/push Build is passing
2024-07-17 10:19:51 +08:00
he 20d557e795 Merge branch 'Uat_IRC_Net8' of https://gitea.frp.extimaging.com/XCKJ/irc-netcore-api into Uat_IRC_Net8
continuous-integration/drone/push Build is passing
2024-07-17 10:10:29 +08:00
he 593ab42882 修改 2024-07-17 10:10:28 +08:00
hang b56d256e10 去掉权限,方便前端测试
continuous-integration/drone/push Build is passing
2024-07-16 10:59:46 +08:00
he 614a3bd70e 返回值修改
continuous-integration/drone/push Build is passing
2024-07-16 10:10:12 +08:00
he 2eb3b04365 Merge branch 'Uat_IRC_Net8' of https://gitea.frp.extimaging.com/XCKJ/irc-netcore-api into Uat_IRC_Net8
continuous-integration/drone/push Build is passing
2024-07-16 09:57:34 +08:00
he 1fa3a5a181 加返回参数 2024-07-16 09:57:33 +08:00
hang cd2007c4fd 减少压缩包访视层级,同时处理单个非dicom 特殊情况压缩包处理
continuous-integration/drone/push Build is passing
2024-07-15 16:55:21 +08:00
hang 67e710eac0 增加打包下载验证
continuous-integration/drone/push Build is passing
2024-07-15 16:28:29 +08:00
hang ef451d82ec 修改ivus影像下载功能
continuous-integration/drone/push Build is passing
2024-07-15 15:46:31 +08:00
he 899ebf2a30 跳过阅片修改
continuous-integration/drone/push Build is passing
2024-07-15 14:43:49 +08:00
he f233d27f96 Merge branch 'Uat_IRC_Net8' of https://gitea.frp.extimaging.com/XCKJ/irc-netcore-api into Uat_IRC_Net8
continuous-integration/drone/push Build is passing
2024-07-15 14:13:14 +08:00
he 9e8ab8acca 跳过阅片修改 2024-07-15 14:13:14 +08:00
hang 2265387f47 Uat 自动打包发布
continuous-integration/drone/push Build is passing
2024-07-15 13:12:43 +08:00
he baf8f39bc6 提示语修改
continuous-integration/drone/push Build is passing
2024-07-12 10:30:44 +08:00
he 3fa14d92ae 配置文件修改
continuous-integration/drone/push Build is passing
2024-07-11 17:29:38 +08:00
he e6c577e68b 阅片时间修改到配置文件
continuous-integration/drone/push Build is passing
2024-07-11 17:28:18 +08:00
hang bb111dbbeb 修改发布文件
continuous-integration/drone/push Build is passing
2024-07-11 15:26:22 +08:00
hang 0df0b10a72 增加用户机构默认值修改
continuous-integration/drone/push Build is failing
2024-07-11 10:14:46 +08:00
hang 0a7ba9f0f5 修改字段名
continuous-integration/drone/push Build is failing
2024-07-11 09:42:15 +08:00
hang cd88990c32 spm cpm 返回增加字段 2024-07-11 09:42:03 +08:00
hang d53a1300fc 增加uat irc 自动打包成镜像
continuous-integration/drone/push Build is passing
2024-07-10 16:49:59 +08:00
hang 07332ff3e1 修改发送邮件配置 2024-07-09 13:12:59 +08:00
hang 8195a1cf3e 修改发件箱 2024-07-09 09:50:30 +08:00
hang f5e5a47624 修改美国irc uat 数据库名称 2024-07-09 09:40:32 +08:00
hang 28608f3ecb 美国验证增加配置文件 2024-07-08 11:39:30 +08:00
hang bb2da7ca81 修改配置文件 2024-07-05 09:07:57 +08:00
hang 713518a68c 增加美国生产环境配置文件 2024-07-04 14:31:50 +08:00
he bc448da297 Merge branch 'Uat_IRC_Net8' of https://gitea.frp.extimaging.com/XCKJ/irc-netcore-api into Uat_IRC_Net8 2024-07-03 15:15:48 +08:00
he 8447878cb2 代码修改 2024-07-03 15:15:46 +08:00
hang 1b5a9673f6 修改一致性核查颜色 2024-07-02 17:16:46 +08:00
he 27711f4184 关键序列修改 2024-07-02 09:33:42 +08:00
he bb9bac1edf 修改医学审核排序 2024-07-01 16:45:07 +08:00
hang 41ae2febc7 改为阿里云 2024-06-26 15:12:06 +08:00
hang c072c526e2 修改uat 配置文件 2024-06-26 14:36:56 +08:00
hang d6bb98b84f 中心调研修改 2024-06-25 10:57:42 +08:00
hang 42587ee59f 删掉邮件日志组件 2024-06-25 09:17:28 +08:00
hang 62a964a3ea 发送邮件的包降级 2024-06-25 09:01:58 +08:00
hang 72447eb82f 修改 界面控制bug 2024-06-24 16:53:53 +08:00
hang 2f83c27fde 修改筛选条件 2024-06-24 16:39:43 +08:00
hang b219593f61 医生入组,没有spm修改逻辑 2024-06-24 16:39:40 +08:00
498 changed files with 16770 additions and 26270 deletions
-4
View File
@@ -1,4 +0,0 @@
FROM registry.cn-shanghai.aliyuncs.com/extimaging/aspnetcore:v8.2
WORKDIR /app
COPY publish .
ENTRYPOINT ["dotnet", "IRaCIS.Core.API.dll"]
@@ -1,37 +0,0 @@
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
namespace IRaCIS.Core.SCP.Filter
{
public class ModelActionFilter : ActionFilterAttribute, IActionFilter
{
public IStringLocalizer _localizer;
public ModelActionFilter(IStringLocalizer localizer)
{
_localizer = localizer;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var validationErrors = context.ModelState
.Keys
.SelectMany(k => context.ModelState[k]!.Errors)
.Select(e => e.ErrorMessage)
.ToArray();
//---提供给接口的参数无效。
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["ModelAction_InvalidAPIParameter"] + JsonConvert.SerializeObject( validationErrors)));
}
}
}
}
@@ -1,28 +0,0 @@
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace IRaCIS.Core.SCP.Filter
{
#region snippet_DisableFormValueModelBindingAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
var factories = context.ValueProviderFactories;
//factories.RemoveType<FormValueProviderFactory>();
factories.RemoveType<FormFileValueProviderFactory>();
factories.RemoveType<JQueryFormValueProviderFactory>();
context.HttpContext.Request.EnableBuffering();
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
}
#endregion
}
@@ -1,61 +0,0 @@
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
namespace IRaCIS.Core.SCP.Filter
{
public class ProjectExceptionFilter : Attribute, IExceptionFilter
{
private readonly ILogger<ProjectExceptionFilter> _logger;
public IStringLocalizer _localizer;
public ProjectExceptionFilter(IStringLocalizer localizer, ILogger<ProjectExceptionFilter> logger)
{
_logger = logger;
_localizer = localizer;
}
public void OnException(ExceptionContext context)
{
//context.ExceptionHandled;//记录当前这个异常是否已经被处理过了
if (!context.ExceptionHandled)
{
if (context.Exception.GetType().Name == "DbUpdateConcurrencyException")
{
//---并发更新,当前不允许该操作
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["ProjectException_ConcurrentUpdateNotAllowed"] + context.Exception.Message));
}
if (context.Exception.GetType() == typeof(BusinessValidationFailedException))
{
var error = context.Exception as BusinessValidationFailedException;
context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message, error!.Code));
}
else if(context.Exception.GetType() == typeof(QueryBusinessObjectNotExistException))
{
context.Result = new JsonResult(ResponseOutput.NotOk( context.Exception.Message, ApiResponseCodeEnum.DataNotExist));
}
else
{
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["Project_ExceptionContactDeveloper"] + (context.Exception.InnerException is null ? (context.Exception.Message /*+ context.Exception.StackTrace*/)
: (context.Exception.InnerException?.Message /*+ context.Exception.InnerException?.StackTrace*/)), ApiResponseCodeEnum.ProgramException));
}
_logger.LogError(context.Exception.InnerException is null ? (context.Exception.Message + context.Exception.StackTrace) : (context.Exception.InnerException?.Message + context.Exception.InnerException?.StackTrace));
}
else
{
//继续
}
context.ExceptionHandled = true;//标记当前异常已经被处理过了
}
}
}
@@ -1,120 +0,0 @@
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure.Extention;
namespace IRaCIS.Application.Services.BusinessFilter
{
/// <summary>
/// 统一返回前端数据包装,之前在控制器包装,现在修改为动态Api 在ResultFilter这里包装,减少重复冗余代码
/// by zhouhang 2021.09.12 周末
/// </summary>
public class UnifiedApiResultFilter : Attribute, IAsyncResultFilter
{
/// <summary>
/// 异步版本
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if (context.Result is ObjectResult objectResult)
{
var statusCode = objectResult.StatusCode ?? context.HttpContext.Response.StatusCode;
//是200 并且没有包装 那么包装结果
if (statusCode == 200 && !(objectResult.Value is IResponseOutput))
{
//if (objectResult.Value == null)
//{
// var apiResponse = ResponseOutput.DBNotExist();
// objectResult.Value = apiResponse;
// objectResult.DeclaredType = apiResponse.GetType();
//}
//else
//{
var type = objectResult.Value?.GetType();
if ( type!=null&& type.IsGenericType&&(type.GetGenericTypeDefinition()==typeof(ValueTuple<,>)|| type.GetGenericTypeDefinition()==typeof(Tuple<,>)))
{
//报错
//var tuple = (object, object))objectResult.Value;
//var (val1, val2) = ((dynamic, dynamic))objectResult.Value;
//var apiResponse = ResponseOutput.Ok(val1, val2);
//OK
var tuple = (dynamic)objectResult.Value;
var apiResponse = ResponseOutput.Ok(tuple.Item1, tuple.Item2);
objectResult.Value = apiResponse;
objectResult.DeclaredType = apiResponse.GetType();
}
else
{
var apiResponse = ResponseOutput.Ok(objectResult.Value);
objectResult.Value = apiResponse;
objectResult.DeclaredType = apiResponse.GetType();
}
//}
}
//如果不是200 是IResponseOutput 不处理
else if (statusCode != 200 && (objectResult.Value is IResponseOutput))
{
}
else if(statusCode != 200&&!(objectResult.Value is IResponseOutput))
{
//---程序错误,请联系开发人员。
var apiResponse = ResponseOutput.NotOk(StaticData.International("UnifiedAPI_ProgramError"));
objectResult.Value = apiResponse;
objectResult.DeclaredType = apiResponse.GetType();
}
}
await next.Invoke();
}
public static bool IsTupleType(Type type, bool checkBaseTypes = false)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type == typeof(Tuple))
return true;
while (type != null)
{
if (type.IsGenericType)
{
var genType = type.GetGenericTypeDefinition();
if (genType == typeof(Tuple<>)
|| genType == typeof(Tuple<,>)
|| genType == typeof(Tuple<,>))
return true;
}
if (!checkBaseTypes)
break;
type = type.BaseType;
}
return false;
}
}
}
-62
View File
@@ -1,62 +0,0 @@
using FellowOakDicom.Imaging;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using System.Security.Cryptography;
using System.Text;
namespace IRaCIS.Core.Application.Helper;
public static class ImageHelper
{
// 采用ImageSharp组件 跨平台,不依赖windows 平台图像处理组件,这里大坑(net 6 下,之前由于Dicom处理最新组件 依赖了这个库的一个旧版本,导致缩略图bug,单独升级依赖组件才解决)
public static void ResizeSave(string filePath, string? fileStorePath)
{
fileStorePath = fileStorePath ?? filePath + ".preview.jpeg";
using (var image = SixLabors.ImageSharp.Image.Load(filePath))
{
image.Mutate(x => x.Resize(500, 500));
image.Save(fileStorePath);
}
}
public static Stream RenderPreviewJpeg(string filePath)
{
string jpegPath = filePath + ".preview.jpg";
if (!File.Exists(jpegPath))
{
using (Stream stream = new FileStream(jpegPath, FileMode.Create))
{
DicomImage image = new DicomImage(filePath);
var sharpimage = image.RenderImage().AsSharpImage();
sharpimage.Save(stream, new JpegEncoder());
}
}
return new FileStream(jpegPath, FileMode.Open);
}
public static void RemovePreviewJpeg(string filePath)
{
string jpegPath = filePath + ".preview.jpg";
if (File.Exists(jpegPath)) File.Delete(jpegPath);
}
}
@@ -1,57 +0,0 @@
using Autofac;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Http;
using Panda.DynamicWebApi;
using System;
using System.Linq;
using System.Reflection;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Application.Services;
using AutoMapper;
using IRaCIS.Core.SCP.Service;
namespace IRaCIS.Core.SCP
{
// ReSharper disable once IdentifierTypo
public class AutofacModuleSetup : Autofac.Module
{
protected override void Load(ContainerBuilder containerBuilder)
{
#region byzhouhang 20210917 Domain层 Infra.EFcore
containerBuilder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>)).InstancePerLifetimeScope();//注册泛型仓储
containerBuilder.RegisterType<Repository>().As<IRepository>().InstancePerLifetimeScope();
#endregion
#region autofac https://www.cnblogs.com/xwhqwer/p/15320838.html
//获取所有控制器类型并使用属性注入
containerBuilder.RegisterAssemblyTypes(typeof(BaseService).Assembly)
.Where(type => typeof(IDynamicWebApi).IsAssignableFrom(type))
.PropertiesAutowired();
#endregion
Assembly application = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + typeof(BaseService).Assembly.GetName().Name+".dll");
containerBuilder.RegisterAssemblyTypes(application).Where(t => t.FullName.Contains("Service"))
.PropertiesAutowired().AsImplementedInterfaces();
//containerBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
//containerBuilder.RegisterType<UserInfo>().As<IUserInfo>().InstancePerLifetimeScope();
}
}
}
-64
View File
@@ -1,64 +0,0 @@
using EntityFramework.Exceptions.SqlServer;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using Medallion.Threading;
using Medallion.Threading.SqlServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace IRaCIS.Core.SCP
{
public static class EFSetup
{
public static void AddEFSetup( this IServiceCollection services, IConfiguration configuration)
{
services.AddHttpContextAccessor();
services.AddScoped<IUserInfo, UserInfo>();
services.AddScoped<ISaveChangesInterceptor, AuditEntityInterceptor>();
//这个注入没有成功--注入是没问题的,构造函数也只是支持参数就好,错在注入的地方不能写DbContext
//Web程序中通过重用池中DbContext实例可提高高并发场景下的吞吐量, 这在概念上类似于ADO.NET Provider原生的连接池操作方式,具有节省DbContext实例化成本的优点
services.AddDbContext<IRaCISDBContext>((sp, options) =>
{
// 在控制台
//public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
var logFactory = LoggerFactory.Create(builder => { builder.AddDebug(); });
options.UseSqlServer(configuration.GetSection("ConnectionStrings:RemoteNew").Value,
contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure());
options.UseLoggerFactory(logFactory);
options.UseExceptionProcessor();
options.EnableSensitiveDataLogging();
options.AddInterceptors(new QueryWithNoLockDbCommandInterceptor());
options.AddInterceptors(sp.GetServices<ISaveChangesInterceptor>());
options.UseProjectables();
});
//// Register an additional context factory as a Scoped service, which gets a pooled context from the Singleton factory we registered above,
//services.AddScoped<IRaCISDBScopedFactory>();
//// Finally, arrange for a context to get injected from our Scoped factory:
//services.AddScoped(sp => sp.GetRequiredService<IRaCISDBScopedFactory>().CreateDbContext());
//注意区分 easy caching 也有 IDistributedLockProvider
services.AddSingleton<IDistributedLockProvider>(sp =>
{
//var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]!);
return new SqlDistributedSynchronizationProvider(configuration.GetSection("ConnectionStrings:RemoteNew").Value);
});
}
}
}
@@ -1,59 +0,0 @@
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
namespace IRaCIS.Core.SCP
{
public static class NewtonsoftJsonSetup
{
public static void AddNewtonsoftJsonSetup(this IMvcBuilder builder, IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<IOSSService,OSSService>();
builder.AddNewtonsoftJson(options =>
{
//options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
// 忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
//处理返回给前端 可空类型 给出默认值 比如in? 为null 设置 默认值0
options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver(); //new DefaultContractResolver();// new NullToEmptyStringResolver();
// 设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
//options.SerializerSettings.Converters.Add(new JSONCustomDateConverter()) ;
//options.SerializerSettings.Converters.Add(services.BuildServiceProvider().GetService<JSONTimeZoneConverter>());
})
.AddControllersAsServices()//动态webApi属性注入需要
.ConfigureApiBehaviorOptions(o =>
{
o.SuppressModelStateInvalidFilter = true; //自己写验证
});
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
//日期类型默认格式化处理
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return setting;
});
}
}
}
@@ -1,36 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
namespace IRaCIS.Core.SCP
{
public class NullToEmptyStringResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
var list= type.GetProperties()
.Select(p =>
{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyStringValueProvider(p);
return jp;
}).ToList();
var uu = list.Select(t => t.PropertyName).ToList();
//获取复杂对象属性
properties = properties.TakeWhile(t => !uu.Contains(t.PropertyName)).ToList();
list.AddRange(properties);
return list;
}
}
}
@@ -1,42 +0,0 @@
using System;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace IRaCIS.Core.SCP
{
public class NullToEmptyStringValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
}
public object GetValue(object target)
{
object result = _MemberInfo.GetValue(target);
if (_MemberInfo.PropertyType == typeof(string) && result == null) result = "";
else if (_MemberInfo.PropertyType == typeof(String[]) && result == null) result = new string[] { };
//else if (_MemberInfo.PropertyType == typeof(Nullable<Int32>) && result == null) result = 0;
else if (_MemberInfo.PropertyType == typeof(Nullable<Decimal>) && result == null) result = 0.00M;
return result;
}
public void SetValue(object target, object value)
{
if(_MemberInfo.PropertyType == typeof(string))
{
//去掉前后空格
_MemberInfo.SetValue(target, value==null?string.Empty: value.ToString()==string.Empty? value:value.ToString().Trim());
}
else
{
_MemberInfo.SetValue(target, value);
}
}
}
}
-36
View File
@@ -1,36 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.14.1" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="DistributedLock.Core" Version="1.0.7" />
<PackageReference Include="DistributedLock.SqlServer" Version="1.0.5" />
<PackageReference Include="fo-dicom" Version="5.1.3" />
<PackageReference Include="fo-dicom.Codecs" Version="5.14.5" />
<PackageReference Include="fo-dicom.Imaging.ImageSharp" Version="5.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.8" />
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Minio" Version="6.0.3" />
<PackageReference Include="My.Extensions.Localization.Json" Version="3.3.0">
<TreatAsUsed>true</TreatAsUsed>
</PackageReference>
<PackageReference Include="Panda.DynamicWebApi" Version="1.2.2" />
<PackageReference Include="Serilog.Enrichers.ClientInfo" Version="2.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\IRaCIS.Core.Domain\IRaCIS.Core.Domain.csproj" />
<ProjectReference Include="..\IRaCIS.Core.Infra.EFCore\IRaCIS.Core.Infra.EFCore.csproj" />
</ItemGroup>
</Project>
-214
View File
@@ -1,214 +0,0 @@
using Autofac;
using Autofac.Extensions.DependencyInjection;
using AutoMapper.EquivalencyExpression;
using FellowOakDicom;
using FellowOakDicom.Imaging;
using FellowOakDicom.Imaging.NativeCodec;
using FellowOakDicom.Network;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.SCP;
using IRaCIS.Core.SCP.Filter;
using IRaCIS.Core.SCP.Service;
using MassTransit;
using MassTransit.NewIdProviders;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Panda.DynamicWebApi;
using Serilog;
using Serilog.Events;
using System.Runtime.InteropServices;
//以配置文件为准,否则 从url中取环境值(服务以命令行传递参数启动,配置文件配置了就不需要传递环境参数)
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var enviromentName = config["ASPNETCORE_ENVIRONMENT"];
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
EnvironmentName = enviromentName
});
#region windows
int urlsIndex = Array.FindIndex(args, arg => arg != null && arg.StartsWith("--port"));
if (urlsIndex > -1)
{
var port = args[urlsIndex].Substring("--port=".Length);
Console.WriteLine(port);
builder.WebHost.UseUrls($"http://0.0.0.0:{port}");
}
#endregion
#region
NewId.SetProcessIdProvider(new CurrentProcessIdProvider());
builder.Configuration.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{enviromentName}.json", false, true);
builder.Host
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.RegisterModule<AutofacModuleSetup>();
})
.UseSerilog();
#endregion
#region
var _configuration = builder.Configuration;
//健康检查
builder.Services.AddHealthChecks();
//本地化
builder.Services.AddJsonLocalization(options => options.ResourcesPath = "Resources");
// 异常、参数统一验证过滤器、Json序列化配置、字符串参数绑型统一Trim()
builder.Services.AddControllers(options =>
{
options.Filters.Add<ModelActionFilter>();
options.Filters.Add<ProjectExceptionFilter>();
options.Filters.Add<UnitOfWorkFilter>();
})
.AddNewtonsoftJsonSetup(builder.Services); // NewtonsoftJson 序列化 处理
builder.Services.AddOptions().Configure<AliyunOSSOptions>(_configuration.GetSection("AliyunOSS"));
builder.Services.AddOptions().Configure<ObjectStoreServiceOptions>(_configuration.GetSection("ObjectStoreService"));
builder.Services.AddOptions().Configure<DicomSCPServiceOption>(_configuration.GetSection("DicomSCPServiceConfig"));
//动态WebApi + UnifiedApiResultFilter 省掉控制器代码
//动态webApi 目前存在的唯一小坑是生成api上服务上的动态代理AOP失效 间接掉用不影响
builder.Services
.AddDynamicWebApi(dynamicWebApiOption =>
{
//默认是 api
dynamicWebApiOption.DefaultApiPrefix = "";
//首字母小写
dynamicWebApiOption.GetRestFulActionName = (actionName) => char.ToLower(actionName[0]) + actionName.Substring(1);
//删除 Service后缀
dynamicWebApiOption.RemoveControllerPostfixes.Add("Service");
});
//AutoMapper
builder.Services.AddAutoMapper(automapper =>
{
automapper.AddCollectionMappers();
}, typeof(BaseService).Assembly);
//EF ORM QueryWithNoLock
builder.Services.AddEFSetup(_configuration);
//转发头设置 获取真实IP
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
//Dicom影像渲染图片 跨平台
//builder.Services.AddDicomSetup();
new DicomSetupBuilder()
.RegisterServices(s =>
s.AddFellowOakDicom()
.AddTranscoderManager<NativeTranscoderManager>()
//.AddTranscoderManager<FellowOakDicom.Imaging.NativeCodec.NativeTranscoderManager>()
.AddImageManager<ImageSharpImageManager>())
.SkipValidation()
.Build();
#endregion
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}
app.UseAuthorization();
app.MapControllers();
#region
//Log.Logger = new LoggerConfiguration()
// .MinimumLevel.Information()
// .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
// // Filter out ASP.NET Core infrastructre logs that are Information and below 日志太多了 一个请求 记录好几条
// .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
// .MinimumLevel.Override("Hangfire", LogEventLevel.Warning)
// .MinimumLevel.Override("System.Net.Http.HttpClient.HttpReports", LogEventLevel.Warning)
// .Enrich.WithClientIp()
// .Enrich.FromLogContext()
// //控制台 方便调试 问题 我们显示记录日志 时 获取上下文的ip 和用户名 用户类型
// .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Warning,
// outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext:l} || {Message} || {Exception} ||end {NewLine}")
// .WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day,
// outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext:l} || {Message} || {Exception} ||end {NewLine}")
// .CreateLogger();
Log.Logger = new LoggerConfiguration()
//.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.WriteTo.Console()
.WriteTo.File($"{AppContext.BaseDirectory}Serilogs/.log", rollingInterval: RollingInterval.Day)
.CreateLogger();
#endregion
#region
Log.Logger.Warning($"当前环境:{enviromentName}");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Log.Logger.Warning($"当前部署平台环境:windows");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Log.Logger.Warning($"当前部署平台环境:linux");
}
else
{
Log.Logger.Warning($"当前部署平台环境:OSX or FreeBSD");
}
#endregion
var logger = app.Services.GetService<Microsoft.Extensions.Logging.ILogger<Program>>();
var server = DicomServerFactory.Create<CStoreSCPService>(_configuration.GetSection("DicomSCPServiceConfig").GetValue<int>("ServerPort"), userState: app.Services,logger: logger);
app.Run();
@@ -1,25 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"Test_IRC_SCP": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:6200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Test_IRC_SCP"
}
},
"Uat_IRC_SCP": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:6200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Uat_IRC_SCP"
}
}
}
}
-111
View File
@@ -1,111 +0,0 @@
using AutoMapper;
using IRaCIS.Application.Services.BusinessFilter;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Localization;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System.Diagnostics.CodeAnalysis;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure.Extention;
using IRaCIS.Core.Domain.Models;
namespace IRaCIS.Core.SCP.Service
{
#pragma warning disable CS8618
#region
[Authorize, DynamicWebApi, UnifiedApiResultFilter]
public class BaseService : IBaseService, IDynamicWebApi
{
public IMapper _mapper { get; set; }
public IUserInfo _userInfo { get; set; }
public IStringLocalizer _localizer { get; set; }
public IWebHostEnvironment _hostEnvironment { get; set; }
public static IResponseOutput Null404NotFound<TEntity>(TEntity? businessObject) where TEntity : class
{
return new ResponseOutput<string>()
.NotOk($"The query object {typeof(TEntity).Name} does not exist , or was deleted by someone else, or an incorrect parameter query caused", code: ApiResponseCodeEnum.DataNotExist);
}
}
public interface IBaseService
{
[MemberNotNull(nameof(_mapper))]
public IMapper _mapper { get; set; }
[MemberNotNull(nameof(_userInfo))]
public IUserInfo _userInfo { get; set; }
[MemberNotNull(nameof(_localizer))]
public IStringLocalizer _localizer { get; set; }
[MemberNotNull(nameof(_hostEnvironment))]
public IWebHostEnvironment _hostEnvironment { get; set; }
}
#endregion
#region
public interface IBaseServiceTest<T> where T : Entity
{
[MemberNotNull(nameof(_mapper))]
public IMapper _mapper { get; set; }
[MemberNotNull(nameof(_userInfo))]
public IUserInfo _userInfo { get; set; }
[MemberNotNull(nameof(_localizer))]
public IStringLocalizer _localizer { get; set; }
}
[Authorize, DynamicWebApi, UnifiedApiResultFilter]
public class BaseServiceTest<T> : IBaseServiceTest<T>, IDynamicWebApi where T : Entity
{
public IMapper _mapper { get; set; }
public IUserInfo _userInfo { get; set; }
public IStringLocalizer _localizer { get; set; }
public static IResponseOutput Null404NotFound<TEntity>(TEntity? businessObject) where TEntity : class
{
return new ResponseOutput<string>()
.NotOk($"The query object {typeof(TEntity).Name} does not exist , or was deleted by someone else, or an incorrect parameter query caused", code: ApiResponseCodeEnum.DataNotExist);
}
}
#endregion
}
-370
View File
@@ -1,370 +0,0 @@
using FellowOakDicom.Network;
using FellowOakDicom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IRaCIS.Core.SCP.Service;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infra.EFCore;
using Medallion.Threading;
using IRaCIS.Core.Domain.Share;
using Serilog;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Microsoft.Extensions.Options;
using System.Data;
using FellowOakDicom.Imaging;
using SharpCompress.Common;
using SixLabors.ImageSharp.Formats.Jpeg;
using IRaCIS.Core.Infrastructure;
namespace IRaCIS.Core.SCP.Service
{
public class DicomSCPServiceOption
{
public List<string> CalledAEList { get; set; }
public string ServerPort { get; set; }
}
public class CStoreSCPService : DicomService, IDicomServiceProvider, IDicomCStoreProvider, IDicomCEchoProvider
{
private IServiceProvider _serviceProvider { get; set; }
private List<Guid> _SCPStudyIdList { get; set; } = new List<Guid>();
private SCPImageUpload _upload { get; set; }
private Guid _trialId { get; set; }
private Guid _trialSiteId { get; set; }
private static readonly DicomTransferSyntax[] _acceptedTransferSyntaxes = new DicomTransferSyntax[]
{
DicomTransferSyntax.ExplicitVRLittleEndian,
DicomTransferSyntax.ExplicitVRBigEndian,
DicomTransferSyntax.ImplicitVRLittleEndian
};
private static readonly DicomTransferSyntax[] _acceptedImageTransferSyntaxes = new DicomTransferSyntax[]
{
// Lossless
DicomTransferSyntax.JPEGLSLossless, //1.2.840.10008.1.2.4.80
DicomTransferSyntax.JPEG2000Lossless, //1.2.840.10008.1.2.4.90
DicomTransferSyntax.JPEGProcess14SV1, //1.2.840.10008.1.2.4.70
DicomTransferSyntax.JPEGProcess14, //1.2.840.10008.1.2.4.57 JPEG Lossless, Non-Hierarchical (Process 14)
DicomTransferSyntax.RLELossless, //1.2.840.10008.1.2.5
// Lossy
DicomTransferSyntax.JPEGLSNearLossless,//1.2.840.10008.1.2.4.81"
DicomTransferSyntax.JPEG2000Lossy, //1.2.840.10008.1.2.4.91
DicomTransferSyntax.JPEGProcess1, //1.2.840.10008.1.2.4.50
DicomTransferSyntax.JPEGProcess2_4, //1.2.840.10008.1.2.4.51
// Uncompressed
DicomTransferSyntax.ExplicitVRLittleEndian, //1.2.840.10008.1.2.1
DicomTransferSyntax.ExplicitVRBigEndian, //1.2.840.10008.1.2.2
DicomTransferSyntax.ImplicitVRLittleEndian //1.2.840.10008.1.2
};
public CStoreSCPService(INetworkStream stream, Encoding fallbackEncoding, Microsoft.Extensions.Logging.ILogger log, DicomServiceDependencies dependencies)
: base(stream, fallbackEncoding, log, dependencies)
{
}
public Task OnReceiveAssociationRequestAsync(DicomAssociation association)
{
_upload = new SCPImageUpload() { StartTime = DateTime.Now, CallingAE = association.CallingAE, CalledAE = association.CalledAE, CallingAEIP = association.RemoteHost };
Log.Logger.Warning($"接收到来自{association.CallingAE}的连接");
_serviceProvider = (IServiceProvider)this.UserState;
var _trialDicomAERepository = _serviceProvider.GetService<IRepository<TrialDicomAE>>();
var trialDicomAEList = _trialDicomAERepository.Select(t => new { t.CalledAE, t.TrialId }).ToList();
var trialCalledAEList = trialDicomAEList.Select(t => t.CalledAE).ToList();
Log.Logger.Information("当前系统配置:", string.Join('|', trialDicomAEList));
var findCalledAE = trialDicomAEList.Where(t => t.CalledAE == association.CalledAE).FirstOrDefault();
var isCanReceiveIamge = false;
if (findCalledAE != null)
{
_trialId = findCalledAE.TrialId;
var _trialSiteDicomAERepository = _serviceProvider.GetService<IRepository<TrialSiteDicomAE>>();
var findTrialSiteAE = _trialSiteDicomAERepository.Where(t => t.CallingAE == association.CallingAE && t.TrialId==_trialId).FirstOrDefault();
if (findTrialSiteAE != null)
{
_trialSiteId = findTrialSiteAE.TrialSiteId;
isCanReceiveIamge = true;
}
}
if (association.CallingAE == "test-callingAE")
{
isCanReceiveIamge = true;
}
if (!trialCalledAEList.Contains(association.CalledAE) || isCanReceiveIamge == false)
{
Log.Logger.Warning($"拒绝CallingAE:{association.CallingAE} CalledAE:{association.CalledAE}的连接");
return SendAssociationRejectAsync(
DicomRejectResult.Permanent,
DicomRejectSource.ServiceUser,
DicomRejectReason.CalledAENotRecognized);
}
foreach (var pc in association.PresentationContexts)
{
if (pc.AbstractSyntax == DicomUID.Verification)
{
pc.AcceptTransferSyntaxes(_acceptedTransferSyntaxes);
}
else if (pc.AbstractSyntax.StorageCategory != DicomStorageCategory.None)
{
pc.AcceptTransferSyntaxes(_acceptedImageTransferSyntaxes);
}
}
return SendAssociationAcceptAsync(association);
}
public async Task OnReceiveAssociationReleaseRequestAsync()
{
await DataMaintenanceAsaync();
//记录监控
var _SCPImageUploadRepository = _serviceProvider.GetService<IRepository<SCPImageUpload>>();
_upload.EndTime = DateTime.Now;
_upload.StudyCount = _SCPStudyIdList.Count;
_upload.TrialId = _trialId;
_upload.TrialSiteId = _trialSiteId;
await _SCPImageUploadRepository.AddAsync(_upload, true);
await SendAssociationReleaseResponseAsync();
}
private async Task DataMaintenanceAsaync()
{
Log.Logger.Warning($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE}传输结束:开始维护数据,处理检查Modality");
//处理检查Modality
var _dictionaryRepository = _serviceProvider.GetService<IRepository<Dictionary>>();
var _seriesRepository = _serviceProvider.GetService<IRepository<SCPSeries>>();
var _studyRepository = _serviceProvider.GetService<IRepository<SCPStudy>>();
var dicModalityList = _dictionaryRepository.Where(t => t.Code == "Modality").SelectMany(t => t.ChildList.Select(c => c.Value)).ToList();
var seriesModalityList = _seriesRepository.Where(t => _SCPStudyIdList.Contains(t.StudyId)).Select(t => new { SCPStudyId = t.StudyId, t.Modality }).ToList();
foreach (var g in seriesModalityList.GroupBy(t => t.SCPStudyId))
{
var modality = string.Join('、', g.Select(t => t.Modality).Distinct().ToList());
//特殊逻辑
var modalityForEdit = dicModalityList.Contains(modality) ? modality : String.Empty;
if (modality == "MR")
{
modalityForEdit = "MRI";
}
if (modality == "PT")
{
modalityForEdit = "PET";
}
if (modality == "PT、CT" || modality == "CT、PT")
{
modalityForEdit = "PET-CT";
}
await _studyRepository.BatchUpdateNoTrackingAsync(t => t.Id == g.Key, u => new SCPStudy() { Modalities = modality, ModalityForEdit = modalityForEdit });
}
Log.Logger.Warning($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE}维护数据结束");
}
public void OnReceiveAbort(DicomAbortSource source, DicomAbortReason reason)
{
Log.Logger.Warning($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE}接收中断,中断原因:{source.ToString() + reason.ToString()}");
/* nothing to do here */
}
public async void OnConnectionClosed(Exception exception)
{
/* nothing to do here */
//奇怪的bug 上传的时候,用王捷修改的影像,会关闭,重新连接,导致检查id 丢失,然后状态不一致
if (exception == null)
{
var _studyRepository = _serviceProvider.GetService<IRepository<SCPStudy>>();
//将检查设置为传输结束
await _studyRepository.BatchUpdateNoTrackingAsync(t => _SCPStudyIdList.Contains(t.Id), u => new SCPStudy() { IsUploadFinished = true });
await _studyRepository.SaveChangesAndClearAllTrackingAsync();
}
Log.Logger.Warning($"连接关闭 {exception?.Message} {exception?.InnerException?.Message}");
}
public async Task<DicomCStoreResponse> OnCStoreRequestAsync(DicomCStoreRequest request)
{
string studyInstanceUid = request.Dataset.GetString(DicomTag.StudyInstanceUID);
string seriesInstanceUid = request.Dataset.GetString(DicomTag.SeriesInstanceUID);
string sopInstanceUid = request.Dataset.GetString(DicomTag.SOPInstanceUID);
//Guid studyId = IdentifierHelper.CreateGuid(studyInstanceUid, trialId.ToString());
Guid seriesId = IdentifierHelper.CreateGuid(studyInstanceUid, seriesInstanceUid, _trialId.ToString());
Guid instanceId = IdentifierHelper.CreateGuid(studyInstanceUid, seriesInstanceUid, sopInstanceUid, _trialId.ToString());
var ossService = _serviceProvider.GetService<IOSSService>();
var dicomArchiveService = _serviceProvider.GetService<IDicomArchiveService>();
var _seriesRepository = _serviceProvider.GetService<IRepository<SCPSeries>>();
var _distributedLockProvider = _serviceProvider.GetService<IDistributedLockProvider>();
var storeRelativePath = string.Empty;
var ossFolderPath = $"{_trialId}/Image/PACS/{_trialSiteId}{studyInstanceUid}";
long fileSize = 0;
try
{
using (MemoryStream ms = new MemoryStream())
{
await request.File.SaveAsync(ms);
//irc 从路径最后一截取Guid
storeRelativePath = await ossService.UploadToOSSAsync(ms, ossFolderPath, instanceId.ToString(), false);
fileSize = ms.Length;
}
Log.Logger.Information($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE} {request.SOPInstanceUID} 上传完成 ");
}
catch (Exception ec)
{
Log.Logger.Warning($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE} 上传异常 {ec.Message}");
}
var @lock = _distributedLockProvider.CreateLock($"{studyInstanceUid}");
using (await @lock.AcquireAsync())
{
try
{
var scpStudyId = await dicomArchiveService.ArchiveDicomFileAsync(request.Dataset, _trialId, _trialSiteId, storeRelativePath, Association.CallingAE, Association.CalledAE,fileSize);
if (!_SCPStudyIdList.Contains(scpStudyId))
{
_SCPStudyIdList.Add(scpStudyId);
}
var series = await _seriesRepository.FindAsync(seriesId);
//没有缩略图
if (series != null && string.IsNullOrEmpty(series.ImageResizePath))
{
// 生成缩略图
using (var memoryStream = new MemoryStream())
{
DicomImage image = new DicomImage(request.Dataset);
var sharpimage = image.RenderImage().AsSharpImage();
sharpimage.Save(memoryStream, new JpegEncoder());
// 上传缩略图到 OSS
var seriesPath = await ossService.UploadToOSSAsync(memoryStream, ossFolderPath, seriesId.ToString() + ".preview.jpg", false);
Console.WriteLine(seriesPath + " Id: " + seriesId);
series.ImageResizePath = seriesPath;
}
}
await _seriesRepository.SaveChangesAsync();
}
catch (Exception ex)
{
Log.Logger.Warning($"CallingAE:{Association.CallingAE} CalledAE:{Association.CalledAE} 传输处理异常:{ex.ToString()}");
}
}
//监控信息设置
_upload.FileCount++;
_upload.FileSize = _upload.FileSize + fileSize;
return new DicomCStoreResponse(request, DicomStatus.Success);
}
public Task OnCStoreRequestExceptionAsync(string tempFileName, Exception e)
{
// let library handle logging and error response
return Task.CompletedTask;
}
public Task<DicomCEchoResponse> OnCEchoRequestAsync(DicomCEchoRequest request)
{
return Task.FromResult(new DicomCEchoResponse(request, DicomStatus.Success));
}
}
}
-356
View File
@@ -1,356 +0,0 @@
using IRaCIS.Core.Domain.Share;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using IRaCIS.Core.Infrastructure;
using Medallion.Threading;
using FellowOakDicom;
using FellowOakDicom.Imaging.Codec;
using System.Data;
using IRaCIS.Core.Domain.Models;
using FellowOakDicom.Network;
using IRaCIS.Core.SCP.Service;
using IRaCIS.Core.Infra.EFCore;
using MassTransit;
using System.Runtime.Intrinsics.X86;
using Serilog.Sinks.File;
namespace IRaCIS.Core.SCP.Service
{
public class DicomArchiveService : BaseService, IDicomArchiveService
{
private readonly IRepository<SCPPatient> _patientRepository;
private readonly IRepository<SCPStudy> _studyRepository;
private readonly IRepository<SCPSeries> _seriesRepository;
private readonly IRepository<SCPInstance> _instanceRepository;
private readonly IRepository<Dictionary> _dictionaryRepository;
private readonly IDistributedLockProvider _distributedLockProvider;
private List<Guid> _instanceIdList = new List<Guid>();
public DicomArchiveService(IRepository<SCPPatient> patientRepository, IRepository<SCPStudy> studyRepository,
IRepository<SCPSeries> seriesRepository,
IRepository<SCPInstance> instanceRepository,
IRepository<Dictionary> dictionaryRepository,
IDistributedLockProvider distributedLockProvider)
{
_distributedLockProvider = distributedLockProvider;
_studyRepository = studyRepository;
_patientRepository = patientRepository;
_seriesRepository = seriesRepository;
_instanceRepository = instanceRepository;
_dictionaryRepository = dictionaryRepository;
}
/// <summary>
/// 单个文件接收 归档
/// </summary>
/// <param name="dataset"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<Guid> ArchiveDicomFileAsync(DicomDataset dataset, Guid trialId, Guid trialSiteId, string fileRelativePath, string callingAE, string calledAE,long fileSize)
{
string studyInstanceUid = dataset.GetString(DicomTag.StudyInstanceUID);
string seriesInstanceUid = dataset.GetString(DicomTag.SeriesInstanceUID);
string sopInstanceUid = dataset.GetString(DicomTag.SOPInstanceUID);
string patientIdStr = dataset.GetSingleValueOrDefault(DicomTag.PatientID,string.Empty);
//Guid patientId= IdentifierHelper.CreateGuid(patientIdStr);
Guid studyId = IdentifierHelper.CreateGuid(studyInstanceUid,trialId.ToString());
Guid seriesId = IdentifierHelper.CreateGuid(studyInstanceUid, seriesInstanceUid, trialId.ToString());
Guid instanceId = IdentifierHelper.CreateGuid(studyInstanceUid, seriesInstanceUid, sopInstanceUid, trialId.ToString());
var isStudyNeedAdd = false;
var isSeriesNeedAdd = false;
var isInstanceNeedAdd = false;
var isPatientNeedAdd = false;
//var @lock = _distributedLockProvider.CreateLock($"{studyInstanceUid}");
//using (@lock.Acquire())
{
var findPatient = await _patientRepository.FirstOrDefaultAsync(t => t.PatientIdStr == patientIdStr && t.TrialSiteId==trialSiteId );
var findStudy = await _studyRepository.FindAsync(studyId);
var findSerice = await _seriesRepository.FindAsync(seriesId);
var findInstance = await _instanceRepository.FindAsync(instanceId);
DateTime? studyTime = dataset.GetSingleValueOrDefault(DicomTag.StudyDate, string.Empty) == string.Empty ? null : dataset.GetSingleValue<DateTime>(DicomTag.StudyDate).Add(dataset.GetSingleValueOrDefault(DicomTag.StudyTime, string.Empty) == string.Empty ? TimeSpan.Zero : dataset.GetSingleValue<DateTime>(DicomTag.StudyTime).TimeOfDay);
//先传输了修改了患者编号的,又传输了没有修改患者编号的,导致后传输的没有修改患者编号的下面的检查为0
if (findPatient == null && findStudy==null)
{
isPatientNeedAdd = true;
findPatient = new SCPPatient()
{
Id = NewId.NextSequentialGuid(),
TrialId=trialId,
TrialSiteId=trialSiteId,
PatientIdStr = dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty),
PatientName = dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty),
PatientAge = dataset.GetSingleValueOrDefault(DicomTag.PatientAge, string.Empty),
PatientSex = dataset.GetSingleValueOrDefault(DicomTag.PatientSex, string.Empty),
PatientBirthDate = dataset.GetSingleValueOrDefault(DicomTag.PatientBirthDate, string.Empty),
EarliestStudyTime = studyTime,
LatestStudyTime = studyTime,
LatestPushTime = DateTime.Now,
};
if (findPatient.PatientBirthDate.Length == 8)
{
var birthDateStr = $"{findPatient.PatientBirthDate[0]}{findPatient.PatientBirthDate[1]}{findPatient.PatientBirthDate[2]}{findPatient.PatientBirthDate[3]}-{findPatient.PatientBirthDate[4]}{findPatient.PatientBirthDate[5]}-{findPatient.PatientBirthDate[6]}{findPatient.PatientBirthDate[7]}";
var yearStr = $"{findPatient.PatientBirthDate[0]}{findPatient.PatientBirthDate[1]}{findPatient.PatientBirthDate[2]}{findPatient.PatientBirthDate[3]}";
int year = 0;
var canParse = int.TryParse(yearStr, out year);
if (canParse && year > 1900)
{
findPatient.PatientBirthDate = birthDateStr;
DateTime birthDate;
if (findPatient.PatientAge == string.Empty && studyTime.HasValue && DateTime.TryParse(findPatient.PatientBirthDate,out birthDate))
{
var patientAge = studyTime.Value.Year - birthDate.Year;
// 如果生日还未到,年龄减去一岁
if (studyTime.Value < birthDate.AddYears(patientAge))
{
patientAge--;
}
findPatient.PatientAge = patientAge.ToString();
}
}
else
{
findPatient.PatientBirthDate = string.Empty;
}
}
}
else
{
if (studyTime < findPatient.EarliestStudyTime)
{
findPatient.EarliestStudyTime = studyTime;
}
if (studyTime > findPatient.LatestStudyTime)
{
findPatient.LatestStudyTime = studyTime;
}
findPatient.LatestPushTime = DateTime.Now;
}
if (findStudy == null)
{
isStudyNeedAdd = true;
findStudy = new SCPStudy
{
CalledAE = calledAE,
CallingAE = callingAE,
PatientId = findPatient.Id,
Id = studyId,
TrialId = trialId,
TrialSiteId = trialSiteId,
StudyInstanceUid = studyInstanceUid,
StudyTime = studyTime,
Modalities = dataset.GetSingleValueOrDefault(DicomTag.Modality, string.Empty),
//ModalityForEdit = modalityForEdit,
Description = dataset.GetSingleValueOrDefault(DicomTag.StudyDescription, string.Empty),
InstitutionName = dataset.GetSingleValueOrDefault(DicomTag.InstitutionName, string.Empty),
PatientIdStr = dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty),
PatientName = dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty),
PatientAge = dataset.GetSingleValueOrDefault(DicomTag.PatientAge, string.Empty),
PatientSex = dataset.GetSingleValueOrDefault(DicomTag.PatientSex, string.Empty),
BodyPartExamined = dataset.GetSingleValueOrDefault(DicomTag.BodyPartExamined, string.Empty),
StudyId = dataset.GetSingleValueOrDefault(DicomTag.StudyID, string.Empty),
AccessionNumber = dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty),
//需要特殊处理
PatientBirthDate = dataset.GetSingleValueOrDefault(DicomTag.PatientBirthDate, string.Empty),
AcquisitionTime = dataset.GetSingleValueOrDefault(DicomTag.AcquisitionTime, string.Empty),
AcquisitionNumber = dataset.GetSingleValueOrDefault(DicomTag.AcquisitionNumber, string.Empty),
TriggerTime = dataset.GetSingleValueOrDefault(DicomTag.TriggerTime, string.Empty),
//IsDoubleReview = addtionalInfo.IsDoubleReview,
SeriesCount = 0,
InstanceCount = 0
};
if (findStudy.PatientBirthDate.Length == 8)
{
findStudy.PatientBirthDate = $"{findStudy.PatientBirthDate[0]}{findStudy.PatientBirthDate[1]}{findStudy.PatientBirthDate[2]}{findStudy.PatientBirthDate[3]}-{findStudy.PatientBirthDate[4]}{findStudy.PatientBirthDate[5]}-{findStudy.PatientBirthDate[6]}{findStudy.PatientBirthDate[7]}";
}
}
if (findSerice == null)
{
isSeriesNeedAdd = true;
findSerice = new SCPSeries
{
Id = seriesId,
StudyId = findStudy.Id,
StudyInstanceUid = findStudy.StudyInstanceUid,
SeriesInstanceUid = seriesInstanceUid,
SeriesNumber = dataset.GetSingleValueOrDefault(DicomTag.SeriesNumber, 1),
//SeriesTime = dataset.GetSingleValueOrDefault(DicomTag.SeriesDate, DateTime.Now).Add(dataset.GetSingleValueOrDefault(DicomTag.SeriesTime, DateTime.Now).TimeOfDay),
//SeriesTime = DateTime.TryParse(dataset.GetSingleValue<string>(DicomTag.SeriesDate) + dataset.GetSingleValue<string>(DicomTag.SeriesTime), out DateTime dt) ? dt : null,
SeriesTime = dataset.GetSingleValueOrDefault(DicomTag.SeriesDate, string.Empty) == string.Empty ? null : dataset.GetSingleValue<DateTime>(DicomTag.SeriesDate).Add(dataset.GetSingleValueOrDefault(DicomTag.SeriesTime, string.Empty) == string.Empty ? TimeSpan.Zero : dataset.GetSingleValue<DateTime>(DicomTag.SeriesTime).TimeOfDay),
Modality = dataset.GetSingleValueOrDefault(DicomTag.Modality, string.Empty),
Description = dataset.GetSingleValueOrDefault(DicomTag.SeriesDescription, string.Empty),
SliceThickness = dataset.GetSingleValueOrDefault(DicomTag.SliceThickness, string.Empty),
ImagePositionPatient = dataset.GetSingleValueOrDefault(DicomTag.ImagePositionPatient, string.Empty),
ImageOrientationPatient = dataset.GetSingleValueOrDefault(DicomTag.ImageOrientationPatient, string.Empty),
BodyPartExamined = dataset.GetSingleValueOrDefault(DicomTag.BodyPartExamined, string.Empty),
SequenceName = dataset.GetSingleValueOrDefault(DicomTag.SequenceName, string.Empty),
ProtocolName = dataset.GetSingleValueOrDefault(DicomTag.ProtocolName, string.Empty),
ImagerPixelSpacing = dataset.GetSingleValueOrDefault(DicomTag.ImagerPixelSpacing, string.Empty),
AcquisitionTime = dataset.GetSingleValueOrDefault(DicomTag.AcquisitionTime, string.Empty),
AcquisitionNumber = dataset.GetSingleValueOrDefault(DicomTag.AcquisitionNumber, string.Empty),
TriggerTime = dataset.GetSingleValueOrDefault(DicomTag.TriggerTime, string.Empty),
InstanceCount = 0
};
++findStudy.SeriesCount;
}
if (findInstance == null)
{
isInstanceNeedAdd = true;
findInstance = new SCPInstance
{
Id = instanceId,
StudyId = findStudy.Id,
SeriesId = findSerice.Id,
StudyInstanceUid = findStudy.StudyInstanceUid,
SeriesInstanceUid = findSerice.SeriesInstanceUid,
SopInstanceUid = sopInstanceUid,
InstanceNumber = dataset.GetSingleValueOrDefault(DicomTag.InstanceNumber, 1),
InstanceTime = dataset.GetSingleValueOrDefault(DicomTag.ContentDate, string.Empty) == string.Empty ? null : dataset.GetSingleValue<DateTime>(DicomTag.ContentDate).Add(dataset.GetSingleValueOrDefault(DicomTag.ContentTime, string.Empty) == string.Empty ? TimeSpan.Zero : dataset.GetSingleValue<DateTime>(DicomTag.ContentTime).TimeOfDay),
//InstanceTime = DateTime.TryParse(dataset.GetSingleValue<string>(DicomTag.ContentDate) + dataset.GetSingleValue<string>(DicomTag.ContentTime), out DateTime dt) ? dt : null,
//InstanceTime = dataset.GetSingleValueOrDefault(DicomTag.ContentDate,(DateTime?)null)?.Add(dataset.GetSingleValueOrDefault(DicomTag.ContentTime, TimeSpan.Zero)),
//dataset.GetSingleValueOrDefault(DicomTag.ContentDate,DateTime.Now);//, DicomTag.ContentTime)
CPIStatus = false,
ImageRows = dataset.GetSingleValueOrDefault(DicomTag.Rows, 0),
ImageColumns = dataset.GetSingleValueOrDefault(DicomTag.Columns, 0),
SliceLocation = dataset.GetSingleValueOrDefault(DicomTag.SliceLocation, 0),
SliceThickness = dataset.GetSingleValueOrDefault(DicomTag.SliceThickness, string.Empty),
NumberOfFrames = dataset.GetSingleValueOrDefault(DicomTag.NumberOfFrames, 0),
PixelSpacing = dataset.GetSingleValueOrDefault(DicomTag.PixelSpacing, string.Empty),
ImagerPixelSpacing = dataset.GetSingleValueOrDefault(DicomTag.ImagerPixelSpacing, string.Empty),
FrameOfReferenceUID = dataset.GetSingleValueOrDefault(DicomTag.FrameOfReferenceUID, string.Empty),
WindowCenter = dataset.GetSingleValueOrDefault(DicomTag.WindowCenter, string.Empty),
WindowWidth = dataset.GetSingleValueOrDefault(DicomTag.WindowWidth, string.Empty),
Path = fileRelativePath,
FileSize= fileSize,
};
++findStudy.InstanceCount;
++findSerice.InstanceCount;
}
if (isPatientNeedAdd)
{
var ss = await _patientRepository.AddAsync(findPatient);
}
if (isStudyNeedAdd)
{
var dd = await _studyRepository.AddAsync(findStudy);
}
else
{
await _studyRepository.BatchUpdateNoTrackingAsync(t => t.Id == findStudy.Id, t => new SCPStudy() { IsUploadFinished = false });
}
if (isSeriesNeedAdd)
{
await _seriesRepository.AddAsync(findSerice);
}
if (isInstanceNeedAdd)
{
await _instanceRepository.AddAsync(findInstance);
}
else
{
await _instanceRepository.BatchUpdateNoTrackingAsync(t => t.Id == instanceId, u => new SCPInstance() { Path = fileRelativePath,FileSize=fileSize });
}
//await _studyRepository.SaveChangesAsync();
return findStudy.Id;
}
}
// 从DICOM文件中获取使用的字符集
private string GetEncodingVaulueFromDicomFile(DicomDataset dataset, DicomTag dicomTag)
{
// 获取DICOM文件的特定元素,通常用于指示使用的字符集
var charset = dataset.GetSingleValueOrDefault(DicomTag.SpecificCharacterSet, string.Empty);
var dicomEncoding = DicomEncoding.GetEncoding(charset);
var dicomStringElement = dataset.GetDicomItem<DicomStringElement>(dicomTag);
var bytes = dicomStringElement.Buffer.Data;
return dicomEncoding.GetString(bytes);
//// 从DICOM文件中获取使用的字符集
//string filePath = "C:\\Users\\hang\\Documents\\WeChat Files\\wxid_r2imdzb7j3q922\\FileStorage\\File\\2024-05\\1.2.840.113619.2.80.169103990.5390.1271401378.4.dcm";
//DicomFile dicomFile = DicomFile.Open(filePath);
//// 获取DICOM文件的特定元素,通常用于指示使用的字符集
//var charset = dicomFile.Dataset.GetSingleValueOrDefault(DicomTag.SpecificCharacterSet, string.Empty);
//var dicomEncoding = DicomEncoding.GetEncoding(charset);
//var value = dicomFile.Dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty);
//var dicomStringElement = dicomFile.Dataset.GetDicomItem<DicomStringElement>(DicomTag.PatientName);
//var bytes = dicomStringElement.Buffer.Data;
//var aa= dicomEncoding.GetString(bytes);
}
}
}
@@ -1,11 +0,0 @@
using FellowOakDicom;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
namespace IRaCIS.Core.SCP.Service
{
public interface IDicomArchiveService
{
Task<Guid> ArchiveDicomFileAsync(DicomDataset dicomDataset,Guid trialId,Guid trialSiteId, string fileRelativePath,string callingAE,string calledAE,long fileSize);
}
}
-442
View File
@@ -1,442 +0,0 @@
using Aliyun.OSS;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Minio.DataModel.Args;
using Minio;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace IRaCIS.Core.SCP
{
public class MinIOOptions : AWSOptions
{
public int port { get; set; }
}
public class AWSOptions
{
public string endPoint { get; set; }
public bool useSSL { get; set; }
public string accessKey { get; set; }
public string secretKey { get; set; }
public string bucketName { get; set; }
public string viewEndpoint { get; set; }
}
public class AliyunOSSOptions
{
public string regionId { get; set; }
public string accessKeyId { get; set; }
public string accessKeySecret { get; set; }
public string internalEndpoint { get; set; }
public string endPoint { get; set; }
public string bucketName { get; set; }
public string roleArn { get; set; }
public string region { get; set; }
public string viewEndpoint { get; set; }
}
public class ObjectStoreServiceOptions
{
public string ObjectStoreUse { get; set; }
public AliyunOSSOptions AliyunOSS { get; set; }
public MinIOOptions MinIO { get; set; }
public AWSOptions AWS { get; set; }
}
public class ObjectStoreDTO
{
public string ObjectStoreUse { get; set; }
public AliyunOSSOptions AliyunOSS { get; set; }
public MinIOOptions MinIO { get; set; }
public AWSOptions AWS { get; set; }
}
public class AliyunOSSTempToken
{
public string AccessKeyId { get; set; }
public string AccessKeySecret { get; set; }
public string SecurityToken { get; set; }
public string Expiration { get; set; }
public string Region { get; set; }
public string BucketName { get; set; }
public string ViewEndpoint { get; set; }
}
public enum ObjectStoreUse
{
AliyunOSS = 0,
MinIO = 1,
AWS = 2,
}
public interface IOSSService
{
public Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true);
public Task<string> UploadToOSSAsync(string localFilePath, string oosFolderPath, bool isFileNameAddGuid = true);
public Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath);
public ObjectStoreServiceOptions ObjectStoreServiceOptions { get; set; }
public Task<string> GetSignedUrl(string ossRelativePath);
}
public class OSSService : IOSSService
{
public ObjectStoreServiceOptions ObjectStoreServiceOptions { get; set; }
public OSSService(IOptionsMonitor<ObjectStoreServiceOptions> options)
{
ObjectStoreServiceOptions = options.CurrentValue;
}
/// <summary>
/// oosFolderPath 不要 "/ "开头 应该: TempFolder/ChildFolder
/// </summary>
/// <param name="fileStream"></param>
/// <param name="oosFolderPath"></param>
/// <param name="fileRealName"></param>
/// <param name="isFileNameAddGuid"></param>
/// <returns></returns>
public async Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true)
{
var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}" : $"{oosFolderPath}/{fileRealName}";
//var ossRelativePath = $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}";
//var ossRelativePath = oosFolderPath + "/" + fileRealName;
try
{
using (var memoryStream = new MemoryStream())
{
fileStream.Seek(0, SeekOrigin.Begin);
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.endPoint : aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.PutObject(aliConfig.bucketName, ossRelativePath, memoryStream);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithStreamData(memoryStream)
.WithObjectSize(memoryStream.Length);
await minioClient.PutObjectAsync(putObjectArgs);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithStreamData(memoryStream)
.WithObjectSize(memoryStream.Length);
await minioClient.PutObjectAsync(putObjectArgs);
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
}
catch (Exception ex)
{
throw new BusinessValidationFailedException($"上传发生异常:{ex.Message}");
}
return "/" + ossRelativePath;
}
/// <summary>
/// oosFolderPath 不要 "/ "开头 应该: TempFolder/ChildFolder
/// </summary>
/// <param name="localFilePath"></param>
/// <param name="oosFolderPath"></param>
/// <returns></returns>
/// <exception cref="BusinessValidationFailedException"></exception>
public async Task<string> UploadToOSSAsync(string localFilePath, string oosFolderPath, bool isFileNameAddGuid = true)
{
var localFileName = Path.GetFileName(localFilePath);
var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{localFileName}" : $"{oosFolderPath}/{localFileName}";
//var ossRelativePath = oosFolderPath + "/" + localFileName;
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.endPoint : aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.PutObject(aliConfig.bucketName, ossRelativePath, localFilePath);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFileName(localFilePath);
await minioClient.PutObjectAsync(putObjectArgs);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFileName(localFilePath);
await minioClient.PutObjectAsync(putObjectArgs);
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
return "/" + ossRelativePath;
}
public async Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath)
{
ossRelativePath = ossRelativePath.TrimStart('/');
try
{
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.endPoint : aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.GetObject(aliConfig.bucketName, ossRelativePath);
// 将下载的文件流保存到本地文件
using (var fs = File.OpenWrite(localFilePath))
{
result.Content.CopyTo(fs);
fs.Close();
}
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var getObjectArgs = new GetObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFile(localFilePath);
await minioClient.GetObjectAsync(getObjectArgs);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var getObjectArgs = new GetObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFile(localFilePath);
await minioClient.GetObjectAsync(getObjectArgs);
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
catch (Exception ex)
{
throw new BusinessValidationFailedException("oss下载失败!" + ex.Message);
}
}
public async Task<string> GetSignedUrl(string ossRelativePath)
{
ossRelativePath = ossRelativePath.TrimStart('/');
try
{
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.endPoint : aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 生成签名URL。
var req = new GeneratePresignedUriRequest(aliConfig.bucketName, ossRelativePath, SignHttpMethod.Get)
{
// 设置签名URL过期时间,默认值为3600秒。
Expiration = DateTime.Now.AddHours(1),
};
var uri = _ossClient.GeneratePresignedUri(req);
return uri.PathAndQuery;
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var args = new PresignedGetObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithExpiry(3600)
/*.WithHeaders(reqParams)*/;
var presignedUrl = await minioClient.PresignedGetObjectAsync(args);
Uri uri = new Uri(presignedUrl);
string relativePath = uri.PathAndQuery;
return relativePath;
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var args = new PresignedGetObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithExpiry(3600);
var presignedUrl = await minioClient.PresignedGetObjectAsync(args);
Uri uri = new Uri(presignedUrl);
string relativePath = uri.PathAndQuery;
return relativePath;
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
catch (Exception ex)
{
throw new BusinessValidationFailedException("oss授权url失败!" + ex.Message);
}
}
}
}
@@ -1,44 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ObjectStoreService": {
"ObjectStoreUse": "AliyunOSS",
"AliyunOSS": {
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endpoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"accessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"bucketName": "zy-irc-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-cache.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"MinIO": {
"endpoint": "http://192.168.3.68",
"port": "8001",
"useSSL": false,
"accessKey": "IDFkwEpWej0b4DtiuThL",
"secretKey": "Lhuu83yMhVwu7c1SnjvGY6lq74jzpYqifK6Qtj4h",
"bucketName": "test"
}
},
"ConnectionStrings": {
"RemoteNew": "Server=prod_mssql_standard,1433;Database=Prod_IRC;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true",
"Hangfire": "Server=prod_mssql_standard,1433;Database=Prod_IRC_Hangfire;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true"
},
"DicomSCPServiceConfig": {
"CalledAEList": [
"STORESCP"
],
"ServerPort": 11112
}
}
@@ -1,80 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ObjectStoreService": {
"ObjectStoreUse": "AliyunOSS",
"AliyunOSS": {
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endPoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"accessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"bucketName": "zy-irc-test-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-test-store.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"MinIO": {
"endPoint": "106.14.89.110",
"port": "9001",
"useSSL": false,
"accessKey": "fbStsVYCIPKHQneeqMwD",
"secretKey": "TzgvyA3zGXMUnpilJNUlyMYHfosl1hBMl6lxPmjy",
"bucketName": "hir-test",
"viewEndpoint": "http://106.14.89.110:9001/hir-test/"
},
"AWS": {
"endPoint": "s3.us-east-1.amazonaws.com",
"useSSL": false,
"accessKey": "AKIAZQ3DRSOHFPJJ6FEU",
"secretKey": "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",
"bucketName": "ei-irc-test-store",
"viewEndpoint": "https://ei-irc-test-store.s3.amazonaws.com/"
}
},
"ConnectionStrings": {
"RemoteNew": "Server=106.14.89.110,1435;Database=Test_IRC;User ID=sa;Password=xc@123456;TrustServerCertificate=true",
"Hangfire": "Server=106.14.89.110,1435;Database=Test_IRC_Hangfire;User ID=sa;Password=xc@123456;TrustServerCertificate=true"
},
"BasicSystemConfig": {
"OpenUserComplexPassword": false,
"OpenSignDocumentBeforeWork": false,
"OpenTrialRelationDelete": true,
"OpenLoginLimit": false,
"LoginMaxFailCount": 5,
"LoginFailLockMinutes": 30
},
"SystemEmailSendConfig": {
"Port": 465,
"Host": "smtp.qiye.aliyun.com",
"FromEmail": "test-study@extimaging.com",
"FromName": "Test_Study",
"AuthorizationCode": "zhanying123",
"SiteUrl": "http://study.test.extimaging.com/login"
},
"DicomSCPServiceConfig": {
"CalledAEList": [
"STORESCP",
"Value1",
"Value2",
"Value3"
],
"ServerPort": 11112
}
}
-67
View File
@@ -1,67 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ObjectStoreService": {
"ObjectStoreUse": "AliyunOSS",
"AliyunOSS": {
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endpoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"accessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"bucketName": "zy-irc-uat-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-uat-store.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"AWS": {
"endPoint": "s3.us-east-1.amazonaws.com",
"useSSL": false,
"accessKey": "AKIAZQ3DRSOHFPJJ6FEU",
"secretKey": "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",
"bucketName": "ei-irc-test-store",
"viewEndpoint": "https://ei-irc-test-store.s3.amazonaws.com/"
}
},
"ConnectionStrings": {
"RemoteNew": "Server=47.117.164.182,1434;Database=Uat_IRC;User ID=sa;Password=xc@123456;TrustServerCertificate=true",
"Hangfire": "Server=47.117.164.182,1434;Database=Uat_IRC.Hangfire;User ID=sa;Password=xc@123456;TrustServerCertificate=true"
},
"BasicSystemConfig": {
"OpenUserComplexPassword": false,
"OpenSignDocumentBeforeWork": false,
"OpenTrialRelationDelete": true,
"OpenLoginLimit": false,
"LoginMaxFailCount": 5,
"LoginFailLockMinutes": 30
},
"SystemEmailSendConfig": {
"Port": 465,
"Host": "smtp.qiye.aliyun.com",
"FromEmail": "uat-study@extimaging.com",
"FromName": "Uat_Study",
"AuthorizationCode": "zhanying123",
"SiteUrl": "http://study.uat.extimaging.com/login"
},
"DicomSCPServiceConfig": {
"CalledAEList": [
"STORESCP",
"Value1",
"Value2",
"Value3"
],
"ServerPort": 11112
}
}
-9
View File
@@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
-6
View File
@@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Infra.EFCore",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Infrastructure", "IRaCIS.Core.Infrastructure\IRaCIS.Core.Infrastructure.csproj", "{07EED0F8-08E6-46F3-ACBE-17BC1391BD4C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IRC.Core.SCP", "IRC.Core.SCP\IRC.Core.SCP.csproj", "{ECD08F47-DC1A-484E-BB91-6CDDC8823CC5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -53,10 +51,6 @@ Global
{07EED0F8-08E6-46F3-ACBE-17BC1391BD4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07EED0F8-08E6-46F3-ACBE-17BC1391BD4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07EED0F8-08E6-46F3-ACBE-17BC1391BD4C}.Release|Any CPU.Build.0 = Release|Any CPU
{ECD08F47-DC1A-484E-BB91-6CDDC8823CC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECD08F47-DC1A-484E-BB91-6CDDC8823CC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECD08F47-DC1A-484E-BB91-6CDDC8823CC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECD08F47-DC1A-484E-BB91-6CDDC8823CC5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+75 -158
View File
@@ -1,5 +1,6 @@
using System;
using System.Net.Http;
using EasyCaching.Core;
using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Auth;
@@ -22,6 +23,9 @@ using System.Linq;
using Microsoft.Extensions.Logging;
using MassTransit;
using Microsoft.AspNetCore.Hosting;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Auth.Sts;
using Aliyun.Acs.Core;
using IRaCIS.Core.Application.Helper;
using Microsoft.Extensions.Options;
using IRaCIS.Core.Application.Contracts;
@@ -29,14 +33,6 @@ using LoginReturnDTO = IRaCIS.Application.Contracts.LoginReturnDTO;
using DocumentFormat.OpenXml.Spreadsheet;
using AutoMapper.QueryableExtensions;
using NetTopologySuite.Algorithm;
using ZiggyCreatures.Caching.Fusion;
using AlibabaCloud.SDK.Sts20150401;
using AlibabaCloud.SDK.Sts20150401.Models;
using Org.BouncyCastle.Tls;
using Amazon.SecurityToken.Model;
using Amazon.SecurityToken;
using Amazon;
using AssumeRoleRequest = Amazon.SecurityToken.Model.AssumeRoleRequest;
namespace IRaCIS.Api.Controllers
{
@@ -104,12 +100,12 @@ namespace IRaCIS.Api.Controllers
[HttpPost, Route("user/login")]
[AllowAnonymous]
public async Task<IResponseOutput> Login(UserLoginDTO loginUser,
[FromServices] IFusionCache _fusionCache,
[FromServices] IEasyCachingProvider provider,
[FromServices] IUserService _userService,
[FromServices] ITokenService _tokenService,
[FromServices] IReadingImageTaskService readingImageTaskService,
[FromServices] IOptionsMonitor<ServiceVerifyConfigOption> _verifyConfig,
[FromServices] IMailVerificationService _mailVerificationService)
[FromServices] ITokenService _tokenService,
[FromServices] IReadingImageTaskService readingImageTaskService,
IOptionsMonitor<ServiceVerifyConfigOption> _verifyConfig,
IMailVerificationService _mailVerificationService)
{
//MFA 邮箱验证 前端传递用户Id 和MFACode
@@ -143,9 +139,9 @@ namespace IRaCIS.Api.Controllers
// 验证阅片休息时间
await readingImageTaskService.ResetReadingRestTime(userId);
await _fusionCache.SetAsync(userId.ToString(), loginReturn.JWTStr, TimeSpan.FromDays(7));
await provider.SetAsync(userId.ToString(), loginReturn.JWTStr, TimeSpan.FromDays(7));
await _fusionCache.SetAsync($"{userId.ToString()}_Online", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(_verifyConfig.CurrentValue.AutoLoginOutMinutes));
await provider.SetAsync($"{userId.ToString()}_Online", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(_verifyConfig.CurrentValue.AutoLoginOutMinutes));
return ResponseOutput.Ok(loginReturn);
@@ -258,9 +254,9 @@ namespace IRaCIS.Api.Controllers
// 验证阅片休息时间
await readingImageTaskService.ResetReadingRestTime(returnModel.Data.BasicInfo.Id);
await _fusionCache.SetAsync(CacheKeys.UserToken(userId), returnModel.Data.JWTStr, TimeSpan.FromDays(7));
await provider.SetAsync(userId.ToString(), returnModel.Data.JWTStr, TimeSpan.FromDays(7));
await _fusionCache.SetAsync(CacheKeys.UserAutoLoginOut(userId), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(_verifyConfig.CurrentValue.AutoLoginOutMinutes));
await provider.SetAsync($"{userId.ToString()}_Online", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(_verifyConfig.CurrentValue.AutoLoginOutMinutes));
}
}
@@ -297,7 +293,7 @@ namespace IRaCIS.Api.Controllers
}
[HttpGet("user/GetObjectStoreToken")]
public async Task<IResponseOutput> GetObjectStoreTokenAsync([FromServices] IOptionsMonitor<ObjectStoreServiceOptions> options)
public IResponseOutput GetObjectStoreToken([FromServices] IOptionsMonitor<ObjectStoreServiceOptions> options)
{
var serviceOption = options.CurrentValue;
@@ -306,177 +302,98 @@ namespace IRaCIS.Api.Controllers
var ossOptions = serviceOption.AliyunOSS;
var client = new Client(new AlibabaCloud.OpenApiClient.Models.Config()
{
AccessKeyId = ossOptions.AccessKeyId,
AccessKeySecret = ossOptions.AccessKeySecret,
//AccessKeyId = "LTAI5tJV76pYX5yPg1N9QVE8",
//AccessKeySecret = "roRNLa9YG1of4pYruJGCNKBXEWTAWa",
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, MinIO = serviceOption.MinIO, AliyunOSS = serviceOption.AliyunOSS, AWS = serviceOption.AWS });
Endpoint = "sts.cn-hangzhou.aliyuncs.com"
});
var assumeRoleRequest = new AlibabaCloud.SDK.Sts20150401.Models.AssumeRoleRequest();
// 将<YOUR_ROLE_SESSION_NAME>设置为自定义的会话名称,例如oss-role-session。
assumeRoleRequest.RoleSessionName = $"session-name-{NewId.NextGuid()}";
// 将<YOUR_ROLE_ARN>替换为拥有上传文件到指定OSS Bucket权限的RAM角色的ARN。
assumeRoleRequest.RoleArn = ossOptions.RoleArn;
//assumeRoleRequest.RoleArn = "acs:ram::1899121822495495:role/webdirect";
assumeRoleRequest.DurationSeconds = ossOptions.DurationSeconds;
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
var response = client.AssumeRoleWithOptions(assumeRoleRequest, runtime);
var credentials = response.Body.Credentials;
var tempToken = new AliyunOSSTempToken()
{
AccessKeyId = credentials.AccessKeyId,
AccessKeySecret = credentials.AccessKeySecret,
Expiration = credentials.Expiration,
SecurityToken = credentials.SecurityToken,
#region token
//IClientProfile profile = DefaultProfile.GetProfile(ossOptions.RegionId, ossOptions.AccessKeyId, ossOptions.AccessKeySecret);
//DefaultAcsClient client = new DefaultAcsClient(profile);
Region = ossOptions.Region,
BucketName = ossOptions.BucketName,
EndPoint = ossOptions.EndPoint,
ViewEndpoint = ossOptions.ViewEndpoint,
//// 创建一个STS请求
//AssumeRoleRequest request = new AssumeRoleRequest
//{
// RoleArn = ossOptions.RoleArn, // 角色ARN,需要替换为你的角色ARN
// RoleSessionName = $"session-name-{NewId.NextGuid()}", // 角色会话名称,可自定义
// DurationSeconds = 900, // 令牌有效期(单位:秒),这里设置为1小时
//};
};
var awstempToken = await GetAWSTemToken(serviceOption);
//AssumeRoleResponse response = client.GetAcsResponse(request);
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, AliyunOSS = tempToken,AWS= awstempToken });
//// 返回STS令牌信息给前端
//var stsToken = new ObjectStoreDTO()
//{
// ObjectStoreUse = serviceOption.ObjectStoreUse,
// AliyunOSS = new AliyunOSSTempToken()
// {
// AccessKeyId = response.Credentials.AccessKeyId,
// AccessKeySecret = response.Credentials.AccessKeySecret,
// SecurityToken = response.Credentials.SecurityToken,
// Expiration = response.Credentials.Expiration,
// Region = ossOptions.Region,
// BucketName = ossOptions.BucketName,
// ViewEndpoint = ossOptions.ViewEndpoint,
// },
// MinIO = serviceOption.MinIO
//};
//return ResponseOutput.Ok(stsToken);
#endregion
}
else if (Enum.TryParse<ObjectStoreUse>(serviceOption.ObjectStoreUse, out var parsedValue) && parsedValue == ObjectStoreUse.MinIO)
{
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, MinIO = serviceOption.MinIO});
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, MinIO = serviceOption.MinIO, AWS = serviceOption.AWS });
}
else
{
var awsOptions = serviceOption.AWS;
//aws 临时凭证
// 创建 STS 客户端
var stsClient = new AmazonSecurityTokenServiceClient(awsOptions.AccessKeyId, awsOptions.SecretAccessKey);
// 使用 AssumeRole 请求临时凭证
var assumeRoleRequest = new AssumeRoleRequest
{
RoleArn = awsOptions.RoleArn, // 角色 ARN
RoleSessionName = $"session-name-{NewId.NextGuid()}",
DurationSeconds = awsOptions.DurationSeconds // 临时凭证有效期
};
var assumeRoleResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest);
var credentials = assumeRoleResponse.Credentials;
var tempToken = new AWSTempToken()
{
AccessKeyId = credentials.AccessKeyId,
SecretAccessKey = credentials.SecretAccessKey,
SessionToken= credentials.SessionToken,
Expiration=credentials.Expiration,
Region=awsOptions.Region,
BucketName = awsOptions.BucketName,
EndPoint = awsOptions.EndPoint,
ViewEndpoint = awsOptions.ViewEndpoint,
};
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, MinIO = serviceOption.MinIO, AWS = tempToken });
return ResponseOutput.Ok(new ObjectStoreDTO() { ObjectStoreUse = serviceOption.ObjectStoreUse, MinIO = serviceOption.MinIO, AWS = serviceOption.AWS });
}
}
private async Task<AWSTempToken> GetAWSTemToken(ObjectStoreServiceOptions serviceOption)
[HttpGet("user/GenerateSTS")]
public IResponseOutput GenerateSTS([FromServices] IOptionsMonitor<AliyunOSSOptions> options)
{
var awsOptions = serviceOption.AWS;
var ossOptions = options.CurrentValue;
//aws 临时凭证
// 创建 STS 客户端
var stsClient = new AmazonSecurityTokenServiceClient(awsOptions.AccessKeyId, awsOptions.SecretAccessKey);
// 使用 AssumeRole 请求临时凭证
var assumeRoleRequest = new AssumeRoleRequest
IClientProfile profile = DefaultProfile.GetProfile(ossOptions.regionId, ossOptions.accessKeyId, ossOptions.accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
// 创建一个STS请求
AssumeRoleRequest request = new AssumeRoleRequest
{
RoleArn = awsOptions.RoleArn, // 角色 ARN
RoleSessionName = $"session-name-{NewId.NextGuid()}",
DurationSeconds = awsOptions.DurationSeconds // 临时凭证有效期
RoleArn = ossOptions.roleArn, // 角色ARN,需要替换为你的角色ARN
RoleSessionName = $"session-name-{NewId.NextGuid()}", // 角色会话名称,可自定义
DurationSeconds = 900, // 令牌有效期(单位:秒),这里设置为1小时
};
var assumeRoleResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest);
var credentials = assumeRoleResponse.Credentials;
AssumeRoleResponse response = client.GetAcsResponse(request);
var tempToken = new AWSTempToken()
// 返回STS令牌信息给前端
var stsToken = new
{
AccessKeyId = credentials.AccessKeyId,
SecretAccessKey = credentials.SecretAccessKey,
SessionToken = credentials.SessionToken,
Expiration = credentials.Expiration,
Region = awsOptions.Region,
BucketName = awsOptions.BucketName,
EndPoint = awsOptions.EndPoint,
ViewEndpoint = awsOptions.ViewEndpoint,
AccessKeyId = response.Credentials.AccessKeyId,
AccessKeySecret = response.Credentials.AccessKeySecret,
SecurityToken = response.Credentials.SecurityToken,
Expiration = response.Credentials.Expiration,
Region = ossOptions.region,
BucketName = ossOptions.bucketName,
ViewEndpoint = ossOptions.viewEndpoint,
};
return tempToken;
return ResponseOutput.Ok(stsToken);
}
#region aliyun-net-sdk-sts
//[HttpGet("user/GenerateSTS")]
//public IResponseOutput GenerateSTS([FromServices] IOptionsMonitor<AliyunOSSOptions> options)
//{
// var ossOptions = options.CurrentValue;
// IClientProfile profile = DefaultProfile.GetProfile(ossOptions.regionId, ossOptions.accessKeyId, ossOptions.accessKeySecret);
// DefaultAcsClient client = new DefaultAcsClient(profile);
// // 创建一个STS请求
// AssumeRoleRequest request = new AssumeRoleRequest
// {
// RoleArn = ossOptions.roleArn, // 角色ARN,需要替换为你的角色ARN
// RoleSessionName = $"session-name-{NewId.NextGuid()}", // 角色会话名称,可自定义
// DurationSeconds = 900, // 令牌有效期(单位:秒),这里设置为1小时
// };
// AssumeRoleResponse response = client.GetAcsResponse(request);
// // 返回STS令牌信息给前端
// var stsToken = new
// {
// AccessKeyId = response.Credentials.AccessKeyId,
// AccessKeySecret = response.Credentials.AccessKeySecret,
// SecurityToken = response.Credentials.SecurityToken,
// Expiration = response.Credentials.Expiration,
// Region = ossOptions.region,
// BucketName = ossOptions.bucketName,
// ViewEndpoint = ossOptions.viewEndpoint,
// };
// return ResponseOutput.Ok(stsToken);
//}
#endregion
[HttpGet("User/UserRedirect")]
[AllowAnonymous]
@@ -510,7 +427,7 @@ namespace IRaCIS.Api.Controllers
[HttpGet, Route("ip")]
[AllowAnonymous]
public IResponseOutput Get([FromServices] IHttpContextAccessor _context)
public IResponseOutput Get([FromServices] IHttpContextAccessor _context/*, [FromServices] IUserService _userService*/)
{
StringBuilder sb = new StringBuilder();
@@ -531,7 +448,7 @@ namespace IRaCIS.Api.Controllers
[HttpGet, Route("ip2")]
[AllowAnonymous]
public IResponseOutput Get2([FromServices] IHttpContextAccessor _context)
public IResponseOutput Get2([FromServices] IHttpContextAccessor _context, [FromServices] IRepository _userService)
{
StringBuilder sb = new StringBuilder();
@@ -19,12 +19,18 @@ namespace IRaCIS.Core.API.Controllers.Special
//谨慎修改 涉及到财务模块
[ApiController, Authorize, ApiExplorerSettings(GroupName = "Financial")]
public class FinancialChangeController(
ITrialService _trialService,
ICalculateService _calculateService,
IStringLocalizer _localizer) : ControllerBase
public class FinancialChangeController : ControllerBase
{
private readonly ITrialService _trialService;
private readonly ICalculateService _calculateService;
private IStringLocalizer _localizer { get; set; }
public FinancialChangeController(ITrialService trialService, ICalculateService calculateService, IStringLocalizer localizer
)
{
_localizer = localizer;
_trialService = trialService;
_calculateService = calculateService;
}
//[TrialAudit(AuditType.TrialAudit, AuditOptType.AddOrUpdateTrial)]
@@ -26,19 +26,78 @@ namespace IRaCIS.Core.API.Controllers
[ApiController, ApiExplorerSettings(GroupName = "Reviewer")]
[UnitOfWork]
public class InspectionController(
ITrialDocumentService _trialDocumentService,
IReadingImageTaskService _iReadingImageTaskService,
ITrialConfigService _trialConfigService,
IClinicalAnswerService _clinicalAnswerService,
IReadingClinicalDataService _readingClinicalDataService,
IQCOperationService _qCOperationService,
IInspectionService _inspectionService,
IReadingMedicalReviewService _readingMedicalReviewService,
IReadingMedicineQuestionService _readingMedicineQuestionService
) : ControllerBase
public class InspectionController : ControllerBase
{
private readonly IRepository _repository;
private readonly IMapper _mapper;
private readonly IUserInfo _userInfo;
private readonly ITrialDocumentService _trialDocumentService;
private readonly IQCListService _qCListService;
private readonly IReadingImageTaskService _iReadingImageTaskService;
private readonly IHttpContextAccessor _httpContext;
private readonly ITrialConfigService _trialConfigService;
private readonly INoneDicomStudyService _noneDicomStudyService;
private readonly IClinicalAnswerService _clinicalAnswerService;
private readonly ISubjectService _subjectService;
private readonly IReadingClinicalDataService _readingClinicalDataService;
private readonly ISubjectVisitService _subjectVisitService;
private readonly IQCOperationService _qCOperationService;
private readonly IClinicalDataService _clinicalDataService;
private readonly IVisitPlanService _visitPlanService;
private readonly IInspectionService _inspectionService;
private readonly IReadingMedicalReviewService _readingMedicalReviewService;
private readonly IReadingMedicineQuestionService _readingMedicineQuestionService;
private readonly IRepository<DataInspection> _dataInspectionRepository;
private delegate Task<IResponseOutput> executionFun(dynamic data);
public InspectionController(IRepository repository,
IRepository<DataInspection> _repositoryDataInspection,
IMapper mapper, IUserInfo userInfo,
ITrialDocumentService trialDocumentService,
IRepository<DataInspection> dataInspectionRepository,
IQCListService _qCListService,
IReadingImageTaskService _iReadingImageTaskService,
IHttpContextAccessor httpContext,
IInspectionService sinspectionService,
IReadingMedicalReviewService readingMedicalReviewService,
IReadingMedicineQuestionService readingMedicineQuestionService,
ITrialConfigService _trialConfigService,
INoneDicomStudyService noneDicomStudyService,
IClinicalAnswerService clinicalAnswerService,
ISubjectService _subjectService,
IReadingClinicalDataService _readingClinicalDataService,
ISubjectVisitService subjectVisitService,
IQCOperationService qCOperationService,
IClinicalDataService clinicalDataService,
IVisitPlanService visitPlanService
)
{
this._repository = repository;
this._mapper = mapper;
this._userInfo = userInfo;
this._inspectionService = sinspectionService;
this._readingMedicalReviewService = readingMedicalReviewService;
this._readingMedicineQuestionService = readingMedicineQuestionService;
this._trialDocumentService = trialDocumentService;
this._qCListService = _qCListService;
this._iReadingImageTaskService = _iReadingImageTaskService;
this._httpContext = httpContext;
this._trialConfigService = _trialConfigService;
this._noneDicomStudyService = noneDicomStudyService;
this._clinicalAnswerService = clinicalAnswerService;
this._subjectService = _subjectService;
this._readingClinicalDataService = _readingClinicalDataService;
this._subjectVisitService = subjectVisitService;
this._qCOperationService = qCOperationService;
this._clinicalDataService = clinicalDataService;
this._visitPlanService = visitPlanService;
this._dataInspectionRepository = dataInspectionRepository;
}
#region
/// <summary>
/// 获取稽查数据
@@ -249,28 +308,11 @@ namespace IRaCIS.Core.API.Controllers
}
/// <summary>
/// PM签名一致性分析临床数据
/// </summary>
/// <param name="opt"></param>
/// <returns></returns>
[HttpPost, Route("Inspection/ReadingClinicalData/SignConsistencyAnalysisReadingClinicalData")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
[UnitOfWork]
public async Task<IResponseOutput> SignConsistencyAnalysisReadingClinicalData(DataInspectionDto<SignConsistencyAnalysisReadingClinicalDataInDto> opt)
{
var singid = await _inspectionService.RecordSing(opt.SignInfo);
var result = await _readingClinicalDataService.SignConsistencyAnalysisReadingClinicalData(opt.Data);
await _inspectionService.CompletedSign(singid, result);
return result;
}
/// <summary>
/// 提交结构化录入并签名
/// </summary>
/// <param name="opt"></param>
/// <returns></returns>
/// <summary>
/// 提交结构化录入并签名
/// </summary>
/// <param name="opt"></param>
/// <returns></returns>
[HttpPost, Route("Inspection/ClinicalAnswer/SubmitClinicalFormAndSign")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
@@ -360,19 +402,6 @@ namespace IRaCIS.Core.API.Controllers
return result;
}
[HttpPost, Route("Inspection/configTrialBasicInfo/ConfigTrialPACSInfoConfirm")]
[UnitOfWork]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "BeforeOngoingCantOpt" })]
public async Task<IResponseOutput> ConfigTrialPACSInfoConfirm(DataInspectionDto<TrialPACSConfig> opt)
{
opt.Data.IsTrialPACSConfirmed = true;
var singid = await _inspectionService.RecordSing(opt.SignInfo);
var result = await _trialConfigService.ConfigTrialPACSInfo(opt.Data);
await _inspectionService.CompletedSign(singid, result);
return result;
}
/// <summary>
/// 签名确认
/// </summary>
@@ -1,5 +1,6 @@
using AutoMapper;
using DocumentFormat.OpenXml.Drawing;
using EasyCaching.Core;
using ExcelDataReader;
using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
@@ -9,7 +10,8 @@ using IRaCIS.Core.Application.Contracts.Dicom;
using IRaCIS.Core.Application.Contracts.Dicom.DTO;
using IRaCIS.Core.Application.Filter;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Command;
using IRaCIS.Core.Application.MediatR.CommandAndQueries;
using IRaCIS.Core.Application.MediatR.Handlers;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.Service.ImageAndDoc;
using IRaCIS.Core.Application.Service.Reading.Dto;
@@ -19,7 +21,7 @@ using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using MassTransit;
using MassTransit.Mediator;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
@@ -44,7 +46,6 @@ using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZiggyCreatures.Caching.Fusion;
using Path = System.IO.Path;
namespace IRaCIS.Core.API.Controllers
@@ -227,14 +228,35 @@ namespace IRaCIS.Core.API.Controllers
[ApiExplorerSettings(GroupName = "Image")]
[ApiController]
public class StudyController(
IMediator _mediator,
QCCommon _qCCommon,
IUserInfo _userInfo,
IRepository<SubjectVisit> _subjectVisitRepository,
IStringLocalizer _localizer) : UploadBaseController
public class StudyController : UploadBaseController
{
public IMapper _mapper { get; set; }
public IUserInfo _userInfo { get; set; }
private readonly IMediator _mediator;
public IStringLocalizer _localizer { get; set; }
private readonly IWebHostEnvironment _hostEnvironment;
private readonly IRepository _repository;
private readonly IEasyCachingProvider _provider;
private readonly QCCommon _qCCommon;
public StudyController(IMapper mapper, IStringLocalizer localizer, IUserInfo userInfo, IWebHostEnvironment hostEnvironment, IMediator mediator, IEasyCachingProvider provider,
QCCommon qCCommon,
IRepository repository)
{
_qCCommon = qCCommon;
_provider = provider;
_hostEnvironment = hostEnvironment;
_mediator = mediator;
_localizer = localizer;
_mapper = mapper;
_userInfo = userInfo;
_repository = repository;
}
[HttpPost, Route("Study/PreArchiveStudy")]
@@ -244,6 +266,11 @@ namespace IRaCIS.Core.API.Controllers
[FromServices] IRepository<StudyMonitor> _studyMonitorRepository)
{
if (_provider.Get<List<SystemAnonymization>>(StaticData.Anonymize.Anonymize_AddFixedFiled).Value == null)
{
await _mediator.Send(new AnonymizeCacheRequest());
}
var savedInfo = _studyService.GetSaveToDicomInfo(preArchiveStudyCommand.SubjectVisitId);
var studyMonitor = new StudyMonitor()
@@ -271,8 +298,9 @@ namespace IRaCIS.Core.API.Controllers
[DisableFormValueModelBinding]
[DisableRequestSizeLimit]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput> ArchiveStudyNew( Guid trialId, Guid subjectVisitId, string studyInstanceUid, Guid? abandonStudyId, Guid studyMonitorId,
public async Task<IResponseOutput> ArchiveStudyNew(/*[FromForm] ArchiveStudyCommand archiveStudyCommand,*/ Guid trialId, Guid subjectVisitId, string studyInstanceUid, Guid? abandonStudyId, Guid studyMonitorId,
[FromServices] ILogger<UploadDownLoadController> _logger,
[FromServices] IEasyCachingProvider _provider,
[FromServices] IStudyService _studyService,
[FromServices] IHubContext<UploadHub, IUploadClient> _uploadHub,
[FromServices] IDicomArchiveService _dicomArchiveService,
@@ -297,6 +325,22 @@ namespace IRaCIS.Core.API.Controllers
var startTime = DateTime.Now;
if (_provider.Exists($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}") && _provider.Get<Guid>($"StudyUid_{trialId}_{studyInstanceUid}").Value == _userInfo.Id)
{
_provider.Set($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}", _userInfo.Id, TimeSpan.FromMinutes(30));
}
//if (_provider.Exists($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}"))
//{
// //---当前已有人正在上传和归档该检查!
// return ResponseOutput.NotOk(StaticData.International("UploadDownLoad_ArchiveInProgress"));
//}
//else
//{
// _provider.Set($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}", _userInfo.Id, TimeSpan.FromMinutes(30));
//}
//到了接口,代表上传结束了
@@ -362,12 +406,13 @@ namespace IRaCIS.Core.API.Controllers
}
catch (Exception)
{
_provider.Remove($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}");
//---请求异常,请重试!
throw new BusinessValidationFailedException(_localizer["UploadDownLoad_RequestError"]);
}
studyMonitor.FileSize = (long)HttpContext.Request.ContentLength;
studyMonitor.FileSize = (decimal)HttpContext.Request.ContentLength;
studyMonitor.FileCount = archiveResult.ReceivedFileCount;
studyMonitor.FailedFileCount = archiveResult.ErrorFiles.Count;
studyMonitor.IsDicomReUpload = archiveStudyCommand.AbandonStudyId != null;
@@ -400,6 +445,7 @@ namespace IRaCIS.Core.API.Controllers
}
finally
{
_provider.Remove($"StudyUid_{trialId}_{archiveStudyCommand.StudyInstanceUid}");
studyMonitor.StudyId = archiveResult.ArchivedDicomStudies.FirstOrDefault()?.Id ?? Guid.Empty;
studyMonitor.StudyCode = archiveResult.ArchivedDicomStudies.FirstOrDefault()?.StudyCode;
@@ -444,15 +490,12 @@ namespace IRaCIS.Core.API.Controllers
/// <param name="incommand"></param>
/// <param name="_noneDicomStudyRepository"></param>
/// <param name="_studyMonitorRepository"></param>
/// <param name="_noneDicomStudyFileRepository"></param>
/// <returns></returns>
[HttpPost("NoneDicomStudy/UploadNoneDicomFile")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput> UploadNoneDicomFile(UploadNoneDicomFileCommand incommand,
[FromServices] IRepository<NoneDicomStudy> _noneDicomStudyRepository,
[FromServices] IRepository<StudyMonitor> _studyMonitorRepository,
[FromServices] IRepository<NoneDicomStudyFile> _noneDicomStudyFileRepository)
[FromServices] IRepository<NoneDicomStudy> _noneDicomStudyRepository, [FromServices] IRepository<StudyMonitor> _studyMonitorRepository)
{
var subjectVisitId = incommand.SubjectVisitId;
@@ -460,9 +503,9 @@ namespace IRaCIS.Core.API.Controllers
var noneDicomStudyId = incommand.NoneDicomStudyId;
await _qCCommon.VerifyIsCRCSubmmitAsync(_subjectVisitRepository, _userInfo, subjectVisitId);
await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId);
var sv = (await _subjectVisitRepository.Where(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.TrialSiteId, t.SubjectId }).FirstOrDefaultAsync()).IfNullThrowConvertException();
var sv = (await _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.TrialSiteId, t.SubjectId }).FirstOrDefaultAsync()).IfNullThrowConvertException();
var studyMonitor = await _studyMonitorRepository.FirstOrDefaultAsync(t => t.Id == studyMonitorId);
@@ -470,7 +513,7 @@ namespace IRaCIS.Core.API.Controllers
foreach (var item in incommand.UploadedFileList)
{
await _noneDicomStudyFileRepository.AddAsync(new NoneDicomStudyFile() { FileName = item.FileName, Path = item.FilePath, NoneDicomStudyId = noneDicomStudyId,FileType=item.FileType,FileSize=item.FileFize });
await _repository.AddAsync(new NoneDicomStudyFile() { FileName = item.FileName, Path = item.FilePath, NoneDicomStudyId = noneDicomStudyId,FileType=item.FileType });
}
var uploadFinishedTime = DateTime.Now;
@@ -489,7 +532,7 @@ namespace IRaCIS.Core.API.Controllers
studyMonitor.IP = _userInfo.IP;
studyMonitor.IsSuccess = true;
await _noneDicomStudyRepository.SaveChangesAsync();
await _repository.SaveChangesAsync();
return ResponseOutput.Ok();
}
@@ -503,13 +546,12 @@ namespace IRaCIS.Core.API.Controllers
/// </summary>
/// <param name="trialId"></param>
/// <param name="oSSService"></param>
/// <param name="_inspectionFileRepository"></param>
/// <returns></returns>
/// <exception cref="BusinessValidationFailedException"></exception>
[HttpPost("QCOperation/UploadVisitCheckExcel/{trialId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput> UploadVisitCheckExcel(Guid trialId, [FromServices] IOSSService oSSService, [FromServices] IRepository<InspectionFile> _inspectionFileRepository)
public async Task<IResponseOutput> UploadVisitCheckExcel(Guid trialId, [FromServices] IOSSService oSSService)
{
var fileName = string.Empty;
@@ -519,9 +561,9 @@ namespace IRaCIS.Core.API.Controllers
{
fileName = realFileName;
if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".csv") && !fileName.EndsWith(".xls"))
{
//---支持.xlsx、.xls格式的文件上传。
//---支持.xlsx、.xls、.csv格式的文件上传。
throw new BusinessValidationFailedException(_localizer["UploadDownLoad_SupportedFormats"]);
}
@@ -531,7 +573,7 @@ namespace IRaCIS.Core.API.Controllers
var ossRelativePath = await oSSService.UploadToOSSAsync(fileStream, "InspectionUpload/Check", realFileName);
await _inspectionFileRepository.AddAsync(new InspectionFile() { FileName = realFileName, RelativePath = ossRelativePath, TrialId = trialId });
await _repository.AddAsync(new InspectionFile() { FileName = realFileName, RelativePath = ossRelativePath, TrialId = trialId });
return ossRelativePath;
@@ -701,16 +743,11 @@ namespace IRaCIS.Core.API.Controllers
//---请保证上传数据符合模板文件中的样式,且存在有效数据。
return ResponseOutput.NotOk(_localizer["UploadDownLoad_InvalidData"]);
}
}
// 适合获取结果的
//var client = _mediator.CreateRequestClient<ConsistenCheckCommand>();
//await client.GetResponse<ConsistenCheckResult>(new ConsistenCheckCommand() { ETCList = etcCheckList, TrialId = trialId });
//不获取结果,不用定义返回类型
await _mediator.Send(new ConsistenCheckCommand() { ETCList = etcCheckList, TrialId = trialId });
await _mediator.Send(new ConsistencyVerificationRequest() { ETCList = etcCheckList, TrialId = trialId });
return ResponseOutput.Ok();
@@ -852,6 +889,89 @@ namespace IRaCIS.Core.API.Controllers
#region
/// <summary>
/// 下载多个医生的所有附件
/// </summary>
/// <param name="doctorIds"></param>
/// <returns></returns>
[Obsolete]
[HttpPost, Route("file/downloadDoctorAttachments")]
public async Task<IResponseOutput<UploadFileInfoDTO>> DownloadAttachment(Guid[] doctorIds)
{
var path = await _fileService.CreateDoctorsAllAttachmentZip(doctorIds);
return ResponseOutput.Ok(new UploadFileInfoDTO
{
FilePath = path,
FullFilePath = path + "?access_token=" + HttpContext.Request.Headers["Authorization"].ToString().Substring(7)
});
}
/// <summary>
/// 下载指定医生的指定附件
/// </summary>
/// <param name="doctorId">医生Id</param>
/// <param name="attachmentIds">要下载的附件Id</param>
/// <returns></returns>
[HttpPost, Route("file/downloadByAttachmentId/{doctorId}")]
[Obsolete]
public async Task<IResponseOutput<UploadFileInfoDTO>> DownloadAttachmentById(Guid doctorId, Guid[] attachmentIds)
{
var path = await _fileService.CreateZipPackageByAttachment(doctorId, attachmentIds);
return ResponseOutput.Ok(new UploadFileInfoDTO
{
FilePath = await _fileService.CreateZipPackageByAttachment(doctorId, attachmentIds),
FullFilePath = path + "?access_token=" + HttpContext.Request.Headers["Authorization"].ToString().Substring(7)
});
}
/// <summary>
/// 下载医生官方简历 首页 区分 中文和英文
/// </summary>
/// <param name="language"></param>
/// <param name="doctorIds"></param>
/// <returns></returns>
[HttpPost, Route("file/downloadOfficialCV/{language}")]
[Obsolete]
public async Task<IResponseOutput<UploadFileInfoDTO>> DownloadOfficialResume(int language, Guid[] doctorIds)
{
var path = await _fileService.CreateDoctorsAllAttachmentZip(doctorIds);
return ResponseOutput.Ok(new UploadFileInfoDTO
{
FilePath = await _fileService.CreateOfficialResumeZip(language, doctorIds),
FullFilePath = path + "?access_token=" + HttpContext.Request.Headers["Authorization"].ToString().Substring(7)
});
}
/// <summary>
/// 入组 项目下载简历
/// </summary>
/// <param name="language"></param>
/// <param name="trialId"></param>
/// <param name="doctorIdArray"></param>
/// <returns></returns>
[HttpPost, Route("enroll/downloadResume/{trialId:guid}/{language}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
[AllowAnonymous]
[Obsolete]
public async Task<IResponseOutput<string>> DownloadResume(int language, Guid trialId, Guid[] doctorIdArray)
{
var zipPath = await _fileService.CreateOfficialResumeZip(language, doctorIdArray);
return ResponseOutput.Ok(zipPath);
}
#endregion
}
#endregion
@@ -944,11 +1064,11 @@ namespace IRaCIS.Core.API.Controllers
}
var generateUserTypeList = new List<string>() { "CRC", "CRA" };
//if (excelList.Any(t => !generateUserTypeList.Contains(t.UserTypeStr.ToUpper())))
//{
// //用户类型仅能为 CRC,SR,CRA 请核查Excel数据
// throw new BusinessValidationFailedException(_localizer["UploadDownLoad_InvalidUserType"]);
//}
if (excelList.Any(t => !generateUserTypeList.Contains(t.UserTypeStr.ToUpper())))
{
//用户类型仅能为 CRC,SR,CRA 请核查Excel数据
throw new BusinessValidationFailedException(_localizer["UploadDownLoad_InvalidUserType"]);
}
if (excelList.Count == 0)
{
throw new BusinessValidationFailedException(_localizer["UploadDownLoad_NoValiddata"]);
+15 -12
View File
@@ -61,23 +61,26 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AlibabaCloud.SDK.Sts20150401" Version="1.1.4" />
<PackageReference Include="aliyun-net-sdk-sts" Version="3.1.2" />
<PackageReference Include="AspNetCoreRateLimit" Version="5.0.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="AWSSDK.SecurityToken" Version="3.7.400.13" />
<PackageReference Include="ConfigMapFileProvider" Version="2.0.1" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.14" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="EasyCaching.Interceptor.Castle" Version="1.9.2" />
<PackageReference Include="EasyCaching.Serialization.MessagePack" Version="1.9.2">
<TreatAsUsed>true</TreatAsUsed>
</PackageReference>
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.12" />
<PackageReference Include="Hangfire.Dashboard.BasicAuthorization" Version="1.0.2" />
<PackageReference Include="Hangfire.InMemory" Version="0.10.3" />
<PackageReference Include="Hangfire.SqlServer" Version="1.8.14" />
<PackageReference Include="Hangfire.SqlServer" Version="1.8.12" />
<PackageReference Include="Invio.Extensions.Authentication.JwtBearer" Version="2.0.1" />
<PackageReference Include="LogDashboard" Version="1.4.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.5" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.2" />
<PackageReference Include="Serilog.Enrichers.ClientInfo" Version="2.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.3" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Enrichers.ClientInfo" Version="2.0.3" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
+43 -18
View File
@@ -29,7 +29,7 @@
<param name="doctorId"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Api.Controllers.ExtraController.Login(IRaCIS.Application.Contracts.UserLoginDTO,ZiggyCreatures.Caching.Fusion.IFusionCache,IRaCIS.Application.Services.IUserService,IRaCIS.Core.Application.Auth.ITokenService,IRaCIS.Core.Application.Contracts.IReadingImageTaskService,Microsoft.Extensions.Options.IOptionsMonitor{IRaCIS.Core.Domain.Share.ServiceVerifyConfigOption},IRaCIS.Application.Services.IMailVerificationService)">
<member name="M:IRaCIS.Api.Controllers.ExtraController.Login(IRaCIS.Application.Contracts.UserLoginDTO,EasyCaching.Core.IEasyCachingProvider,IRaCIS.Application.Services.IUserService,IRaCIS.Core.Application.Auth.ITokenService,IRaCIS.Core.Application.Contracts.IReadingImageTaskService,Microsoft.Extensions.Options.IOptionsMonitor{IRaCIS.Core.Domain.Share.ServiceVerifyConfigOption},IRaCIS.Application.Services.IMailVerificationService)">
<summary> 系统用户登录接口[New] </summary>
</member>
<member name="M:IRaCIS.Core.API.Controllers.Special.FinancialChangeController.AddOrUpdateTrialInspection(IRaCIS.Core.Application.Service.Inspection.DTO.DataInspectionDto{IRaCIS.Application.Contracts.TrialCommand})">
@@ -167,13 +167,6 @@
<param name="opt"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.InspectionController.SignConsistencyAnalysisReadingClinicalData(IRaCIS.Core.Application.Service.Inspection.DTO.DataInspectionDto{IRaCIS.Core.Application.Service.Reading.Dto.SignConsistencyAnalysisReadingClinicalDataInDto})">
<summary>
PM签名一致性分析临床数据
</summary>
<param name="opt"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.InspectionController.SubmitClinicalFormAndSign(IRaCIS.Core.Application.Service.Inspection.DTO.DataInspectionDto{IRaCIS.Core.Application.Service.Reading.Dto.SubmitClinicalFormInDto})">
<summary>
提交结构化录入并签名
@@ -278,26 +271,24 @@
<member name="M:IRaCIS.Core.API.Controllers.UploadBaseController.DicomFileUploadAsync(System.Func{System.String,System.IO.Stream,System.Int32,System.Threading.Tasks.Task},System.String)">
<summary> 流式上传 Dicom上传 </summary>
</member>
<member name="M:IRaCIS.Core.API.Controllers.StudyController.ArchiveStudyNew(System.Guid,System.Guid,System.String,System.Nullable{System.Guid},System.Guid,Microsoft.Extensions.Logging.ILogger{IRaCIS.Core.API.Controllers.UploadDownLoadController},IRaCIS.Core.Application.Contracts.IStudyService,Microsoft.AspNetCore.SignalR.IHubContext{IRaCIS.Core.API.UploadHub,IRaCIS.Core.API.IUploadClient},IRaCIS.Core.Application.Contracts.Dicom.IDicomArchiveService,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.StudyMonitor})">
<member name="M:IRaCIS.Core.API.Controllers.StudyController.ArchiveStudyNew(System.Guid,System.Guid,System.String,System.Nullable{System.Guid},System.Guid,Microsoft.Extensions.Logging.ILogger{IRaCIS.Core.API.Controllers.UploadDownLoadController},EasyCaching.Core.IEasyCachingProvider,IRaCIS.Core.Application.Contracts.IStudyService,Microsoft.AspNetCore.SignalR.IHubContext{IRaCIS.Core.API.UploadHub,IRaCIS.Core.API.IUploadClient},IRaCIS.Core.Application.Contracts.Dicom.IDicomArchiveService,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.StudyMonitor})">
<summary>Dicom 归档</summary>
</member>
<member name="M:IRaCIS.Core.API.Controllers.StudyController.UploadNoneDicomFile(IRaCIS.Core.API.Controllers.StudyController.UploadNoneDicomFileCommand,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.NoneDicomStudy},IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.StudyMonitor},IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.NoneDicomStudyFile})">
<member name="M:IRaCIS.Core.API.Controllers.StudyController.UploadNoneDicomFile(IRaCIS.Core.API.Controllers.StudyController.UploadNoneDicomFileCommand,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.NoneDicomStudy},IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.StudyMonitor})">
<summary>
上传非Dicom 文件 支持压缩包 多文件上传
</summary>
<param name="incommand"></param>
<param name="_noneDicomStudyRepository"></param>
<param name="_studyMonitorRepository"></param>
<param name="_noneDicomStudyFileRepository"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.StudyController.UploadVisitCheckExcel(System.Guid,IRaCIS.Core.Application.Helper.IOSSService,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.InspectionFile})">
<member name="M:IRaCIS.Core.API.Controllers.StudyController.UploadVisitCheckExcel(System.Guid,IRaCIS.Core.Application.Helper.IOSSService)">
<summary>
一致性核查 excel上传 支持三种格式
</summary>
<param name="trialId"></param>
<param name="oSSService"></param>
<param name="_inspectionFileRepository"></param>
<returns></returns>
<exception cref="T:IRaCIS.Core.Infrastructure.BusinessValidationFailedException"></exception>
</member>
@@ -328,6 +319,38 @@
<param name="_attachmentrepository"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.FileController.DownloadAttachment(System.Guid[])">
<summary>
下载多个医生的所有附件
</summary>
<param name="doctorIds"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.FileController.DownloadAttachmentById(System.Guid,System.Guid[])">
<summary>
下载指定医生的指定附件
</summary>
<param name="doctorId">医生Id</param>
<param name="attachmentIds">要下载的附件Id</param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.FileController.DownloadOfficialResume(System.Int32,System.Guid[])">
<summary>
下载医生官方简历 首页 区分 中文和英文
</summary>
<param name="language"></param>
<param name="doctorIds"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.FileController.DownloadResume(System.Int32,System.Guid,System.Guid[])">
<summary>
入组 项目下载简历
</summary>
<param name="language"></param>
<param name="trialId"></param>
<param name="doctorIdArray"></param>
<returns></returns>
</member>
<member name="M:IRaCIS.Core.API.Controllers.UploadDownLoadController.DownloadCommonFile(System.String,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.CommonDocument})">
<summary> 通用文件下载 </summary>
</member>
@@ -353,11 +376,6 @@
序列化,反序列化的时候,处理时间 时区转换
</summary>
</member>
<member name="M:IRaCIS.Core.API.JSONTimeZoneConverter.#ctor(Microsoft.AspNetCore.Http.IHttpContextAccessor)">
<summary>
序列化,反序列化的时候,处理时间 时区转换
</summary>
</member>
<member name="M:IRaCIS.Core.API.NullToEmptyStringResolver.CreateProperties(System.Type,Newtonsoft.Json.MemberSerialization)">
<summary>
创建属性
@@ -366,6 +384,13 @@
<param name="memberSerialization">序列化成员</param>
<returns></returns>
</member>
<member name="M:IRaCIS.WX.CoreApi.Auth.AuthMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext)">
<summary>
为了前端 一段时间无操作,需要重新登陆
</summary>
<param name="httpContext"></param>
<returns></returns>
</member>
<member name="T:TimeZoneAdjustmentMiddleware">
<summary>
废弃,没用
+28 -104
View File
@@ -4,6 +4,8 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using MediatR;
using IRaCIS.Core.Application.MediatR.Handlers;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.NewIdProviders;
@@ -26,16 +28,8 @@ using FellowOakDicom.Network;
using IRaCIS.Core.Application.Service.ImageAndDoc;
using IP2Region.Net.Abstractions;
using IP2Region.Net.XDB;
using IRaCIS.Core.Application.BusinessFilter;
using Microsoft.AspNetCore.Http;
using IRaCIS.Core.Infrastructure.Extention;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Diagnostics;
using IRaCIS.Core.Application.MassTransit.Command;
using IRaCIS.Core.Application.MassTransit.Consumer;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
#region
//以配置文件为准,否则 从url中取环境值(服务以命令行传递参数启动,配置文件配置了就不需要传递环境参数)
var config = new ConfigurationBuilder()
@@ -82,8 +76,8 @@ if (urlsIndex > -1)
NewId.SetProcessIdProvider(new CurrentProcessIdProvider());
builder.Configuration.AddJsonFile(ConfigMapFileProvider.FromRelativePath(""), "appsettings.json", false, true)
.AddJsonFile(ConfigMapFileProvider.FromRelativePath(""), $"appsettings.{enviromentName}.json", false, true);
builder.Configuration.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{enviromentName}.json", false, true);
builder.Host
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
@@ -110,9 +104,11 @@ builder.Services.AddControllers(options =>
options.Filters.Add<ModelActionFilter>();
options.Filters.Add<ProjectExceptionFilter>();
options.Filters.Add<UnitOfWorkFilter>();
options.Filters.Add<EncreptApiResultFilter>(10);
options.Filters.Add<LimitUserRequestAuthorization>();
if (_configuration.GetSection("BasicSystemConfig").GetValue<bool>("OpenLoginLimit"))
{
options.Filters.Add<LimitUserRequestAuthorization>();
}
})
.AddNewtonsoftJsonSetup(builder.Services); // NewtonsoftJson 序列化 处理
@@ -121,8 +117,6 @@ builder.Services.AddOptions().Configure<SystemEmailSendConfig>(_configuration.Ge
builder.Services.AddOptions().Configure<ServiceVerifyConfigOption>(_configuration.GetSection("BasicSystemConfig"));
builder.Services.AddOptions().Configure<AliyunOSSOptions>(_configuration.GetSection("AliyunOSS"));
builder.Services.AddOptions().Configure<ObjectStoreServiceOptions>(_configuration.GetSection("ObjectStoreService"));
builder.Services.AddOptions().Configure<EncreptResponseOption>(_configuration.GetSection("EncrypteResponseConfig"));
builder.Services.AddOptions().Configure<SystemPacsConfig>(_configuration.GetSection("SystemPacsConfig"));
//动态WebApi + UnifiedApiResultFilter 省掉控制器代码
@@ -130,7 +124,7 @@ builder.Services.AddDynamicWebApiSetup();
//AutoMapper
builder.Services.AddAutoMapperSetup();
//EF ORM QueryWithNoLock
builder.Services.AddEFSetup(_configuration,enviromentName);
builder.Services.AddEFSetup(_configuration);
//Http 响应压缩
builder.Services.AddResponseCompressionSetup();
//Swagger Api 文档
@@ -139,30 +133,9 @@ builder.Services.AddSwaggerSetup();
builder.Services.AddJWTAuthSetup(_configuration);
// MediatR 进程内消息 事件解耦 从程序集中 注册命令和handler对应关系
//builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<ConsistencyVerificationHandler>());
#region MassTransit
//masstransit组件 也支持MediatR 中介者模式,但是支持分布式,考虑后续,所以在次替代MediatR
builder.Services.AddMediator(cfg =>
{
cfg.AddConsumer<ConsistencyCheckConsumer>();
});
builder.Services.AddMassTransit(cfg =>
{
cfg.UsingInMemory();
});
#endregion
#region FusionCache
builder.Services.AddFusionCache();
#endregion
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<ConsistencyVerificationHandler>());
// EasyCaching 缓存
//builder.Services.AddEasyCachingSetup(_configuration);
builder.Services.AddEasyCachingSetup(_configuration);
// hangfire 定时任务框架 有界面,更友好~
builder.Services.AddhangfireSetup(_configuration);
@@ -190,8 +163,6 @@ builder.Services.AddSingleton<IUserIdProvider, IRaCISUserIdProvider>();
builder.Services.AddSingleton<ISearcher>(new Searcher(CachePolicy.Content, Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources, "ip2region.xdb")));
//builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
//builder.Services.AddProblemDetails();
#region
//builder.Services.AddMemoryCache();
@@ -218,56 +189,6 @@ var env = app.Environment;
// Configure the HTTP request pipeline.
#region 400 -500
//app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseStatusCodePages(async context =>
{
var code = context.HttpContext.Response.StatusCode;
context.HttpContext.Response.ContentType = "application/json";
if (code < 500)
{
await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk($"Client error, actual request error status code({code})")));
}
else
{
//ResultFilter 里面的异常并不会到这里
await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject((ResponseOutput.NotOk($"Server error , actual request error status code({code})"))));
}
});
//app.UseExceptionHandler(o => { });
//这里没生效,原因未知,官方文档也是这种写法,也用了GlobalExceptionHandler 尝试,还是不行,怀疑框架bug
//app.UseExceptionHandler(configure =>
//{
// configure.Run(async context =>
// {
// var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
//var ex = exceptionHandlerPathFeature?.Error;
//context.Response.ContentType = "application/json";
//if (ex != null)
//{
// var errorInfo = $"Exception: {ex.Message}[{ex.StackTrace}]" + (ex.InnerException != null ? $" InnerException: {ex.InnerException.Message}[{ex.InnerException.StackTrace}]" : "");
// await context.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk($"{ex?.Message}")));
// Log.Logger.Error(errorInfo);
//}
// });
//});
#endregion
//本地化
app.UseLocalization();
@@ -276,11 +197,12 @@ app.UseForwardedHeaders();
//响应压缩
app.UseResponseCompression();
//app.UseCors(t => t.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
//不需要 token 访问的静态文件 wwwroot css, JavaScript, and images don't require authentication.
app.UseStaticFiles();
app.UseMiddleware<MultiDiskStaticFilesMiddleware>();
//LogDashboard
app.UseLogDashboard("/LogDashboard");
@@ -288,24 +210,22 @@ app.UseLogDashboard("/LogDashboard");
//hangfire
app.UseHangfireConfig(env);
#region
//app.UseMiddleware<MultiDiskStaticFilesMiddleware>();
////限流 中间件
//app.UseIpRateLimiting();
//if (env.IsDevelopment())
//{
// app.UseDeveloperExceptionPage();
//}
//else
//{
// //app.UseHsts();
//}
#endregion
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//app.UseHsts();
}
// 特殊异常处理 比如 404
app.UseStatusCodePagesWithReExecute("/Error/{0}");
SwaggerSetup.Configure(app, env);
@@ -375,6 +295,10 @@ try
//Log.Logger.Warning($"ContentRootPath——xx{Path.GetDirectoryName(Path.GetDirectoryName(env.ContentRootPath))}");
var server = DicomServerFactory.Create<CStoreSCPService>(11112,userState: app.Services);
app.Run();
}
@@ -24,14 +24,6 @@
},
"applicationUrl": "http://localhost:6100"
},
"IRaCIS.Test_IRC_PGSQL": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Test_IRC_PGSQL"
},
"applicationUrl": "http://localhost:6100"
},
"IRaCIS.Event_IRC": {
"commandName": "Project",
"launchBrowser": true,
+2 -1
View File
@@ -1,4 +1,5 @@
using IRaCIS.Core.Domain.Share;
using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.SignalR;
@@ -0,0 +1,66 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Threading.Tasks;
using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
namespace IRaCIS.WX.CoreApi.Auth
{
public class AuthMiddleware
{
private readonly RequestDelegate _next;
private readonly IEasyCachingProvider _provider;
public AuthMiddleware(RequestDelegate next, IEasyCachingProvider provider)
{
_next = next;
_provider = provider;
}
/// <summary>
///为了前端 一段时间无操作,需要重新登陆
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public async Task Invoke(HttpContext httpContext)
{
var isLogin = httpContext.Request.Path.ToString().ToLower().Contains("login");
var result = await httpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (!isLogin)
{
if (!result.Succeeded)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await httpContext.Response.WriteAsync("Unauthorized");
}
else
{
var toekn = result.Properties.Items[".Token.access_token"];
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(toekn);
object userId;
jwtToken.Payload.TryGetValue("id", out userId);
var cacheValueExist = await _provider.ExistsAsync(userId.ToString()); //Get<string>(userId.ToString()).ToString();
if (!cacheValueExist)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await httpContext.Response.WriteAsync("Unauthorized");
}
else
{
await _provider.SetAsync(userId.ToString(), userId.ToString(), TimeSpan.FromMinutes(15));
httpContext.User = result.Principal;
await _next.Invoke(httpContext);
}
}
}
else await _next.Invoke(httpContext);
}
}
}
@@ -1,5 +1,4 @@
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Localization;
using System.Collections.Generic;
using System.Globalization;
@@ -13,9 +12,8 @@ namespace IRaCIS.Core.API
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo(StaticData.CultureInfo.en_US),
new CultureInfo(StaticData.CultureInfo.zh_CN)
new CultureInfo("en-US"),
new CultureInfo("zh-CN")
};
var options = new RequestLocalizationOptions
@@ -20,20 +20,18 @@ namespace IRaCIS.Core.API
// Set all the common properties available for every request
diagnosticContext.Set("Host", request.Host);
diagnosticContext.Set("Protocol", request.Protocol);
diagnosticContext.Set("Scheme", request.Scheme);
#region old
//这种获取的Ip不准 配置服务才行
//diagnosticContext.Set("RequestIP", httpContext.Connection.RemoteIpAddress.ToString());
//这种方式可以,但是serilog提供了 就不用了
//diagnosticContext.Set("TestIP", httpContext.GetUserIp());
diagnosticContext.Set("Protocol", request.Protocol);
diagnosticContext.Set("Scheme", request.Scheme);
//这种方式不行 读取的body为空字符串 必须在中间件中读取
//diagnosticContext.Set("RequestBody", await ReadRequestBody(httpContext.Request));
//diagnosticContext.Set("RequestBody", RequestPayload);
#endregion
// Only set it if available. You're not sending sensitive data in a querystring right?!
if (request.QueryString.HasValue)
@@ -1,6 +1,5 @@
using AutoMapper.EquivalencyExpression;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Domain.Models;
using Microsoft.Extensions.DependencyInjection;
namespace IRaCIS.Core.API
@@ -15,15 +14,11 @@ namespace IRaCIS.Core.API
//AutoMapper.Collection.EntityFrameworkCore
automapper.AddCollectionMappers();
// 全局忽略 DomainEvents 属性
automapper.AddGlobalIgnore(nameof(Entity.DomainEvents));
#region 使 IncludeMembers 使
//mapping an EntityFramework Core DbContext-object.
//automapper.UseEntityFrameworkCoreModel<IRaCISDBContext>(services);
//automapper.ForAllMaps((a, b) => b.ForAllMembers(opt => opt.Condition((src, dest, srcMember, desMenber) =>
//{
// //// Can test When Guid? -> Guid if source is null will change to Guid.Empty
@@ -32,7 +27,7 @@ namespace IRaCIS.Core.API
// // not want to map a null Guid? value to db Guid value
//})));
#endregion
}, typeof(QCConfig).Assembly);
@@ -1,4 +1,5 @@
using Autofac;
using Autofac.Extras.DynamicProxy;
using IRaCIS.Core.Application;
using IRaCIS.Core.Application.BackGroundJob;
using IRaCIS.Core.Infra.EFCore;
@@ -9,6 +10,7 @@ using System.Linq;
using System.Reflection;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using MediatR;
using IRaCIS.Application.Services;
using IRaCIS.Application.Interfaces;
using AutoMapper;
@@ -49,12 +51,12 @@ namespace IRaCIS.Core.API
Assembly application = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "IRaCIS.Core.Application.dll");
containerBuilder.RegisterAssemblyTypes(application).Where(t => t.FullName.Contains("Service"))
.PropertiesAutowired().AsImplementedInterfaces();
.PropertiesAutowired().AsImplementedInterfaces().EnableClassInterceptors();
//containerBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
//containerBuilder.RegisterType<UserInfo>().As<IUserInfo>().InstancePerLifetimeScope();
containerBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
containerBuilder.RegisterType<UserInfo>().As<IUserInfo>().InstancePerLifetimeScope();
//注册hangfire任务 依赖注入
+6 -46
View File
@@ -1,65 +1,31 @@
using EntityFramework.Exceptions.SqlServer;
using Hangfire.SqlServer;
using Hangfire.SqlServer;
using IRaCIS.Core.Application.Triggers;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Infra.EFCore.Interceptor;
using Medallion.Threading;
using Medallion.Threading.SqlServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
namespace IRaCIS.Core.API
{
public static class EFSetup
{
public static void AddEFSetup( this IServiceCollection services, IConfiguration configuration,string envName)
public static void AddEFSetup( this IServiceCollection services, IConfiguration configuration)
{
services.AddHttpContextAccessor();
services.AddScoped<IUserInfo, UserInfo>();
services.AddScoped<ISaveChangesInterceptor, AuditEntityInterceptor>();
services.AddScoped<ISaveChangesInterceptor, DispatchDomainEventsInterceptor>();
// First, register a pooling context factory as a Singleton service, as usual:
//services.AddScoped<DbContext, IRaCISDBContext>();
//这个注入没有成功--注入是没问题的,构造函数也只是支持参数就好,错在注入的地方不能写DbContext
//Web程序中通过重用池中DbContext实例可提高高并发场景下的吞吐量, 这在概念上类似于ADO.NET Provider原生的连接池操作方式,具有节省DbContext实例化成本的优点
services.AddDbContext<IRaCISDBContext>((sp, options) =>
services.AddDbContext<IRaCISDBContext>(options =>
{
// 在控制台
//public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
var logFactory = LoggerFactory.Create(builder => { builder.AddDebug(); });
var dbType = configuration.GetSection("ConnectionStrings:Db_Type").Value ;
if (!string.IsNullOrWhiteSpace(dbType) && dbType == "pgsql")
{
options.UseNpgsql(configuration.GetSection("ConnectionStrings:RemoteNew").Value, contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure());
}
else
{
options.UseSqlServer(configuration.GetSection("ConnectionStrings:RemoteNew").Value, contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure());
}
options.UseLoggerFactory(logFactory);
options.UseExceptionProcessor();
options.UseSqlServer(configuration.GetSection("ConnectionStrings:RemoteNew").Value,
contextOptionsBuilder => contextOptionsBuilder.EnableRetryOnFailure());
options.EnableSensitiveDataLogging();
options.AddInterceptors(new QueryWithNoLockDbCommandInterceptor());
options.AddInterceptors(sp.GetServices<ISaveChangesInterceptor>());
options.UseProjectables();
@@ -96,12 +62,6 @@ namespace IRaCIS.Core.API
});
// Register an additional context factory as a Scoped service, which gets a pooled context from the Singleton factory we registered above,
//services.AddScoped<IRaCISDBScopedFactory>();
//// Finally, arrange for a context to get injected from our Scoped factory:
//services.AddScoped(sp => sp.GetRequiredService<IRaCISDBScopedFactory>().CreateDbContext());
//注意区分 easy caching 也有 IDistributedLockProvider
services.AddSingleton<IDistributedLockProvider>(sp =>
{
@@ -1,4 +1,7 @@
using Microsoft.Extensions.Configuration;
using EasyCaching.Core;
using EasyCaching.Core.Configurations;
using EasyCaching.Interceptor.Castle;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace IRaCIS.Core.API
@@ -7,18 +10,18 @@ namespace IRaCIS.Core.API
{
public static void AddEasyCachingSetup(this IServiceCollection services, IConfiguration configuration)
{
//services.AddEasyCaching(options =>
//{
// options.UseInMemory();
services.AddEasyCaching(options =>
{
options.UseInMemory();
// //options.UseRedis(configuration, EasyCachingConstValue.DefaultRedisName).WithMessagePack(EasyCachingConstValue.DefaultRedisName);
//options.UseRedis(configuration, EasyCachingConstValue.DefaultRedisName).WithMessagePack(EasyCachingConstValue.DefaultRedisName);
//});
});
////services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultRedisName);
//services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultRedisName);
//services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultInMemoryName);
services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultInMemoryName);
}
}
}
@@ -11,39 +11,19 @@ namespace IRaCIS.Core.API
/// <summary>
/// 序列化,反序列化的时候,处理时间 时区转换
/// </summary>
public class JSONTimeZoneConverter(IHttpContextAccessor _httpContextAccessor) : DateTimeConverterBase
public class JSONTimeZoneConverter : DateTimeConverterBase
{
private readonly IHttpContextAccessor _httpContextAccessor;
private TimeZoneInfo _clientTimeZone;
private string _dateFormat;
public override bool CanConvert(Type objectType)
private readonly TimeZoneInfo _clientTimeZone;
public JSONTimeZoneConverter(IHttpContextAccessor httpContextAccessor)
{
#region
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
if (!isEn_US)
{
// Chinese date format
_dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
_dateFormat = "MM/dd/yyyy HH:mm:ss";
}
#endregion
#region
_httpContextAccessor = httpContextAccessor;
//默认是UTC
//var timeZoneId = "Etc/UTC";
var timeZoneId = "Asia/Shanghai";
var timeZoneIdHeader = _httpContextAccessor?.HttpContext?.Request?.Headers["TimeZoneId"];
if (timeZoneIdHeader is not null && !string.IsNullOrEmpty(timeZoneIdHeader.Value))
@@ -53,12 +33,12 @@ namespace IRaCIS.Core.API
_clientTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
#endregion
}
public override bool CanConvert(Type objectType)
{
// 仅支持 DateTime 类型的转换
return objectType == typeof(DateTime)|| objectType == typeof(DateTime?);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
@@ -111,10 +91,7 @@ namespace IRaCIS.Core.API
{
//第一个参数默认使用系统本地时区 也就是应用服务器的时区
DateTime clientZoneTime = TimeZoneInfo.ConvertTime(nullableDateTime.Value, _clientTimeZone);
//writer.WriteValue(clientZoneTime);
writer.WriteValue(clientZoneTime.ToString(_dateFormat));
writer.WriteValue(clientZoneTime);
}
else
{
@@ -1,99 +0,0 @@
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Globalization;
using System.Reflection;
namespace IRaCIS.Core.API
{
//public class CustomContractResolver : DefaultContractResolver
//{
// protected override JsonContract CreateContract(Type objectType)
// {
// var contract = base.CreateContract(objectType);
// // 检查类是否有 LowercaseJsonAttribute 标记
// if (objectType.GetCustomAttribute<LowerCamelCaseJsonAttribute>() != null)
// {
// contract.NamingStrategy = new IRCCamelCaseNamingStrategy();
// }
// return contract;
// }
//}
#region
public class MyDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return reader.ReadAsDateTime().Value;
}
public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
string dateFormat;
if (!isEn_US)
{
// Chinese date format
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
dateFormat = "MM/dd/yyyy HH:mm:ss";
}
writer.WriteValue(value.ToString(dateFormat));
}
}
public class MyNullableDateTimeConverter : JsonConverter<DateTime?>
{
public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var val = reader.ReadAsDateTime();
return val;
}
public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
string dateFormat;
if (!isEn_US)
{
// Chinese date format
dateFormat = "yyyy-MM-dd HH:mm:ss";
}
else
{
// Default or English date format
dateFormat = "MM/dd/yyyy HH:mm:ss";
}
if (value.HasValue)
{
writer.WriteValue(value.Value.ToString(dateFormat));
}
else
{
writer.WriteValue(default(DateTime?));
}
}
}
#endregion
}
@@ -1,16 +1,10 @@
using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Globalization;
using System.Text.Json;
using Newtonsoft.Json.Serialization;
namespace IRaCIS.Core.API
{
@@ -18,43 +12,34 @@ namespace IRaCIS.Core.API
{
public static void AddNewtonsoftJsonSetup(this IMvcBuilder builder, IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<JSONTimeZoneConverter>();
services.AddScoped<ObjectStorePathConvert>();
services.AddScoped<IOSSService, OSSService>();
services.AddScoped<CustomStringConverter>();
services.AddScoped<IOSSService,OSSService>();
builder.AddNewtonsoftJson(options =>
{
//大驼峰
//options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//小驼峰
//options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
// 忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
//处理返回给前端 可空类型 给出默认值 比如in? 为null 设置 默认值0
options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver();
// 设置时间格式 isEn_US? "MM/dd/yyyy HH:mm:ss" :
//options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver(); //new DefaultContractResolver();// new NullToEmptyStringResolver();
// 设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
//options.SerializerSettings.Converters.Add(new JSONCustomDateConverter()) ;
//二者只能取其一
//options.SerializerSettings.Converters.Add(new MyDateTimeConverter());
//options.SerializerSettings.Converters.Add(new MyNullableDateTimeConverter());
//必须放在后面
options.SerializerSettings.Converters.Add(services.BuildServiceProvider().GetService<JSONTimeZoneConverter>());
//options.SerializerSettings.Converters.Add(services.BuildServiceProvider().GetService<CustomStringConverter>());
//IsoDateTimeConverter
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
})
.AddControllersAsServices()//动态webApi属性注入需要
@@ -1,10 +1,8 @@
using IRaCIS.Core.Infrastructure.NewtonsoftJson;
using Newtonsoft.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace IRaCIS.Core.API
{
@@ -32,20 +30,8 @@ namespace IRaCIS.Core.API
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
// 检查类是否有 LowerCamelCaseJsonAttribute 标记 有的话,属性名小写
if (type.GetCustomAttribute<LowerCamelCaseJsonAttribute>() != null)
{
base.NamingStrategy= new LowerCamelCaseNamingStrategy();
}
else
{
base.NamingStrategy = null;
}
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
var list= type.GetProperties()
.Select(p =>
{
@@ -9,13 +9,15 @@ using System.Text.RegularExpressions;
namespace IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson
{
public class ObjectStorePathConvert : JsonConverter<string>
public class CustomStringConverter : JsonConverter<string>
{
//private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IOSSService _oSSService;
// 构造函数
public ObjectStorePathConvert( IOSSService oSSService)
public CustomStringConverter(/*IHttpContextAccessor httpContextAccessor*/ IOSSService oSSService)
{
//_httpContextAccessor = httpContextAccessor;
_oSSService = oSSService;
}
@@ -1,30 +1,18 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using System.IO.Compression;
namespace IRaCIS.Core.API
{
public static class ResponseCompressionSetup
public static class ResponseCompressionSetup
{
public static void AddResponseCompressionSetup(this IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
}
}
}
@@ -31,13 +31,13 @@ namespace IRaCIS.Core.API
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("LocalIP", httpContext.Connection.LocalIpAddress.MapToIPv4().ToString()));
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TokenUserRealName", httpContext?.User?.FindFirst(ClaimAttributes.RealName)?.Value));
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TokenUserType", httpContext?.User?.FindFirst(JwtIRaCISClaimType.UserTypeShortName)?.Value));
//这样读取没用
//logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestBody", await ReadRequestBody(httpContext.Request)));
//logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestIP", IPHelper.GetIP(httpContext.Request) ));
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TokenUserRealName", httpContext?.User?.FindFirst(ClaimAttributes.RealName)?.Value));
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("TokenUserType", httpContext?.User?.FindFirst(JwtIRaCISClaimType.UserTypeShortName)?.Value));
//logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Referer", httpContext.Request.Headers["Referer"].ToString()));
//logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("request_path", httpContext.Request.Path));
//logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("request_method", httpContext.Request.Method));
@@ -3,7 +3,6 @@ using Hangfire.SqlServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Runtime.InteropServices;
namespace IRaCIS.Core.API
{
@@ -15,29 +14,19 @@ namespace IRaCIS.Core.API
services.AddHangfire(hangFireConfig =>
{
//本地window 调试 使用内存,服务器部署使用数据库,防止服务器任务调度到本地
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
//hangFireConfig.UseInMemoryStorage();
//指定存储介质
hangFireConfig.UseSqlServerStorage(hangFireConnStr, new SqlServerStorageOptions()
{
hangFireConfig.UseInMemoryStorage();
}
else
{
//指定存储介质
hangFireConfig.UseSqlServerStorage(hangFireConnStr, new SqlServerStorageOptions()
{
SchemaName = "dbo",
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
});
}
SchemaName = "dbo",
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
});
//hangFireConfig.UseTagsWithSql(); //nuget引入Hangfire.Tags.SqlServer
//.UseHangfireHttpJob();
+1 -5
View File
@@ -47,11 +47,7 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
"ReadingRestTimeMin": 10
},
"SystemEmailSendConfig": {
"Port": 465,
+1 -8
View File
@@ -49,10 +49,8 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ReadingRestTimeMin": 10
"ChangePassWordDays": 90
},
"SystemEmailSendConfig": {
@@ -68,10 +66,5 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗"
},
"SystemPacsConfig": {
"Port": "11113",
"IP": "101.132.193.237"
}
}
+27 -35
View File
@@ -9,6 +9,7 @@
"ConnectionStrings": {
"RemoteNew": "Server=106.14.89.110,1435;Database=Test_IRC;User ID=sa;Password=xc@123456;TrustServerCertificate=true",
"Hangfire": "Server=106.14.89.110,1435;Database=Test_IRC_Hangfire;User ID=sa;Password=xc@123456;TrustServerCertificate=true"
},
"ObjectStoreService": {
@@ -16,36 +17,33 @@
"ObjectStoreUse": "AliyunOSS",
"AliyunOSS": {
"RegionId": "cn-shanghai",
"InternalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"EndPoint": "https://oss-cn-shanghai.aliyuncs.com",
"AccessKeyId": "LTAI5tJV76pYX5yPg1N9QVE8",
"AccessKeySecret": "roRNLa9YG1of4pYruJGCNKBXEWTAWa",
"BucketName": "zy-irc-test-store",
"RoleArn": "acs:ram::1899121822495495:role/webdirect",
"ViewEndpoint": "https://zy-irc-test-store.oss-cn-shanghai.aliyuncs.com",
"Region": "oss-cn-shanghai",
"DurationSeconds": 7200
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endPoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"accessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"bucketName": "zy-irc-test-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-test-store.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"MinIO": {
"EndPoint": "hir-oss.test.extimaging.com",
"Port": "443",
"UseSSL": true,
"AccessKey": "fbStsVYCIPKHQneeqMwD",
"SecretKey": "TzgvyA3zGXMUnpilJNUlyMYHfosl1hBMl6lxPmjy",
"BucketName": "irc-test",
"ViewEndpoint": "https://hir-oss.test.extimaging.com/irc-test"
"endPoint": "hir-oss.test.extimaging.com",
"port": "443",
"useSSL": true,
"accessKey": "fbStsVYCIPKHQneeqMwD",
"secretKey": "TzgvyA3zGXMUnpilJNUlyMYHfosl1hBMl6lxPmjy",
"bucketName": "irc-test",
"viewEndpoint": "https://hir-oss.test.extimaging.com/irc-test"
},
"AWS": {
"Region": "us-east-1",
"EndPoint": "s3.us-east-1.amazonaws.com",
"UseSSL": true,
"RoleArn": "arn:aws:iam::471112624751:role/sts_s3_upload",
"AccessKeyId": "AKIAW3MEAFJXWRCGSX5Z",
"SecretAccessKey": "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",
"BucketName": "ei-med-s3-lili-uat-store",
"ViewEndpoint": "https://ei-med-s3-lili-uat-store.s3.amazonaws.com/",
"DurationSeconds": 7200
"endPoint": "s3.us-east-1.amazonaws.com",
"useSSL": true,
"accessKey": "AKIAZQ3DRSOHFPJJ6FEU",
"secretKey": "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",
"bucketName": "ei-irc-test-store",
"viewEndpoint": "https://ei-irc-test-store.s3.amazonaws.com/"
}
},
@@ -69,10 +67,7 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
"ReadingRestTimeMin": 10
},
"SystemEmailSendConfig": {
@@ -81,6 +76,7 @@
"FromEmail": "test@extimaging.com",
"FromName": "Test_IRC",
"AuthorizationCode": "SHzyyl2021",
"SiteUrl": "http://irc.test.extimaging.com/login",
"OrganizationName": "Extlmaging",
@@ -89,10 +85,6 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗"
},
"SystemPacsConfig": {
"Port": "11113",
"IP": "106.14.89.110"
}
}
@@ -1,95 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"Db_Type": "pgsql",
"RemoteNew": "Host=106.14.89.110;Port=5432;Username=sa;Password=pgsql_pwd;Database=Test2_PG",
"Hangfire": "Server=106.14.89.110,1435;Database=Test_IRC_Hangfire;User ID=sa;Password=xc@123456;TrustServerCertificate=true"
},
"ObjectStoreService": {
"ObjectStoreUse": "AliyunOSS",
"AliyunOSS": {
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endPoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"accessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"bucketName": "zy-irc-test-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-test-store.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"MinIO": {
"endPoint": "hir-oss.test.extimaging.com",
"port": "443",
"useSSL": true,
"accessKey": "fbStsVYCIPKHQneeqMwD",
"secretKey": "TzgvyA3zGXMUnpilJNUlyMYHfosl1hBMl6lxPmjy",
"bucketName": "irc-test",
"viewEndpoint": "https://hir-oss.test.extimaging.com/irc-test"
},
"AWS": {
"endPoint": "s3.us-east-1.amazonaws.com",
"useSSL": true,
"accessKey": "AKIAZQ3DRSOHFPJJ6FEU",
"secretKey": "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",
"bucketName": "ei-irc-test-store",
"viewEndpoint": "https://ei-irc-test-store.s3.amazonaws.com/"
}
},
"BasicSystemConfig": {
"OpenUserComplexPassword": false,
"OpenSignDocumentBeforeWork": false,
"OpenTrialRelationDelete": true,
"OpenLoginLimit": false,
"LoginMaxFailCount": 5,
"LoginFailLockMinutes": 1,
"AutoLoginOutMinutes": 1,
"OpenLoginMFA": false,
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
},
"SystemEmailSendConfig": {
"Port": 465,
"Host": "smtp.qiye.aliyun.com",
"FromEmail": "test@extimaging.com",
"FromName": "Test_IRC",
"AuthorizationCode": "SHzyyl2021",
"SiteUrl": "http://irc.test.extimaging.com/login",
"OrganizationName": "Extlmaging",
"OrganizationNameCN": "Extlmaging",
"CompanyName": "Extensive Imaging",
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗"
},
"SystemPacsConfig": {
"Port": "11113",
"IP": "106.14.89.110"
}
}
+2 -14
View File
@@ -15,18 +15,6 @@
"ObjectStoreService": {
"ObjectStoreUse": "AWS",
"AliyunOSS": {
"regionId": "cn-shanghai",
"internalEndpoint": "https://oss-cn-shanghai-internal.aliyuncs.com",
"endPoint": "https://oss-cn-shanghai.aliyuncs.com",
"accessKeyId": "",
"accessKeySecret": "",
"bucketName": "zy-irc-test-store",
"roleArn": "acs:ram::1899121822495495:role/oss-upload",
"viewEndpoint": "https://zy-irc-test-store.oss-cn-shanghai.aliyuncs.com",
"region": "oss-cn-shanghai"
},
"MinIO": {
"endPoint": "44.210.231.169",
"port": "9001",
@@ -59,14 +47,14 @@
"LoginMaxFailCount": 5,
"LoginFailLockMinutes": 30,
"AutoLoginOutMinutes": 60,
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
"OpenLoginMFA": false
},
"SystemEmailSendConfig": {
+1 -4
View File
@@ -69,10 +69,7 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
"ReadingRestTimeMin": 10
},
"SystemEmailSendConfig": {
@@ -62,9 +62,6 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90,
"OpenLoginMFA": true
},
+8 -15
View File
@@ -28,12 +28,12 @@
"MinIO": {
"endPoint": "hir-oss.uat.extimaging.com",
"port": "80",
"useSSL": false,
"viewEndpoint": "http://hir-oss.uat.extimaging.com/irc-uat",
//"port": "443",
//"useSSL": true,
//"viewEndpoint": "https://hir-oss.uat.extimaging.com/irc-uat",
//"port": "80",
//"useSSL": false,
//"viewEndpoint": "http://hir-oss.uat.extimaging.com/irc-uat",
"port": "443",
"useSSL": true,
"viewEndpoint": "https://hir-oss.uat.extimaging.com/irc-uat",
"accessKey": "b9Ul0e98xPzt6PwRXA1Q",
"secretKey": "DzMaU2L4OXl90uytwOmDXF2encN0Jf4Nxu2XkYqQ",
"bucketName": "irc-uat"
@@ -56,10 +56,7 @@
"ContinuousReadingTimeMin": 120,
"ReadingRestTimeMin": 10,
"IsNeedChangePassWord": true,
"ChangePassWordDays": 90
"ReadingRestTimeMin": 10
},
"SystemEmailSendConfig": {
@@ -75,11 +72,7 @@
"CompanyNameCN": "上海展影医疗科技有限公司",
"CompanyShortName": "Extensive Imaging",
"CompanyShortNameCN": "展影医疗"
},
"SystemPacsConfig": {
"Port": "11113",
"IP": "47.117.164.182"
}
}
+1 -7
View File
@@ -90,13 +90,7 @@
"DicomStudyCodePrefix": "ST",
"SystemSiteCodePrefix": "S",
"DefaultPassword": "123456",
"DefaultInternalOrganizationName": "ExtImaging",
"ImageShareExpireDays": 10
},
"EncrypteResponseConfig": {
"IsEnable": true,
"ApiPathList": [
"/test/get"
]
}
}
@@ -1,4 +1,5 @@
using Hangfire;
using EasyCaching.Core;
using Hangfire;
using Hangfire.Storage;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.Service;
@@ -8,7 +9,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SharpCompress.Common;
using ZiggyCreatures.Caching.Fusion;
namespace IRaCIS.Application.Services.BackGroundJob
{
@@ -16,50 +16,172 @@ namespace IRaCIS.Application.Services.BackGroundJob
public interface IIRaCISHangfireJob
{
//Task MemoryCacheTrialStatusAsync();
Task MemoryCacheTrialStatusAsync();
Task InitHangfireJobTaskAsync();
}
public class IRaCISCHangfireJob(ILogger<IRaCISCHangfireJob> _logger,
IRepository<Internationalization> _internationalizationRepository,
IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository
) : IIRaCISHangfireJob
public class IRaCISCHangfireJob : IIRaCISHangfireJob
{
public static string JsonFileFolder = Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources);
public static FileSystemWatcher FileSystemWatcher_US { get; set; }
public static FileSystemWatcher FileSystemWatcher_CN { get; set; }
private readonly IRepository<Trial> _trialRepository;
private readonly IEasyCachingProvider _provider;
private readonly ILogger<IRaCISCHangfireJob> _logger;
private readonly IRepository<SystemAnonymization> _systemAnonymizationRepository;
private readonly IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository;
private readonly IRepository<Internationalization> _internationalizationRepository;
public IRaCISCHangfireJob(IRepository<Trial> trialRepository, ILogger<IRaCISCHangfireJob> logger, IEasyCachingProvider provider, IRepository<TrialEmailNoticeConfig> trialEmailNoticeConfigRepository, IRepository<Internationalization> internationalizationRepository, IRepository<SystemAnonymization> systemAnonymizationRepository)
{
_trialRepository = trialRepository;
_provider = provider;
_logger = logger;
_trialEmailNoticeConfigRepository = trialEmailNoticeConfigRepository;
_internationalizationRepository = internationalizationRepository;
_systemAnonymizationRepository = systemAnonymizationRepository;
}
public async Task InitHangfireJobTaskAsync()
{
_logger.LogInformation("项目启动 hangfire 任务初始化 执行开始~");
//初始化国际化
await InternationalizationHelper.InitInternationlizationDataAndWatchJsonFileAsync(_internationalizationRepository);
//项目状态 立即加载到缓存中
await MemoryCacheTrialStatusAsync();
await MemoryCacheAnonymizeData();
//创建项目缓存 定时任务
HangfireJobHelper.AddOrUpdateInitCronJob<IIRaCISHangfireJob>("RecurringJob_Cache_TrialState", t => t.MemoryCacheTrialStatusAsync(), Cron.Daily());
//初始化
await InitInternationlizationDataAndWatchJsonFileAsync();
//创建邮件定时任务
await InitSysAndTrialCronJobAsync();
#region
////项目状态 立即加载到缓存中
//await MemoryCacheTrialStatusAsync();
////await MemoryCacheAnonymizeData();
////创建项目缓存 定时任务
//HangfireJobHelper.AddOrUpdateInitCronJob<IIRaCISHangfireJob>("RecurringJob_Cache_TrialState", t => t.MemoryCacheTrialStatusAsync(), Cron.Daily());
#endregion
_logger.LogInformation("项目启动 hangfire 任务初始化 执行结束");
}
/// <summary>
/// 缓存项目状态
/// </summary>
/// <returns></returns>
public async Task MemoryCacheTrialStatusAsync()
{
var list = await _trialRepository.Select(t => new { TrialId = t.Id, TrialStatusStr = t.TrialStatusStr })
.ToListAsync();
list.ForEach(t => _provider.Set(t.TrialId.ToString(), t.TrialStatusStr, TimeSpan.FromDays(7)));
}
public async Task MemoryCacheAnonymizeData()
{
var systemAnonymizationList = await _systemAnonymizationRepository.Where(t => t.IsEnable).ToListAsync();
_provider.Set(StaticData.Anonymize.Anonymize_AddFixedFiled, systemAnonymizationList.Where(t => t.IsAdd && t.IsFixed).ToList(), TimeSpan.FromDays(7));
_provider.Set(StaticData.Anonymize.Anonymize_AddIRCInfoFiled, systemAnonymizationList.Where(t => t.IsAdd && t.IsFixed == false).ToList(), TimeSpan.FromDays(7));
_provider.Set(StaticData.Anonymize.Anonymize_FixedField, systemAnonymizationList.Where(t => t.IsAdd == false && t.IsFixed).ToList(), TimeSpan.FromDays(7));
_provider.Set(StaticData.Anonymize.Anonymize_IRCInfoField, systemAnonymizationList.Where(t => t.IsAdd == false && t.IsFixed == false).ToList(), TimeSpan.FromDays(7));
}
#region
public async Task InitInternationlizationDataAndWatchJsonFileAsync()
{
//查询数据库的数据
var toJsonList = await _internationalizationRepository.Where(t => t.InternationalizationType == 1).Select(t => new
{
t.Code,
t.Value,
t.ValueCN
}).ToListAsync();
//组织成json 文件
var usJsonPath = Path.Combine(JsonFileFolder, StaticData.En_US_Json);
var cnJsonPath = Path.Combine(JsonFileFolder, StaticData.Zh_CN_Json);
//本地静态文件国际化需要
foreach (var tojsonItem in toJsonList)
{
StaticData.En_US_Dic[tojsonItem.Code] = tojsonItem.Value;
StaticData.Zh_CN_Dic[tojsonItem.Code] = tojsonItem.ValueCN;
}
File.WriteAllText(usJsonPath, JsonConvert.SerializeObject(StaticData.En_US_Dic));
File.WriteAllText(cnJsonPath, JsonConvert.SerializeObject(StaticData.Zh_CN_Dic));
//监测Json文件变更 实时刷新数据
if (!File.Exists(usJsonPath)|| !File.Exists(cnJsonPath))
{
throw new BusinessValidationFailedException(StaticData.International("IRaCISCHangfireJob_FileNotFound"));
}
FileSystemWatcher_US = new FileSystemWatcher
{
Path = Path.GetDirectoryName(usJsonPath)!,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = Path.GetFileName(usJsonPath),
EnableRaisingEvents = true,
};
// 添加文件更改事件的处理程序
FileSystemWatcher_US.Changed += (sender, e) => LoadJsonFile(usJsonPath);
FileSystemWatcher_CN = new FileSystemWatcher
{
Path = Path.GetDirectoryName(cnJsonPath)!,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = Path.GetFileName(cnJsonPath),
EnableRaisingEvents = true,
};
FileSystemWatcher_CN.Changed += (sender, e) => LoadJsonFile(cnJsonPath);
}
private void LoadJsonFile(string filePath)
{
Console.WriteLine("刷新json内存数据");
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(filePath,false,true);
IConfigurationRoot enConfiguration = builder.Build();
foreach (IConfigurationSection section in enConfiguration.GetChildren())
{
if (filePath.Contains(StaticData.En_US_Json))
{
StaticData.En_US_Dic[section.Key] = section.Value;
}
else
{
StaticData.Zh_CN_Dic[section.Key] = section.Value;
}
}
}
#endregion
public async Task InitSysAndTrialCronJobAsync()
{
@@ -101,9 +223,6 @@ namespace IRaCIS.Application.Services.BackGroundJob
}
}
+13 -15
View File
@@ -8,8 +8,6 @@ using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System.Diagnostics.CodeAnalysis;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using ZiggyCreatures.Caching.Fusion;
namespace IRaCIS.Core.Application
{
@@ -19,21 +17,20 @@ namespace IRaCIS.Core.Application
#region
[TypeFilter(typeof(UnifiedApiResultFilter))]
[Authorize, DynamicWebApi]
[Authorize, DynamicWebApi, UnifiedApiResultFilter]
public class BaseService : IBaseService, IDynamicWebApi
{
public IMapper _mapper { get; set; }
public IUserInfo _userInfo { get; set; }
public IRepository _repository { get; set; }
public IStringLocalizer _localizer { get; set; }
public IWebHostEnvironment _hostEnvironment { get; set; }
public IFusionCache _fusionCache { get; set; }
public static IResponseOutput Null404NotFound<TEntity>(TEntity? businessObject) where TEntity : class
@@ -52,6 +49,8 @@ namespace IRaCIS.Core.Application
[MemberNotNull(nameof(_userInfo))]
public IUserInfo _userInfo { get; set; }
[MemberNotNull(nameof(_repository))]
public IRepository _repository { get; set; }
[MemberNotNull(nameof(_localizer))]
public IStringLocalizer _localizer { get; set; }
@@ -59,9 +58,6 @@ namespace IRaCIS.Core.Application
[MemberNotNull(nameof(_hostEnvironment))]
public IWebHostEnvironment _hostEnvironment { get; set; }
[MemberNotNull(nameof(_fusionCache))]
public IFusionCache _fusionCache { get; set; }
}
#endregion
@@ -77,25 +73,27 @@ namespace IRaCIS.Core.Application
[MemberNotNull(nameof(_userInfo))]
public IUserInfo _userInfo { get; set; }
[MemberNotNull(nameof(_repository))]
public IRepository _repository { get; set; }
[MemberNotNull(nameof(_localizer))]
public IStringLocalizer _localizer { get; set; }
[MemberNotNull(nameof(_fusionCache))]
public IFusionCache _fusionCache { get; set; }
}
[TypeFilter(typeof(UnifiedApiResultFilter))]
[Authorize, DynamicWebApi]
[Authorize, DynamicWebApi, UnifiedApiResultFilter]
public class BaseServiceTest<T> : IBaseServiceTest<T>, IDynamicWebApi where T : Entity
{
public IMapper _mapper { get; set; }
public IUserInfo _userInfo { get; set; }
public IStringLocalizer _localizer { get; set; }
public IRepository _repository { get; set; }
public IFusionCache _fusionCache { get; set; }
public IStringLocalizer _localizer { get; set; }
public static IResponseOutput Null404NotFound<TEntity>(TEntity? businessObject) where TEntity : class
{
@@ -1,71 +0,0 @@
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.BusinessFilter
{
public class EncreptApiResultFilter : IAsyncResultFilter
{
private readonly IOptionsMonitor<EncreptResponseOption> _encreptResponseMonitor;
public EncreptApiResultFilter(IOptionsMonitor<EncreptResponseOption> encreptResponseMonitor)
{
_encreptResponseMonitor = encreptResponseMonitor;
}
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if(_encreptResponseMonitor.CurrentValue.IsEnable)
{
if (context.Result is ObjectResult objectResult)
{
var statusCode = objectResult.StatusCode ?? context.HttpContext.Response.StatusCode;
var objectValue = objectResult.Value;
if (objectValue is IResponseOutput)
{
var responseOutput = objectValue as IResponseOutput<object>;
var path = context.HttpContext?.Request.Path.Value?.ToLower();
if(!string.IsNullOrEmpty(path) && path.Length>5 && _encreptResponseMonitor.CurrentValue.ApiPathList.Contains(path.ToLower()))
{
if(responseOutput.IsSuccess)
{
responseOutput.Code = ApiResponseCodeEnum.ResultEncrepted;
responseOutput.Data = JsonConvert.SerializeObject(Convert.ToBase64String(Encoding.UTF8.GetBytes(responseOutput.Data.ToString())));
objectResult.Value = responseOutput;
}
}
}
}
}
await next.Invoke();
}
}
}
@@ -1,50 +0,0 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.BusinessFilter
{
/// <summary>
/// 不生效,不知道为啥
/// </summary>
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
this._logger = logger;
}
public ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
httpContext.Response.ContentType = "application/json";
var ex = exception;
var errorInfo = $"Exception: {ex.Message}[{ex.StackTrace}]" + (ex.InnerException != null ? $" InnerException: {ex.InnerException.Message}[{ex.InnerException.StackTrace}]" : "");
httpContext.Response.WriteAsJsonAsync(ResponseOutput.NotOk($"{ex?.Message}"));
_logger.LogError(errorInfo);
// return true to signal that this exception is handled
return ValueTask.FromResult(false);
}
}
}
@@ -1,4 +1,4 @@
using IRaCIS.Core.Application.Helper;
using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
@@ -8,7 +8,6 @@ using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using ZiggyCreatures.Caching.Fusion;
namespace IRaCIS.Core.Application.Filter;
@@ -19,15 +18,15 @@ public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
{
public IStringLocalizer _localizer { get; set; }
private readonly IFusionCache _fusionCache;
private readonly IEasyCachingProvider _provider;
private readonly IUserInfo _userInfo;
private readonly IOptionsMonitor<ServiceVerifyConfigOption> _verifyConfig;
public LimitUserRequestAuthorization(IFusionCache fusionCache, IUserInfo userInfo, IStringLocalizer localizer ,IOptionsMonitor<ServiceVerifyConfigOption> verifyConfig)
public LimitUserRequestAuthorization(IEasyCachingProvider provider, IUserInfo userInfo, IStringLocalizer localizer ,IOptionsMonitor<ServiceVerifyConfigOption> verifyConfig)
{
_fusionCache = fusionCache;
_provider = provider;
_userInfo = userInfo;
_verifyConfig = verifyConfig;
_localizer = localizer;
@@ -64,7 +63,7 @@ public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
//2、在这里取缓存 进行比较 看是否有其他人进行了登陆,如果其他人登陆了,就把之前用户挤掉
var cacheUserToken = await _fusionCache.GetOrDefaultAsync<string>(CacheKeys.UserToken(_userInfo.Id));
var cacheUserToken = (await _provider.GetAsync<string>(_userInfo.Id.ToString())).Value;
@@ -74,17 +73,17 @@ public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
cacheUserToken = _userInfo.UserToken;
//设置当前用户最新Token
await _fusionCache.SetAsync(CacheKeys.UserToken(_userInfo.Id), _userInfo.UserToken, TimeSpan.FromDays(7));
await _provider.SetAsync(_userInfo.Id.ToString(), _userInfo.UserToken, TimeSpan.FromDays(7));
//重启应用程序,所有人续期,不一下子踢出所有人
await _fusionCache.SetAsync(CacheKeys.UserAutoLoginOut(_userInfo.Id), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(minutes));
await _provider.SetAsync($"{_userInfo.Id.ToString()}_Online", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(minutes));
}
//是同一个人
else if (cacheUserToken == _userInfo.UserToken)
{
var cacheTime = await _fusionCache.GetOrDefaultAsync<string>(CacheKeys.UserAutoLoginOut(_userInfo.Id));
var cacheTime = (await _provider.GetAsync<string>($"{_userInfo.Id.ToString()}_Online")).Value;
//过期了 需要自动退出
if (string.IsNullOrEmpty(cacheTime))
@@ -92,23 +91,33 @@ public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["LimitUser_AccountAuto_LoginOut"], ApiResponseCodeEnum.AutoLoginOut));
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["LimitUser_AccountAuto_LoginOut"], ApiResponseCodeEnum.AutoLoginOut));
}
else
{
await _fusionCache.SetAsync(CacheKeys.UserAutoLoginOut(_userInfo.Id), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(minutes));
await _provider.SetAsync($"{_userInfo.Id.ToString()}_Online", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), TimeSpan.FromMinutes(minutes));
}
}
else
{
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
//---您的账户在其他地方已登陆,您被迫下线。
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["LimitUser_AccountLoggedInElsewhere"], ApiResponseCodeEnum.LoginInOtherPlace));
//await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(ResponseOutput.NotOk(_localizer["LimitUser_AccountLoggedInElsewhere"], ApiResponseCodeEnum.LoginInOtherPlace)));
}
}
}
@@ -116,3 +125,52 @@ public class LimitUserRequestAuthorization : IAsyncAuthorizationFilter
}
}
//public class UserTypeRequirement : IAuthorizationRequirement
//{
//}
//public class UserTypeHandler : AuthorizationHandler<UserTypeRequirement>
//{
// private IUserInfo _userInfo;
// public UserTypeHandler(IUserInfo userInfo)
// {
// _userInfo = userInfo;
// }
// protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserTypeRequirement requirement)
// {
// //if (context.User.Claims.Count() == 0)
// //{
// // return Task.CompletedTask;
// //}
// //string userId = context.User.Claims.First(c => c.Type == "Userid").Value;
// //string qq = context.User.Claims.First(c => c.Type == "QQ").Value;
// //if (_UserService.Validata(userId, qq))
// //{
// // context.Succeed(requirement); //验证通过了
// //}
// ////在这里就可以做验证
// return Task.CompletedTask;
// }
//}
@@ -1,5 +1,4 @@
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
@@ -12,13 +11,13 @@ namespace IRaCIS.Core.Application.Filter
{
private readonly ILogger<ProjectExceptionFilter> _logger;
public IStringLocalizer _localizer;
public IStringLocalizer _localizer;
public ProjectExceptionFilter(IStringLocalizer localizer, ILogger<ProjectExceptionFilter> logger)
public ProjectExceptionFilter(IStringLocalizer localizer, ILogger<ProjectExceptionFilter> logger)
{
_logger = logger;
_localizer = localizer;
}
_localizer = localizer;
}
public void OnException(ExceptionContext context)
{
//context.ExceptionHandled;//记录当前这个异常是否已经被处理过了
@@ -27,7 +26,7 @@ namespace IRaCIS.Core.Application.Filter
{
if (context.Exception.GetType().Name == "DbUpdateConcurrencyException")
{
//---并发更新,当前不允许该操作
//---并发更新,当前不允许该操作
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["ProjectException_ConcurrentUpdateNotAllowed"] + context.Exception.Message));
}
@@ -35,43 +34,28 @@ namespace IRaCIS.Core.Application.Filter
{
var error = context.Exception as BusinessValidationFailedException;
var info = string.Empty;
if (!string.IsNullOrWhiteSpace(error!.LocalizedKey) && StaticData.Log_Locoalize_Dic.ContainsKey(error!.LocalizedKey))
{
info = $"[{error!.LocalizedKey}]:{StaticData.Log_Locoalize_Dic[error!.LocalizedKey]}";
}
context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message, "", error!.Code, localizedInfo: info));
//warning 级别记录
//_logger.LogWarning($"[{error!.LocalizedKey}]:{StaticData.Log_Locoalize_Dic[error!.LocalizedKey]}");
context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message, error!.Code));
}
else if (context.Exception.GetType() == typeof(QueryBusinessObjectNotExistException))
else if(context.Exception.GetType() == typeof(QueryBusinessObjectNotExistException))
{
context.Result = new JsonResult(ResponseOutput.NotOk(context.Exception.Message, ApiResponseCodeEnum.DataNotExist));
context.Result = new JsonResult(ResponseOutput.NotOk( context.Exception.Message, ApiResponseCodeEnum.DataNotExist));
}
else
{
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["Project_ExceptionContactDeveloper"] + (context.Exception.InnerException is null ? (context.Exception.Message /*+ context.Exception.StackTrace*/)
: (context.Exception.InnerException?.Message /*+ context.Exception.InnerException?.StackTrace*/)), ApiResponseCodeEnum.ProgramException));
_logger.LogError(context.Exception.InnerException is null ? (context.Exception.Message + context.Exception.StackTrace) : (context.Exception.InnerException?.Message + context.Exception.InnerException?.StackTrace));
}
context.ExceptionHandled = true;//标记当前异常已经被处理过了
_logger.LogError(context.Exception.InnerException is null ? (context.Exception.Message + context.Exception.StackTrace) : (context.Exception.InnerException?.Message + context.Exception.InnerException?.StackTrace));
//throw new Exception("test-result-exceptioin");
}
else
{
//继续
}
context.ExceptionHandled = true;//标记当前异常已经被处理过了
}
}
}
@@ -1,11 +1,10 @@
using IRaCIS.Core.Application.Helper;
using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using System.Text.RegularExpressions;
using ZiggyCreatures.Caching.Fusion;
using static IRaCIS.Core.Domain.Share.StaticData;
namespace IRaCIS.Core.Application.Filter
@@ -15,36 +14,49 @@ namespace IRaCIS.Core.Application.Filter
/// </summary>
public class TrialResourceFilter : Attribute, IAsyncResourceFilter
{
private readonly IEasyCachingProvider _provider;
private readonly IUserInfo _userInfo;
private readonly IFusionCache _fusionCache;
public IStringLocalizer _localizer;
private readonly IRepository<Trial> _trialRepository;
private readonly List<string> _trialOptList = new List<string>();
private readonly List<string> _trialOptList=new List<string>();
public TrialResourceFilter(IFusionCache fusionCache, IRepository<Trial> trialRepository, IStringLocalizer localizer, IUserInfo userInfo, string trialOpt = null, string trialOpt2 = null, string trialOpt3 = null)
public TrialResourceFilter(IEasyCachingProvider provider, IStringLocalizer localizer , IUserInfo userInfo, string trialOpt = null, string trialOpt2 = null, string trialOpt3 = null)
{
_fusionCache = fusionCache;
_provider = provider;
_userInfo = userInfo;
_localizer = localizer;
_trialRepository = trialRepository;
//_trialOpt = trialOpt;
if (!string.IsNullOrWhiteSpace(trialOpt)) _trialOptList.Add(trialOpt.Trim());
if (!string.IsNullOrWhiteSpace(trialOpt)) _trialOptList.Add(trialOpt.Trim());
if (!string.IsNullOrWhiteSpace(trialOpt2)) _trialOptList.Add(trialOpt2.Trim());
if (!string.IsNullOrWhiteSpace(trialOpt3)) _trialOptList.Add(trialOpt3.Trim());
}
//public TrialResourceFilter(IEasyCachingProvider provider, IUserInfo userInfo)
//{
// _provider = provider;
// _userInfo = userInfo;
//}
//优先选择异步的方法
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
// var typeFilter = context.ActionDescriptor.EndpointMetadata.Where(t => t.GetType() == typeof(TypeFilterAttribute)).Select(t => (TypeFilterAttribute)t).ToList().FirstOrDefault();
//var _trialOptList= typeFilter.Arguments.Select(t => t.ToString()).ToList();
// var typeFilter = context.ActionDescriptor.EndpointMetadata.Where(t => t.GetType() == typeof(TypeFilterAttribute)).Select(t => (TypeFilterAttribute)t).ToList().FirstOrDefault();
//var _trialOptList= typeFilter.Arguments.Select(t => t.ToString()).ToList();
#region
// 后期列举出具体的类型,其他任何用户类型,都不允许操作
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA && _userInfo.RequestUrl.ToLower() != "TrialDocument/userConfirm".ToLower())
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA && _userInfo.RequestUrl.ToLower()!= "TrialDocument/userConfirm".ToLower())
{
//---对不起,您的账户没有操作权限。
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["TrialResource_NoAccessPermission"]));
@@ -85,7 +97,7 @@ namespace IRaCIS.Core.Application.Filter
}
else
{
//---正则取请求Refer 中trialId 失败,请联系开发人员核查
//---正则取请求Refer 中trialId 失败,请联系开发人员核查
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["TrialResource_ReferTrialIdFailed"]));
}
@@ -116,20 +128,20 @@ namespace IRaCIS.Core.Application.Filter
if (matchResult.Success)
{
//有可能匹配错误 "trialId":"","documentId":"b8180000-3e2c-0016-9fe0-08da33f96236" 从缓存里面验证下
var cacheResultDic = _provider.GetAll<string>(new[] { matchResult.Value });
trialIdStr = matchResult.Value;
var trialStatusStr = cacheResultDic[matchResult.Value.ToLower()].Value;
var trialStatusStr = await _fusionCache.GetOrSetAsync(CacheKeys.Trial(trialIdStr), _ => CacheHelper.GetTrialStatusAsync(Guid.Parse(trialIdStr), _trialRepository), TimeSpan.FromDays(7));
if (string.IsNullOrWhiteSpace(trialStatusStr))
if (!string.IsNullOrWhiteSpace(trialStatusStr))
{
//数据库 检查该项目Id不对
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["TrialResource_ReferTrialIdFailed"]));
trialIdStr = matchResult.Value;
}
}
else
{
//---正则取请求Refer 中trialId 失败,请联系开发人员核查
//---正则取请求Refer 中trialId 失败,请联系开发人员核查
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["TrialResource_ReferTrialIdFailed"]));
}
@@ -141,12 +153,34 @@ namespace IRaCIS.Core.Application.Filter
}
//通过path 或者body 找到trialId 了
if (!string.IsNullOrWhiteSpace(trialIdStr))
if ( !string.IsNullOrWhiteSpace(trialIdStr))
{
var trialStatusStr = await _fusionCache.GetOrSetAsync(CacheKeys.Trial(trialIdStr), _ => CacheHelper.GetTrialStatusAsync(Guid.Parse(trialIdStr), _trialRepository), TimeSpan.FromDays(7));
//如果没缓存数据,可能定时任务没执行或者缓存丢失 在此重新缓存
if (_provider.GetCount() == 0)
{
var _trialRepository = context.HttpContext.RequestServices.GetService(typeof(IRepository<Trial>)) as IRepository<Trial>;
var list = _trialRepository.IfNullThrowException().Select(t => new { TrialId = t.Id, TrialStatusStr = t.TrialStatusStr })
.ToList();
list.ForEach(t => _provider.Set(t.TrialId.ToString(), t.TrialStatusStr, TimeSpan.FromDays(7)));
}
var cacheResultDic = _provider.GetAll<string>(new[] { trialIdStr });
var trialStatusStr = cacheResultDic[trialIdStr].Value;
//意外 导致缓存过期,调整服务器时间,测试不想重启程序
if (string.IsNullOrWhiteSpace(trialStatusStr))
{
var trialRepository = context.HttpContext.RequestServices.GetService(typeof(IRepository<Trial>)) as IRepository<Trial>;
trialStatusStr = trialRepository?.Where(t => t.Id == Guid.Parse(trialIdStr)).Select(t => t.TrialStatusStr).FirstOrDefault();
}
// 这里是统一拦截 项目有关的操作允许情况(特殊的地方,比如项目配置(有的在多种状态(初始化,ongoing)都可以操作,有的仅仅在Initializing)还有 项目添加和更新,不走这里,特殊处理,不然在这里显得很乱,判断是哪个接口)
if (trialStatusStr == StaticData.TrialState.TrialOngoing || _trialOptList.Any(t => t == TrialOpt.BeforeOngoingCantOpt))
if (trialStatusStr == StaticData.TrialState.TrialOngoing || _trialOptList.Any(t=>t== TrialOpt.BeforeOngoingCantOpt) )
{
await next.Invoke();
@@ -155,14 +189,14 @@ namespace IRaCIS.Core.Application.Filter
// 项目停止、或者完成 不允许操作
else
{
//---本次请求被配置规则拦截:项目状态处于进行中时,才允许操作,若此处逻辑有误,请联系开发人员修改
//---本次请求被配置规则拦截:项目状态处于进行中时,才允许操作,若此处逻辑有误,请联系开发人员修改
context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["TrialResource_InterceptedProjectStatusRule"]));
}
}
//添加项目 签名系统文档的时候 不做拦截 但是更新项目 签名项目文档的时候需要拦截
else if (_trialOptList.Any(t => t == TrialOpt.AddOrUpdateTrial || t == TrialOpt.SignSystemDocNoTrialId))
else if (_trialOptList.Any(t => t == TrialOpt.AddOrUpdateTrial ||t ==TrialOpt.SignSystemDocNoTrialId))
{
await next.Invoke();
}
@@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Domain.Share;
using Microsoft.Extensions.Logging;
namespace IRaCIS.Application.Services.BusinessFilter
{
@@ -9,15 +8,8 @@ namespace IRaCIS.Application.Services.BusinessFilter
/// 统一返回前端数据包装,之前在控制器包装,现在修改为动态Api 在ResultFilter这里包装,减少重复冗余代码
/// by zhouhang 2021.09.12 周末
/// </summary>
public class UnifiedApiResultFilter : Attribute, IAsyncResultFilter
{
private readonly ILogger _logger;
public UnifiedApiResultFilter(ILogger<UnifiedApiResultFilter> logger)
{
_logger = logger;
}
public class UnifiedApiResultFilter : Attribute, IAsyncResultFilter
{
/// <summary>
/// 异步版本
/// </summary>
@@ -34,15 +26,25 @@ namespace IRaCIS.Application.Services.BusinessFilter
//是200 并且没有包装 那么包装结果
if (statusCode == 200 && !(objectResult.Value is IResponseOutput))
{
//if (objectResult.Value == null)
//{
// var apiResponse = ResponseOutput.DBNotExist();
// objectResult.Value = apiResponse;
// objectResult.DeclaredType = apiResponse.GetType();
//}
//else
//{
var type = objectResult.Value?.GetType();
if (type != null && type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(ValueTuple<,>) || type.GetGenericTypeDefinition() == typeof(Tuple<,>)))
if ( type!=null&& type.IsGenericType&&(type.GetGenericTypeDefinition()==typeof(ValueTuple<,>)|| type.GetGenericTypeDefinition()==typeof(Tuple<,>)))
{
//报错
//var tuple = (object, object))objectResult.Value;
//var (val1, val2) = ((dynamic, dynamic))objectResult.Value;
//var apiResponse = ResponseOutput.Ok(val1, val2);
@@ -62,24 +64,18 @@ namespace IRaCIS.Application.Services.BusinessFilter
objectResult.DeclaredType = apiResponse.GetType();
}
//}
}
//如果是200 是IResponseOutput 记录下日志
else if (statusCode == 200 && (objectResult.Value is IResponseOutput))
//如果是200 是IResponseOutput 不处理
else if (statusCode != 200 && (objectResult.Value is IResponseOutput))
{
var result = objectResult.Value as IResponseOutput;
if (!string.IsNullOrWhiteSpace(result.LocalizedInfo))
{
//统一在这里记录国际化的日志信息
_logger.LogWarning($"{result.LocalizedInfo}");
}
}
else if (statusCode != 200 && !(objectResult.Value is IResponseOutput))
else if(statusCode != 200&&!(objectResult.Value is IResponseOutput))
{
//---程序错误,请联系开发人员。
//---程序错误,请联系开发人员。
var apiResponse = ResponseOutput.NotOk(StaticData.International("UnifiedAPI_ProgramError"));
objectResult.Value = apiResponse;
@@ -1,75 +0,0 @@
using IRaCIS.Core.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Helper
{
public static class CacheKeys
{
public static string Trial(string trialIdStr) => $"TrialId:{trialIdStr}";
public static string TrialStudyMaxCode(Guid trialId) => $"TrialStudyMaxCode:{trialId}";
public static string TrialStudyUidUploading(Guid trialId, string studyUid) => $"TrialStudyUid:{trialId}_{studyUid}";
public static string TrialStudyUidDBLock(Guid trialId, string studyUid) => $"TrialStudyUidDBLock:{trialId}_{studyUid}";
public static string SystemAnonymization => $"SystemAnonymization";
public static string FrontInternational => $"FrontInternationalList";
//登录挤账号
public static string UserToken(Guid userId) => $"UserToken:{userId}";
//超时没请求接口自动退出
public static string UserAutoLoginOut(Guid userId) => $"UserAutoLoginOut:{userId}";
// 你可以为其他实体和模块定义更多的键
/// <summary>
/// 跳过阅片
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static string SkipReadingCacheKey(Guid userId) => $"{userId}SkipReadingCache";
/// <summary>
/// 开始阅片时间
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static string StartReadingTimeKey(Guid userId) => $"{userId}StartReadingTime";
/// <summary>
/// 开始休息时间
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static string StartRestTime(Guid userId) => $"{userId}StartRestTime";
}
public static class CacheHelper
{
public static async Task<string?> GetTrialStatusAsync(Guid trialId, IRepository<Trial> _trialRepository)
{
var statusStr = await _trialRepository.Where(t => t.Id == trialId, ignoreQueryFilters: true).Select(t => t.TrialStatusStr).FirstOrDefaultAsync();
return statusStr;
}
public static async Task<List<SystemAnonymization>> GetSystemAnonymizationListAsync(IRepository<SystemAnonymization> _systemAnonymizationRepository)
{
var list = await _systemAnonymizationRepository.Where(t => t.IsEnable).ToListAsync();
return list;
}
}
}
@@ -3,7 +3,6 @@ using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.API._ServiceExtensions.NewtonsoftJson;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Hosting;
@@ -15,8 +14,6 @@ using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.IO;
namespace IRaCIS.Core.Application.Service;
@@ -26,13 +23,19 @@ public static class ExcelExportHelper
//MiniExcel_Export
public static async Task<IActionResult> DataExportAsync(string code, ExcelExportInfo data, string exportFileNamePrefix, IRepository<CommonDocument> _commonDocumentRepository, IWebHostEnvironment _hostEnvironment, IDictionaryService? _dictionaryService = null, Type? translateType = null, CriterionType? criterionType = null)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
//判断是否有字典翻译
object translateData = data;
if (_dictionaryService != null && translateType != null)
{
////只标注单个的时候
//var needTranslatePropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DictionaryTranslateAttribute), true))
// .Select(c => new { c.Name, DicParentCode = ((DictionaryTranslateAttribute?)c.GetCustomAttributes(typeof(DictionaryTranslateAttribute), false)[0])?.DicParentCode }).ToList();
//一个值 对应不同的字典翻译
var needTranslatePropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DictionaryTranslateAttribute), true))
.SelectMany(c =>
@@ -59,18 +62,12 @@ public static class ExcelExportHelper
var newObjList = new List<object>();
var no = 1;
foreach (var item in dic[key] as IList)
foreach (var item in dic[key] as IList )
{
//var itemDic = JsonConvert.DeserializeObject<IDictionary<string, object>>(item.ToJsonNotIgnoreNull());
var itemDic = item.ConvertToDictionary();
//处理集合里面时间类型,根据当前语言将时间转变为字符串
foreach (var itemValuePair in itemDic)
{
if (DateTime.TryParse(itemValuePair.Value?.ToString(), out DateTime result))
{
itemDic[itemValuePair.Key] = ExportExcelConverterDate.DateTimeInternationalToString(result );
}
}
foreach (var needTranslateProperty in needTranslatePropertyList)
@@ -82,7 +79,7 @@ public static class ExcelExportHelper
{
var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t=>data.IsEn_US?t.Value:t.ValueCN).FirstOrDefault() ?? String.Empty;
}
}
//普通翻译 或者某一标准翻译
@@ -91,7 +88,7 @@ public static class ExcelExportHelper
var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => data.IsEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
}
@@ -107,7 +104,6 @@ public static class ExcelExportHelper
dic[key] = newObjList;
}
}
@@ -121,7 +117,7 @@ public static class ExcelExportHelper
var (physicalPath, fileName) = await FileStoreHelper.GetCommonDocPhysicalFilePathAsync(_hostEnvironment, _commonDocumentRepository, code);
var (physicalPath, fileNmae) = await FileStoreHelper.GetCommonDocPhysicalFilePathAsync(_hostEnvironment, _commonDocumentRepository, code);
//模板路径
@@ -143,7 +139,7 @@ public static class ExcelExportHelper
if (sheetCount == 2)
{
if (isEn_US)
if (data.IsEn_US)
{
workbook.RemoveSheetAt(0);
}
@@ -153,7 +149,7 @@ public static class ExcelExportHelper
}
var memoryStream2 = new MemoryStream();
workbook.Write(memoryStream2, true);
workbook.Write(memoryStream2,true);
memoryStream2.Seek(0, SeekOrigin.Begin);
@@ -161,12 +157,17 @@ public static class ExcelExportHelper
}
// 文件名称 从sheet里面取
//fileNmae = workbook.GetSheetName(0);
fileNmae = workbook.GetSheetName(0);
#endregion
#region MiniExcel
var memoryStream = new MemoryStream();
var memoryStream = new MemoryStream();
var config = new OpenXmlConfiguration()
{
@@ -180,18 +181,29 @@ public static class ExcelExportHelper
return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = $"{(string.IsNullOrEmpty(exportFileNamePrefix) ? "" : exportFileNamePrefix + "_")}{Path.GetFileNameWithoutExtension(fileName)}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
FileDownloadName = $"{exportFileNamePrefix}_{fileNmae/*.Substring(0, fileNmae.LastIndexOf('.'))*/}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
};
#endregion
#region Magicodes
////创建Excel导出对象
//IExportFileByTemplate exporter = new ExcelExporter();
////根据模板导出
//var result = await exporter.ExportBytesByTemplate(exportInfo, tplPath);
//return new XlsxFileResult(bytes: result, fileDownloadName: $"{doc.Name}_{DateTime.Now.ToString("yyyy-MM-dd:hh:mm:ss")}.xlsx");
#endregion
}
public static async Task<(MemoryStream, string)> DataExport_NpoiTestAsync(string code, ExcelExportInfo data, IRepository<CommonDocument> _commonDocumentRepository, IWebHostEnvironment _hostEnvironment, IDictionaryService? _dictionaryService = null, Type? translateType = null, CriterionType? criterionType = null)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
//判断是否有字典翻译
object translateData = data;
@@ -199,6 +211,11 @@ public static class ExcelExportHelper
if (_dictionaryService != null && translateType != null)
{
////只标注单个的时候
//var needTranslatePropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DictionaryTranslateAttribute), true))
// .Select(c => new { c.Name, DicParentCode = ((DictionaryTranslateAttribute?)c.GetCustomAttributes(typeof(DictionaryTranslateAttribute), false)[0])?.DicParentCode }).ToList();
//一个值 对应不同的字典翻译
var needTranslatePropertyList = translateType.GetProperties().Where(t => t.IsDefined(typeof(DictionaryTranslateAttribute), true))
.SelectMany(c =>
@@ -230,15 +247,6 @@ public static class ExcelExportHelper
//var itemDic = JsonConvert.DeserializeObject<IDictionary<string, object>>(item.ToJsonNotIgnoreNull());
var itemDic = item.ConvertToDictionary();
//处理集合里面时间类型,根据当前语言将时间转变为字符串
foreach (var itemValuePair in itemDic)
{
if (DateTime.TryParse(itemValuePair.Value?.ToString(), out DateTime result))
{
itemDic[itemValuePair.Key] = ExportExcelConverterDate.DateTimeInternationalToString(result);
}
}
foreach (var needTranslateProperty in needTranslatePropertyList)
{
//翻译的属性依赖其他属性
@@ -248,7 +256,7 @@ public static class ExcelExportHelper
{
var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => data.IsEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
}
}
//普通翻译 或者某一标准翻译
@@ -257,7 +265,7 @@ public static class ExcelExportHelper
var beforeValue = itemDic[needTranslateProperty.Name]?.ToString();
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => isEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
itemDic[needTranslateProperty.Name] = translateDataList[needTranslateProperty.DicParentCode].Where(t => t.Code.ToLower() == beforeValue?.ToLower()).Select(t => data.IsEn_US ? t.Value : t.ValueCN).FirstOrDefault() ?? String.Empty;
}
@@ -302,7 +310,7 @@ public static class ExcelExportHelper
if (sheetCount == 2)
{
if (isEn_US)
if (data.IsEn_US)
{
workbook.RemoveSheetAt(0);
}
@@ -312,7 +320,7 @@ public static class ExcelExportHelper
}
var memoryStream2 = new MemoryStream();
workbook.Write(memoryStream2, true);
workbook.Write(memoryStream2,true);
memoryStream2.Seek(0, SeekOrigin.Begin);
@@ -320,7 +328,7 @@ public static class ExcelExportHelper
}
// 文件名称 从sheet里面取
//fileName = workbook.GetSheetName(0);
fileName = workbook.GetSheetName(0);
#endregion
#region MiniExcel
@@ -347,7 +355,4 @@ public static class ExcelExportHelper
#endregion
}
}
@@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Globalization;
using System.Text.RegularExpressions;
namespace IRaCIS.Core.Application.Helper;
@@ -129,6 +128,65 @@ public static class FileStoreHelper
#endregion
/// <summary>
///
/// </summary>
/// <param name="_hostEnvironment"></param>
/// <param name="_clinicalDataTrialSetRepository"></param>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="BusinessValidationFailedException"></exception>
public static async Task<(string PhysicalPath, string FileName)> GetSystemClinicalPathAsync(IWebHostEnvironment _hostEnvironment, IRepository<ClinicalDataSystemSet> _clinicalDataTrialSetRepository, Guid id)
{
var systemClinicalData = await _clinicalDataTrialSetRepository.FirstOrDefaultAsync(t => t.Id == id);
if (systemClinicalData == null || systemClinicalData.Path == string.Empty)
{
//---数据库没有找到对应的数据模板文件,请联系系统运维人员。
throw new BusinessValidationFailedException(StaticData.International("FileStore_TemplateFileNotFound"));
}
var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, systemClinicalData.Path);
if (!System.IO.File.Exists(filePath))
{
//---数据模板文件存储路径上未找对应文件,请联系系统运维人员。
throw new BusinessValidationFailedException(StaticData.International("FileStore_TemplateFileStoragePathInvalid"));
}
return (filePath, systemClinicalData.FileName);
}
/// <summary>
///
/// </summary>
/// <param name="_hostEnvironment"></param>
/// <param name="_clinicalDataTrialSetRepository"></param>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="BusinessValidationFailedException"></exception>
public static async Task<(string PhysicalPath, string FileName)> GetTrialClinicalPathAsync(IWebHostEnvironment _hostEnvironment, IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository, Guid id)
{
var trialClinicalData = await _clinicalDataTrialSetRepository.FirstOrDefaultAsync(t => t.Id == id);
if (trialClinicalData == null|| trialClinicalData.Path==string.Empty)
{
//---数据库没有找到对应的数据模板文件,请联系系统运维人员。
throw new BusinessValidationFailedException(StaticData.International("FileStore_TemplateFileNotFound"));
}
var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, trialClinicalData.Path);
if (!System.IO.File.Exists(filePath))
{
//---数据模板文件存储路径上未找对应文件,请联系系统运维人员。
throw new BusinessValidationFailedException(StaticData.International("FileStore_TemplateFileStoragePathInvalid"));
}
return (filePath, trialClinicalData.FileName);
}
//通过编码获取通用文档具体物理路径
@@ -136,7 +194,6 @@ public static class FileStoreHelper
{
var doc = await _commonDocumentRepository.FirstOrDefaultAsync(t => t.Code == code);
var isEn_US = CultureInfo.CurrentCulture.Name!= StaticData.CultureInfo.zh_CN;
if (doc == null)
{
//---数据库没有找到对应的数据模板文件,请联系系统运维人员。
@@ -151,7 +208,7 @@ public static class FileStoreHelper
throw new BusinessValidationFailedException(StaticData.International("FileStore_TemplateFileStoragePathInvalid"));
}
return (filePath, isEn_US? doc.Name.Trim('/'): doc.NameCN.Trim('/'));
return (filePath, doc.Name.Trim('/'));
}
@@ -178,6 +235,44 @@ public static class FileStoreHelper
return writeCount;
}
// 获取项目签名文档存放路径
public static (string PhysicalPath, string RelativePath) GetTrialSignDocPath(IWebHostEnvironment _hostEnvironment, Guid trialId, string fileName)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//文件类型路径处理
var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), StaticData.Folder.SignDocumentFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{StaticData.Folder.SignDocumentFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
// 获取系统签名文档存放路径
public static (string PhysicalPath, string RelativePath) GetSystemSignDocPath(IWebHostEnvironment _hostEnvironment, string fileName)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//文件类型路径处理
var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, StaticData.Folder.SignDocumentFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{ StaticData.Folder.SignDocumentFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
// 获取通用文档存放路径(excel模板 )
@@ -200,6 +295,224 @@ public static class FileStoreHelper
return (serverFilePath, relativePath);
}
//获取系统通知文档存放路径
public static (string PhysicalPath, string RelativePath) GetSystemNoticePath(IWebHostEnvironment _hostEnvironment, string fileName)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//文件类型路径处理
var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, StaticData.Folder.NoticeAttachment);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{StaticData.Folder.NoticeAttachment}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
// 获取一致性核查路径
public static (string PhysicalPath, string RelativePath) GetTrialCheckFilePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//上传根路径
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), StaticData.Folder.UploadEDCData);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
//存放核对表
var (trustedFileNameForFileStorage, realFileName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{StaticData.Folder.UploadEDCData}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
public static (string PhysicalPath, string RelativePath, string FileRealName) GetClinicalTemplatePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, "ClinicalTemplate", trialId.ToString(), StaticData.Folder.TreatmenthistoryFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/ClinicalTemplate/{trialId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
public static (string PhysicalPath, string RelativePath, string FileRealName) GetReadClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid siteId, Guid subjectId, Guid readingId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteId.ToString(), subjectId.ToString(), StaticData.Folder.Reading, readingId.ToString());
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{StaticData.Folder.Reading}/{readingId}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
//获取临床数据存放路径
public static (string PhysicalPath, string RelativePath,string FileRealName) GetClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName,Guid trialId,Guid siteId,Guid subjectId,Guid subjectVisitId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(),siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.TreatmenthistoryFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
public static (string PhysicalPath, string RelativePath, string FileRealName) GetClinicalDataPath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId , Guid subjectId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), subjectId.ToString(), StaticData.Folder.TreatmenthistoryFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{subjectId}/{StaticData.Folder.TreatmenthistoryFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
/// <summary>
/// 上传截图
/// </summary>
/// <param name="_hostEnvironment"></param>
/// <param name="fileName"></param>
/// <param name="trialId"></param>
/// <param name="siteid"></param>
/// <param name="subjectId"></param>
/// <returns></returns>
public static (string PhysicalPath, string RelativePath, string FileRealName) GetUploadPrintscreenFilePath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid siteid, Guid subjectId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteid.ToString(), subjectId.ToString());
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteid}/{subjectId}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
/// <summary>
/// 通用获取文件路径
/// </summary>
/// <param name="_hostEnvironment"></param>
/// <param name="fileName"></param>
/// <param name="trialId"></param>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public static (string PhysicalPath, string RelativePath, string FileRealName) GetFilePath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid id,string type)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), id.ToString(), type);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{id}/{type}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
public static (string PhysicalPath, string RelativePath, string FileRealName) GetMedicalReviewImage(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid taskMedicalReviewId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), taskMedicalReviewId.ToString(), StaticData.Folder.MedicalReview);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{taskMedicalReviewId}/{StaticData.Folder.MedicalReview}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
//获取非dicom文件存放路径
public static (string PhysicalPath, string RelativePath, string FileRealName) GetNoneDicomFilePath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid siteId, Guid subjectId, Guid subjectVisitId)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
string uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.TrialDataFolder, trialId.ToString(), siteId.ToString(), subjectId.ToString(), subjectVisitId.ToString(), StaticData.Folder.NoneDicomFolder);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{trialId}/{siteId}/{subjectId}/{subjectVisitId}/{StaticData.Folder.NoneDicomFolder}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath, fileRealName);
}
// 获取 入组确认 PD 进展发送邮件Word|PDF 存放路径
public static (string PhysicalPath, string RelativePath, string FileRealName) GetSubjectEnrollConfirmOrPDEmailPath(IWebHostEnvironment _hostEnvironment, string fileName, Guid trialId, Guid trialSiteId, Guid subjectId,bool isChangeToPdfFormat=false)
@@ -316,7 +629,49 @@ public static class FileStoreHelper
// 获取医生通用文件存放路径
public static (string PhysicalPath, string RelativePath) GetDoctorOrdinaryFilePath(IWebHostEnvironment _hostEnvironment, string fileName,Guid doctorId,string attachmentType)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//文件类型路径处理
var uploadFolderPath = Path.Combine(rootPath, "UploadFile", doctorId.ToString(), attachmentType);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.UploadFileFolder}/{doctorId}/{attachmentType}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
public static (string PhysicalPath, string RelativePath) GetNonDoctorFilePath(IWebHostEnvironment _hostEnvironment, string fileName, string attachmentType)
{
var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);
//文件类型路径处理
var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.UploadFileFolder, attachmentType);
if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath);
var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName);
var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.UploadFileFolder}/{attachmentType}/{trustedFileNameForFileStorage}";
var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage);
return (serverFilePath, relativePath);
}
@@ -1,111 +0,0 @@
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Helper
{
#region
public class HolidayCalendar
{
public string Name { get; set; }
public string Version { get; set; }
public string Generated { get; set; }
public string Timezone { get; set; }
public string Author { get; set; }
public string URL { get; set; }
public Dictionary<string, List<HolidayYear>> Years { get; set; }
}
public class HolidayYear
{
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Duration { get; set; }
public List<DateTime> CompDays { get; set; }
public string URL { get; set; }
public string Memo { get; set; }
}
#endregion
public class HolidayHelper
{
/// <summary>
/// github 链接:https://github.com/lanceliao/china-holiday-calender?tab=readme-ov-file 
/// 接口请求参考文档:https://www.koudingke.cn/docs/zh-Hans/net-lib-docs/latest/RestSharp/Usage/Usage
/// </summary>
private static RestClient _client => new RestClient("https://www.shuyz.com/githubfiles/china-holiday-calender/master/holidayAPI.json");
private static HolidayCalendar _holidayCalendar { get; set; }
private static List<DateTime> _holidays = new List<DateTime>();
private static List<DateTime> _compensatedWorkdays = new List<DateTime>();
static HolidayHelper()
{
_holidayCalendar = _client.Get<HolidayCalendar>(new RestRequest()) ?? new HolidayCalendar();
foreach (var year in _holidayCalendar.Years.Values.SelectMany(x => x))
{
// 添加节假日到假日集合
for (DateTime date = year.StartDate; date <= year.EndDate; date = date.AddDays(1))
{
_holidays.Add(date);
}
// 添加补班日到补班日集合
foreach (var compDay in year.CompDays)
{
_compensatedWorkdays.Add(compDay);
}
}
}
public static TimeSpan GetChinaWorkTimeSpan(DateTime startDate, DateTime endDate)
{
if (startDate > endDate)
{
throw new ArgumentException("结束日期必须大于或等于开始日期");
}
var diffTimeSpan = endDate - startDate;
// 初始化工作日数为0
int workdays = 0;
// 找出在给定日期范围内的假期和补班日
var filteredHolidays = _holidays.Where(d => d >= startDate && d <= endDate).ToList();
var filteredCompensatedWorkdays = _compensatedWorkdays.Where(d => d >= startDate && d <= endDate).ToList();
// 遍历日期范围,计算工作日 注意 这里是小于
for (DateTime date = startDate.Date; date < endDate.Date; date = date.AddDays(1))
{
// 判断是否为工作日
bool isWeekend = date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
bool isHoliday = filteredHolidays.Contains(date);
bool isCompensatedWorkday = filteredCompensatedWorkdays.Contains(date);
// 如果是补班日,或是平日(非假期,非周末),则算作工作日
if (isCompensatedWorkday || (!isWeekend && !isHoliday))
{
workdays++;
}
}
return new TimeSpan(workdays, diffTimeSpan.Hours, diffTimeSpan.Minutes, diffTimeSpan.Seconds);
}
}
}
@@ -9,6 +9,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BeetleX.Redis.Commands.HSCAN;
using static IRaCIS.Core.Application.Service.Common.SystemMonitor;
namespace IRaCIS.Core.Application.Helper
@@ -17,9 +18,6 @@ namespace IRaCIS.Core.Application.Helper
{
public static string JsonFileFolder = Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources);
public static FileSystemWatcher FileSystemWatcher_US { get; set; }
public static FileSystemWatcher FileSystemWatcher_CN { get; set; }
private static void VerifyFolder()
{
if (!Directory.Exists(JsonFileFolder) ||
@@ -53,9 +51,6 @@ namespace IRaCIS.Core.Application.Helper
jsonObject[item.Code] = item.Value;
StaticData.En_US_Dic[item.Code] = item.Value;
//日志记录该信息方便自己人看, 返回给客户的是配置的
StaticData.Log_Locoalize_Dic[item.Code] = item.Description;
}
}
else
@@ -74,7 +69,7 @@ namespace IRaCIS.Core.Application.Helper
}
}
public static async Task AddOrUpdateJsonKeyValueAsync(string key, string value, string valueCN,string description)
public static async Task AddOrUpdateJsonKeyValueAsync(string key, string value, string valueCN)
{
VerifyFolder();
@@ -97,9 +92,6 @@ namespace IRaCIS.Core.Application.Helper
jsonObject[key] = value;
StaticData.En_US_Dic[key] = value;
//日志记录该信息方便自己人看, 返回给客户的是配置的
StaticData.Log_Locoalize_Dic[key] = description;
}
else
{
@@ -115,16 +107,14 @@ namespace IRaCIS.Core.Application.Helper
}
public static async Task InitInternationlizationDataAndWatchJsonFileAsync(IRepository<Internationalization> _internationalizationRepository)
public static async Task InitInternationlizationDataAndWatchJsonFileAsync(IRepository _repository)
{
//查询数据库的数据
var toJsonList = await _internationalizationRepository.Where(t => t.InternationalizationType == 1).Select(t => new
var toJsonList = await _repository.Where<Internationalization>(t => t.InternationalizationType == 1).Select(t => new
{
t.Code,
t.Value,
t.ValueCN,
t.Description
t.ValueCN
}).ToListAsync();
//组织成json 文件
@@ -138,9 +128,6 @@ namespace IRaCIS.Core.Application.Helper
{
StaticData.En_US_Dic[tojsonItem.Code] = tojsonItem.Value;
StaticData.Zh_CN_Dic[tojsonItem.Code] = tojsonItem.ValueCN;
//日志记录该信息方便自己人看, 返回给客户的是配置的
StaticData.Log_Locoalize_Dic[tojsonItem.Code] = tojsonItem.Description;
}
File.WriteAllText(usJsonPath, JsonConvert.SerializeObject(StaticData.En_US_Dic));
@@ -149,45 +136,29 @@ namespace IRaCIS.Core.Application.Helper
//监测Json文件变更 实时刷新数据
if (!File.Exists(usJsonPath) || !File.Exists(cnJsonPath))
WatchJsonFile(usJsonPath);
WatchJsonFile(cnJsonPath);
}
public static void WatchJsonFile(string filePath)
{
if (!File.Exists(filePath))
{
throw new BusinessValidationFailedException(StaticData.International("IRaCISCHangfireJob_FileNotFound"));
throw new BusinessValidationFailedException("国际化Json文件不存在");
}
// //监测Json文件变更 实时刷新数据
FileSystemWatcher_US = new FileSystemWatcher
{
Path = Path.GetDirectoryName(usJsonPath)!,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = Path.GetFileName(usJsonPath),
EnableRaisingEvents = true,
};
// 添加文件更改事件的处理程序
FileSystemWatcher_US.Changed += (sender, e) => LoadJsonFile(StaticData.Folder.Resources + "\\" + StaticData.En_US_Json);
FileSystemWatcher_CN = new FileSystemWatcher
{
Path = Path.GetDirectoryName(cnJsonPath)!,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
Filter = Path.GetFileName(cnJsonPath),
EnableRaisingEvents = true,
};
FileSystemWatcher_CN.Changed += (sender, e) => LoadJsonFile(StaticData.Folder.Resources + "\\" + StaticData.Zh_CN_Json);
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath), Path.GetFileName(filePath));
watcher.Changed += (sender, e) => LoadJsonFile(filePath);
watcher.EnableRaisingEvents = true;
}
private static void LoadJsonFile(string filePath)
{
Console.WriteLine("刷新json内存数据");
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(filePath, false, false);
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(filePath);
IConfigurationRoot enConfiguration = builder.Build();
@@ -204,11 +175,5 @@ namespace IRaCIS.Core.Application.Helper
}
}
}
}
}
+112 -345
View File
@@ -1,9 +1,11 @@
using Aliyun.OSS;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Minio.DataModel.Args;
using Minio;
using NPOI.HPSF;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
@@ -13,73 +15,48 @@ using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Text.Json.Serialization;
using Minio.ApiEndpoints;
using System.Reactive.Linq;
using IRaCIS.Core.Domain.Share;
using static MassTransit.ValidationResultExtensions;
using IRaCIS.Core.Infrastructure.NewtonsoftJson;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using MassTransit.Caching.Internals;
namespace IRaCIS.Core.Application.Helper
{
#region
[LowerCamelCaseJson]
public class MinIOOptions : AWSOptions
{
public int Port { get; set; }
public int port { get; set; }
}
public class AWSOptions
{
public string EndPoint { get; set; }
public bool UseSSL { get; set; }
public string AccessKeyId { get; set; }
public string RoleArn { get; set; }
public string SecretAccessKey { get; set; }
public string BucketName { get; set; }
public string ViewEndpoint { get; set; }
public int DurationSeconds { get; set; }
public string Region { get; set; }
public string endPoint { get; set; }
public bool useSSL { get; set; }
public string accessKey { get; set; }
public string secretKey { get; set; }
public string bucketName { get; set; }
public string viewEndpoint { get; set; }
}
public class AliyunOSSOptions
{
public string RegionId { get; set; }
public string AccessKeyId { get; set; }
public string AccessKeySecret { get; set; }
public string regionId { get; set; }
public string accessKeyId { get; set; }
public string accessKeySecret { get; set; }
public string InternalEndpoint { get; set; }
public string internalEndpoint { get; set; }
public string EndPoint { get; set; }
public string BucketName { get; set; }
public string endPoint { get; set; }
public string bucketName { get; set; }
public string RoleArn { get; set; }
public string Region { get; set; }
public string ViewEndpoint { get; set; }
public int DurationSeconds { get; set; }
public string roleArn { get; set; }
public string region { get; set; }
public string viewEndpoint { get; set; }
}
public class ObjectStoreServiceOptions
{
public string ObjectStoreUse { get; set; }
public AliyunOSSOptions AliyunOSS { get; set; }
public MinIOOptions MinIO { get; set; }
public AWSOptions AWS { get; set; }
@@ -90,51 +67,28 @@ namespace IRaCIS.Core.Application.Helper
{
public string ObjectStoreUse { get; set; }
public AliyunOSSTempToken AliyunOSS { get; set; }
public AliyunOSSOptions AliyunOSS { get; set; }
public MinIOOptions MinIO { get; set; }
public AWSTempToken AWS { get; set; }
public AWSOptions AWS { get; set; }
}
[LowerCamelCaseJson]
public class AliyunOSSTempToken
{
public string AccessKeyId { get; set; }
public string AccessKeySecret { get; set; }
public string EndPoint { get; set; }
public string BucketName { get; set; }
public string Region { get; set; }
public string ViewEndpoint { get; set; }
public string SecurityToken { get; set; }
public string Expiration { get; set; }
}
[LowerCamelCaseJson]
public class AWSTempToken
{
public string Region { get; set; }
public string SessionToken { get; set; }
public string EndPoint { get; set; }
public string AccessKeyId { get; set; }
public string SecretAccessKey { get; set; }
public string BucketName { get; set; }
public string ViewEndpoint { get; set; }
public DateTime Expiration { get; set; }
}
public enum ObjectStoreUse
{
AliyunOSS = 0,
@@ -142,10 +96,6 @@ namespace IRaCIS.Core.Application.Helper
AWS = 2,
}
#endregion
// aws 参考链接 https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/S3_Basics
public interface IOSSService
{
public Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true);
@@ -157,7 +107,6 @@ namespace IRaCIS.Core.Application.Helper
public Task<string> GetSignedUrl(string ossRelativePath);
public Task DeleteFromPrefix(string prefix);
}
@@ -182,84 +131,69 @@ namespace IRaCIS.Core.Application.Helper
public async Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true)
{
var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}" : $"{oosFolderPath}/{fileRealName}";
//var ossRelativePath = $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}";
//var ossRelativePath = oosFolderPath + "/" + fileRealName;
try
using (var memoryStream = new MemoryStream())
{
using (var memoryStream = new MemoryStream())
fileStream.Seek(0, SeekOrigin.Begin);
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
fileStream.Seek(0, SeekOrigin.Begin);
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);
var _ossClient = new OssClient(aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.PutObject(aliConfig.BucketName, ossRelativePath, memoryStream);
// 上传文件
var result = _ossClient.PutObject(aliConfig.bucketName, ossRelativePath, memoryStream);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
.Build();
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithObject(ossRelativePath)
.WithStreamData(memoryStream)
.WithObjectSize(memoryStream.Length);
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithStreamData(memoryStream)
.WithObjectSize(memoryStream.Length);
await minioClient.PutObjectAsync(putObjectArgs);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var awsConfig = ObjectStoreServiceOptions.AWS;
await minioClient.PutObjectAsync(putObjectArgs);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
// 提供awsAccessKeyId和awsSecretAccessKey构造凭证
var credentials = new BasicAWSCredentials(awsConfig.AccessKeyId, awsConfig.SecretAccessKey);
//提供awsEndPoint(域名)进行访问配置
var clientConfig = new AmazonS3Config
{
ServiceURL = awsConfig.EndPoint
};
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var amazonS3Client = new AmazonS3Client(credentials, clientConfig);
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithStreamData(memoryStream)
.WithObjectSize(memoryStream.Length);
var putObjectRequest = new Amazon.S3.Model.PutObjectRequest()
{
BucketName = awsConfig.BucketName,
InputStream = memoryStream,
Key = ossRelativePath,
};
await amazonS3Client.PutObjectAsync(putObjectRequest);
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
await minioClient.PutObjectAsync(putObjectArgs);
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
catch (Exception ex)
{
throw new BusinessValidationFailedException($"上传发生异常:{ex.Message}");
}
return "/" + ossRelativePath;
@@ -273,7 +207,6 @@ namespace IRaCIS.Core.Application.Helper
/// </summary>
/// <param name="localFilePath"></param>
/// <param name="oosFolderPath"></param>
/// <param name="isFileNameAddGuid"></param>
/// <returns></returns>
/// <exception cref="BusinessValidationFailedException"></exception>
public async Task<string> UploadToOSSAsync(string localFilePath, string oosFolderPath, bool isFileNameAddGuid = true)
@@ -283,14 +216,17 @@ namespace IRaCIS.Core.Application.Helper
var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{localFileName}" : $"{oosFolderPath}/{localFileName}";
//var ossRelativePath = oosFolderPath + "/" + localFileName;
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);
var _ossClient = new OssClient(aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.PutObject(aliConfig.BucketName, ossRelativePath, localFilePath);
var result = _ossClient.PutObject(aliConfig.bucketName, ossRelativePath, localFilePath);
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
@@ -298,12 +234,12 @@ namespace IRaCIS.Core.Application.Helper
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFileName(localFilePath);
@@ -311,28 +247,19 @@ namespace IRaCIS.Core.Application.Helper
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var awsConfig = ObjectStoreServiceOptions.AWS;
var minIOConfig = ObjectStoreServiceOptions.AWS;
// 提供awsAccessKeyId和awsSecretAccessKey构造凭证
var credentials = new BasicAWSCredentials(awsConfig.AccessKeyId, awsConfig.SecretAccessKey);
//提供awsEndPoint(域名)进行访问配置
var clientConfig = new AmazonS3Config
{
ServiceURL = awsConfig.EndPoint
};
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var amazonS3Client = new AmazonS3Client(credentials, clientConfig);
var putObjectRequest = new Amazon.S3.Model.PutObjectRequest()
{
BucketName = awsConfig.BucketName,
FilePath = localFilePath,
Key = ossRelativePath,
};
await amazonS3Client.PutObjectAsync(putObjectRequest);
var putObjectArgs = new PutObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFileName(localFilePath);
await minioClient.PutObjectAsync(putObjectArgs);
}
else
{
@@ -345,7 +272,7 @@ namespace IRaCIS.Core.Application.Helper
public async Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath)
{
ossRelativePath = ossRelativePath.TrimStart('/');
try
{
@@ -355,10 +282,10 @@ namespace IRaCIS.Core.Application.Helper
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);
var _ossClient = new OssClient(aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 上传文件
var result = _ossClient.GetObject(aliConfig.BucketName, ossRelativePath);
var result = _ossClient.GetObject(aliConfig.bucketName, ossRelativePath);
// 将下载的文件流保存到本地文件
using (var fs = File.OpenWrite(localFilePath))
@@ -372,12 +299,12 @@ namespace IRaCIS.Core.Application.Helper
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var getObjectArgs = new GetObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFile(localFilePath);
@@ -386,29 +313,18 @@ namespace IRaCIS.Core.Application.Helper
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var awsConfig = ObjectStoreServiceOptions.AWS;
var minIOConfig = ObjectStoreServiceOptions.AWS;
// 提供awsAccessKeyId和awsSecretAccessKey构造凭证
var credentials = new BasicAWSCredentials(awsConfig.AccessKeyId, awsConfig.SecretAccessKey);
//提供awsEndPoint(域名)进行访问配置
var clientConfig = new AmazonS3Config
{
ServiceURL = awsConfig.EndPoint
};
var amazonS3Client = new AmazonS3Client(credentials, clientConfig);
var getObjectArgs = new Amazon.S3.Model.GetObjectRequest()
{
BucketName = awsConfig.BucketName,
Key = ossRelativePath,
};
await (await amazonS3Client.GetObjectAsync(getObjectArgs)).WriteResponseStreamToFileAsync(localFilePath, true, CancellationToken.None);
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var getObjectArgs = new GetObjectArgs()
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithFile(localFilePath);
await minioClient.GetObjectAsync(getObjectArgs);
}
else
{
@@ -427,7 +343,7 @@ namespace IRaCIS.Core.Application.Helper
}
public async Task<string> GetSignedUrl(string ossRelativePath)
public async Task<string> GetSignedUrl(string ossRelativePath)
{
ossRelativePath = ossRelativePath.TrimStart('/');
try
@@ -438,10 +354,10 @@ namespace IRaCIS.Core.Application.Helper
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);
var _ossClient = new OssClient(aliConfig.internalEndpoint, aliConfig.accessKeyId, aliConfig.accessKeySecret);
// 生成签名URL。
var req = new GeneratePresignedUriRequest(aliConfig.BucketName, ossRelativePath, SignHttpMethod.Get)
var req = new GeneratePresignedUriRequest(aliConfig.bucketName, ossRelativePath, SignHttpMethod.Get)
{
// 设置签名URL过期时间,默认值为3600秒。
Expiration = DateTime.Now.AddHours(1),
@@ -455,13 +371,17 @@ namespace IRaCIS.Core.Application.Helper
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}:{minIOConfig.port}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
//var reqParams = new Dictionary<string, string>(StringComparer.Ordinal)
// {
// { "response-content-type", "application/json" }
// };
var args = new PresignedGetObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithBucket(minIOConfig.bucketName)
.WithObject(ossRelativePath)
.WithExpiry(3600)
/*.WithHeaders(reqParams)*/;
@@ -480,23 +400,11 @@ namespace IRaCIS.Core.Application.Helper
{
var minIOConfig = ObjectStoreServiceOptions.AWS;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.endPoint}")
.WithCredentials(minIOConfig.accessKey, minIOConfig.secretKey).WithSSL(minIOConfig.useSSL)
.Build();
var args = new PresignedGetObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithObject(ossRelativePath)
.WithExpiry(3600);
var presignedUrl = await minioClient.PresignedGetObjectAsync(args);
Uri uri = new Uri(presignedUrl);
string relativePath = uri.PathAndQuery;
return relativePath;
return string.Empty;
}
else
{
@@ -510,147 +418,6 @@ namespace IRaCIS.Core.Application.Helper
}
}
/// <summary>
/// 删除某个目录的文件
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
public async Task DeleteFromPrefix(string prefix)
{
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);
try
{
ObjectListing objectListing = null;
string nextMarker = null;
do
{
// 使用 prefix 模拟目录结构,设置 MaxKeys 和 NextMarker
objectListing = _ossClient.ListObjects(new Aliyun.OSS.ListObjectsRequest(aliConfig.BucketName)
{
Prefix = prefix,
MaxKeys = 1000,
Marker = nextMarker
});
List<string> keys = objectListing.ObjectSummaries.Select(t => t.Key).ToList();
// 删除获取到的文件
if (keys.Count > 0)
{
_ossClient.DeleteObjects(new Aliyun.OSS.DeleteObjectsRequest(aliConfig.BucketName, keys, false));
}
// 设置 NextMarker 以获取下一页的数据
nextMarker = objectListing.NextMarker;
} while (objectListing.IsTruncated);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient().WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey).WithSSL(minIOConfig.UseSSL)
.Build();
var listArgs = new ListObjectsArgs().WithBucket(minIOConfig.BucketName).WithPrefix(prefix).WithRecursive(true);
// 创建一个空列表用于存储对象键
var objects = new List<string>();
// 使用 await foreach 来异步迭代对象列表
await foreach (var item in minioClient.ListObjectsEnumAsync(listArgs))
{
objects.Add(item.Key);
}
if (objects.Count > 0)
{
var objArgs = new RemoveObjectsArgs()
.WithBucket(minIOConfig.BucketName)
.WithObjects(objects);
// 删除对象
await minioClient.RemoveObjectsAsync(objArgs);
}
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var awsConfig = ObjectStoreServiceOptions.AWS;
// 提供awsAccessKeyId和awsSecretAccessKey构造凭证
var credentials = new BasicAWSCredentials(awsConfig.AccessKeyId, awsConfig.SecretAccessKey);
//提供awsEndPoint(域名)进行访问配置
var clientConfig = new AmazonS3Config
{
ServiceURL = awsConfig.EndPoint
};
var amazonS3Client = new AmazonS3Client(credentials, clientConfig);
// 列出指定前缀下的所有对象
var listObjectsRequest = new ListObjectsV2Request
{
BucketName = awsConfig.BucketName,
Prefix = prefix
};
var listObjectsResponse = await amazonS3Client.ListObjectsV2Async(listObjectsRequest);
if (listObjectsResponse.S3Objects.Count > 0)
{
// 准备删除请求
var deleteObjectsRequest = new Amazon.S3.Model.DeleteObjectsRequest
{
BucketName = awsConfig.BucketName,
Objects = new List<KeyVersion>()
};
foreach (var s3Object in listObjectsResponse.S3Objects)
{
deleteObjectsRequest.Objects.Add(new KeyVersion
{
Key = s3Object.Key
});
}
// 批量删除对象
var deleteObjectsResponse = await amazonS3Client.DeleteObjectsAsync(deleteObjectsRequest);
}
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
}
@@ -1,97 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
namespace IRaCIS.Core.Application.Helper
{
/// <summary>
/// https://www.cnblogs.com/NBDWDYS2214143926/p/13329231.html
/// </summary>
public class RSAHelper
{
public static AsymmetricCipherKeyPair GenerateRSAKeyPair(int keySize)
{
var keyGenerationParameters = new KeyGenerationParameters(new SecureRandom(), keySize);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
return keyPairGenerator.GenerateKeyPair();
}
public static string ExportPublicKey(AsymmetricKeyParameter publicKey)
{
using (StringWriter sw = new StringWriter())
{
PemWriter pw = new PemWriter(sw);
pw.WriteObject(publicKey);
pw.Writer.Flush();
return sw.ToString();
}
}
public static string ExportPrivateKey(AsymmetricKeyParameter privateKey)
{
using (StringWriter sw = new StringWriter())
{
PemWriter pw = new PemWriter(sw);
pw.WriteObject(privateKey);
pw.Writer.Flush();
return sw.ToString();
}
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="privateKey">私钥</param>
/// <param name="decryptstring">待解密的字符串(Base64)</param>
/// <returns>解密后的字符串</returns>
public static string Decrypt(string privateKey, string decryptstring)
{
using (TextReader reader = new StringReader(privateKey))
{
dynamic key = new PemReader(reader).ReadObject();
var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
if (key is AsymmetricKeyParameter)
{
key = (AsymmetricKeyParameter)key;
}
else if (key is AsymmetricCipherKeyPair)
{
key = ((AsymmetricCipherKeyPair)key).Private;
}
rsaDecrypt.Init(false, key); //这里加密是true;解密是false
byte[] entData = Convert.FromBase64String(decryptstring);
entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
return Encoding.UTF8.GetString(entData);
}
}/// <summary>
/// 加密
/// </summary>
/// <param name="publicKey">公钥</param>
/// <param name="encryptstring">待加密的字符串</param>
/// <returns>加密后的Base64</returns>
public static string Encrypt(string publicKey, string encryptstring)
{
using (TextReader reader = new StringReader(publicKey))
{
AsymmetricKeyParameter key = new PemReader(reader).ReadObject() as AsymmetricKeyParameter;
Pkcs1Encoding pkcs1 = new Pkcs1Encoding(new RsaEngine());
pkcs1.Init(true, key);//加密是true;解密是false;
byte[] entData = Encoding.UTF8.GetBytes(encryptstring);
entData = pkcs1.ProcessBlock(entData, 0, entData.Length);
return Convert.ToBase64String(entData);
}
}
}
}
@@ -52,19 +52,15 @@ public static class SendEmailHelper
public static async Task<bool> TestEmailConfigAsync(SystemEmailSendConfig _systemEmailConfig)
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
await client.ConnectAsync(_systemEmailConfig.Host, _systemEmailConfig.Port, SecureSocketOptions.Auto, cts.Token);
await client.ConnectAsync(_systemEmailConfig.Host, _systemEmailConfig.Port, SecureSocketOptions.Auto);
await client.AuthenticateAsync(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode, cts.Token);
await client.AuthenticateAsync(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode);
await client.DisconnectAsync(true);
}
await client.DisconnectAsync(true);
}
return true;
}
@@ -1,101 +0,0 @@
using IRaCIS.Core.Domain.Share;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xceed.Document.NET;
using Xceed.Words.NET;
namespace IRaCIS.Core.Application.Helper
{
/// <summary>
/// 利用DocX 库 处理word国际化模板
/// </summary>
public static class WordTempleteHelper
{
public static void DocX_GetInternationalTempleteStream(string filePath, Stream memoryStream)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
using (DocX document = DocX.Load(filePath))
{
// 查找书签
var bookmarkEn_Start = document.Bookmarks.FirstOrDefault(b => b.Name == StaticData.CultureInfo.en_US_bookMark);
if (bookmarkEn_Start != null)
{
// 获取书签的起始位置
//int bookmarkCNStartPos = bookmarkCn_Start.Paragraph.StartIndex;
var bookmarkENStartPos = bookmarkEn_Start.Paragraph.StartIndex;
// 创建一个要删除段落的列表
List<Paragraph> paragraphsToRemove = new List<Paragraph>();
foreach (var item in document.Paragraphs)
{
//中文模板在前,英文在后,英文模板,就删除英文之前的,中文模板就删除英文之后的
if (isEn_US ? item.EndIndex < bookmarkENStartPos : item.StartIndex >= bookmarkENStartPos)
{
paragraphsToRemove.Add(item);
}
}
foreach (var paragraph in paragraphsToRemove)
{
document.RemoveParagraph(paragraph);
}
}
// 保存修改
document.SaveAs(memoryStream);
}
}
public static void Npoi_GetInternationalTempleteStream(string filePath, Stream memoryStream)
{
var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
XWPFDocument doc = new XWPFDocument(fs);
// 查找包含指定书签的段落及其索引
var bookmarkParagraph = doc.Paragraphs
.FirstOrDefault(p => p.GetCTP().GetBookmarkStartList().Any(b => b.name == StaticData.CultureInfo.en_US_bookMark));
if (bookmarkParagraph != null)
{
int bookmarkIndex = doc.Paragraphs.IndexOf(bookmarkParagraph);
if (isEn_US)
{
// 从书签所在段落开始,删除之前的所有段落
for (int i = bookmarkIndex - 1; i >= 0; i--)
{
doc.RemoveBodyElement(i);
}
}
else
{
// 删除书签之后的所有段落
for (int i = doc.Paragraphs.Count - 1; i >= bookmarkIndex; i--)
{
doc.RemoveBodyElement(i);
}
}
}
doc.Write(memoryStream);
}
}
}
}
@@ -42,7 +42,7 @@
<ItemGroup>
<None Remove="IRaCIS.Core.Application.xml" />
<None Remove="Resources\en-US.json" />
<None Remove="Resources\zh_ch.json" />
<None Remove="Resources\zh-CN.json" />
<None Remove="Service\Allocation\TaskConsistentRuleService.cs~RF1603d47.TMP" />
<None Remove="Service\Reading\ReadingImageTask\ReadingImageTaskService.cs~RF2f9323.TMP" />
<None Remove="Service\Reading\ReadingImageTask\ReadingJudgeTaskService.cs~RF198afd23.TMP" />
@@ -50,6 +50,11 @@
<ItemGroup>
<Content Include="Resources\zh-CN.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="Resources\en-US.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
@@ -58,34 +63,35 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.14.1" />
<PackageReference Include="AWSSDK.S3" Version="3.7.402.4" />
<PackageReference Include="DocX" Version="3.0.1" />
<PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.13.0" />
<PackageReference Include="FreeSpire.Doc" Version="12.2.0" />
<PackageReference Include="Hangfire.Core" Version="1.8.14" />
<PackageReference Include="ExcelDataReader" Version="3.7.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.7.0" />
<PackageReference Include="Hangfire.Core" Version="1.8.12" />
<PackageReference Include="BeetleX.BNR" Version="1.0.1" />
<PackageReference Include="Castle.Core.AsyncInterceptor" Version="2.1.0" />
<PackageReference Include="EasyCaching.Redis" Version="1.9.2" />
<PackageReference Include="EasyCaching.InMemory" Version="1.9.2" />
<PackageReference Include="ExcelDataReader" Version="3.6.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
<PackageReference Include="DistributedLock.Redis" Version="1.0.3" />
<PackageReference Include="DistributedLock.SqlServer" Version="1.0.5" />
<PackageReference Include="fo-dicom" Version="5.1.3" />
<PackageReference Include="fo-dicom.Imaging.ImageSharp" Version="5.1.3" />
<PackageReference Include="fo-dicom.Codecs" Version="5.14.5" />
<PackageReference Include="DistributedLock.SqlServer" Version="1.0.4" />
<PackageReference Include="fo-dicom" Version="5.1.2" />
<PackageReference Include="fo-dicom.Imaging.ImageSharp" Version="5.1.2" />
<PackageReference Include="fo-dicom.Codecs" Version="5.12.0" />
<PackageReference Include="IP2Region.Net" Version="2.0.2" />
<PackageReference Include="MailKit" Version="4.2.0" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="MimeKit" Version="4.2.0" />
<PackageReference Include="MiniExcel" Version="1.34.1" />
<PackageReference Include="Minio" Version="6.0.3" />
<PackageReference Include="MiniExcel" Version="1.32.0" />
<PackageReference Include="Minio" Version="6.0.2" />
<PackageReference Include="MiniWord" Version="0.8.0" />
<PackageReference Include="My.Extensions.Localization.Json" Version="3.3.0">
<TreatAsUsed>true</TreatAsUsed>
</PackageReference>
<PackageReference Include="NPOI" Version="2.7.1" />
<PackageReference Include="NPOI" Version="2.7.0" />
<PackageReference Include="Panda.DynamicWebApi" Version="1.2.2" />
<PackageReference Include="RestSharp" Version="112.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.4" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.2" />
<PackageReference Include="MassTransit.AspNetCore" Version="7.3.1" />
<PackageReference Include="ZiggyCreatures.FusionCache" Version="1.3.0" />
<PackageReference Include="WinSCP" Version="6.3.3" />
</ItemGroup>
<ItemGroup>
File diff suppressed because it is too large Load Diff
@@ -1,96 +0,0 @@
using MiniExcelLibs.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.MassTransit.Command
{
public record ConsistenCheckCommand
{
public List<CheckViewModel> ETCList { get; set; } = new List<CheckViewModel>();
public Guid TrialId { get; set; }
}
public record ConsistenCheckResult
{
}
public class CheckDBModel : CheckViewModel
{
public Guid SubjectVisitId { get; set; }
public Guid StudyId { get; set; }
}
//[ExcelImporter(/*ImportResultFilter = typeof(ImportResultFilteTest),*/ IsLabelingError = true)]
public class CheckViewModel
{
//[Required(ErrorMessage = "中心编号不能为空")]
//[ImporterHeader(Name = "Site ID", AutoTrim = true)]
[ExcelColumnName("Site ID")]
public string SiteCode { get; set; } = string.Empty;
//[Required(ErrorMessage = "受试者筛选号不能为空")]
//[ImporterHeader(Name = "Subject ID", AutoTrim = true)]
[ExcelColumnName("Subject ID")]
public string SubjectCode { get; set; } = string.Empty;
//[Required(ErrorMessage = "访视名称不能为空")]
//[ImporterHeader(Name = "Visit Name", AutoTrim = true)]
[ExcelColumnName("Visit Name")]
public string VisitName { get; set; } = string.Empty;
//[Required(ErrorMessage = "检查日期不能为空")]
[CanConvertToTime(ErrorMessage = "Does not conform to Study Date format")]
//[ImporterHeader(Name = "Study Date", AutoTrim = true)]
[ExcelColumnName("Study Date")]
public string StudyDate { get; set; } = string.Empty;
//[Required(ErrorMessage = "Modality不能为空")]
//[ImporterHeader(Name = "Modality", AutoTrim = true)]
[ExcelColumnName("Modality")]
public string Modality { get; set; } = string.Empty;
public override bool Equals(object? obj)
{
if (obj == null) return false;
var checkModel = obj as CheckViewModel;
if (checkModel is not null)
{
return SiteCode == checkModel.SiteCode && SubjectCode == checkModel.SubjectCode && VisitName == checkModel.VisitName && StudyDate == checkModel.StudyDate && Modality == checkModel.Modality;
}
else
{
return false;
}
}
public override int GetHashCode()
{
return (SiteCode + SubjectCode + VisitName + StudyDate + Modality).GetHashCode();
}
}
}
@@ -1,2 +1,593 @@
{
"test{0}{1}": "英文本地化{0}{1}",
"RequiredAttribute": "{0} is required",
// ------------------------------------------------------------_ServiceExtensions--------------------------------------------------------------------
//ApiResponseHandler
"ApiResponse_NoAccess": "You do not have access to this API",
"ApiResponse_Permission": "You do not have permission to do this",
// ------------------------------------------------------------Controllers--------------------------------------------------------------------
//FinancialChangeController
"Financial_ChargeSettled": "Expenses have been settled and workload can not be reset.",
"Financial_InvalidParameter": "Invalid parameter.",
//UploadDownLoadController
"UploadDownLoad_UnsupportedMedia": "Unsupported media type.",
"UploadDownLoad_ArchiveInProgress": "Another user is uploading or archiving this study.",
"UploadDownLoad_InvalidData": "Please ensure that the uploaded data conforms to the style of the template file and contains valid data.",
"UploadDownLoad_RequestError": "Request error, please try again!",
"UploadDownLoad_SupportedFormats": "Supports upload of .xlsx, .xls, and .csv formats.",
// ------------------------------------------------------------_MediatR--------------------------------------------------------------------
//ConsistencyVerificationRequest
"ConsistencyVerification_Tech": "Study Type",
"ConsistencyVerification_Time": "Incorrect time format",
//ConsistencyVerificationHandler
"ConsistencyVerification_Img": "Hello, according to the automatic recognition of this system, the imaging study submitted by the subject in the current visit in the IRC system is as follows:",
"ConsistencyVerification_Of": "Of",
"ConsistencyVerification_ImgC": "Imaging study",
"ConsistencyVerification_EDCA": "Check EDC data, completely consistent, approved",
"ConsistencyVerification_EDCB": "Check EDC data, completely consistent",
"ConsistencyVerification_Auto": "Automatically verified pass",
"ConsistencyVerification_Prob": "The following problems exist:",
"ConsistencyVerification_EdcL": "Image study (EDC missing)",
"ConsistencyVerification_IrcL": "Image study (IRC missing)",
"ConsistencyVerification_Desc": "Description: In order to efficiently solve all the above doubts, please verify the actual image study accurately. Please note that the image date may not be consistent with the actual study date, and multiple modalities of image studys (such as PET-CT) may exist at the same time. After accurate verification, please reply with the correct image study for this visit.",
"ConsistencyVerification_Conf": "According to the imported consistency check data, please confirm the following inconsistent inspection item information of this visit:",
"ConsistencyVerification_Edc": "EDC is lack of:",
"ConsistencyVerification_IrcLi": "IRC is lack of:",
//-------------------------------------------------------------------------------------Reading-----------------------------------------------------------------
//ClinicalDataSetService
"ClinicalDataSet_Apply": "",
"ClinicalDataSet_DupTypeFail": "The same type of clinical data exists. The operation failed.",
//ClinicalQuestionService
"ClinicalQuestion_Repeat": "",
//ReadingClinicalDataService
"ReadingClinicalData_DupTypeFail": "The same type of clinical data exists. The operation failed.",
"ReadingClinicalData_Unchecked": "The current clinical data status is not verified and signing is not allowed!",
//ReadingGlobalTaskService
"ReadingGlobal_NotGlobal": "System call error. The current read is not a global review read.",
//ReadingImageTaskService
"ReadingImage_NotVisit": "System call error. The current read is not a timepoint read.",
"ReadingImage_CantSplit": "The current read is a baseline read, and lesion split is not allowed.",
"ReadingImage_BeSigned": "The current read has already been signed. Please do not submit it again.",
"ReadingImage_Beinvalid": "The current read has already been invalidated, and reading is not allowed anymore.",
"ReadingImage_PresenceReview": "The current subject has a re-read request that has not been processed and is not allowed to operate",
"ReadingImage_NotaTask": "The coalesced lesions are not from the same timepoint.",
"ReadingImage_DeleteError": "Other lesions have split from or coalesced into the current lesion. Deletion failed.",
"ReadingImage_Idnotcorrespond": "Failed to add the lesion mark. The Instance ID and Series ID of the image do not match.",
"ReadingImage_IsLymphNotbigger": "The short diameter of this nodal non-target lesion on the current visit is smaller than the value on the previous visit, and the state cannot be set to 'Unequivocal progression'.",
"ReadingImage_NotLymphNotbigger": "The long diameter of this non-nodal non-target lesion on the current visit is smaller than the value on the previous visit, and the state cannot be set to 'Unequivocal progression'.",
"ReadingImage_Twice": "System call error. Questions & answers submitted are duplicated.",
"ReadingImage_MaxQuestion": "According to the imaging charter, the number of {0} cannot exceed {1}.",
"ReadingImage_Maxlesion": "According to the imaging charter, the number of target lesions in the same organ cannot exceed {0}. Please confirm.",
"ReadingImage_Maximum": "{0} can only be repeated {1} times, and it has been repeated {2} times so far.",
"ReadingImage_PCWGMaximum": "According to the imaging charter, the number of baseline lesions at the same location should enter only {0} time. Please confirm.",
"ReadingImage_NotNewFocus": "There should be no new lesions in the converted task",
"ReadingImage_RequiredQuestion": "Before submission, please fill in {0}.",
"ReadingImage_ClinicalRead": "The clinical data has not been read. Please confirm!",
"ReadingImage_IDMust": "System call failed. When there is no Read ID, the standard ID must be passed.",
"ReadingImage_TaskFinish": "Please note that all reads of the current subject have been completed.",
"ReadingImage_NeedRest": "You have been continuously reading for {0} hours. Please take a break of {1} minutes before resumption.",
//ReadingJudgeTaskService
"ReadingJudge_SouceIdNull": "System call failed. The Source ID of the global review which is being adjudicated currently is 'null'.",
//ReadingOncologyTaskService
"ReadingOncology_TaskError": "System call error. The current read is not an oncology read.",
"ReadingOncology_Abnormal": "System call exception. The result of adjudication is null",
//ReadingCalculate
"ReadingCalculate_Abnormal": "Configuration error of PCWG3 criteria. Data verification failed.",
"ReadingCalculate_questionable": "Problems with the lesions are as follows:",
"ReadingCalculate_NoMarker": "Lesion {0} lacks mark.",
"ReadingCalculate_StatusIsEmpty": "The state of Lesion {0} is empty.",
"ReadingCalculate_NoMarkerEmpty": "Lesion {0} is not marked, and its state is empty.",
"ReadingCalculate_NoDeveloped": "Please note that the current standard automatic calculation has not been developed.",
//ReadingMedicalReviewService
"MedicalReview_invalid": "This medical review read has already been invalidated, and the operation failed.",
"MedicalReview_SaveQuestion": "Unable to perform the current operation. Please save the medical review questions first.",
"MedicalReview_NeedSave": "Unable to perform the current operation. Please save the medical review questions and conclusions first.",
"MedicalReview_NotClosed": "Unable to perform the current operation. The current medical query conversation has not been closed.",
"MedicalReview_Finish": "The current medical review is the last one.",
//ReadingMedicineQuestionService
"ReadingMed_QNumDup": "Current question number is repeated",
"ReadingMed_HasSubQ": "This question has sub-question, please delete it first",
"ReadingMed_NoMedQ": "Medical review question has not been added yet. Please add it first before confirming",
"ReadingMed_MedQNumDup": "The display number of the medical imaging review question cannot be duplicated.",
"ReadingMed_ParentNumSmall": "The display number of the parent question should be smaller than that of the child question, please confirm.",
"ReadingMed_VisitQNotConfig": "This review criteria has no medical review questions for 'visit'",
"ReadingMed_GlobalQNotConfig": "The global review read is enabled in the current criterion, but has not configured with medical review questions",
"ReadingMed_ArbitrateQNotConfig": "Adjudication review reading is enabled in the current criterion, but has not configured with medical review questions",
"ReadingMed_TumorQNotConfig": "Oncology reading is enabled in the current criterion, but the oncology medical review question has not been configured",
//UserService
"User_CheckNameOrPw": "Please check the username or password.",
//Repository
"Repository_UpdateError": "Updated data does not exist in the database. ",
"Repository_DeleteError": "Deleted data does not exist in the database.",
//OrganInfoService
"OrganInfo_DuplicateData": "There are duplicate data, operation failed.",
//ReadingCriterionService
"ReadingCriterion_Referenced": "The current criterion has been referenced and cannot be deleted.",
"ReadingCriterion_InUse": "This criterion has been used in the project and cannot be deleted.",
"ReadingCriterion_ArbitratorWithoutJudgment": "There is no referee problem but there is an arbitration object, operation failed.",
//ReadingQuestionService
"ReadingQuestion_IdDup": "Duplicate problem ID.",
"ReadingQuestion_ChildrenExist": "This problem has sub-problems, please delete the sub-problems first.",
"ReadingQuestion_GroupReferenced": "This grouping has been referenced, please delete the referenced problems first.",
"ReadingQuestion_JudgmentSet": "The current question already has a referee criterion set, modification failed.",
"ReadingQuestion_ExcludeWithDependency": "The displayed dependent parent question and the required dependent question are the same, but the answers are mutually exclusive, operation failed.",
"ReadingQuestion_CircularDependency": "Calculation dependency has looped!",
//ReadingPeriodSetService
"ReadingPeriodSet_NameDup": "Review period name duplicate, operation failed",
"ReadingPeriodSet_Global": "Review period name cannot be Global",
"ReadingPeriodSet_AlreadyAdded": "{0} has already added the review period, cannot set it effective.",
"ReadingPeriodSet_TaskCompletedCannotRevoke": "The current criterion has generated reads and the reads have been completed, revoke failed.",
"ReadingPeriodSet_LastVisit": "Last visit.",
//ReadModuleService
"ReadModule_AlreadyAdded": "The current visit has already added a review period.",
"ReadModule_AddGlobalFirst": "Please add global review first.",
"ReadModule_VisitNotFound": "No qualified visit was found.",
"ReadModule_SignedDataCannotDelete": "Clinical data has been signed and cannot be deleted.",
"ReadModule_TumorExists": "The current visit has a tumor review, please delete it first.",
"ReadModule_TaskGenerated": "The current review has generated reads, operation failed.",
//UserWLTemplateService
"UserWLTS_MaxTemplate": "The same user can add a maximum of 10 templates.",
"UserWLTS_NameRepeated": "The template name is repeated",
"UserWLTS_ContentRepeated": "The template content is repeated",
// ------------------------------------------------------------Allocation--------------------------------------------------------------------
//TaskAllocationRuleService
"TaskAllocation_DoctorIdNotFound": "Error, the doctor's account Id was not found in the enrollment table.",
"TaskAllocation_DoctorConfigExists": "The doctor configuration is already available, and continued additions cannot be allowed.",
"TaskAllocation_TaskAssigned": "A read has been assigned to the doctor and it cannot be deleted.",
//TaskConsistentRuleService
"TaskConsistent_ConsistencyConfigExists": "Please configure the doctor for consistency analysis.",
"TaskConsistent_TaskGenerated": "The trial configuration is already available, and no continued additions are allowed.",
"TaskConsistent_MedicalAuditTaskExists": "The criterion already has reads generated by the Subject, and configuration modification is not allowed.",
"TaskConsistent_SignedTaskCannotBeInvalidated": "This criterion has generated a consistency analysis task and cannot be deleted.",
//TaskMedicalReviewRuleService
"TaskMedicalRule_TaskAlreadyAssigned": "The doctor configuration is already available, and continued additions cannot be allowed.",
"TaskMedicalRule_TaskStarted": "A medical review task has been generated.",
//TaskMedicalReviewService
"TaskMedical_DirtyData": "Signed files cannot be set to invalid.",
"TaskMedical_SubjectInOtherArm": "A task is currently assigned to someone else,and it cannot be assigned. Please refresh the list.",
//VisitTaskService
"VisitTask_VisitTask_TaskAlreadyApplied": "The trial has not confirmed any of the review criteria.",
"VisitTask_DoctorConfigNotFound": "The current doctor has begun to do the task of this standard of subject, so assignment cannot be canceled.",
"VisitTask_BackendDataError": "One of the reeads has been assigned to the doctor and is not allowed to be assigned.",
"VisitTask_DirtyData": "Dirty data appears, and the task source field has no value.",
"VisitTask_MissingTaskSource": "The subject had a visit and entered the return process, which has not been verified for consistency and is not allowed to be assigned.",
"VisitTask_InconsistentSubjectStatus": "There is a subject that already has the doctor in another Arm group. It is not allowed to add the doctor to a new group.",
"VisitTask_DuplicateDoctorInArm": "There is a subject that already has the doctor in another Arm group, so the futher assignment is not allowed. Please refresh the page to confirm whether the data on the page is expired.",
"VisitTask_DoctorAlreadyInArm": "The assignment of a Subject task cannot be canceled because it has been applied.",
"VisitTask_TaskAlreadyApplied": "The configured doctor cannot be found in the configuration table, and the binding cannot be applied. Please check the data.",
"VisitTask_DoctorConfiguration": "Background data error",
"VisitTask_BackendData": "Reads that have not been completed or have not been effective are not allowed to request re-reading.",
"VisitTask_UnreadTask": "Reads that re-read has been applied or approved are not allowed to apply for re-reading.",
"VisitTask_NoPMRecheck": "Additional review reads do not allow the PM to apply for re-reading",
"VisitTask_Reapply": "PM is not allowed to apply for re-reading of consistency analysis reads.",
"VisitTask_ConsistencyAnalysis": "PM is only allowed to apply for re-reading that the view type is visit.",
"VisitTask_VisitTypeRestriction": "This is chronological read, and the subject has visit that has applied for re-read by PM, but has not been processed, so it cannot been applied for continuing re-read at this time.",
"VisitTask_SequentialReading": "This is chronological read, and the subject has visit that has applied for re-read, but has not been processed, so it cannot been applied for re-read for now.",
"VisitTask_ImageProblem": "This is chronological read, and there is something wrong with the image. PM has applied for returning, so it cannot been applied for re-reading now.",
"VisitTask_LastReading": "This is chronological read, and only the request for re-readinng by the subject reader after completing the global task for the last time is allowed.",
"VisitTask_LastOncologistRecheck": "This is chronological read, and the subject will only be allowed to re-read after IR completing the last oncology read ",
"VisitTask_LastAdjudicatorRecheck": "This is chronological read, and the subject will only be allowed to re-read after IR completing the last adjudication read ",
"VisitTask_IRGlobalRecheck": "This is random read, IR is only allowed to apply for re-reading global and visit reads",
"VisitTask_IRReapply": "This is random read, IR is only allowed to apply for re-reading global and visit reads ",
"VisitTask_InvalidReapplyStatus": "The current re-read status is not requested and cannot be processed. Please refresh the page.",
"VisitTask_ReapplyStatusConflict": "The current re-read status has been affected by another re-read reads. The re-read review operation is not allowed for reads in this state",
"VisitTask_ReReadTaskNotApplied": "Only reads with visit type are allowed to approve of re-read.",
"VisitTask_ReReadTaskAlreadyAffected": "Do not conform to the PM request and SPM / CPM approve , or IR request and PM approve.",
"VisitTask_TaskTypeNotApproved": "The current re-read status is not requested and cannot be processed. Please refresh the page.",
"VisitTask_NoImageReturn": "Additional review reads do not allow PM to apply for re-reading",
"VisitTask_NonEffectiveTaskCannotBeReturned": "Only effective and unfinished visit read can be returned. Please refresh the page data.",
"VisitTask_NoFurtherReturn": "The current visit has been returned to image upload, so continuing to return is not allowed!",
"VisitTask_ConsistencyTaskCannotBeReturned": "The consistency analysis read is not allowed to be set return back.",
"VisitTask_PMOnlyAllowedForReturn": "Only PM can perform the return back.",
"VisitTask_UnsupportedTaskType": "Re-read types are not supported.",
"VisitTask_UndefinedList": "The current user view list is not defined.",
"VisitTask_NoConsistencyReturn": "The conformance analysis read cannot be returned back",
"VisitTask_VisitTypeTaskAllowedForPMOnly": "Only read with visit type can be returned by PM.",
// ------------------------------------------------------------Common--------------------------------------------------------------------
//CommonDocumentService
"Document_CodeDuplication": "The Code of the document cannot be repeated.",
"Document_SingleTemplate": "Only one template file is allowed per scenario and standard.",
"Document_ TemplateRead": "Failed to read the template content, please try saving the file as docx format!",
//DictionaryService
"Dictionary_DictionaryName": "There is already a dictionary with the name {0}.",
"Dictionary_DictionaryDeletion": "The current dictionary is referenced in the standard and cannot be deleted!",
"Dictionary_SubitemDeletion": "There is child data, direct deletion is not allowed!",
"Dictionary_ResumeReference": "The current entry has been referenced in the reader resume.",
"Dictionary_ProjectReference": "The current entry has been referenced in the trial information.",
"Dictionary_StandardReference": "The current entry has been referenced in the review criteria.",
//ExcelExportService
"ExcelExport_UnsupportedExport": "Currently the criterion export is not supported.",
//MailService
"Mail_EmailResetReminder": "[From Extensive Imaging IRC] A reminder about resetting the email.",
"Mail_Dear": "Dear {0},",
"Mail_ResettingEmail": "You are resetting an email address.",
"Mail_IRCResettingPassword ": "[From Extensive Imaging IRC] A reminder about resetting your password",
"Mail_ResettingPassword ": "You are resetting the email password",
"Mail_ImagingIRCReminder": "[From Extensive Imaging IRC] A reminder",
"Mail_IRCProject": "You are participating in the Extensive Imaging IRC trial",
"Mail_ProjectParticipationReminder": "[From Extensive Imaging IRC] [{0}] A reminder of the Site Survey",
"Mail_CenterResearchReminder": "You are participating in the Site Survey of the Extensive Imaging IRC trial.",
"Mail_AccountCreationReminder": "[From Extensive Imaging IRC] A reminder about creating an account",
"Mail_AccountPasswordResetReminder": "[From Extensive Imaging IRC] A reminder about resetting account passwords",
"Mail_InvitationEmail": "[From Extensive Imaging IRC][{0}]Invitation",
//SystemMonitor
"SysMon_JsonConfig": "Parsing the Json file configuration failed",
// ------------------------------------------------------------Doctor--------------------------------------------------------------------
//DoctorService
"Doctor_DupPhoneOrEmail": "The current tel or email number already existed",
"Doctor_DupPhone": "The current tel number already existed!",
"Doctor_DupEmail": "The current email already existed!",
"Doctor_StandardDuplicateFileTypeError": "This type of file has already been added to the current criterion.",
"Doctor_RequiredDocumentsError": "Resume & Consultant Agreement must be upload",
// ------------------------------------------------------------Document--------------------------------------------------------------------
//SystemDocumentService
"SystemD_DuplicateFile": "A file with the same type and same name already exists in the system.",
"SystemD_CannotDeleteSignedFile": "The file has already been read and signed by a user, and not allowed to be deleted.",
//TrialDocumentService
"TrialD_DuplicateFileInProject": "A file with the same type and same name already exists in this trial .",
"TrialD_DocumentHasAlready": "The file has already been read and signed by a user, and not allowed to be deleted.",
"TrialD_FileAlreadySigned": "The file has been signed.",
"TrialD_ObsoleteFile": "The file has been revoked. Signature failed!",
//TrialEmailNoticeConfigService
"TrialEmailN_TaskNotSigned": "Before sending the email, the task must have been signed and triggered to complete the corresponding task generation.",
"TrialEmailN_NoRecipient": "The message cannot be sent without the recipient.",
"TrialEmailN_InvalidEmailConfig": "The configuration of the sender mail of the trial is wrong, please check.",
"TrialEmailN_EmailTemplateNotFound": "The email template in the standard scenario of this trial cannot be found.",
"TrialEmailN_EnrollmentConfirmation": "[Enrollment Confirmation Report] About {0} item {1}Subject",
"TrialEmailN_Enrollment": "The attachment is the Enrollment Confirmation Report, please check.",
"TrialEmailN_PDReport": "[PD Confirmation Report] About {0} item {1}Subject",
"TrialEmailN_SubjectDiseaseProgression": "The attachment is the PD Confirmation Report, please check.",
"TrialEmailN_SingleBlindedSet": "The configuration of the single and chronological read is incorrect (there should be no adjudicator configuration), please check!",
"TrialEmailN_SingleBlindedSequenced": "The single and chronological read, should not enter the logic here, please contact the background developers to check!",
"TrialEmailN_PDProgressEmailTask": "Send PD progress email found problem with the task data!",
"TrialEmailN_DoubleBlindedError": "The double and chronological read does not defined the adjudication rule logic, please contact the developers to check!",
"TrialEmailN_InCons": "The trial is not configured with the Enrollment Confirmation!",
"TrialEmailN_NoBaseLine": "There is no baseline visit configured with Enrollment Confirmation and IR readedso email failed to send",
"TrialEmailN_IncompBase": "The baseline reads for enrollment confirmation has not been finished for IR!",
"TrialEmailN_EmailFail": "Email failed to generate manuallyplease contact developer to verify the failure cause",
"TrialEmailN_NoReader": "No IR has finished the baseline read at present!",
"TrialEmailN_NoPDConfig": "The trial is not configured with PD Confirmation!",
"TrialEmailN_NoPDTasks": "There is no baseline visit configured with “PD Confirmation” and IR readedso email failed to send",
"TrialEmailN_PDNotFinished": "The completion status of the latest PD interview and film reading task of the current subject does not meet the sending conditions",
"TrialEmailN_PDNoImaging": "The trial is configured with review period adjudication, but the current subject' s latest visit marked 'PD' have no review period",
"TrialEmailN_PDPhaseNotFinished": "The review period status of the current subject's latest PD visit does not meet the sending conditions",
"TrialEmailN_NoRuleDefined": "The sending logic for adjudication rule is not defined! ",
"TrialEmailN_NoDoubleOrder": "The current trial is not double and chronological read, so the sending condition is not met",
"TrialEmailN_NoSendLogicDefined": "The current trial is not defined sending logic",
"TrialEmailN_BlindedSequencedReading": "The configuration of the chronological read is wrong (should be single or double reading), please check!",
"TrialEmailN_UnblindedSequencedReading": "The configuration of random read is wrong (should be single read without adjudication, or double read with adjudication for visiting ), please check!",
"TrialEmailN_InvalidTaskTypeForEmailSending": "Do not send emails for other type except visit, adjudication and global read. Please check the logic.",
"TrialEmailN_PDLogicNotDefined": "Reads for this criterion has not yet defined the PD logic, please supplement it after consultation with the developer.",
"TrialEmailN_MailboxWrong": "The configuration of the sender mailbox of the trial is wrong, please check it.",
"TrialEmailN_InvalidRecipient": "The trial does not have a valid recipient, so the message cannot be sent.",
"TrialEmailN_EmailTestMessage": "Trial mail test",
"TrialEmailN_ConfigurationCorrect": "If this email is received, the email configuration is correct.",
"TrialEmailN_InvalidSenderEmailConfig": "The sender configuration is incorrect. Please check whether the server address or authorization code is correct or not.",
// ------------------------------------------------------------Financial--------------------------------------------------------------------
//CalculateService
"Cal_VolDataErr": "Volume reward data error.",
//ExchangeRateService
"ExR_SameMthExist": "The exchange rate of the same month already existed.",
"ExR_MthPymtRate": "The exchange rate has been used in monthly payment",
//PaymentAdjustmentService
"PayAdj_DocPymtLock": "Doctor payment has confirmed lock",
//RankPriceService
"RP_TitleUsedByRev": "This title has been used by reviewer payment information",
//TrialRevenuesPriceService
"TRP_AddMeaningful": "Please add meaningful data",
// ------------------------------------------------------------ImageAndDoc--------------------------------------------------------------------
//DicomArchiveService
"DAS_NoAnonCacheData": "The cache data for anonymous config is not obtained, and the upload stops. Please contact the developer to verify.",
//ImageShareService
"ISS_NoImgToShare": "There are no images to share for the current study.",
"ISS_ResNotExists": "The request resource wasnt found.",
"ISS_SharePwdError": "The shared password is incorrect.",
"ISS_ShareExpiration": "Resource sharing expires.",
//StudyService
"Study_VisitBeforePrevError": "The current visit check time {0} cannot be earlier than the previous visit check time {1}. Please check whether the check data is correct.",
"Study_VisitAfterSubseqError": "The current visit check time {0} cannot be later than the visit check time {1} .Please check whether the check data is correct.",
"Study_UploadArchiving": "Someone is currently uploading and archiving this visit!",
"Study_VisitEndedNotAllowed": "Subject visit is over, and uploading is not allowed!",
"Study_ImgAlreadyUploaded": "Uploading is not allowed above here.The current image check has been uploaded to {1} of subject {0}",
// ------------------------------------------------------------Inspection--------------------------------------------------------------------
//FrontAuditConfigService
"FrontAudit_IdDup": "The identifier is duplicated.",
"FrontAudit_NameDup": "The name is duplicated .",
"FrontAudit_CannotDelSub": "Subclasses exist, cannot delete.",
//InspectionService
"Inspection_UserDisabled": "The current user has been disabled.",
// ------------------------------------------------------------Institution--------------------------------------------------------------------
//CROService
"CRO_DupName": "CRO with the same name already exists. Please confirm.",
"CRO_InProject": "The CRO has participated in the trial and cannot be deleted.",
//HospitalService
"Hospital_DupName": "Hospital with the same name already exists. Please confirm.",
"Hospital_SiteAdded": "The current Site has been added to another Hospital.",
"Hospital_HasDoctors": "There are already doctors registered under the hospital's account and cannot be deleted.",
//SiteService
"Site_DupName": "Site with the same name already exists. Please confirm.",
"Site_InProject": "This site has been added to the project and cannot be deleted.",
//SponsorService
"Sponsor_DupName": "Sponsor with the same name already exists. Please confirm.",
"Sponsor_InProject": "The sponsor has been added to the trial and it is not allowed to delete.",
// ------------------------------------------------------------Management--------------------------------------------------------------------
//MenuService
"Menu_ParentDupChild": "A child node with the same name already exists under the parent node.",
"Menu_ChildExist": "Child nodes already exists under this node . Delete the child nodes before deleting the node.",
//UserService
"User_UsernameExist": "The user name already exists.",
"User_PhoneDup": "A user with the same phone number already exists in this user type.",
"User_EmailDup": "A user with the same email already exists in this user type.",
"User_NewOldPwdSame": "The new password is the same as the old one.",
"User_OldPwdInvalid": "Failed to verify the old password.",
"User_LegalEmail": "Please input a legal email.",
"User_VerificationCodeError": "The verification code is wrong.",
"User_VerificationCodeExpired": "The verification code has expired.",
"User_CreateFailed": "Check the email address or contact maintainers. The email fails to be sent and the account cannot be created.",
"User_InvalidEmail": "Please enter a correct E-mail address.",
"User_EmailError": "The email adress is wrong.",
"User_InProject": "The user has participated in the trial and cannot be deleted.",
"User_Disabled": "The user has been disabled.",
//UserTypeService
"UserType_InUse": "User already exists in that user type, and it cannot be deleted.",
// ------------------------------------------------------------QC--------------------------------------------------------------------
//QCCommon
"QCCommon_CannotOperate": "CRC has submitted the image. Operation is not allowed.",
"QCCommon_NoPermission": "You are not the current recipient of the image QC. No operation authority!",
"QCCommon_CheckTimeEarly": "The current visit study time {0} cannot be earlier than the previous visit study time {1}. Please check whether the study data is correct.",
"QCCommon_CheckTimeLate": "The current visit study time {0} cannot be later than the visit study time {1} .Please check whether the study data is correct.",
//QCOperationService
"QCOperation_CheckFirst": "Please check the image first and save review questions before query.",
"QCOperation_QuestionExist": "The unclosed query of the current visit has been set to approve CRC reupload. After CRC has reuploaded image, please close the original query first and then add a new query.",
"QCOperation_QuestionCannotClose": "CRC has applied for reuploading or QC has agreed to reupload. To close the query is not allowed. Please do not close the query until the QC rejects or the CRC reuploads the image.",
"QCOperation_CloseReason": "Reason for closing:",
"QCOperation_QuestionReplied": "The QC query has been answered.",
"QCOperation_NoPermissionReply": "You do not have permission to reply to the data reconciliation conversation.",
"QCOperation_CannotClose": "The current visit status is CRC request re-upload. The query is not allowed to be closed.",
"QCOperation_Reason": "Notes:",
"QCOperation_CannotPass": "The current visit is in the return status, and the data reconciliation cannot be set.",
"QCOperation_PassAfterClose": "Please close the data reconciliation query first, and then set the data reconciliation pass.",
"QCOperation_Cannotback": "The current visit has passed the consistency check and cannot be applied for re-upload.",
"QCOperation_CRCRollback": "CRC apples for re-upload.",
"QCOperation_OtherCRC": "Other CRCs have applied for processing. Please refresh the page.",
"QCOperation_PMReject": "PM/APM rejected the data reconciliation return.",
"QCOperation_NoPermission": "You do not have operation permission.",
"QCOperation_CannotRollback": "If the current visit has not do reconciliation or has passed, setbacks are not allowed.",
"QCOperation_PMAPMConsistency": "PM/APM agrees to the data reconciliation rollback.",
"QCOperation_NoModifyAfterSubmit": "Once submitted, no modifications are allowed.",
"QCOperation_UnresolvedQCQuery": "Image query of the current visit is not closed. This operation is not allowed.",
"QCOperation_CrcNoDelete": "The CRC has been committed and cannot be deleted.",
"QCOperation_NoRecipient": "You are not the current recipient of the quality control task, no operation authority!",
"QCOperation_QCImageTaskAlreadyReleased": "The image QC of the current visit has been released by the original recipient. You can get it by 'claime'.",
"QCOperation_QCTaskNoAccess": "The image quality control task of the current visit has been claimed by other QC, so it is not allowed to claim.",
"QCOperation_QCConfigFirst": "Please configure the image QC questions before claiming any image QC work.",
"QCOperation_NoQC": "The trial configuration of image QC was not check, and the QC Task was not be claimed.",
"QCOperation_InitialAuditPassed": "The first review has passed, continue to receive can not be allowed.",
"QCOperation_NoSingleAudit": "The trial is configured with single image QC , does not meet Submmit State: Submitted or Audit State: pending QC/ in QC, not allowed to collect.Please refresh the page.",
"QCOperation_NoSameReviewer": "The secondary QC cannot be the same person as the primary QC.",
"QCOperation_NoSecondaryAudit": "The trial is configured withr double image QC , does not meet Submmit State: Submitted or Audit State: pending review/ in QC, not allowed to collect.Please refresh the page.",
"QCOperation_NoTaskAccess": "You are not the current recipient of the quality control task, no operation authority!",
"QCOperation_NoQCFunction": "The project configuration of image QC process was not check, so there is no need to cancel the task function.",
"QCOperation_NoTaskOwner": "The current visiting image QC has not been claimed by anyone, and cannot been released.",
"QCOperation_DiseaseProgressConfirmation": "Current visit required PD Confirmation. Please process the unsubmitted prior visit before submitting the current visit: {0}.",
"QCOperation_UnsubmittedVisits": "After submitting the current visit, please submit any prior visits which have not been submitted as soon as possible. ({0})",
"QCOperation_NoBaselineData": "No clinical data at baseline. Confirm to submit?",
"QCOperation_NoImageData": "Dicom/ Non-dicom image data has not been uploaded. Submission is not allowed.",
"QCOperation_ImagesSubmitted": "The image data of the current visit has been submitted by another CRC.",
"QCOperation_BatchImagesSubmitted": "The visit image data is currently submitted in batches, part of which has been submitted by other CRCs.",
"QCOperation_MissingBaselineDate": "The trial is configured with the visit start date, but the visit start date for the subject is not filled. Submittion is not allowed.",
"QCOperation_RemoveItem": "You have been removed from the trial and have no operation rights.",
"QCOperation_QCNotClosed": "The QC query has not been closed for the current visit. This operation cannot be performed.",
"QCOperation_NoQCNeeded": "The trial configuration of image QC was no. No need to set image QC as pass.",
"QCOperation_QCNotSaved": "Image QC question is not saved. This operation is not allowed.",
"QCOperation_NotChangePass": "The trial configuration of image QC process was double check, so the current image QC task cannot change from the current state to pass.",
"QCOperation_CannotChangeToPass": "The trial configuration of image QC process was double check. The current audit state is {0}, which cannot be changed to approved.",
"QCOperation_NoQCNeededNotEnd": "The trial configuration of image QC process was not check, and setting image quality control termination is not allowed.",
"QCOperation_CannotChangeToStop": "The trial configuration of image QC process was single check, and the current review state is not In Primary QC and cannot be changed to the QC termination.",
"QCOperation_CannotChangeStop": "The trial configuration of image QC process was double check, and the current review state is {0} and cannot be changed to the QC termination.",
"QCOperation_InvalidResend": "The current reupload state is not QC agree, so reuploading is not allowed.",
"QCOperation_NoResendNeeded": "No check operation, there will be no need to reupload!",
"QCOperation_InvalidAgreeResend": "The current re-upload- status is not CRC requested and the approve of reuploading cannot be set.",
"QCOperation_CannotAgreeResend": "At the current visit, there is an unclosed query that QC set to agree to reupload, CRC has not uploaded, currently is not allowed to set again.",
"QCOperation_AgreeResend": "QC agrees to re-upload.",
"QCOperation_InvalidCompleteResend": "The current reupload status is not QC approved, setting reuploading completion is not allowed.",
"QCOperation_NoImageNotAllowed": "No image is currently available. Setting reuploaded is not allowed.",
"QCOperation_CRCTransferCompleted": "CRC reuploading has been completed. ",
"QCOperation_InvalidTransferStatus": "The current query re-upload status is not the initial| CRC re-uploaded. Application for re-uploading is not allowed",
"QCOperation_CRCTransfer": "CRC requests to reupload/upload images.",
"QCOperation_CannotModifyConfirmation": "The visit has been submitted, and the enrollment confirmation state cannot be modified.",
"QCOperation_CannotModifyPDStatus": "This visit status is return back. Modification of PD Confirmation status is not allowed.",
"QCOperation_ForwardingFailed": "Failed to forward the image:",
//QCQuestionService
"QCQuestion_DuplicateIndexFailed": "Operation failed because the serial number is repeated.",
"QCQuestion_HasChildQuestion": "The current task has a sub-question. Deletion failed.",
//TrialQCQuestionService
"TrialQCQuestion_TemplateConfirmed": "Image QC question template has been confirmed. No operation is allowed.",
"TrialQCQuestion_DuplicateIndexFailed": "Operation failed because the serial number is repeated.",
"TrialQCQuestion_DeleteChildFirst": "Before deleting the parent question, delete the child question that references the parent question.",
"TrialQCQuestion_ReferencedByQCProcess": "This review question has been cited by the image QC. Deletion is not allowed.",
// ------------------------------------------------------------QC--------------------------------------------------------------------
// ------------------------------------------------------------SiteSurvey--------------------------------------------------------------------
//TrialSiteEquipmentSurveyService
"TrialSiteEquipment_Locked": "Locked and operation is not allowed.",
//TrialSiteSurveyService
"TrialSiteSurvey_InvalidEmail": "Please enter the correct email address.",
"TrialSiteSurvey_WrongVerificationCode": "The verification code is incorrect.",
"TrialSiteSurvey_ExpiredVerificationCode": "The verification code has expired.",
"TrialSiteSurvey_NoRecordToUpdate": "The site does not have a site survey record for the transferor , so it is not allowed to choose to update.",
"TrialSiteSurvey_RecordUnderReview": "Your site survey record is in review and cannot be updated. If you need to update, please do so after rejection.",
"TrialSiteSurvey_LockedByCurrentUser": "In the current site, the submitted survey record has been locked. Updation of other people's email survey records is not allowed.",
"TrialSiteSurvey_LockedByOtherUsers": "The submitted survey record of the current site has been locked. Currently, the survey record submitted by other personnel is not locked. Updation of the survey submitted before is not allowed.",
"TrialSiteSurvey_UnlockedRecordsExist": "The current site has unlocked survey records. Locked survey records cannot be updated.",
"TrialSiteSurvey_NonLatestLockedRecord": "The site survey corresponding to the mailbox {0} is not the latest. Updation is not allowed",
"TrialSiteSurvey_AlreadyFilledByOtherUsers": "There are already survey filled out by other users under this site. You are not allowed to fill them out",
"TrialSiteSurvey_Locked": "The site survey has been locked, and no operation is allowed.",
"TrialSiteSurvey_IRCNotification": "[from Extensive Imaging IRC] A reminder about the site survey approval.",
"TrialSiteSurvey_CancelUnsubmittedRecord": "Only unsubmitted records are allowed to be repealed.",
"TrialSiteSurvey_NoAdminAcces": "The operation is not allowed by the administrator.",
"TrialSiteSurvey_FailedToGenerateAccountId": "If no value is obtained for the generated account Id. Please check.",
"TrialSiteSurvey_IRCInvitation": "[from Extensive Imaging IRC][{0}] Invitation letter",
"TrialSiteSurvey_IRCInvitationContent": "Hello, as the IRC supplier of experiment plan No. {0} trial, Extensive Imaging sincerely invites you to participate in the IRC related work of this project. Your guidance and suggestions are welcome.",
"TrialSiteSurvey_ViewAndConfirm": "Check and confirm",
//TrialSiteUserSurveyService
"TrialSiteUser_Locked": "Locked and not allowed to operate.",
"TrialSiteUser_InconsistentInfo": "The corresponding user of this email address is {0}, and the phone number is {1}. Please modify the inputted information and make it consistent with that already in the system, and then save.",
"TrialSiteUser_NoTestUserForFormal": "Formal and training triala are not allowed to add test users.",
"TrialSiteUser_NoFormalUserForTest": "It is the test project that regular users are not allowed in.",
// ------------------------------------------------------------Stat--------------------------------------------------------------------
// ------------------------------------------------------------TrialSiteUser--------------------------------------------------------------------
//TrialConfigService
"TrialConfig_JudgeTaskFail": "There are adjudication questions that the conditions for generating adjudication review read are not configured. Operation failed!",
"TrialConfig_StdConfigMissing": "Questions are not configured under the current criterion.",
"TrialConfig_AddEvalReq": "Selected additional assessment, must check additional assessment type",
"TrialConfig_SignTemplateMissing": "This operation requires electronic signature confirmation, but the signature template for this scenario is not found in the system.",
"TrialConfig_ProjectEnded": "The trial has ended or stopped. Configuration changes are not allowed.",
"TrialConfig_NoImageAuditQuestion": "No image QC question is currently added. Please add the image QC questions first, and then confirm.",
"TrialConfig_DuplicateAuditQuestionId": "Image QC question display number cannot be repeated.",
"TrialConfig_InvalidParentQuestionId": "Make sure that the display sequence number of the parent question is smaller than that of the child.",
"TrialConfig_AuditQuestionConfirmed": "The image QC questions have been confirmed by other personnel. Cofirmation again is not allowed. ",
"TrialConfig_ProjectNotInitialized": "The current trial status is not initialized. This operation is not allowed.",
"TrialConfig_UnconfirmedConfiguration": "This trials project configuration, & visit management have not been finished, and its status cannot be changed to “Ongoing”.",
"TrialConfig_UnconfirmedUNACKD": "This trials project configuration, & visit management have not been all confirmed, and its status cannot be changed",
"TrialConfig_ProjectNotStarted": "This trial status is not “Ongoing”, and cannot be set to Stoped or Completed.",
//TrialExternalUserService
"TrialExternalUser_Inconsistency": "The corresponding user of this email address is {0}, and the phone number is {1}. Please modify the inputted information and make it consistent with that already in the system, and then save.",
"TrialExternalUser_EmailTypeDuplicate": "Please confirm that the system already has an account with the same email address and user type as the one entered in the list.",
"TrialExternalUser_TestUserNotAllowed": "Formal and training trials are not allowed to add test users.",
"TrialExternalUser_FormalUserNotAllowed": "It is a training trial that regular users are not allowed in.",
"TrialExternalUser_NotEditable": "Staff information cannot be edited. Please delete it and add it again.",
"TrialExternalUser_CannotDelete": "The current user has participated in the trial and cannot be deleted.",
"TrialExternalUser_IRCInvitation": "Hello, as the IRC supplier of experiment plan No. {0} trial, Extensive Imaging sincerely invites you to participate in the IRC related work of this project. Your guidance and suggestions are welcome.",
"TrialExternalUser_ViewAndConfirm": "Check and confirm",
"TrialExternalUser_InvitationExpired": "The invitation time has expired. You can only confirm it after you are invited again.",
"TrialExternalUser_AccountInfo": "[from Extensive Imaging IRC][{0}] account information",
"TrialExternalUser_Welcome": "Hello, welcome to participate in the relevant work of trial scheme No. {0}IRC of the project. This trial adopts electronic workflow. The system and your account information are as follows:",
"TrialExternalUser_ProjectNumber": "Trial ID: {0}",
"TrialExternalUser_ExperimentPlanNumber": "Protocol ID: {0}",
"TrialExternalUser_ExperimentName": "Study Name: {0}",
"TrialExternalUser_Username": "User name: {0}",
"TrialExternalUser_Password": "Password: {0}Please modify it after login: ***You already have your account. If you forget your password, please find it by email",
"TrialExternalUser_Role": "User role: {0}",
"TrialExternalUser_LoginUrl": "System login address: {0} ",
"TrialExternalUser_ReinvitationRequired": "The invitation time has expired. You can only confirm it after you are invited again.",
"TrialExternalUser_UserIdStorageProblem": "There is a problem with the system user Id storage of the survey table. ",
"TrialExternalUser_IRCAccountInfo": "[from Extensive Imaging IRC][{0}] account information",
//TrialMaintenanceService
"TrialMaint_PersonnelJoined": "Participant has participated in site maintenance",
//TrialService
"Trial_PMApmPermission": "Only PM/APM has the operation permission!",
"Trial_TestUserCreateOnlyNonFormal": "Test users can only create informal projects",
"Trial_DuplicateProjectNumber": "The same project ID already exists.",
"Trial_InvalidProjectStatus": "Operations are allowed only when the project state is: initializing or ongoing.",
"Trial_CannotDeleteProject": "Deleting project data is not allowed in the current running environment.",
//TrialSiteService
"TrialSite_ParticipantJoined": "The subjects has been added to this site, and couldn't be disable.",
"TrialSite_CodeDuplicate": "Code is not allowed to be repeated",
"TrialSite_CannotDeleteAssociatedCRC": "The site has been associated with CRC, and couldn't be deleted.",
"TrialSite_CannotDeleteAssociatedSubject": "The subjects has been added, and couldn't be deleted.",
"TrialSite_CannotDeleteUploadedData": "The site has been uploaded survey, and couldn't be deleted.",
// ------------------------------------------------------------Visit--------------------------------------------------------------------
//SubjectService
"Subject_NoConfirmedPlan": "The visit plan of the trial is not confirmed. Please contact PM to confirm the visit plan before adding subjects.",
"Subject_DuplicateSubjectNum": "Subjects with the relevant subject ID already exists.",
"Subject_UploadedVisitNoDelete": "The subject has visit that has uploaded the image. Deletion is not allowed.",
//SubjectVisitService
"Visit_DuplicateVisitNo": "The subject's visit schedule already includes a visit with the same visit ID.",
"Visit_LastVisitNoChange": "The subject has already had a visit set as the last, and the current visit cannot be set as the last visit.",
"Visit_DuplicateVisitName": "The subject's visit schedule already includes a visit with the same visit name.",
"Visit_NoExtraVisitAfterLast": "Unplanned visits cannot be added after the last assessment is set.",
"Visit_FinishedTasksNoAdd": "The subject has reads completed in follow-up visit ( chronological read ) , which is not allowed to be added here. If necessary, please return.",
"Visit_NoPDStatusChangeAfterSubmission": "The PD Confirmation status cannot be modified after the current visit image is submitted.",
"Visit_UploadedNoLost": "The current visit has already uploaded images and cannot be set as visit lost to follow-up.",
"Visit_UploadedNoDelete": "The current visit has already uploaded images and deletion is not allowed.",
"Visit_PlanVisitNoDelete": "Planned visits are not allowed to be deleted.",
"Visit_PreviousVisitNoDelete": "The current visit has been set to the previous visit of another visit and cannot be deleted.",
//VisitPlanService
"VisitPlan_OnlyInitOrOngoing": "Can be operated only when the trial state is: Initialized or ongoing.",
"VisitPlan_LargerVisitNumLargerInterval": "In the visit plan, the interval between visits with a large number should also be larger than that of a visit with a smaller number.",
"VisitPlan_LargerPlanNumLargerInterval": "In the visit plan, the planned visit with a large number should also have a larger interval than the planned visit with a smaller event number.",
"VisitPlan_ExistNameOrNumTemplate": "A plan visit template with visit name or visit ID of trial already exists in the visit plan.",
"VisitPlan_ExistBaseline": "A baseline already exists in the visit plan.",
"VisitPlan_ExistBaselineImgNoModify": "The subjects baseline image data has been uploaded, so modification of baseline visits is not allowed.",
"VisitPlan_OnlyInitOrOngoingModifyConfirm": "Modification confirmation is allowed only when the trial is initialized or ongoing.",
"VisitPlan_NoBaselineNotConfirm": "No baseline, no confirmation allowed.",
"VisitPlan_ConfigNotConfirmNotConfirm": "If the trial configuration is not confirmed, the visit plan cannot be confirmed.",
"VisitPlan_BaselineNotMinDayNotConfirm": "Baseline's VisitDay is not minimal. Confirmation is not allowed.",
"VisitPlan_CheckExport": "Study export _{0}.xlsx",
"VisitPlan_Assigned": "The visit plan has been assigned to the subjects and executed.",
// ------------------------------------------------------------WorkLoad--------------------------------------------------------------------
//DoctorWorkloadService
"DoctorWorkload_AssignType": "A task has been assigned and does not allow you to reduce the reading type.",
"DoctorWorkload_Unique": "This type of data can only have one",
"DoctorWorkload_FeeSettled": "Expenses have been settled and workload cannot be modified.",
//EnrollService
"Enroll_NotFound": "Cannot find trial {0}",
"Enroll_EmailFormat": "The {0} mailbox format is faulty.",
"Enroll_CannotRollback": "Reviewers with workload cannot go back",
// ------------------------------------------------------------Triggers--------------------------------------------------------------------
//AddlTrialUserTrigger
"AddlTrialUser_NoTestUser": "Formal and training trials are not allowed to be added test users.",
"AddlTrialUser_NoFormalUser": "It is a training trial that regular users are not allowed in.",
//SubjectStateTrigger
"SubjectState_CannotSetCurrentAsLastVisit": "The subject has already had a visit set as the last, and the current visit cannot be set as the last.",
"SubjectState_CannotSetAsLastVisitWithImage": "The image of the subject's visit after the current visit has been uploaded, and the current visit is not allowed to be set as the last visit.",
//SubjectVisitFinalVisitTrigger
"SubjectVisit_CannotSetAsLastVisit": "The subject's follow-up visits has uploaded images or submitted , and the current visit is not allowed to be set as the last visit.",
// ------------------------------------------------------------BusinessFilter--------------------------------------------------------------------
//LimitUserRequestAuthorization
"LimitUser_AuthTokenMissing": "User token was not retrieved from Header/URL, please contact developer",
"LimitUser_AccountLoggedInElsewhere": "User token was not retrieved from Header/URL, please contact developer",
//ModelActionFilter
"ModelAction_InvalidAPIParameter": "Invalid parameters provided for the API.",
//ProjectExceptionFilter
"ProjectException_ConcurrentUpdateNotAllowed": "Concurrent update, operation not allowed at this time.",
"Project_ExceptionContactDeveloper": "Program exception, please contact developer.",
//TrialResourceFilter
"TrialResource_NoAccessPermission": "Sorry, your account does not have operation permissions.",
"TrialResource_ReferTrialIdFailed": "Regular expression failed to fetch trialId from request Refer, please contact developer to check",
"TrialResource_InterceptedProjectStatusRule": "This request was blocked by configured rules: only operations allowed when project status is in progress, please contact developer if this logic is incorrect and needs to be modified",
"TrialResource_MissingProjectNumber": "Project number not passed in the API parameters, please verify.",
//UnifiedApiResultFilter
"UnifiedAPI_ProgramError": "Program error, please contact developer.",
// ------------------------------------------------------------Helper--------------------------------------------------------------------
//FileStoreHelper
"FileStore_TemplateFileNotFound": "Database did not find the corresponding data template file for FileStoreHelper, please contact system maintenance personnel.",
"FileStore_TemplateFileStoragePathInvalid": "File doesnt exist. Please contact the system administrator!",
//SendEmailHelper
"SendEmail_SendFail": "Failed to send email in SendEmailHelper. Your operation was unsuccessful, please check your email or contact maintenance personnel.",
"SendEmail_NoRecipient": "No recipient in SendEmailHelper.",
// ------------------------------------------------------------IRaCIS.Core.Domain--------------------------------------------------------------------
//Trial
"Trial_number": "Subject ID is composed of 5 digits. The first 2 are the Site ID, and the following 3 are the order number. Please ensure it is identical to the ID from the EDC system. ",
// ------------------------------------------------------------IRaCIS.Core.Infrastructure--------------------------------------------------------------------
//ResponseOutput
"RO_BizObjNotExistsOrParamIncorrect": "The business object{0} does not exist in the database, or was deleted by someone else, or an incorrect parameter query caused",
"RO_ExpectChangeButNoEffect": "Expect a change, but the database data has not changed",
"RO_SaveFailed": "Saved failed"
}
@@ -1,2 +1,593 @@
{
"test{0}{1}": "中文本地化{0}{1}",
"RequiredAttribute": "{0} 字段是必须的",
// ------------------------------------------------------------_ServiceExtensions--------------------------------------------------------------------
//ApiResponseHandler
"ApiResponse_NoAccess": "您无权访问该接口",
"ApiResponse_Permission": "您的权限不允许进行该操作",
// ------------------------------------------------------------Controllers--------------------------------------------------------------------
//FinancialChangeController
"Financial_ChargeSettled": "费用已经结算,无法重置工作量",
"Financial_InvalidParameter": "无效的参数。",
//UploadDownLoadController
"UploadDownLoad_UnsupportedMedia": "不支持的MediaType",
"UploadDownLoad_ArchiveInProgress": "当前已有人正在上传和归档该检查!",
"UploadDownLoad_InvalidData": "请保证上传数据符合模板文件中的样式,且存在有效数据。",
"UploadDownLoad_RequestError": "请求异常,请重试!",
"UploadDownLoad_SupportedFormats": "支持.xlsx、.xls、.csv格式的文件上传。",
// ------------------------------------------------------------_MediatR--------------------------------------------------------------------
//ConsistencyVerificationRequest
"ConsistencyVerification_Tech": "检查技术",
"ConsistencyVerification_Time": "时间格式不对",
//ConsistencyVerificationHandler
"ConsistencyVerification_Img": "您好,根据本系统自动识别,该受试者当前访视在IRC系统中已提交的影像检查情况如下:",
"ConsistencyVerification_Of": "的",
"ConsistencyVerification_ImgC": "影像检查",
"ConsistencyVerification_EDCA": "核对EDC数据,完全一致, 审核通过",
"ConsistencyVerification_EDCB": "核对EDC数据,完全一致",
"ConsistencyVerification_Auto": "自动核查通过",
"ConsistencyVerification_Prob": "存在问题如下:",
"ConsistencyVerification_EdcL": "影像检查(EDC 缺少)",
"ConsistencyVerification_IrcL": "影像检查(IRC 缺少)",
"ConsistencyVerification_Desc": "说明:为高效解决/处理以上全部质疑问题,麻烦您准确核实实际影像检查情况。请注意影像日期与实际检查的日期可能会不一致,部分检查(如PET -CT)可能同时存在多种模态影像。准确核实后,请回复该访视正确的影像检查情况。",
"ConsistencyVerification_Conf": "根据导入的一致性核查数据,请确认本访视以下不一致检查项信息:",
"ConsistencyVerification_Edc": "EDC 缺少:",
"ConsistencyVerification_IrcLi": "IRC 缺少:",
// ------------------------------------------------------------Reading--------------------------------------------------------------------
//ClinicalDataSetService
"ClinicalDataSet_Apply": "当前临床数据需要配置一个检查日期才能应用",
"ClinicalDataSet_DupTypeFail": "存在同类型的临床数据,操作失败",
//ClinicalQuestionService
"ClinicalQuestion_Repeat": "存在相同的问题名称!",
//ReadingClinicalDataService
"ReadingClinicalData_DupTypeFail": "存在同类型的临床数据,操作失败",
"ReadingClinicalData_Unchecked": "当前临床数据状态不是已核查状态,不允许签名!",
//ReadingGlobalTaskService
"ReadingGlobal_NotGlobal": "系统调用错误,当前任务不是全局阅片任务。",
//ReadingImageTaskService
"ReadingImage_NotVisit": "系统调用错误,当前任务不是访视任务。",
"ReadingImage_CantSplit": "当前任务是基线任务,不能执行分裂病灶的操作。",
"ReadingImage_BeSigned": "当前任务已经签名,请勿重复提交。",
"ReadingImage_Beinvalid": "当前任务已失效,不能执行阅片。",
"ReadingImage_PresenceReview": "当前受试者存在重阅申请还未处理,不允许操作",
"ReadingImage_NotaTask": "合并的病灶并非同一个访视任务",
"ReadingImage_DeleteError": "当前病灶分裂出其他病灶或者其他病灶合并到了当前病灶,删除失败。",
"ReadingImage_Idnotcorrespond": "病灶标记添加失败,影像的Instance ID和Series ID不对应。",
"ReadingImage_IsLymphNotbigger": "当前访视该淋巴结非靶病灶的短径小于上一访视的值,不能设置为显著增大。",
"ReadingImage_NotLymphNotbigger": "当前访视该非淋巴结非靶病灶的长径小于上一访视的值,不能设置为显著增大。",
"ReadingImage_Twice": "系统调用错误,提交的问题及答案重复。",
"ReadingImage_MaxQuestion": "按照《独立影像评估章程》的相关规则,当前{0}的病灶数量不能超过{1}个。",
"ReadingImage_Maxlesion": "按照《独立影像评估章程》的相关规则,同一器官的靶病灶数量不能超过{0}个,请确认",
"ReadingImage_Maximum": "{0}的重复次数限制为{1},目前已重复{2}次。",
"ReadingImage_PCWGMaximum": "按照《独立影像评估章程》的相关规则,同一部位的基线病灶只需录入{0}次,请确认。",
"ReadingImage_NotNewFocus": "转换后的任务不应该存在新病灶",
"ReadingImage_RequiredQuestion": "提交前,请完成{0}",
"ReadingImage_ClinicalRead": "临床数据未阅读,请确认!",
"ReadingImage_IDMust": "系统调用失败,当没有任务ID的时候,标准ID必传。",
"ReadingImage_TaskFinish": "当前受试者所有阅片任务已完成,请知悉。",
"ReadingImage_NeedRest": "您已连续阅片{0}个小时,请休息{1}分钟后,再继续阅片。",
//ReadingJudgeTaskService
"ReadingJudge_SouceIdNull": "系统调用失败,当前裁判的全局任务的SouceId为null。",
//ReadingOncologyTaskService
"ReadingOncology_TaskError": "系统调用错误,当前任务不是肿瘤学任务。",
"ReadingOncology_Abnormal": "系统调用异常,裁判结果为null。",
//ReadingCalculate
"ReadingCalculate_Abnormal": "PCWG3标准配置错误,数据验证失败。",
"ReadingCalculate_questionable": "病灶存在以下问题:",
"ReadingCalculate_NoMarker": "病灶{0}缺少标记",
"ReadingCalculate_StatusIsEmpty": "病灶{0}状态为空",
"ReadingCalculate_NoMarkerEmpty": "病灶{0}未做标记,且状态为空",
"ReadingCalculate_NoDeveloped": "当前标准自动计算未完成开发,请知悉。",
//ReadingMedicalReviewService
"MedicalReview_invalid": "该医学审核任务已失效,操作失败。",
"MedicalReview_SaveQuestion": "无法执行当前操作,请先保存医学审核问题。",
"MedicalReview_NeedSave": "无法执行当前操作,请先保存医学审核问题和结论。",
"MedicalReview_NotClosed": "无法执行当前操作,当前医学质询对话未关闭。",
"MedicalReview_Finish": "当前医学审核任务为最后一个任务。",
//ReadingMedicineQuestionService
"ReadingMed_QNumDup": "当前问题序号存在重复",
"ReadingMed_HasSubQ": "此问题存在子问题,请先删除子问题",
"ReadingMed_NoMedQ": "当前未添加医学审核问题。请先添加医学审核问题,再进行确认。",
"ReadingMed_MedQNumDup": "影像医学审核问题显示序号不能重复。",
"ReadingMed_ParentNumSmall": "父问题的显示序号要比子问题的显示序号小,请确认。",
"ReadingMed_VisitQNotConfig": "当前标准未配置访视医学审核问题。",
"ReadingMed_GlobalQNotConfig": "当前标准启用了全局阅片,但未配置全局医学审核问题",
"ReadingMed_ArbitrateQNotConfig": "当前标准启用了仲裁阅片,但未配置仲裁医学审核问题",
"ReadingMed_TumorQNotConfig": "当前标准启用了肿瘤学阅片,但未配置肿瘤学医学审核问题",
//UserService
"User_CheckNameOrPw": "请检查用户名或者密码。",
//Repository
"Repository_UpdateError": "修改的数据在数据库不存在。",
"Repository_DeleteError": "删除的数据在数据库不存在。",
//OrganInfoService
"OrganInfo_DuplicateData": "存在相同的数据,操作失败",
//ReadingCriterionService
"ReadingCriterion_Referenced": "当前标准被引用过了,不可以删除",
"ReadingCriterion_InUse": "此标准在项目里面已被使用,操作失败",
"ReadingCriterion_ArbitratorWithoutJudgment": "无裁判问题却有仲裁对象,操作失败",
//ReadingQuestionService
"ReadingQuestion_IdDup": "问题编号重复",
"ReadingQuestion_ChildrenExist": "此问题存在子问题,请先删除子问题",
"ReadingQuestion_GroupReferenced": "此分组已被引用,请先删除被引用的问题",
"ReadingQuestion_JudgmentSet": "当前问题已经设置了裁判标准了,修改失败",
"ReadingQuestion_ExcludeWithDependency": "显示依赖父问题和必填依赖的问题为同一个,但答案互斥,操作失败",
"ReadingQuestion_CircularDependency": "计算依赖循环了!",
//ReadingPeriodSetService
"ReadingPeriodSet_NameDup": "阅片期名称重复,操作失败",
"ReadingPeriodSet_Global": "阅片期名称不能为Global",
"ReadingPeriodSet_AlreadyAdded": "{0}已经添加过阅片期,无法设置生效",
"ReadingPeriodSet_TaskCompletedCannotRevoke": "当前标准阅片已生成任务并且阅片完成,撤销失败。",
"ReadingPeriodSet_LastVisit": "末次访视",
//ReadModuleService
"ReadModule_AlreadyAdded": "当前访视已经添加过阅片期",
"ReadModule_AddGlobalFirst": "请先添加全局阅片",
"ReadModule_VisitNotFound": "未找到符合要求的访视",
"ReadModule_SignedDataCannotDelete": "临床资料已签名,不允许删除",
"ReadModule_TumorExists": "当前访视存在肿瘤学阅片,请先删除肿瘤学阅片",
"ReadModule_TaskGenerated": "当前阅片已生成任务,操作失败。",
//UserWLTemplateService
"UserWLTS_MaxTemplate": "同一个用户最多只能添加10个模板",
"UserWLTS_NameRepeated": "模板名称存在重复",
"UserWLTS_ContentRepeated": "模板内容存在重复",
// ------------------------------------------------------------Allocation--------------------------------------------------------------------
//TaskAllocationRuleService
"TaskAllocation_DoctorIdNotFound": "错误,未在入组表中找到该医生的账号Id",
"TaskAllocation_DoctorConfigExists": "已有该医生配置,不允许继续增加",
"TaskAllocation_TaskAssigned": "已分配任务给该医生,不允许删除",
//TaskConsistentRuleService
"TaskConsistent_ConsistencyConfigExists": "请配置一致性分析的医生",
"TaskConsistent_TaskGenerated": "已有该项目配置,不允许继续增加",
"TaskConsistent_MedicalAuditTaskExists": "该标准已有Subject 生成了任务,不允许修改配置",
"TaskConsistent_SignedTaskCannotBeInvalidated": "该标准已产生一致性分析任务,不允许删除",
//TaskMedicalReviewRuleService
"TaskMedicalRule_TaskAlreadyAssigned": "已有该医生配置,不允许继续增加",
"TaskMedicalRule_TaskStarted": "已产生医学审核任务",
//TaskMedicalReviewService
"TaskMedical_DirtyData": "已签名的不允许设置为失效",
"TaskMedical_SubjectInOtherArm": "当前有任务已分配给其他人,不允许分配,请刷新列表",
//VisitTaskService
"VisitTask_VisitTask_TaskAlreadyApplied": "该项目还未确认任何一个阅片标准",
"VisitTask_DoctorConfigNotFound": "当前医生已开始做该Subject 该标准的任务,不允许取消分配",
"VisitTask_BackendDataError": "其中一个任务已分配给该医生,不允许分配",
"VisitTask_DirtyData": "出现脏数据 任务来源字段没有值",
"VisitTask_MissingTaskSource": "该受试者有访视进入了退回流程,还未经过一致性核查通过,不允许分配",
"VisitTask_InconsistentSubjectStatus": "有Subject 在其他Arm组已有该医生,不允许在新的组添加该医生",
"VisitTask_DuplicateDoctorInArm": "有Subject 已有该Arm组的医生,不允许继续分配,请刷新页面,确认页面数据是否过期",
"VisitTask_DoctorAlreadyInArm": "有Subject任务已应用,不允许取消分配",
"VisitTask_TaskAlreadyApplied": "在配置表中未找到配置的医生,无法应用绑定,请核对数据",
"VisitTask_DoctorConfiguration": "后台数据有错误",
"VisitTask_BackendData": "未阅片完成,或者未生效的任务不允许申请重阅",
"VisitTask_UnreadTask": "重阅已申请,或者重阅已同意状态下不允许申请重阅",
"VisitTask_NoPMRecheck": "附加评估标准任务不允许PM 申请影像重阅",
"VisitTask_Reapply": "PM 不允许对一致性分析任务进行申请重阅",
"VisitTask_ConsistencyAnalysis": "PM 仅仅允许对访视类型的任务申请重阅",
"VisitTask_VisitTypeRestriction": "当前为有序阅片,该受试者已有访视已申请重阅还未处理(项目组申请),暂不能继续申请重阅",
"VisitTask_SequentialReading": "当前为有序阅片,该受试者已有访视已申请重阅还未处理,暂不能继续申请重阅",
"VisitTask_ImageProblem": "当前为有序阅片,影像存在问题,项目组已申请回退,暂不能申请重阅",
"VisitTask_LastReading": "有序阅片,只允许申请该受试者阅片人最后一次完成全局任务重阅",
"VisitTask_LastOncologistRecheck": "有序阅片,只允许申请该受试者阅片人最后一次完成肿瘤学任务重阅",
"VisitTask_LastAdjudicatorRecheck": "有序阅片,只允许申请该受试者阅片人最后一次完成裁判的任务重阅",
"VisitTask_IRGlobalRecheck": "无序阅片,仅仅允许IR 申请 全局和访视类型类别的任务进行重阅",
"VisitTask_IRReapply": "无序阅片,仅仅允许IR申请全局和访视类型类别的任务进行重阅",
"VisitTask_InvalidReapplyStatus": "当前重阅任务状态不为已申请状态,不允许进行处理,请刷新页面",
"VisitTask_ReapplyStatusConflict": "当前申请重阅任务的状态,已被其他任务重阅已影响,不允许对该状态下的任务进行重阅同意与否操作",
"VisitTask_ReReadTaskNotApplied": "仅允许同意访视类型的任务重阅",
"VisitTask_ReReadTaskAlreadyAffected": "不符合 PM申请 SPM / CPM审批 | IR申请 PM 审批 ",
"VisitTask_TaskTypeNotApproved": "当前重阅任务状态不为已申请状态,不允许进行处理,请刷新页面",
"VisitTask_NoImageReturn": "附加评估标准任务不允许在此入口影像退回",
"VisitTask_NonEffectiveTaskCannotBeReturned": "仅仅允许针对生效、未完成的访视任务进行退回操作,请刷新页面数据",
"VisitTask_NoFurtherReturn": "当前访视已回退到影像上传,不允许继续回退!",
"VisitTask_ConsistencyTaskCannotBeReturned": "一致性分析的任务,不允许设置退回",
"VisitTask_PMOnlyAllowedForReturn": "仅PM 可以进行回退操作",
"VisitTask_UnsupportedTaskType": "不支持重阅的任务类型",
"VisitTask_UndefinedList": "当前用户查看列表未定义",
"VisitTask_NoConsistencyReturn": "不允许退回一致性分析任务",
"VisitTask_VisitTypeTaskAllowedForPMOnly": "仅仅访视类型的任务支持PM退回",
// ------------------------------------------------------------Common--------------------------------------------------------------------
//CommonDocumentService
"Document_CodeDuplication": "文档的Code不能够重复。",
"Document_SingleTemplate": "一个场景一个标准只允许有一个模板文档",
"Document_ TemplateRead": "读取模板内容失败, 请将文件另存为docx格式尝试!",
//DictionaryService
"Dictionary_DictionaryName": "已有{0}名称的字典",
"Dictionary_DictionaryDeletion": "当前字典在标准中被引用,不允许删除!",
"Dictionary_SubitemDeletion": "有子项数据,不允许直接删除!",
"Dictionary_ResumeReference": "当前条目已经在阅片人的简历中被引用。",
"Dictionary_ProjectReference": "当前条目已经在项目信息中被引用。",
"Dictionary_StandardReference": "当前条目已经在阅片标准中被引用。",
//ExcelExportService
"ExcelExport_UnsupportedExport": "当前标准导出还未支持",
//MailService
"Mail_EmailResetReminder": "[来自展影IRC] 关于重置邮箱的提醒",
"Mail_Dear": " 尊敬的 {0} , ",
"Mail_ResettingEmail": "您正在进行邮箱重置操作",
"Mail_IRCResettingPassword ": "[来自展影IRC] 关于重置密码的提醒",
"Mail_ResettingPassword ": "您正在进行邮箱重置密码操作",
"Mail_ImagingIRCReminder": "[来自展影IRC]的提醒",
"Mail_IRCProject": "您正在参与展影医疗IRC项目",
"Mail_ProjectParticipationReminder": "[来自展影IRC] [{0}] 关于中心调研的提醒",
"Mail_CenterResearchReminder": "您正在参与展影医疗IRC项目中心调研工作",
"Mail_AccountCreationReminder": "[来自展影IRC] 关于创建账户的提醒",
"Mail_AccountPasswordResetReminder": "[来自展影IRC] 关于重置账户密码的提醒",
"Mail_InvitationEmail": "[来自展影IRC] [{0}]邀请信",
//SystemMonitor
"SysMon_JsonConfig": "解析Json文件配置出现问题",
// ------------------------------------------------------------Doctor--------------------------------------------------------------------
//DoctorService
"Doctor_DupPhoneOrEmail": "当前的电话或电子邮件号码已经存在",
"Doctor_DupPhone": "当前的电话号码已经存在!",
"Doctor_DupEmail": "当前的邮箱已经存在!",
"Doctor_StandardDuplicateFileTypeError": "当前标准已添加过此类型文件",
"Doctor_RequiredDocumentsError": "简历及顾问协议必须上传",
// ------------------------------------------------------------Document--------------------------------------------------------------------
//SystemDocumentService
"SystemD_DuplicateFile": "系统中已存在同类型的同名文件。",
"SystemD_CannotDeleteSignedFile": "已有用户阅读该文档,并签名,不允许删除。",
//TrialDocumentService
"TrialD_DuplicateFileInProject": "该项目中已经存在同类型的同名文件。",
"TrialD_DocumentHasAlready": "已有用户阅读该文档,并签名,不允许删除。",
"TrialD_FileAlreadySigned": "该文件已经签名",
"TrialD_ObsoleteFile": "文件已废除,签署失败!",
//TrialEmailNoticeConfigService
"TrialEmailN_TaskNotSigned": "进行邮件发送前,该任务必须已签名完成并已经触发完成相应的任务生成",
"TrialEmailN_NoRecipient": "没有收件人,无法发送邮件",
"TrialEmailN_InvalidEmailConfig": "项目发件邮箱配置有误,请核实",
"TrialEmailN_EmailTemplateNotFound": "找不到该项目标准场景下邮件模板",
"TrialEmailN_EnrollmentConfirmation": "【入组确认报告】关于{0}项目{1}受试者",
"TrialEmailN_Enrollment": " 附件为入组确认报告,请查收",
"TrialEmailN_PDReport": "【疾病进展确认报告】关于{0}项目{1}受试者",
"TrialEmailN_SubjectDiseaseProgression": " 附件为疾病进展确认报告,请查收 ",
"TrialEmailN_SingleBlindedSet": "单重有序阅片配置有误(不应该有仲裁对象配置),请核查!",
"TrialEmailN_SingleBlindedSequenced": "单重有序阅片 该类型的任务不应进入此处逻辑,请联系后台开发核查!",
"TrialEmailN_PDProgressEmailTask": "发送PD 进展邮件中发现任务数据有问题!",
"TrialEmailN_DoubleBlindedError": "双重有序阅片 没有定义该仲裁规则处理逻辑,请联系业务和后台开发核查!",
"TrialEmailN_InCons": "项目未配置入组确认!",
"TrialEmailN_NoBaseLine": "不存在配置了入组确认的并且已阅的基线访视",
"TrialEmailN_IncompBase": "做入组确认的阅片人基线任务没有阅片完!",
"TrialEmailN_EmailFail": "邮件手动生成失败,请联系开发核实该场景失败原因",
"TrialEmailN_NoReader": "当前未有阅片人读完基线任务!",
"TrialEmailN_NoPDConfig": "项目未配置PD进展!",
"TrialEmailN_NoPDTasks": "不存在配置了PD进展的并且已阅的访视",
"TrialEmailN_PDNotFinished": "当前受试者最新PD访视阅片任务完成状态不符合发送条件",
"TrialEmailN_PDNoImaging": "项目配置了阅片期仲裁,但是当前受试者最新PD访视没有影像学阅片期",
"TrialEmailN_PDPhaseNotFinished": "当前受试者最新PD访视阅片期任务完成状态不符合发送条件",
"TrialEmailN_NoRuleDefined": "未定义该仲裁规则发送业务逻辑!",
"TrialEmailN_NoDoubleOrder": "当前项目配置,不满足双重有序阅片,不满足发送条件!",
"TrialEmailN_NoSendLogicDefined": "当前项目配置,未定义发送业务逻辑!",
"TrialEmailN_BlindedSequencedReading": "有序阅片配置有误(应为单重或者双重阅片),请核查!",
"TrialEmailN_UnblindedSequencedReading": "无序阅片配置有误(应为单重无仲裁对象,双重针对访视仲裁),请核查!",
"TrialEmailN_InvalidTaskTypeForEmailSending": "不应有除访视、裁判、全局其他类型的任务进行发送邮件,请核查业务逻辑",
"TrialEmailN_PDLogicNotDefined": "该标准任务还未定义PD获取逻辑,联系业务和后台开发协商后补充",
"TrialEmailN_MailboxWrong": "项目发件邮箱配置有误,请核实",
"TrialEmailN_InvalidRecipient": "项目没有有效的收件人,无法发送邮件",
"TrialEmailN_EmailTestMessage": "项目邮件测试",
"TrialEmailN_ConfigurationCorrect": " 收到此邮件,代表邮件配置正确",
"TrialEmailN_InvalidSenderEmailConfig": "发件人配置错误,请核对服务器地址或者授权码是否填写有误",
// ------------------------------------------------------------Financial--------------------------------------------------------------------
//CalculateService
"Cal_VolDataErr": "体积数据错误",
//ExchangeRateService
"ExR_SameMthExist": "同月的汇率已存在",
"ExR_MthPymtRate": "按月付款采用汇率",
//PaymentAdjustmentService
"PayAdj_DocPymtLock": "医生付款已确认锁定",
//RankPriceService
"RP_TitleUsedByRev": "此标题已被审稿人付款信息所使用",
//TrialRevenuesPriceService
"TRP_AddMeaningful": "请添加有意义的数据",
// ------------------------------------------------------------ImageAndDoc--------------------------------------------------------------------
//DicomArchiveService
"DAS_NoAnonCacheData": "未取到缓存匿名化配置数据,上传停止,请联系开发人员核实",
//ImageShareService
"ISS_NoImgToShare": "当前检查没有影像可以分享。 ",
"ISS_ResNotExists": "资源不存在。",
"ISS_SharePwdError": "分享密码错误。",
"ISS_ShareExpiration": "资源分享过期。",
//StudyService
"Study_VisitBeforePrevError": "当前访视检查时间{0}不能早于前序访视检查时间{1},请核对检查数据是否有误",
"Study_VisitAfterSubseqError": "当前访视检查时间{0}不能晚于该访视之后的检查时间{1},请核对检查数据是否有误",
"Study_UploadArchiving": "当前有人正在上传归档该检查!",
"Study_VisitEndedNotAllowed": "受试者访视结束,不允许上传!",
"Study_ImgAlreadyUploaded": "此处不可以上传。当前影像检查已经上传给受试者{0}的{1}",
// ------------------------------------------------------------Inspection--------------------------------------------------------------------
//FrontAuditConfigService
"FrontAudit_IdDup": "标识重复",
"FrontAudit_NameDup": "名称重复",
"FrontAudit_CannotDelSub": "存在子类 不能删除",
//InspectionService
"Inspection_UserDisabled": "当前用户已被禁用。",
// ------------------------------------------------------------Institution--------------------------------------------------------------------
//CROService
"CRO_DupName": "已经存在同名的CRO,请确认。",
"CRO_InProject": "该CRO已经参与项目,不能被删除。",
//HospitalService
"Hospital_DupName": "已经存在同名的医院,请确认。",
"Hospital_SiteAdded": "当前Site已经添加到其他Hospital了。",
"Hospital_HasDoctors": "该医院下已经注册有医生,不可以删除。",
//SiteService
"Site_DupName": "已经存在同名的中心,请确认。",
"Site_InProject": "该中心已经加入项目,不可以被删除。",
//SponsorService
"Sponsor_DupName": "已经存在同名的申办方,请确认。",
"Sponsor_InProject": "该申办方已经加入项目,不允许删除。",
// ------------------------------------------------------------Management--------------------------------------------------------------------
//MenuService
"Menu_ParentDupChild": "该父节点下已经存在同名的子节点。",
"Menu_ChildExist": "该节点存在子节点,请在删除子节点后,再删除该节点。",
//UserService
"User_UsernameExist": "用户名已经存在。",
"User_PhoneDup": "该用户类型中已存在具有相同的电话的用户。",
"User_EmailDup": "该用户类型中已存在具有相同邮箱的用户。",
"User_NewOldPwdSame": "新密码与旧密码相同。",
"User_OldPwdInvalid": "旧密码验证失败。",
"User_LegalEmail": "请输入合法的电子邮件。",
"User_VerificationCodeError": "验证码错误。",
"User_VerificationCodeExpired": "验证码已经过期。",
"User_CreateFailed": "请检查邮箱地址或者联系维护人员, 邮件发送失败, 未能创建账户成功。",
"User_InvalidEmail": "请输入一个正确的邮箱。",
"User_EmailError": "邮箱错误。",
"User_InProject": "该用户已经参加项目,不能够删除。",
"User_Disabled": "该用户已经被禁用。",
//UserTypeService
"UserType_InUse": "该用户类型中已存在用户,不能删除。",
// ------------------------------------------------------------QC--------------------------------------------------------------------
//QCCommon
"QCCommon_CannotOperate": "CRC已提交影像,不能进行操作。",
"QCCommon_NoPermission": "您不是该质控任务当前领取人,没有操作权限!",
"QCCommon_CheckTimeEarly": "当前访视检查时间{0}不能早于前序访视检查时间{1},请核对检查数据是否有误",
"QCCommon_CheckTimeLate": "当前访视检查时间{0}不能晚于该访视之后的检查时间{1},请核对检查数据是否有误",
//QCOperationService
"QCOperation_CheckFirst": "请先核查图像,并保存审核问题,然后再发质疑。",
"QCOperation_QuestionExist": "当前访视未关闭的质疑已设置了同意CRC重传影像。请在CRC完成影像重传后,先关闭原质疑,再添加新的质疑。",
"QCOperation_QuestionCannotClose": "CRC已申请重传或者QC同意重传,不允许关闭该质疑。请在QC拒绝重传申请或者CRC设置重传影像后,再关闭质疑。",
"QCOperation_CloseReason": "关闭原因: ",
"QCOperation_QuestionReplied": "当前QC质疑已经回复。",
"QCOperation_NoPermissionReply": "您没有权限回复一致性核查对话。",
"QCOperation_CannotClose": "当前访视处于申请重传状态, 不允许关闭质疑。",
"QCOperation_Reason": "原因:",
"QCOperation_CannotPass": "当前访视处于回退状态,不允许设置一致性核查通过",
"QCOperation_PassAfterClose": "请先关闭一致性核查质疑后,再设置一致性核查通过。",
"QCOperation_Cannotback": "当前访视已通过一致性核查,不允许申请重传",
"QCOperation_CRCRollback": "CRC申请重传",
"QCOperation_OtherCRC": "其他CRC已申请处理,请刷新页面",
"QCOperation_PMReject": "PM/APM拒绝一致性核查回退",
"QCOperation_NoPermission": "您不具备操作权限。",
"QCOperation_CannotRollback": "当前访视还未进行核查或者核查已通过,不允许设置回退。",
"QCOperation_PMAPMConsistency": "PM/APM同意一致性核查回退。",
"QCOperation_NoModifyAfterSubmit": "提交之后,不允许修改!",
"QCOperation_UnresolvedQCQuery": "当前访视有质疑未关闭,不允许该操作",
"QCOperation_CrcNoDelete": "CRC已经提交,不允许删除。",
"QCOperation_NoRecipient": "您不是该质控任务当前领取人,没有操作权限!",
"QCOperation_QCImageTaskAlreadyReleased": "当前访视的影像质控任务已被原领取人释放。您可以通过“领取”获得",
"QCOperation_QCTaskNoAccess": "当前访视的影像质控任务已被其他QC领取,不允许领取",
"QCOperation_QCConfigFirst": "请先配置影像质控审核问题,再领取影像质控任务",
"QCOperation_NoQC": "项目配置为不审,没有领取QC Task",
"QCOperation_InitialAuditPassed": "初审已通过,不能继续领取",
"QCOperation_NoSingleAudit": "项目配置为单审,不满足Submmit State:已提交 或者 Audit State:待审核/审核中, 不允许领取,请刷新界面",
"QCOperation_NoSameReviewer": "复审不能和初审是同一个人",
"QCOperation_NoSecondaryAudit": "项目配置为复审,不满足提交状态:已提交或者审核状态:待审核/QC中, 不允许领取,请刷新界面",
"QCOperation_NoTaskAccess": "您不是该质控任务当前领取人,没有操作权限!",
"QCOperation_NoQCFunction": "项目配置影像质控为不审,不需要取消任务功能",
"QCOperation_NoTaskOwner": "当前访视影像质控任务没有当前领取人,不能释放。",
"QCOperation_DiseaseProgressConfirmation": "当前访视要求进行疾病进展确认。请在提交当前访视前,先处理未提交的前序访视:{0}。",
"QCOperation_UnsubmittedVisits": "在提交当前访视后,请尽快处理尚未提交的前序访视:{0}。",
"QCOperation_NoBaselineData": "基线没有临床数据,确认提交?",
"QCOperation_NoImageData": "有访视未上传任何Dicom/非Dicom影像数据,不允许提交",
"QCOperation_ImagesSubmitted": "当前访视的影像数据,已经由其他CRC提交。",
"QCOperation_BatchImagesSubmitted": "当前批量提交访视的影像数据,其中部分已由其他CRC提交。",
"QCOperation_MissingBaselineDate": "项目配置了需要填写访视基准日期。但是受试者没有填写访视基准日期,不允许提交",
"QCOperation_RemoveItem": "您已经被移出项目,没有操作权限。",
"QCOperation_QCNotClosed": "当前访视有影像质控质疑未关闭,不能进行此操作。",
"QCOperation_NoQCNeeded": "项目配置影像质控为不审,不需要设置为影像质控通过。",
"QCOperation_QCNotSaved": "影像质控审核问题没有保存,不能进行此操作。",
"QCOperation_NotChangePass": "项目配置影像质控为单审,当前访视影像质控任务不能从当前审核状态变更到 审核通过。",
"QCOperation_CannotChangeToPass": "项目配置影像质控为双审。当前审核状态为 {0},不能变更到 审核通过。",
"QCOperation_NoQCNeededNotEnd": "项目配置影像质控为不审,不允许设置影像质控终止。",
"QCOperation_CannotChangeToStop": "项目配置影像质控为单审,当前审核状态不为 In Primary QC,不能变更到 审核终止",
"QCOperation_CannotChangeStop": "项目配置影像质控为双审,当前审核状态为 {0},不能变更到 审核终止",
"QCOperation_InvalidResend": "当前重传状态不为QC同意重传,不允许重传",
"QCOperation_NoResendNeeded": "不审操作,不会有需要重传的操作!",
"QCOperation_InvalidAgreeResend": "当前重传状态不为CRC申请重传,不允许设置同意重传",
"QCOperation_CannotAgreeResend": "当前访视,有一个未关闭的质疑 QC设置了同意重传,CRC还未完成上传,当前不允许再次设置",
"QCOperation_AgreeResend": "QC同意重传",
"QCOperation_InvalidCompleteResend": "当前重传状态不为QC同意重传,不允许设置重传完成",
"QCOperation_NoImageNotAllowed": "当前没有影像,不允许设置重传完成",
"QCOperation_CRCTransferCompleted": "CRC已重传完成",
"QCOperation_InvalidTransferStatus": "当前质疑重传状态不为初始状态|CRC重传完成状态,不允许申请重传",
"QCOperation_CRCTransfer": "CRC申请重传/上传影像",
"QCOperation_CannotModifyConfirmation": "该访视已提交,不能修改入组确认状态",
"QCOperation_CannotModifyPDStatus": "该访视为回退访视,不允许修改PD确认状态",
"QCOperation_ForwardingFailed": "转发影像失败。",
//QCQuestionService
"QCQuestion_DuplicateIndexFailed": "序号重复,操作失败",
"QCQuestion_HasChildQuestion": "当前任务存在子问题,删除失败",
//TrialQCQuestionService
"TrialQCQuestion_TemplateConfirmed": "影像质控审核问题模板已经确认,不允许操作。",
"TrialQCQuestion_DuplicateIndexFailed": "序号重复,操作失败",
"TrialQCQuestion_DeleteChildFirst": "请在删除父问题前,请先删除引用该父问题的子问题。",
"TrialQCQuestion_ReferencedByQCProcess": "该审核问题已被影像质控过程引用,不允许删除",
// ------------------------------------------------------------QC--------------------------------------------------------------------
// ------------------------------------------------------------SiteSurvey--------------------------------------------------------------------
//TrialSiteEquipmentSurveyService
"TrialSiteEquipment_Locked": "已锁定,不允许操作",
//TrialSiteSurveyService
"TrialSiteSurvey_InvalidEmail": "请输入正确的邮箱地址。",
"TrialSiteSurvey_WrongVerificationCode": "验证码错误。",
"TrialSiteSurvey_ExpiredVerificationCode": "验证码已经过期。",
"TrialSiteSurvey_NoRecordToUpdate": "该中心不存在该交接人的中心调研记录表,不允许选择更新。",
"TrialSiteSurvey_RecordUnderReview": "您的中心调研记录正在审核中,不允许进行更新操作。若需要更新,请在驳回后进行操作。",
"TrialSiteSurvey_LockedByCurrentUser": "当前中心中,您提交调研记录表已锁定,不允许更新其他人邮箱调研记录。",
"TrialSiteSurvey_LockedByOtherUsers": "当前中心,您提交的调研记录表已锁定。当前存在其他人员提交的调研记录表未锁定,不允许更新您之前提交的调研记录。",
"TrialSiteSurvey_UnlockedRecordsExist": "当前中心存在未锁定的调研记录,不允许更新已锁定的调研记录。",
"TrialSiteSurvey_NonLatestLockedRecord": "该邮箱{0}对应的调查表不是最新锁定的记录,不允许更新!",
"TrialSiteSurvey_AlreadyFilledByOtherUsers": "该中心下已经有其他用户已填写的调研表,您不被允许继续填写",
"TrialSiteSurvey_Locked": "中心调研已锁定,不允许操作。",
"TrialSiteSurvey_IRCNotification": "[来自展影IRC] [{0}] 关于中心调研审批的提醒",
"TrialSiteSurvey_CancelUnsubmittedRecord": "只允许废除未提交的记录。",
"TrialSiteSurvey_NoAdminAcces": "不允许管理员操作。",
"TrialSiteSurvey_FailedToGenerateAccountId": "生成账户Id 未取到值,请排查",
"TrialSiteSurvey_IRCInvitation": "[来自展影IRC] [{0}] 邀请信",
"TrialSiteSurvey_IRCInvitationContent": " 您好,展影医疗作为 实验方案号:{0} 项目的IRC供应商,诚邀您参加该项目IRC相关工作,欢迎您提供指导和建议,非常感谢!",
"TrialSiteSurvey_ViewAndConfirm": "查看并确认",
//TrialSiteUserSurveyService
"TrialSiteUser_Locked": "已锁定,不允许操作",
"TrialSiteUser_InconsistentInfo": "该邮件地址在系统中所对应的用户为 {0}, 电话号码是 {1}。请将所输入的信息修改为与系统一致后,再保存。",
"TrialSiteUser_NoTestUserForFormal": "正式类型 、培训类型的项目 不允许加入测试用户",
"TrialSiteUser_NoFormalUserForTest": "测试项目 不允许加入正式用户",
// ------------------------------------------------------------Stat--------------------------------------------------------------------
// ------------------------------------------------------------TrialSiteUser--------------------------------------------------------------------
//TrialConfigService
"TrialConfig_JudgeTaskFail": "有裁判问题未配置产生裁判阅片任务的条件,操作失败!",
"TrialConfig_StdConfigMissing": "当前标准下未配置问题",
"TrialConfig_AddEvalReq": "选择了附加评估,必须勾选附加评估类型",
"TrialConfig_SignTemplateMissing": "该操作需要电子签名确认,但未在系统中找到该场景的签名模板。",
"TrialConfig_ProjectEnded": "该项目已结束或停止,不允许修改配置。",
"TrialConfig_NoImageAuditQuestion": "当前未添加影像质控审核问题。请先添加影像质控审核问题,再进行确认。",
"TrialConfig_DuplicateAuditQuestionId": "影像质控审核问题显示序号不能重复。",
"TrialConfig_InvalidParentQuestionId": "父问题的显示序号要比子问题的显示序号小,请确认。",
"TrialConfig_AuditQuestionConfirmed": "影像质控审核问题已被其他人员确认,不允许再次确认。",
"TrialConfig_ProjectNotInitialized": "该项目当前状态不是初始化,不允许进行该操作。",
"TrialConfig_UnconfirmedConfiguration": "该项目的项目配置、访视管理尚未完成,无法将项目状态设为”启动”。",
"TrialConfig_UnconfirmedUNACKD": "该项目的项目配置、访视管理中,有未确认项,无法变更项目状态。",
"TrialConfig_ProjectNotStarted": "项目没有进入启动状态,不能设置为停止或完成状态",
//TrialExternalUserService
"TrialExternalUser_Inconsistency": "该邮件地址在系统中所对应的用户为 {0}, 电话号码是 {1}。请将所输入的信息修改为与系统一致后,再保存。",
"TrialExternalUser_EmailTypeDuplicate": "系统已经存在与列表中填写的邮箱和用户类型相同的账户,请确认。",
"TrialExternalUser_TestUserNotAllowed": "正式类型 、培训类型的项目 不允许加入测试用户 ",
"TrialExternalUser_FormalUserNotAllowed": "测试项目 不允许加入正式用户 ",
"TrialExternalUser_NotEditable": "人员信息不支持编辑,请删除后重新添加。",
"TrialExternalUser_CannotDelete": "当前用户已参与到项目,不允许删除",
"TrialExternalUser_IRCInvitation": " 您好,展影医疗作为 实验方案号:{0} 项目的IRC供应商,诚邀您参加该项目IRC相关工作,欢迎您提供指导和建议,非常感谢!",
"TrialExternalUser_ViewAndConfirm": "查看并确认",
"TrialExternalUser_InvitationExpired": "邀请加入时间已过期,重新被邀请后才可以进行确认操作",
"TrialExternalUser_AccountInfo": "[来自展影IRC] [{0}] 账户信息",
"TrialExternalUser_Welcome": "您好,欢迎您参加项目 实验方案号:{0}IRC相关工作。该项目采用电子化工作流,系统及您的账号信息如下:",
"TrialExternalUser_ProjectNumber": "项目编号: {0}",
"TrialExternalUser_ExperimentPlanNumber": "试验方案号: {0}",
"TrialExternalUser_ExperimentName": "试验名称: {0}",
"TrialExternalUser_Username": "用户名: {0}",
"TrialExternalUser_Password": "密码: ({0})(请在登录后进行修改) : ***(您已有账号, 若忘记密码, 请通过邮箱找回)",
"TrialExternalUser_Role": "角色: {0}",
"TrialExternalUser_LoginUrl": "系统登录地址: {0} ",
"TrialExternalUser_ReinvitationRequired": "邀请加入时间已过期,重新被邀请后才可以进行确认操作",
"TrialExternalUser_UserIdStorageProblem": "调研表系统用户Id 存储有问题",
"TrialExternalUser_IRCAccountInfo": "[来自展影IRC] [{0}] 账户信息",
//TrialMaintenanceService
"TrialMaint_PersonnelJoined": "人员已加入现场维护",
//TrialService
"Trial_PMApmPermission": "只有PM/APM拥有操作权限!",
"Trial_TestUserCreateOnlyNonFormal": "测试用户 只能创建非正式项目",
"Trial_DuplicateProjectNumber": "已经存在相同的项目编号。",
"Trial_InvalidProjectStatus": "项目状态只有处于:初始化或者进行中时,才允许操作。",
"Trial_CannotDeleteProject": "当前运行环境下,不允许删除项目数据。",
//TrialSiteService
"TrialSite_ParticipantJoined": "已有受试者加入中心,无法禁用",
"TrialSite_CodeDuplicate": "代码不能重复",
"TrialSite_CannotDeleteAssociatedCRC": "中心已经和CRC关联,不能删除",
"TrialSite_CannotDeleteAssociatedSubject": "受试者已经添加,不能删除",
"TrialSite_CannotDeleteUploadedData": "中心已经上传调研,无法删除",
// ------------------------------------------------------------Visit--------------------------------------------------------------------
//SubjectService
"Subject_NoConfirmedPlan": "项目访视计划没有确认。请联系项目经理确认项目访视计划后,再添加受试者。",
"Subject_DuplicateSubjectNum": "已存在具有相关受试者编号的受试者。",
"Subject_UploadedVisitNoDelete": "该受试者已经有访视已经上传影像,不允许删除。",
//SubjectVisitService
"Visit_DuplicateVisitNo": "该受试者的访视计划中已经包含一个具有相同访视号的访视。",
"Visit_LastVisitNoChange": "该受试者已经有访视设置为末次访视,不允许将当前访视设置为末次访视。",
"Visit_DuplicateVisitName": "该受试者的访视计划中已经包含一个具有相同访视名称的访视。",
"Visit_NoExtraVisitAfterLast": "设置末次评估后,不允许添加计划外访视。",
"Visit_FinishedTasksNoAdd": "该受试者后续访视已有任务完成阅片(有序阅片标准),不允许在此添加,如果确实需要,请回退",
"Visit_NoPDStatusChangeAfterSubmission": "当前访视影像提交后,不允许修改PD确认状态。",
"Visit_UploadedNoLost": "当前访视已经有影像上传,不允许设置为失访。",
"Visit_UploadedNoDelete": "当前访视已经有影像上传,不允许删除。",
"Visit_PlanVisitNoDelete": "计划内的访视不允许删除。",
"Visit_PreviousVisitNoDelete": "当前访视已经被设置为另一访视的上一访视,不允许删除。",
//VisitPlanService
"VisitPlan_OnlyInitOrOngoing": "只有当项目状态为:初始化或进行中时,可以操作。",
"VisitPlan_LargerVisitNumLargerInterval": "访视计划中,访视号大的访视,其访视间隔也应该比访视号小的访视大。",
"VisitPlan_LargerPlanNumLargerInterval": "访视计划中,访视号大的计划访视,其访视间隔也应该比访视号小的计划访视大。",
"VisitPlan_ExistNameOrNumTemplate": "访视计划中已经存在具有项目访视名称或者访视号的计划访视模板。",
"VisitPlan_ExistBaseline": "访视计划中已经存在基线。",
"VisitPlan_ExistBaselineImgNoModify": "有受试者的基线已经上传了影像数据,不允许修改基线访视。",
"VisitPlan_OnlyInitOrOngoingModifyConfirm": "仅仅在项目初始化或者进行中时,才允许修改确认",
"VisitPlan_NoBaselineNotConfirm": "没有基线,不允许确认",
"VisitPlan_ConfigNotConfirmNotConfirm": "项目配置未确认,不允许确认访视计划",
"VisitPlan_BaselineNotMinDayNotConfirm": "基线VisitDay 不是最小的, 不允许确认",
"VisitPlan_CheckExport": "检查导出_{0}.xlsx",
"VisitPlan_Assigned": "访问计划已分配给受试者并已执行",
// ------------------------------------------------------------WorkLoad--------------------------------------------------------------------
//DoctorWorkloadService
"DoctorWorkload_AssignType": "已分配任务,不允许减少阅片类型",
"DoctorWorkload_Unique": "此类数据唯一",
"DoctorWorkload_FeeSettled": "费用已结算,工作量无法修改",
//EnrollService
"Enroll_NotFound": "无法找到项目{0}",
"Enroll_EmailFormat": "{0}邮箱格式存在问题",
"Enroll_CannotRollback": "已有分配的审核人员不能回退",
// ------------------------------------------------------------Triggers--------------------------------------------------------------------
//AddlTrialUserTrigger
"AddlTrialUser_NoTestUser": "正式类型 、培训类型的项目 不允许加入测试用户",
"AddlTrialUser_NoFormalUser": "测试项目不允许加入正式用户",
//SubjectStateTrigger
"SubjectState_CannotSetCurrentAsLastVisit": "该受试者已经有访视被设置为末次访视,不允许将当前访视设置为末次访视。",
"SubjectState_CannotSetAsLastVisitWithImage": "该受试者当前访视后有访视的影像已上传,当前访视不允许设置为末次访视。",
//SubjectVisitFinalVisitTrigger
"SubjectVisit_CannotSetAsLastVisit": "该受试者已有后续访视已上传影像或已提交,当前访视不允许设置为末次访视。",
// ------------------------------------------------------------BusinessFilter--------------------------------------------------------------------
//LimitUserRequestAuthorization
"LimitUser_AuthTokenMissing": "当前请求未从Header/Url取到用户Token,请联系开发者",
"LimitUser_AccountLoggedInElsewhere": "您的账户在其他地方已登陆,您被迫下线。",
//ModelActionFilter
"ModelAction_InvalidAPIParameter": "提供给接口的参数无效。",
//ProjectExceptionFilter
"ProjectException_ConcurrentUpdateNotAllowed": "并发更新,当前不允许该操作",
"Project_ExceptionContactDeveloper": "程序异常,请联系开发人员。 ",
//TrialResourceFilter
"TrialResource_NoAccessPermission": "对不起,您的账户没有操作权限。",
"TrialResource_ReferTrialIdFailed": "正则取请求Refer 中trialId 失败,请联系开发人员核查",
"TrialResource_InterceptedProjectStatusRule": "本次请求被配置规则拦截:项目状态处于进行中时,才允许操作,若此处逻辑有误,请联系开发人员修改",
"TrialResource_MissingProjectNumber": "该接口参数中,没有传递项目编号,请核对。",
//UnifiedApiResultFilter
"UnifiedAPI_ProgramError": "程序错误,请联系开发人员。",
// ------------------------------------------------------------Helper--------------------------------------------------------------------
//FileStoreHelper
"FileStore_TemplateFileNotFound": "数据库没有找到对应的数据模板文件,请联系系统运维人员。",
"FileStore_TemplateFileStoragePathInvalid": "文件不存在,请联系系统管理员!",
//SendEmailHelper
"SendEmail_SendFail": "邮件发送失败,您进行的操作未能成功,请检查邮箱或联系维护人员",
"SendEmail_NoRecipient": "没有收件人",
// ------------------------------------------------------------IRaCIS.Core.Domain--------------------------------------------------------------------
//Trial
"Trial_number": "编号由5位数字组成,前2位为中心编号,后3位为顺序号,请与EDC录入的编号保持一致",
// ------------------------------------------------------------IRaCIS.Core.Infrastructure--------------------------------------------------------------------
//ResponseOutput
"RO_BizObjNotExistsOrParamIncorrect": "业务对象{0}在数据库中不存在,或被他人删除,或参数查询不正确导致",
"RO_ExpectChangeButNoEffect": "期望发生更改,但数据库数据没有更改",
"RO_SaveFailed": "保存失败"
}
@@ -33,6 +33,7 @@ namespace IRaCIS.Core.Application.ViewModel
public class TaskConsistentRuleBasic : TaskConsistentRuleAddOrEdit
{
}
public class SubjectGeneratedTask
@@ -106,7 +107,7 @@ namespace IRaCIS.Core.Application.ViewModel
public class DoctorSelfConsistentSubjectView: ConsistentCommonView
{
public string FirstGlobalVisitName { get; set; } = string.Empty;
public string? BlindSubjectCode { get; set; }
public List<VisitTaskSimpleDTO> VisitTaskList { get; set; }
@@ -182,8 +183,7 @@ namespace IRaCIS.Core.Application.ViewModel
public string TaskCode { get; set; }
[JsonIgnore]
//可以不查询
public List<VisitTaskSimpleDTO> GlobalVisitTaskList { get; set; }
@@ -287,14 +287,7 @@ namespace IRaCIS.Core.Application.ViewModel
}
public class GetConsistentRuleOut
{
public TaskConsistentRuleBasic? ConsistentRuleBasic { get; set; }
/// <summary>
/// 任务展示访视 读片任务显示是否顺序
/// </summary>
public ReadingOrder IsReadingTaskViewInOrder { get; set; } = ReadingOrder.InOrder;
}
///<summary>TaskConsistentRuleQuery 列表查询参数模型</summary>
public class TaskConsistentRuleQuery
@@ -26,13 +26,6 @@ namespace IRaCIS.Core.Application.ViewModel
public bool IsUrgent { get; set; }
public bool? IsSelfAnalysis { get; set; }
/// <summary>
/// 是否是一致性分析产生
/// </summary>
public bool IsAnalysisCreate { get; set; }
/// <summary>
/// 加急类型
/// </summary>
@@ -208,13 +201,6 @@ namespace IRaCIS.Core.Application.ViewModel
public Guid? SourceSubjectVisitId { get; set; }
public Guid? SouceReadModuleId { get; set; }
public bool IsHaveFeedBack { get; set; }
/// <summary>
/// 是否手动生成
/// </summary>
public bool IsManualGeneration { get; set; }
//public bool IsAfterConvertedTask { get; set; }
}
@@ -223,9 +209,7 @@ namespace IRaCIS.Core.Application.ViewModel
{
public bool? IsSelfAnalysis { get; set; }
public int ConsistentClinicalDataCount { get; set; } = 0;
public bool IsReReadingOrBackInfluenceAnalysis { get; set; }
public bool IsReReadingOrBackInfluenceAnalysis { get; set; }
}
@@ -270,12 +254,6 @@ namespace IRaCIS.Core.Application.ViewModel
//产生重阅的根任务Id
public Guid RootReReadingTaskId { get; set; }
/// <summary>
/// 是否是一致性分析产生
/// </summary>
public bool IsAnalysisCreate { get; set; }
public bool? IsSelfAnalysis { get; set; }
}
@@ -18,14 +18,27 @@ namespace IRaCIS.Core.Application.Service
/// 分配规则
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class TaskAllocationRuleService(
IRepository<TaskAllocationRule> _taskAllocationRuleRepository,
IRepository<User> _userRepository,
IRepository<Enroll> _enrollRepository,
IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
IRepository<SubjectCanceDoctor> _subjectCanceDoctorRepository) : BaseService, ITaskAllocationRuleService
public class TaskAllocationRuleService : BaseService, ITaskAllocationRuleService
{
private readonly IRepository<TaskAllocationRule> _taskAllocationRuleRepository;
private readonly IRepository<User> _userRepository;
private readonly IRepository<Trial> _trialRepository;
private readonly IRepository<SubjectCanceDoctor> _subjectCanceDoctorRepository;
public TaskAllocationRuleService(IRepository<TaskAllocationRule> taskAllocationRuleRepository, IRepository<User> userRepository, IRepository<Trial> trialRepository, IRepository<SubjectCanceDoctor> subjectCanceDoctorRepository)
{
_taskAllocationRuleRepository = taskAllocationRuleRepository;
_userRepository = userRepository;
_trialRepository = trialRepository;
_subjectCanceDoctorRepository = subjectCanceDoctorRepository;
}
/// <summary>
@@ -39,7 +52,7 @@ namespace IRaCIS.Core.Application.Service
var list = await _taskAllocationRuleRepository.Where(t => t.TrialId == trialId).ProjectTo<TaskAllocationRuleDTO>(_mapper.ConfigurationProvider).ToListAsync();
//所有标准都是一样 后台只返回任意一个标准的就好了
var trialTaskConfig = await _readingQuestionCriterionTrialRepository.Where(t => t.TrialId == trialId && t.IsConfirm).ProjectTo<TrialTaskConfigView>(_mapper.ConfigurationProvider).FirstNotNullAsync();
var trialTaskConfig = await _repository.Where<ReadingQuestionCriterionTrial>(t => t.TrialId == trialId && t.IsConfirm).ProjectTo<TrialTaskConfigView>(_mapper.ConfigurationProvider).FirstNotNullAsync();
return (list, trialTaskConfig);
}
@@ -55,7 +68,7 @@ namespace IRaCIS.Core.Application.Service
//冗余 存
var enrollId = _enrollRepository.Where(t => t.TrialId == addOrEditTaskAllocationRule.TrialId && t.DoctorUserId == addOrEditTaskAllocationRule.DoctorUserId).Select(t => t.Id).FirstOrDefault();
var enrollId = _repository.Where<Enroll>(t => t.TrialId == addOrEditTaskAllocationRule.TrialId && t.DoctorUserId == addOrEditTaskAllocationRule.DoctorUserId).Select(t => t.Id).FirstOrDefault();
if (enrollId == Guid.Empty)
{
@@ -19,8 +19,6 @@ using Medallion.Threading;
using IRaCIS.Core.Infrastructure.Extention;
using System;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NPOI.SS.Formula.Functions;
using IRaCIS.Core.Application.Service.Reading.Dto;
namespace IRaCIS.Core.Application.Service
{
@@ -28,22 +26,41 @@ namespace IRaCIS.Core.Application.Service
/// 一致性分析配置表
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class TaskConsistentRuleService(
IRepository<TaskConsistentRule> _taskConsistentRuleRepository,
IRepository<VisitTask> _visitTaskRepository,
IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository,
IReadingClinicalDataService _readingClinicalDataService,
IRepository<Subject> _subjectRepository,
IDistributedLockProvider _distributedLockProvider,
IRepository<Trial> _trialRepository,
IRepository<TrialSite> _trialSiteRepository,
IRepository<Enroll> _enrollRepository,
IRepository<User> _userRepository,
IRepository<TrialVirtualSiteCodeUpdate> _trialVirtualSiteCodeUpdateRepository,
IVisitTaskHelpeService _visitTaskCommonService) : BaseService, ITaskConsistentRuleService
public class TaskConsistentRuleService : BaseService, ITaskConsistentRuleService
{
private readonly IRepository<TaskConsistentRule> _taskConsistentRuleRepository;
private readonly IRepository<VisitTask> _visitTaskRepository;
private readonly IRepository<SubjectUser> _subjectUserRepository;
private readonly IRepository<Subject> _subjectRepository;
private readonly IRepository<Enroll> _enrollRepository;
private readonly IDistributedLockProvider _distributedLockProvider;
private readonly IRepository<Trial> _trialRepository;
private readonly IRepository<TrialSite> _trialSiteRepository;
private readonly IRepository<TrialVirtualSiteCodeUpdate> _trialVirtualSiteCodeUpdateRepository;
private readonly IVisitTaskHelpeService _visitTaskCommonService;
public TaskConsistentRuleService(IRepository<VisitTask> visitTaskRepository, IRepository<Enroll> enrollRepository, IRepository<TaskConsistentRule> taskConsistentRuleRepository, IRepository<SubjectUser> subjectUserRepository, IRepository<Subject> subjectRepository, IDistributedLockProvider distributedLockProvider,
IRepository<Trial> trialRepository, IRepository<TrialSite> trialSiteRepository, IRepository<TrialVirtualSiteCodeUpdate> trialVirtualSiteCodeUpdateRepository, IVisitTaskHelpeService visitTaskCommonService)
{
_taskConsistentRuleRepository = taskConsistentRuleRepository;
_visitTaskRepository = visitTaskRepository;
_subjectUserRepository = subjectUserRepository;
_subjectRepository = subjectRepository;
_enrollRepository = enrollRepository;
_distributedLockProvider = distributedLockProvider;
_trialRepository = trialRepository;
_trialSiteRepository = trialSiteRepository;
_trialVirtualSiteCodeUpdateRepository = trialVirtualSiteCodeUpdateRepository;
_visitTaskCommonService = visitTaskCommonService;
}
/// <summary>
/// 设置一致性分析任务失效
@@ -67,54 +84,40 @@ namespace IRaCIS.Core.Application.Service
/// <summary>
/// 一致性分析列表 (自身 组内 最后勾选 产生的任务)
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<IResponseOutput<PageOutput<AnalysisTaskView>>> GetAnalysisTaskList(VisitTaskQuery inQuery)
public async Task<IResponseOutput<PageOutput<AnalysisTaskView>>> GetAnalysisTaskList(VisitTaskQuery queryVisitTask )
{
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId)
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId)
.Where(t => t.IsAnalysisCreate)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
.WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.IsSelfAnalysis != null, t => t.IsSelfAnalysis == inQuery.IsSelfAnalysis)
.WhereIf(inQuery.ArmEnum != null, t => t.ArmEnum == inQuery.ArmEnum)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => /*(t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) ||*/ (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) /*&& t.IsAnalysisCreate == false*/))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => ((t.Subject.Code.Contains(inQuery.SubjectCode) || t.Subject.MedicalNo.Contains(inQuery.SubjectCode)) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime >= inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime <= inQuery.EndAllocateDate)
.WhereIf(inQuery.BeginSignTime != null, t => t.SignTime >= inQuery.BeginSignTime)
.WhereIf(inQuery.EndSignTime != null, t => t.SignTime <= inQuery.EndSignTime)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.IsSelfAnalysis != null, t => t.IsSelfAnalysis == queryVisitTask.IsSelfAnalysis)
.WhereIf(queryVisitTask.ArmEnum != null, t => t.ArmEnum == queryVisitTask.ArmEnum)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => /*(t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) ||*/ (t.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) /*&& t.IsAnalysisCreate == false*/))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.TaskName.Contains(queryVisitTask.TaskName) || t.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => ((t.Subject.Code.Contains(queryVisitTask.SubjectCode)||t.Subject.MedicalNo.Contains(queryVisitTask.SubjectCode)) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.AllocateTime >= queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.AllocateTime <= queryVisitTask.EndAllocateDate)
.WhereIf(queryVisitTask.BeginSignTime != null, t => t.SignTime >= queryVisitTask.BeginSignTime)
.WhereIf(queryVisitTask.EndSignTime != null, t => t.SignTime <= queryVisitTask.EndSignTime)
.ProjectTo<AnalysisTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
#region
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
foreach (var item in pageList.CurrentPageData)
{
item.ConsistentClinicalDataCount = (await _readingClinicalDataService.GetClinicalDataList(new GetReadingOrTaskClinicalDataListInDto()
{
SubjectId = item.SubjectId,
TrialId = item.TrialId,
SelectIsSign = false,
IsGetAllConsistencyAnalysis = false,
VisitTaskId = item.Id,
})).Count();
}
#endregion
var trialTaskConfig = _trialRepository.Where(t => t.Id == inQuery.TrialId).Select(t => new { IsHaveDoubleReadCriterion = t.TrialReadingCriterionList.Any(t => t.IsSigned && t.IsConfirm && t.ReadingType == ReadingMethod.Double), t.VitrualSiteCode }).FirstOrDefault();
var trialTaskConfig = _repository.Where<Trial>(t => t.Id == queryVisitTask.TrialId).Select(t => new { IsHaveDoubleReadCriterion=t.TrialReadingCriterionList.Any(t=>t.IsSigned && t.IsConfirm && t.ReadingType==ReadingMethod.Double), t.VitrualSiteCode }).FirstOrDefault();
return ResponseOutput.Ok(pageList, trialTaskConfig);
}
@@ -130,7 +133,7 @@ namespace IRaCIS.Core.Application.Service
{
var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.Id == inQuery.TaskConsistentRuleId);
var pagedList = await GetIQueryableDoctorSelfConsistentSubjectView(filterObj, inQuery.DoctorUserId).ToPagedListAsync(inQuery, nameof(DoctorSelfConsistentSubjectView.SubjectCode));
var pagedList = await GetIQueryableDoctorSelfConsistentSubjectView(filterObj, inQuery.DoctorUserId).ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(DoctorSelfConsistentSubjectView.SubjectCode) : inQuery.SortField, inQuery.Asc);
return pagedList;
}
@@ -150,7 +153,7 @@ namespace IRaCIS.Core.Application.Service
{
var filterObj = await _taskConsistentRuleRepository.Where(t => t.Id == inCommand.TaskConsistentRuleId).Include(t => t.TrialReadingCriterion).FirstOrDefaultAsync();
var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.Id == inCommand.TaskConsistentRuleId);
var doctorUserId = inCommand.DoctorUserId;
var trialReadingCriterionId = filterObj.TrialReadingCriterionId;
@@ -165,17 +168,19 @@ namespace IRaCIS.Core.Application.Service
throw new BusinessValidationFailedException(_localizer["TaskConsistent_NotAllowedGenerate"]);
}
if (subjectList.Count < 2 * filterObj.PlanSubjectCount)
if (subjectList.Count<2 * filterObj.PlanSubjectCount)
{
throw new BusinessValidationFailedException(_localizer["TaskConsistent_NotAllowedGenerate1"]);
}
inCommand.SubejctIdList = subjectList.Select(t => t.SubjectId).ToList().GetRandomCountList(filterObj.PlanSubjectCount);
inCommand.SubejctIdList = GetRandomSubjectIdList(subjectList.Select(t => t.SubjectId).ToList(), filterObj.PlanSubjectCount);
}
var list = await GetIQueryableDoctorSelfConsistentSubjectView(filterObj, doctorUserId, inCommand.SubejctIdList).ToListAsync();
//var (group, query) = GetIQueryableDoctorSelfConsistentRuleSubjectView(filterObj, inCommand.SubejctIdList);
//var list = query.OrderByDescending(t => t.IsHaveGeneratedTask).ToList();
var @lock = _distributedLockProvider.CreateLock($"VisitTaskCode");
@@ -208,18 +213,7 @@ namespace IRaCIS.Core.Application.Service
blindSubjectCode = filterObj.BlindTrialSiteCode + (maxCodeInt + 1).ToString($"D{filterObj.BlindSubjectNumberOfPlaces}");
}
//有序阅片
if (filterObj.TrialReadingCriterion.IsReadingTaskViewInOrder == ReadingOrder.InOrder)
{
subject.VisitTaskList = subject.VisitTaskList.Take(filterObj.PlanVisitCount).ToList();
}
else
{
//完全随机 和受试者随机,都是随机挑选访视
subject.VisitTaskList = subject.VisitTaskList.GetRandomCountList(filterObj.PlanVisitCount);
}
subject.VisitTaskList = subject.VisitTaskList.Take(filterObj.PlanVisitCount).ToList();
subject.VisitTaskList.ForEach(t =>
{
@@ -249,19 +243,7 @@ namespace IRaCIS.Core.Application.Service
TaskName = lastTask.TaskName + "_Global",
TaskBlindName = lastTask.TaskBlindName + "_Global",
TrialReadingCriterionId = trialReadingCriterionId,
VisitTaskNum = lastTask.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]
};
var afterGlobal = _visitTaskRepository.Where(t => t.SubjectId == lastTask.SubjectId && t.TrialReadingCriterionId == trialReadingCriterionId && t.TaskState == TaskState.Effect && t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum > lastTask.VisitTaskNum).ProjectTo<VisitTaskSimpleDTO>(_mapper.ConfigurationProvider).FirstOrDefault();
if (afterGlobal == null)
{
throw new BusinessValidationFailedException("联系后台排查数据,没找到后续全局");
}
else
{
existGlobal.SouceReadModuleId = afterGlobal.SouceReadModuleId;
}
}
@@ -302,7 +284,7 @@ namespace IRaCIS.Core.Application.Service
/// <param name="inQuery"></param>
/// <returns></returns>
[HttpPost]
public async Task<IResponseOutput<PageOutput<DoctorGroupConsistentSubjectView>>> GetGroupConsistentRuleSubjectList(GroupConsistentQuery inQuery)
public async Task<IResponseOutput<PageOutput<DoctorGroupConsistentSubjectView>> > GetGroupConsistentRuleSubjectList(GroupConsistentQuery inQuery)
{
var trialId = inQuery.TrialId;
@@ -312,21 +294,21 @@ namespace IRaCIS.Core.Application.Service
if (filterObj == null)
{
object tt = null;
return ResponseOutput.Ok(new PageOutput<DoctorGroupConsistentSubjectView>(), new { Rule = tt, IsAllowAutoAllocate = false });
return ResponseOutput.Ok(new PageOutput<DoctorGroupConsistentSubjectView>(), new { Rule = tt, IsAllowAutoAllocate = false }) ;
}
var query = await GetGroupConsistentQueryAsync(filterObj);
var pagedList = await query.ToPagedListAsync(inQuery, nameof(DoctorSelfConsistentSubjectView.SubjectCode));
var pagedList = await query.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(DoctorSelfConsistentSubjectView.SubjectCode) : inQuery.SortField, inQuery.Asc);
var rule = await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == false && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
var list = await GetGroupConsistentRuleMatchSubjectIdListAsync(new GroupConsistentSimpleQuery() { TrialId = inQuery.TrialId, TrialReadingCriterionId = inQuery.TrialReadingCriterionId });
var isAllowAutoAllocate = !list.Any(t => t.IsHaveGeneratedTask) && list.Count() > 2 * (rule?.PlanSubjectCount ?? 0);
var isAllowAutoAllocate = !list.Any(t => t.IsHaveGeneratedTask) && list.Count() > 2*(rule?.PlanSubjectCount??0);
return ResponseOutput.Ok(pagedList, new { Rule = rule, IsAllowAutoAllocate = isAllowAutoAllocate });
return ResponseOutput.Ok(pagedList, new {Rule=rule, IsAllowAutoAllocate = isAllowAutoAllocate });
}
@@ -344,12 +326,10 @@ namespace IRaCIS.Core.Application.Service
{
var trialId = inCommand.TrialId;
var filterObj = await _taskConsistentRuleRepository.Where(t => t.TrialId == trialId && t.TrialReadingCriterionId == inCommand.TrialReadingCriterionId && t.IsSelfAnalysis == false).Include(t => t.TrialReadingCriterion).FirstNotNullAsync();
var filterObj = await _taskConsistentRuleRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.TrialReadingCriterionId == inCommand.TrialReadingCriterionId && t.IsSelfAnalysis == false);
var trialReadingCriterionId = filterObj.TrialReadingCriterionId;
//随机分配
if (inCommand.IsAutoAllocateGenerateTask)
{
@@ -361,12 +341,12 @@ namespace IRaCIS.Core.Application.Service
throw new BusinessValidationFailedException(_localizer["TaskConsistent_NotAllowedGenerate"]);
}
if (subjectSelectList.Count < 2 * filterObj.PlanSubjectCount)
if (subjectSelectList.Count< 2 * filterObj.PlanSubjectCount)
{
throw new BusinessValidationFailedException(_localizer["TaskConsistent_NotAllowedGenerate1"]);
}
inCommand.SubejctIdList = subjectSelectList.Select(t => t.SubjectId).ToList().GetRandomCountList(filterObj.PlanSubjectCount);
inCommand.SubejctIdList = GetRandomSubjectIdList(subjectSelectList.Select(t => t.SubjectId).ToList(), filterObj.PlanSubjectCount);
}
@@ -375,9 +355,9 @@ namespace IRaCIS.Core.Application.Service
var subjectList = query.ToList();
var doctorUserIdQuery = from enroll in _enrollRepository.Where(t => t.TrialId == trialId).Where(t => t.EnrollReadingCategoryList.Where(t => t.TrialReadingCriterionId == trialReadingCriterionId).Any(c => c.ReadingCategory == ReadingCategory.Global || c.ReadingCategory == ReadingCategory.Visit))
var doctorUserIdQuery = from enroll in _repository.Where<Enroll>(t => t.TrialId == trialId).Where(t => t.EnrollReadingCategoryList.Where(t => t.TrialReadingCriterionId == trialReadingCriterionId).Any(c => c.ReadingCategory == ReadingCategory.Global || c.ReadingCategory == ReadingCategory.Visit))
.Where(t => t.EnrollReadingCriteriaList.Any(t => t.TrialReadingCriterionId == trialReadingCriterionId && t.IsJoinAnalysis == true))
join user in _userRepository.Where() on enroll.DoctorId equals user.DoctorId
join user in _repository.Where<User>() on enroll.DoctorId equals user.DoctorId
select user.Id;
var configDoctorUserIdList = await doctorUserIdQuery.ToListAsync();
@@ -436,11 +416,6 @@ namespace IRaCIS.Core.Application.Service
foreach (var needAddDoctorUserId in needAddDoctorUserIdList)
{
//if(filterObj.TrialReadingCriterion.IsReadingTaskViewInOrder== ReadingOrder.InOrder)
//{
//}
//每个医生 都生成处理的任务
foreach (var task in subject.SubjectTaskVisitList.Take(filterObj.PlanVisitCount))
{
@@ -493,9 +468,7 @@ namespace IRaCIS.Core.Application.Service
TrialReadingCriterionId = trialReadingCriterionId,
BlindSubjectCode = blindSubjectCode,
BlindTrialSiteCode = filterObj.BlindTrialSiteCode,
VisitTaskNum = lastTask.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]
BlindTrialSiteCode = filterObj.BlindTrialSiteCode
};
}
@@ -551,13 +524,10 @@ namespace IRaCIS.Core.Application.Service
var trialReadingCriterionId = filterObj.TrialReadingCriterionId;
//防止生成sql生成GETDATE() 时区导致的问题
var appDateTimeNow = DateTime.Now;
#region Subejct
Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == trialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.ReadingTaskState == ReadingTaskState.HaveSigned && u.TrialReadingCriterionId == trialReadingCriterionId &&
u.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < appDateTimeNow && (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject) && u.DoctorUserId == doctorUserId;
u.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject) && u.DoctorUserId == doctorUserId;
@@ -575,15 +545,14 @@ namespace IRaCIS.Core.Application.Service
//{
// //这里的过滤条件 不能用 where(comonTaskFilter) 会报错,奇怪的问题 只能重新写一遍
// visitTaskFilter = visitTaskFilter.And(c => c.Subject.SubjectVisitTaskList.Any(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && t.ReadingCategory == ReadingCategory.Global && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned &&
// t.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < appDateTimeNow && (t.ReReadingApplyState == ReReadingApplyState.Default || t.ReReadingApplyState == ReReadingApplyState.Reject)));
// t.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (t.ReReadingApplyState == ReReadingApplyState.Default || t.ReReadingApplyState == ReReadingApplyState.Reject)));
//}
var subjectQuery = _subjectRepository.Where(t => t.TrialId == trialId &&
t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).Count() >= filterObj.PlanVisitCount)
.WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter)
.Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).Any(t => t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum > filterObj.PlanVisitCount - 1))
.WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(filterObj.PlanVisitCount + 1).Any(t => t.ReadingCategory == ReadingCategory.Global))
;
@@ -598,8 +567,6 @@ namespace IRaCIS.Core.Application.Service
IsReReadingOrBackInfluenceAnalysis = t.IsReReadingOrBackInfluenceAnalysis,
FirstGlobalVisitName = t.ReadModuleList.Where(c => c.TrialReadingCriterionId == trialReadingCriterionId && c.ModuleType == ModuleTypeEnum.Global).OrderBy(k => k.SubjectVisit.VisitNum).Select(u => u.SubjectVisit.VisitName).FirstOrDefault(),
BlindSubjectCode = t.SubjectVisitTaskList.Where(t => t.IsAnalysisCreate && t.TrialReadingCriterionId == trialReadingCriterionId).OrderByDescending(t => t.BlindSubjectCode).Select(t => t.BlindSubjectCode).FirstOrDefault(),
IsHaveGeneratedTask = t.SubjectVisitTaskList.Any(c => c.DoctorUserId == doctorUserId && c.IsSelfAnalysis == true && c.TrialReadingCriterionId == trialReadingCriterionId),
@@ -629,27 +596,29 @@ namespace IRaCIS.Core.Application.Service
IsClinicalDataSign = c.IsClinicalDataSign,
IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,
//自身一致性才有意义
//IsHaveGeneratedTask = c.Subject.SubjectVisitTaskList.Any(t => t.ConsistentAnalysisOriginalTaskId == c.Id),
//GlobalVisitTaskList = c.Subject.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]).Select(c => new VisitTaskSimpleDTO()
//{
// Id = c.Id,
// ReadingCategory = c.ReadingCategory,
// ReadingTaskState = c.ReadingTaskState,
// TaskBlindName = c.TaskBlindName,
// TaskCode = c.TaskCode,
// TaskName = c.TaskName,
// TaskState = c.TaskState,
// ArmEnum = c.ArmEnum,
// SubjectId = c.SubjectId,
// VisitTaskNum = c.VisitTaskNum,
// TrialId = c.TrialId,
// SourceSubjectVisitId = c.SourceSubjectVisitId,
// SouceReadModuleId = c.SouceReadModuleId,
GlobalVisitTaskList = c.Subject.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global]).Select(c => new VisitTaskSimpleDTO()
{
Id = c.Id,
ReadingCategory = c.ReadingCategory,
ReadingTaskState = c.ReadingTaskState,
TaskBlindName = c.TaskBlindName,
TaskCode = c.TaskCode,
TaskName = c.TaskName,
TaskState = c.TaskState,
ArmEnum = c.ArmEnum,
SubjectId = c.SubjectId,
VisitTaskNum = c.VisitTaskNum,
TrialId = c.TrialId,
SourceSubjectVisitId = c.SourceSubjectVisitId,
SouceReadModuleId = c.SouceReadModuleId,
// TrialReadingCriterionId = c.TrialReadingCriterionId,
// IsClinicalDataSign = c.IsClinicalDataSign,
// IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,
//}).ToList(),
TrialReadingCriterionId = c.TrialReadingCriterionId,
IsClinicalDataSign = c.IsClinicalDataSign,
IsNeedClinicalDataSign = c.IsNeedClinicalDataSign,
}).ToList(),
}).ToList()
});
@@ -669,11 +638,13 @@ namespace IRaCIS.Core.Application.Service
/// <returns></returns>
private async Task<IQueryable<DoctorGroupConsistentSubjectView>> GetGroupConsistentQueryAsync(TaskConsistentRule filterObj, List<Guid>? subejctIdList = null)
{
//单重阅片没有组件一致性
var trialId = filterObj.TrialId;
var trialReadingCriterionId = filterObj.TrialReadingCriterionId;
//var trialConfig = (await _repository.Where<Trial>(t => t.Id == trialId).Select(t => new { TrialId = t.Id, t.ReadingType, t.IsReadingTaskViewInOrder }).FirstOrDefaultAsync()).IfNullThrowException();
Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == trialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.ReadingTaskState == ReadingTaskState.HaveSigned && u.TrialReadingCriterionId == trialReadingCriterionId
&& (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject);
@@ -687,16 +658,28 @@ namespace IRaCIS.Core.Application.Service
Expression<Func<VisitTask, bool>> visitTaskFilter = comonTaskFilter.And(t => t.ReadingCategory == ReadingCategory.Visit);
////所选访视数量 的访视 其中必有一个访视后有全局任务
//if (filterObj.IsHaveReadingPeriod == true)
//{
// //visitTaskFilter = visitTaskFilter.And(t => t.Subject.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Any(u => u.VisitTaskNum == t.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && u.ReadingCategory == ReadingCategory.Global));
// //这里的过滤条件 不能用 where(comonTaskFilter) 会报错,奇怪的问题 只能重新写一遍
// visitTaskFilter = visitTaskFilter.And(c => c.Subject.SubjectVisitTaskList.Any(t => t.VisitTaskNum == c.VisitTaskNum + ReadingCommon.TaskNumDic[ReadingCategory.Global] && t.ReadingCategory == ReadingCategory.Global && t.IsAnalysisCreate == false && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned &&
// t.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && (t.ReReadingApplyState == ReReadingApplyState.Default || t.ReReadingApplyState == ReReadingApplyState.Reject)));
//}
IQueryable<Subject> subjectQuery = default;
//单重阅片没有组件一致性
//双重阅片,并且都阅片完成
subjectQuery = _subjectRepository.Where(t => t.TrialId == trialId &&
t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).Select(t => t.DoctorUserId).Distinct().Count() == 2 &&
t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter).GroupBy(t => new { t.SubjectId, t.VisitTaskNum }).Where(g => g.Count() == 2).Count() >= filterObj.PlanVisitCount
)
//.WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(filterObj.PlanVisitCount * 2 + 2).Any(t => t.ReadingCategory == ReadingCategory.Global))
.WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum > filterObj.PlanVisitCount - 1).Select(t => t.DoctorUserId).Distinct().Count() == 2)
.WhereIf(filterObj.IsHaveReadingPeriod == true, u => u.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter).Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(filterObj.PlanVisitCount * 2 + 2).Any(t => t.ReadingCategory == ReadingCategory.Global))
;
@@ -712,7 +695,7 @@ namespace IRaCIS.Core.Application.Service
IsHaveGeneratedTask = t.SubjectVisitTaskList.Any(c => c.IsSelfAnalysis == false && c.TrialReadingCriterionId == trialReadingCriterionId),
DoctorUserList = t.SubjectDoctorList.Where(t => t.TrialReadingCriterionId == trialReadingCriterionId && t.IsConfirmed && t.ArmEnum <= Arm.DoubleReadingArm2).Select(t => new UserSimpleInfo()
DoctorUserList = t.SubjectDoctorList.Where(t => t.TrialReadingCriterionId == trialReadingCriterionId && t.IsConfirmed).Select(t => new UserSimpleInfo()
{
UserId = t.Id,
FullName = t.DoctorUser.FullName,
@@ -756,16 +739,9 @@ namespace IRaCIS.Core.Application.Service
[HttpPost]
public async Task<GetConsistentRuleOut> GetConsistentRule(TaskConsistentRuleQuery inQuery)
public async Task<TaskConsistentRuleBasic?> GetConsistentRule(TaskConsistentRuleQuery inQuery)
{
var IsReadingTaskViewInOrder = await _trialReadingCriterionRepository.Where(x => x.Id == inQuery.TrialReadingCriterionId).Select(x => x.IsReadingTaskViewInOrder).FirstNotNullAsync();
var result = await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == inQuery.IsSelfAnalysis && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
return new GetConsistentRuleOut()
{
ConsistentRuleBasic = result,
IsReadingTaskViewInOrder = IsReadingTaskViewInOrder
};
return await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == inQuery.IsSelfAnalysis && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
}
/// <summary>
@@ -780,20 +756,17 @@ namespace IRaCIS.Core.Application.Service
var trialId = inQuery.TrialId;
//防止生成sql生成GETDATE() 时区导致的问题
var appDateTimeNow = DateTime.Now;
Expression<Func<VisitTask, bool>> comonTaskFilter = u => u.TrialId == trialId && u.IsAnalysisCreate == false && u.TaskState == TaskState.Effect && u.ReadingTaskState == ReadingTaskState.HaveSigned && (u.ReReadingApplyState == ReReadingApplyState.Default || u.ReReadingApplyState == ReReadingApplyState.Reject);
//&& u.TrialReadingCriterionId == trialReadingCriterionId &&u.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < appDateTimeNow && u.DoctorUserId == doctorUserId;
//&& u.TrialReadingCriterionId == trialReadingCriterionId &&u.SignTime!.Value.AddDays(filterObj.IntervalWeeks * 7) < DateTime.Now && u.DoctorUserId == doctorUserId;
Expression<Func<VisitTask, bool>> visitTaskFilter = comonTaskFilter.And(t => t.ReadingCategory == ReadingCategory.Visit);
var taskConsistentRuleQueryable = from enroll in _enrollRepository.Where(t => t.TrialId == trialId && t.EnrollStatus == EnrollStatus.ConfirmIntoGroup
var taskConsistentRuleQueryable = from enroll in _repository.Where<Enroll>(t => t.TrialId == trialId && t.EnrollStatus == EnrollStatus.ConfirmIntoGroup
&& t.EnrollReadingCriteriaList.Any(c => c.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && c.IsJoinAnalysis))
join user in _userRepository.Where() on enroll.DoctorUserId equals user.Id
join taskConsistentRule in _taskConsistentRuleRepository.Where(t => t.TrialId == trialId && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.IsSelfAnalysis) on enroll.TrialId equals taskConsistentRule.TrialId
join user in _repository.Where<User>() on enroll.DoctorUserId equals user.Id
join taskConsistentRule in _repository.Where<TaskConsistentRule>(t => t.TrialId == trialId && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.IsSelfAnalysis) on enroll.TrialId equals taskConsistentRule.TrialId
select new TaskConsistentRuleView()
{
Id = taskConsistentRule.Id,
@@ -817,20 +790,12 @@ namespace IRaCIS.Core.Application.Service
MatchSubejctCount = taskConsistentRule.Trial.SubjectList.AsQueryable()
.Where(t => taskConsistentRule.IsHaveReadingPeriod == false ? t.SubjectVisitTaskList.AsQueryable()
.Where(visitTaskFilter).Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.SignTime!.Value.AddDays(taskConsistentRule.IntervalWeeks * 7) < appDateTimeNow && t.DoctorUserId == user.Id)
.Where(visitTaskFilter).Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.SignTime!.Value.AddDays(taskConsistentRule.IntervalWeeks * 7) < DateTime.Now && t.DoctorUserId == user.Id)
.Count() >= taskConsistentRule.PlanVisitCount :
//全局要>计划访视数量后面
t.SubjectVisitTaskList.AsQueryable().Where(comonTaskFilter)
.Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.SignTime!.Value.AddDays(taskConsistentRule.IntervalWeeks * 7) < appDateTimeNow && t.DoctorUserId == user.Id)
.Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).Any(t => t.ReadingCategory == ReadingCategory.Global && t.VisitTaskNum > taskConsistentRule.PlanVisitCount - 1)
&&
t.SubjectVisitTaskList.AsQueryable().Where(visitTaskFilter)
.Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.SignTime!.Value.AddDays(taskConsistentRule.IntervalWeeks * 7) < appDateTimeNow && t.DoctorUserId == user.Id)
.Count() >= taskConsistentRule.PlanVisitCount
)
.Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId && t.SignTime!.Value.AddDays(taskConsistentRule.IntervalWeeks * 7) < DateTime.Now && t.DoctorUserId == user.Id)
.Where(t => t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global).OrderBy(t => t.VisitTaskNum).Take(taskConsistentRule.PlanVisitCount + 1).Any(t => t.ReadingCategory == ReadingCategory.Global))
.Count(),
@@ -860,9 +825,9 @@ namespace IRaCIS.Core.Application.Service
//var taskConsistentRuleQueryable = _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId)
// .ProjectTo<TaskConsistentRuleView>(_mapper.ConfigurationProvider);
var list = await taskConsistentRuleQueryable.ToListAsync();
var list= await taskConsistentRuleQueryable.ToListAsync();
var rule = await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == true && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
var rule= await _taskConsistentRuleRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsSelfAnalysis == true && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).ProjectTo<TaskConsistentRuleBasic>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
return ResponseOutput.Ok(list, rule);
}
@@ -899,7 +864,7 @@ namespace IRaCIS.Core.Application.Service
public async Task<List<UpdateTrialSiteCodeCommandView>> GetUpdateVirtualSiteCodeList(Guid trialId)
{
var list = await _trialVirtualSiteCodeUpdateRepository.Where(t => t.TrialId == trialId).Select(t => new UpdateTrialSiteCodeCommandView() { TrialId = trialId, VirtualSiteCode = t.VirturalSiteCode, Creatime = t.CreateTime }).OrderByDescending(t => t.Creatime).ToListAsync();
var list = await _trialVirtualSiteCodeUpdateRepository.Where(t => t.TrialId == trialId).Select(t => new UpdateTrialSiteCodeCommandView() { TrialId = trialId, VirtualSiteCode = t.VirturalSiteCode, Creatime = t.CreateTime }).OrderByDescending(t=>t.Creatime).ToListAsync();
return list;
}
@@ -995,10 +960,35 @@ namespace IRaCIS.Core.Application.Service
/// <summary>
/// 随机算法,选择指定数量的 subject
/// </summary>
/// <param name="matchSubjectIdList"></param>
/// <param name="countToSelect"></param>
/// <returns></returns>
public List<Guid> GetRandomSubjectIdList(List<Guid> matchSubjectIdList, int countToSelect)
{
// 使用 Fisher-Yates 随机置换算法来选择指定数量的 GUID
Random random = new Random();
for (int i = 0; i < countToSelect; i++)
{
// 生成一个随机索引
int randomIndex = random.Next(i, matchSubjectIdList.Count);
// 将选中的元素与当前元素交换位置
Guid temp = matchSubjectIdList[randomIndex];
matchSubjectIdList[randomIndex] = matchSubjectIdList[i];
matchSubjectIdList[i] = temp;
}
return matchSubjectIdList.Take(countToSelect).ToList();
// 使用洗牌算法来随机选择指定数量的GUID
//Random random = new Random();
//return matchSubjectIdList.OrderBy(g => random.Next()).Take(countToSelect).ToList();
}
}
}
@@ -16,12 +16,17 @@ namespace IRaCIS.Core.Application.Service
/// 医学审核生成规则 废弃
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class TaskMedicalReviewRuleService(
IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository,
IRepository<TrialUser> _trialUserRepository) : BaseService, ITaskMedicalReviewRuleService
public class TaskMedicalReviewRuleService : BaseService, ITaskMedicalReviewRuleService
{
private readonly IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository;
private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;
public TaskMedicalReviewRuleService(IRepository<TaskMedicalReviewRule> taskMedicalReviewRuleRepository,IRepository<TaskMedicalReview> taskMedicalReviewRepository)
{
_taskMedicalReviewRuleRepository = taskMedicalReviewRuleRepository;
_taskMedicalReviewRepository = taskMedicalReviewRepository;
}
[HttpPost]
public async Task<(List<TaskMedicalReviewRuleView>,object)> GetTaskMedicalReviewRuleList(TaskMedicalReviewRuleQuery inQuery)
@@ -31,7 +36,7 @@ namespace IRaCIS.Core.Application.Service
var taskTaskMedicalReviewRuleQueryable = _taskMedicalReviewRuleRepository.Where(t => t.TrialId == inQuery.TrialId)
.ProjectTo<TaskMedicalReviewRuleView>(_mapper.ConfigurationProvider);
var isHaveMIM = await _trialUserRepository.AnyAsync(t => t.User.UserTypeEnum == Domain.Share.UserTypeEnum.MIM && t.TrialId==inQuery.TrialId);
var isHaveMIM = await _repository.AnyAsync<TrialUser>(t => t.User.UserTypeEnum == Domain.Share.UserTypeEnum.MIM && t.TrialId==inQuery.TrialId);
return (await taskTaskMedicalReviewRuleQueryable.ToListAsync(),new {IsHaveMIM=isHaveMIM});
}
@@ -19,14 +19,31 @@ namespace IRaCIS.Core.Application.Service
/// 任务医学审核
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class TaskMedicalReviewService(
IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
IRepository<TrialUser> _trialUserRepository,
IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
IRepository<VisitTask> _visitTaskRepository) : BaseService, ITaskMedicalReviewService
public class TaskMedicalReviewService : BaseService, ITaskMedicalReviewService
{
private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;
private readonly IRepository<Trial> _trialRepository;
private readonly IRepository<TrialUser> _trialUserRepository;
private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository;
private readonly IRepository<VisitTask> _visitTaskRepository;
private readonly IRepository<TaskMedicalReviewRule> _taskMedicalReviewRuleRepository;
public TaskMedicalReviewService(IRepository<TaskMedicalReview> taskMedicalReviewRepository,
IRepository<Trial> trialRepository,
IRepository<TrialUser> trialUserRepository,
IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrialRepository,
IRepository<VisitTask> visitTaskRepository,
IRepository<TaskMedicalReviewRule> taskMedicalReviewRuleRepository)
{
_taskMedicalReviewRepository = taskMedicalReviewRepository;
this._trialRepository = trialRepository;
_trialUserRepository = trialUserRepository;
this._readingQuestionCriterionTrialRepository = readingQuestionCriterionTrialRepository;
_visitTaskRepository = visitTaskRepository;
_taskMedicalReviewRuleRepository = taskMedicalReviewRuleRepository;
}
/// <summary>
/// PM 医学审核(挑选任务生成后的列表)
@@ -39,6 +56,9 @@ namespace IRaCIS.Core.Application.Service
var taskMedicalReviewQueryable = _taskMedicalReviewRepository.Where(t => t.VisitTask.TrialId == inQuery.TrialId)
.WhereIf(inQuery.IsEffect == true, t => t.VisitTask.TaskState == TaskState.Effect || t.VisitTask.TaskState == TaskState.Freeze)
.WhereIf(inQuery.IsEffect == false, t => t.VisitTask.TaskState == TaskState.Adbandon || t.VisitTask.TaskState == TaskState.HaveReturned)
.WhereIf(inQuery.TrialSiteId != null, t => t.VisitTask.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.VisitTask.SubjectId == inQuery.SubjectId)
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.VisitTask.Subject.Code.Contains(inQuery.SubjectCode) || t.VisitTask.Subject.MedicalNo.Contains(inQuery.SubjectCode))
@@ -67,7 +87,7 @@ namespace IRaCIS.Core.Application.Service
.ProjectTo<TaskMedicalReviewView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(TaskMedicalReviewView.AuditState), nameof(TaskMedicalReviewView.SubjectId), nameof(TaskMedicalReviewView.ArmEnum) , nameof(TaskMedicalReviewView.VisitTaskNum) };
var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, inQuery.SortField, inQuery.Asc, string.IsNullOrWhiteSpace(inQuery.SortField), defalutSortArray);
return pageList;
}
@@ -103,7 +123,7 @@ namespace IRaCIS.Core.Application.Service
.ProjectTo<GenerateMedicalReviewTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(GenerateMedicalReviewTaskView.IsUrgent) + " desc", nameof(GenerateMedicalReviewTaskView.SubjectId) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, inQuery.SortField, inQuery.Asc, string.IsNullOrWhiteSpace(inQuery.SortField), defalutSortArray);
return pageList;
@@ -240,7 +260,7 @@ namespace IRaCIS.Core.Application.Service
var defalutSortArray = new string[] { nameof(TaskMedicalReviewView.SubjectId), nameof(TaskMedicalReviewView.ArmEnum), nameof(TaskMedicalReviewView.VisitTaskNum) };
var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await taskMedicalReviewQueryable.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, inQuery.SortField, inQuery.Asc, string.IsNullOrWhiteSpace(inQuery.SortField), defalutSortArray);
return ResponseOutput.Ok(pageList, new
{
@@ -8,6 +8,7 @@ using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using AutoMapper;
@@ -16,9 +17,6 @@ using IRaCIS.Core.Infra.EFCore.Common;
using System.Linq.Expressions;
using IRaCIS.Core.Domain.Share.Reading;
using IRaCIS.Core.Application.Service.Reading.Dto;
using System.Runtime.InteropServices;
using IRaCIS.Core.Application.Helper;
using ZiggyCreatures.Caching.Fusion;
namespace IRaCIS.Core.Application.Service
{
@@ -28,23 +26,72 @@ namespace IRaCIS.Core.Application.Service
/// 访视读片任务
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class VisitTaskHelpeService(
IRepository<VisitTask> _visitTaskRepository,
IRepository<Trial> _trialRepository,
IRepository<SubjectVisit> _subjectVisitRepository,
IRepository<ReadingJudgeInfo> _readingJudgeInfoRepository,
IRepository<SubjectUser> _subjectUserRepository,
IRepository<ReadModule> _readModuleRepository,
IRepository<ReadingOncologyTaskInfo> _readingOncologyTaskInfoRepository,
IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository,
IRepository<ClinicalDataTrialSet> _trialClinicalDataSetRepository,
IRepository<ReadingClinicalData> _readingClinicalDataRepository,
IRepository<ReadingConsistentClinicalData> _readingConsistentClinicalDataRepository) : BaseService, IVisitTaskHelpeService
public class VisitTaskHelpeService : IVisitTaskHelpeService
{
private readonly IRepository<VisitTask> _visitTaskRepository;
private readonly IRepository<Trial> _trialRepository;
private readonly IEasyCachingProvider _provider;
private readonly IRepository<SubjectVisit> _subjectVisitRepository;
private readonly IRepository<ReadingJudgeInfo> _readingJudgeInfoRepository;
private readonly IRepository<TaskAllocationRule> _taskAllocationRuleRepository;
private readonly IRepository<SubjectUser> _subjectUserRepository;
private readonly IRepository<ReadModule> _readModuleRepository;
private readonly IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository;
private readonly IRepository<ReadingTableAnswerRowInfo> _readingTableAnswerRowInfoRepository;
private readonly IRepository<ReadingTableQuestionAnswer> _readingTableQuestionAnswerRepository;
private readonly IRepository<ReadingOncologyTaskInfo> _readingOncologyTaskInfoRepository;
private readonly IRepository<ReadingTableQuestionTrial> _readingTableQuestionTrialRepository;
private readonly IRepository<ReadingQuestionTrial> _readingQuestionTrialRepository;
private readonly IMapper _mapper;
private readonly IUserInfo _userInfo;
private readonly IRepository<VisitTaskReReading> _visitTaskReReadingRepository;
private readonly IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository;
private readonly IRepository<ClinicalDataTrialSet> _trialClinicalDataSetRepository;
private readonly IRepository<ReadingClinicalData> _readingClinicalDataRepository;
private readonly IRepository<SubjectCriteriaEvaluation> _subjectCriteriaEvaluationRepository;
public VisitTaskHelpeService(IRepository<VisitTask> visitTaskRepository, IRepository<SubjectUser> subjectUserRepository, IRepository<Trial> trialRepository, IEasyCachingProvider provider,
IRepository<SubjectVisit> subjectVisitRepository,
IRepository<ReadModule> readModuleRepository,
IRepository<ReadingTaskQuestionAnswer> readingTaskQuestionAnswerRepository,
IRepository<ReadingTableAnswerRowInfo> readingTableAnswerRowInfoRepository,
IRepository<ReadingTableQuestionAnswer> readingTableQuestionAnswerRepository,
IRepository<ReadingOncologyTaskInfo> ReadingOncologyTaskInfoRepository,
IRepository<ReadingTableQuestionTrial> readingTableQuestionTrialRepository,
IRepository<ReadingQuestionTrial> readingQuestionTrialRepository,
IRepository<ReadingJudgeInfo> readingJudgeInfoRepository,
IRepository<TaskAllocationRule> taskAllocationRuleRepository, IMapper mapper, IUserInfo userInfo, IRepository<VisitTaskReReading> visitTaskReReadingRepository,
IRepository<ReadingQuestionCriterionTrial> trialReadingCriterionRepository, IRepository<ClinicalDataTrialSet> trialClinicalDataSetRepository, IRepository<ReadingClinicalData> readingClinicalDataRepository,
IRepository<SubjectCriteriaEvaluation> subjectCriteriaEvaluationRepository)
{
_readingClinicalDataRepository = readingClinicalDataRepository;
_trialClinicalDataSetRepository = trialClinicalDataSetRepository;
_visitTaskRepository = visitTaskRepository;
_trialRepository = trialRepository;
this._readModuleRepository = readModuleRepository;
this._readingTaskQuestionAnswerRepository = readingTaskQuestionAnswerRepository;
this._readingTableAnswerRowInfoRepository = readingTableAnswerRowInfoRepository;
this._readingTableQuestionAnswerRepository = readingTableQuestionAnswerRepository;
_readingOncologyTaskInfoRepository = ReadingOncologyTaskInfoRepository;
this._readingTableQuestionTrialRepository = readingTableQuestionTrialRepository;
this._readingQuestionTrialRepository = readingQuestionTrialRepository;
_provider = provider;
_subjectVisitRepository = subjectVisitRepository;
this._readingJudgeInfoRepository = readingJudgeInfoRepository;
_taskAllocationRuleRepository = taskAllocationRuleRepository;
_subjectUserRepository = subjectUserRepository;
_mapper = mapper;
_userInfo = userInfo;
_visitTaskReReadingRepository = visitTaskReReadingRepository;
_subjectCriteriaEvaluationRepository = subjectCriteriaEvaluationRepository;
_trialReadingCriterionRepository = trialReadingCriterionRepository;
}
//查询列表的时候,一致性核查通过未产生任务的 自动产生任务 如果是一致性核查,那么还会自动分配
public async Task GenerateVisitTaskAsync(Guid trialId, List<Guid> subjectVisitIdList, bool isAssignSubjectToDoctor = false)
@@ -136,7 +183,7 @@ namespace IRaCIS.Core.Application.Service
var dbMaxCode = _visitTaskRepository.Where(t => t.TrialId == trialId).Select(t => t.Code).DefaultIfEmpty().Max();
var cacheMaxCodeInt =_fusionCache.GetOrDefault<int>(CacheKeys.TrialStudyMaxCode(trialId));
var cacheMaxCodeInt = _provider.Get<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}").Value;
int currentMaxCodeInt = cacheMaxCodeInt > dbMaxCode ? cacheMaxCodeInt : dbMaxCode;
@@ -160,7 +207,7 @@ namespace IRaCIS.Core.Application.Service
if (trialReadingCriterionConfig.IsReadingTaskViewInOrder == ReadingOrder.InOrder)
{
if (visitNumList.IndexOf(subjectVisit.VisitNum) == 0 && subjectVisit.VisitNum == 0)
if (visitNumList.IndexOf(subjectVisit.VisitNum) == 0 && subjectVisit.VisitNum==0)
{
blindTaskName = visitBlindConfig.BlindBaseLineName;
}
@@ -170,9 +217,9 @@ namespace IRaCIS.Core.Application.Service
}
}
else
else
{
blindTaskName = "Timepoint";
blindTaskName ="Timepoint";
}
@@ -268,7 +315,7 @@ namespace IRaCIS.Core.Application.Service
}
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
@@ -329,7 +376,7 @@ namespace IRaCIS.Core.Application.Service
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
@@ -401,19 +448,6 @@ namespace IRaCIS.Core.Application.Service
}
/// <summary>
/// 获取GetIsClinicalDataSignTest
/// </summary>
/// <param name="visitTask"></param>
/// <returns></returns>
public async Task<bool> GetIsClinicalDataSignTest(Guid visitTask)
{
var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTask).FirstNotNullAsync();
var clinicalDataConfirmList = _trialClinicalDataSetRepository.Where(t => t.TrialId == taskinfo.TrialId && t.IsConfirm).Include(t => t.TrialClinicalDataSetCriteriaList).ToList();
Guid readingid = taskinfo.SourceSubjectVisitId == null ? taskinfo.SouceReadModuleId!.Value : taskinfo.SourceSubjectVisitId.Value;
return IsClinicalDataSign(taskinfo.ReadingCategory, taskinfo.VisitTaskNum == 0m, taskinfo.TrialReadingCriterionId, clinicalDataConfirmList, readingid, taskinfo.TrialId); ;
}
// 有可能在任务生成之前 就签名完了临床数据
private bool IsClinicalDataSign(ReadingCategory readingCategory, bool isbaseLine, Guid trialReadingCriterionId, List<ClinicalDataTrialSet> trialClinicalDataSetList, Guid readingId, Guid trialId)
@@ -432,9 +466,7 @@ namespace IRaCIS.Core.Application.Service
//CRC 的自动签名 不用管 只用处理PM的就好
var haveSignedCount = _readingClinicalDataRepository
.Where(t => t.TrialId == trialId && t.IsSign
&& t.ClinicalDataTrialSet.TrialClinicalDataSetCriteriaList.Any(x=>x.TrialReadingCriterionId== trialReadingCriterionId)
&& t.ReadingClinicalDataState == ReadingClinicalDataStatus.HaveSigned && t.ReadingId == readingId && t.ClinicalDataTrialSet.UploadRole == UploadRole.PM).Count();
.Where(t => t.TrialId == trialId && t.IsSign && t.ReadingClinicalDataState == ReadingClinicalDataStatus.HaveSigned && t.ReadingId == readingId && t.ClinicalDataTrialSet.UploadRole == UploadRole.PM).Count();
var readModule = _readModuleRepository.Where(t => t.Id == readingId).FirstOrDefault();
@@ -575,7 +607,7 @@ namespace IRaCIS.Core.Application.Service
var dbMaxCode = _visitTaskRepository.Where(t => t.TrialId == trialId).Select(t => t.Code).DefaultIfEmpty().Max();
var cacheMaxCodeInt =_fusionCache.GetOrDefault<int>(CacheKeys.TrialStudyMaxCode(trialId));
var cacheMaxCodeInt = _provider.Get<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}").Value;
int currentMaxCodeInt = cacheMaxCodeInt > dbMaxCode ? cacheMaxCodeInt : dbMaxCode;
@@ -669,8 +701,8 @@ namespace IRaCIS.Core.Application.Service
&& t.TrialReadingCriterionId == trialReadingCriterionId && t.TaskState == TaskState.Effect
/* && t.TaskAllocationState == TaskAllocationState.NotAllocate && t.DoctorUserId == null*/ && t.SourceSubjectVisitId == subjectVisit.Id).ToList();
VisitTask? task1 = existCurrentVisitTaskList.FirstOrDefault(t => t.ArmEnum == Arm.DoubleReadingArm1);
VisitTask? task2 = existCurrentVisitTaskList.FirstOrDefault(t => t.ArmEnum == Arm.DoubleReadingArm2);
VisitTask? task1 = null;
VisitTask? task2 = null;
if (!existCurrentVisitTaskList.Any(t => t.ArmEnum == Arm.DoubleReadingArm1))
@@ -702,7 +734,6 @@ namespace IRaCIS.Core.Application.Service
});
}
if (!existCurrentVisitTaskList.Any(t => t.ArmEnum == Arm.DoubleReadingArm2))
{
currentMaxCodeInt = currentMaxCodeInt + 1;
@@ -732,7 +763,7 @@ namespace IRaCIS.Core.Application.Service
}
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
#region
@@ -905,7 +936,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
}
@@ -973,7 +1004,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
}
@@ -1056,7 +1087,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
#region
@@ -1184,7 +1215,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
}
@@ -1373,69 +1404,15 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
//}
break;
case GenerateTaskCategory.SelfConsistent:
var readingCriterionId = generateTaskCommand.GenerataConsistentTaskList.First().TrialReadingCriterionId;
var isReadingTaskViewInOrder = await _trialReadingCriterionRepository.Where(t => t.Id == readingCriterionId).Select(x => x.IsReadingTaskViewInOrder).FirstNotNullAsync();
var subjectId = generateTaskCommand.GenerataConsistentTaskList.First().SubjectId;
//var trialReadingCriterion=_trialReadingCriterionRepository.Where(t=>t.Id== trialReadingCriterionId).FirstOrDefault();
//判断是否存在传输方式为Pdf得临床数据
var firsttask = generateTaskCommand.GenerataConsistentTaskList[0];
var clinicalDataList = _readingClinicalDataRepository.Where(t => t.SubjectId == subjectId
&& t.ClinicalDataTrialSet.TrialClinicalDataSetCriteriaList.Any(y => y.TrialReadingCriterionId == firsttask.TrialReadingCriterionId)
&& t.ClinicalDataTrialSet.ClinicalDataLevel!= ClinicalLevel.Study
&& t.ClinicalDataTrialSet.ClinicalUploadType == ClinicalUploadType.PDF)
// crc受试者和访视的临床数据没上传 一致性分析的时候也不用显示
.Where(x=>x.ClinicalDataTrialSet.UploadRole == UploadRole.PM||x.FileCount>0)
.Include(t => t.ReadingClinicalDataPDFList).Include(t => t.ClinicalDataTrialSet).ToList();
foreach (var clinicalData in clinicalDataList)
{
var consistnentClinicalData = _mapper.Map<ReadingConsistentClinicalData>(clinicalData);
var id = NewId.NextSequentialGuid();
consistnentClinicalData.Id = id;
if (consistnentClinicalData.ClinicalDataTrialSet.ClinicalUploadType == ClinicalUploadType.PDF)
{
consistnentClinicalData.IsSign = false;
consistnentClinicalData.IsBlind = false;
consistnentClinicalData.IsComplete = true;
consistnentClinicalData.ReadingClinicalDataState = ReadingClinicalDataStatus.HaveUploaded;
consistnentClinicalData.ClinicalDataTrialSet = null;
}
var consistanClinicalDataPdfList = _mapper.Map<List<ReadingConsistentClinicalDataPDF>>(clinicalData.ReadingClinicalDataPDFList);
consistanClinicalDataPdfList.ForEach(t => { t.ReadingConsistentClinicalDataId = id; t.Id = Guid.Empty; });
consistnentClinicalData.ReadingClinicalDataPDFList = consistanClinicalDataPdfList;
await _readingConsistentClinicalDataRepository.AddAsync(consistnentClinicalData);
}
foreach (var task in generateTaskCommand.GenerataConsistentTaskList)
{
var exsitPDF = await _readingClinicalDataRepository
.WhereIf(isReadingTaskViewInOrder== ReadingOrder.Random,t=>t.ReadingId== task.SouceReadModuleId|| t.ReadingId == task.SourceSubjectVisitId)
.AnyAsync(t => t.TrialId == trialId &&
t.SubjectId== task.SubjectId&&
t.ClinicalDataTrialSet.TrialClinicalDataSetCriteriaList.Any(c => c.TrialReadingCriterionId == readingCriterionId)
&& t.ClinicalDataTrialSet.ClinicalDataLevel != ClinicalLevel.Study
&& t.ClinicalDataTrialSet.ClinicalUploadType == ClinicalUploadType.PDF);
var taskState = exsitPDF ? TaskState.NotEffect : TaskState.Effect;
var consistentTask = new VisitTask()
{
TrialId = task.TrialId,
@@ -1447,7 +1424,7 @@ namespace IRaCIS.Core.Application.Service
VisitTaskNum = task.VisitTaskNum,
ReadingCategory = task.ReadingCategory,
TaskState = taskState,
TaskState = TaskState.Effect,
Code = currentMaxCodeInt + 1,
TaskCode = AppSettings.GetCodeStr(currentMaxCodeInt + 1, nameof(VisitTask)),
@@ -1474,7 +1451,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
break;
@@ -1521,7 +1498,7 @@ namespace IRaCIS.Core.Application.Service
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
break;
@@ -1559,7 +1536,7 @@ namespace IRaCIS.Core.Application.Service
await _visitTaskRepository.AddAsync(visitTask);
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
await _visitTaskRepository.BatchUpdateNoTrackingAsync(x => generateTaskCommand.JudgeVisitTaskIdList.Contains(x.Id), x => new VisitTask()
{
@@ -1620,7 +1597,7 @@ namespace IRaCIS.Core.Application.Service
});
currentMaxCodeInt = currentMaxCodeInt + 1;
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
}
@@ -1690,7 +1667,7 @@ namespace IRaCIS.Core.Application.Service
TrialId = originalTaskInfo.TrialId
});
_fusionCache.Set<int>(CacheKeys.TrialStudyMaxCode(trialId), currentMaxCodeInt, TimeSpan.FromMinutes(30));
_provider.Set<int>($"{trialId}_{StaticData.CacheKey.TaskMaxCode}", currentMaxCodeInt, TimeSpan.FromMinutes(30));
}
break;
}
@@ -19,6 +19,7 @@ using DocumentFormat.OpenXml.Office2010.Word;
using System.Linq.Dynamic.Core;
using System.Linq;
using DocumentFormat.OpenXml.Bibliography;
using Org.BouncyCastle.Crypto;
using IRaCIS.Core.Domain.Share.Reading;
using MassTransit;
using System.Reactive.Subjects;
@@ -30,33 +31,57 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// 访视读片任务
/// </summary>
[ApiExplorerSettings(GroupName = "Trial")]
public class VisitTaskService(IRepository<VisitTask> _visitTaskRepository,
IRepository<Trial> _trialRepository,
IRepository<SubjectVisit> _subjectVisitRepository,
IRepository<TaskAllocationRule> _taskAllocationRuleRepository,
IRepository<Subject> _subjectRepository,
IRepository<SubjectUser> _subjectUserRepository,
IRepository<ReadModule> _readModuleRepository,
IRepository<VisitTaskReReading> _visitTaskReReadingRepository,
IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
IRepository<ReadingClinicalData> _readingClinicalDataReposiotry,
IRepository<SubjectCriteriaEvaluation> _subjectCriteriaEvaluationRepository,
IRepository<SubjectCriteriaEvaluationVisitFilter> _subjectCriteriaEvaluationVisitFilterRepository,
IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository,
IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository,
IRepository<DicomInstance> _dicomInstanceRepository,
IRepository<DicomSeries> _dicomSeriesRepository,
IRepository<SubjectCanceDoctor> _subjectCanceDoctorRepository,
IRepository<ReadingTaskQuestionMark> _readingTaskQuestionMarkRepository,
IRepository<ReadingTableAnswerRowInfo> _readingTableAnswerRowInfoRepository,
IRepository<ReadingCustomTag> _readingCustomTagRepository,
IRepository<TaskInfluence> _taskInfluenceRepository,
IRepository<TrialQCQuestionAnswer> _trialQCQuestionAnswerRepository,
IRepository<SubjectCriteriaEvaluationVisitStudyFilter> _subjectCriteriaEvaluationVisitStudyFilterRepository) : BaseService, IVisitTaskService
public class VisitTaskService : BaseService, IVisitTaskService
{
private readonly IRepository<VisitTask> _visitTaskRepository;
private readonly IRepository<Trial> _trialRepository;
private readonly IRepository<SubjectVisit> _subjectVisitRepository;
private readonly IRepository<TaskAllocationRule> _taskAllocationRuleRepository;
private readonly IRepository<Subject> _subjectRepository;
private readonly IRepository<SubjectUser> _subjectUserRepository;
private readonly IRepository<ReadModule> _readModuleRepository;
private readonly IRepository<VisitTaskReReading> _visitTaskReReadingRepository;
private readonly IRepository<TaskMedicalReview> _taskMedicalReviewRepository;
private readonly IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository;
private readonly IRepository<ReadingClinicalData> _readingClinicalDataReposiotry;
private readonly IRepository<SubjectCriteriaEvaluation> _subjectCriteriaEvaluationRepository;
private readonly IRepository<SubjectCriteriaEvaluationVisitFilter> _subjectCriteriaEvaluationVisitFilterRepository;
private readonly IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository;
private readonly IRepository<SubjectCriteriaEvaluationVisitStudyFilter> _subjectCriteriaEvaluationVisitStudyFilterRepository;
public VisitTaskService(IRepository<SubjectVisit> subjectVisitRepository, IRepository<VisitTask> visitTaskRepository, IRepository<Trial> trialRepository,
IRepository<Subject> subjectRepository, IRepository<SubjectUser> subjectUserRepository, IRepository<TaskAllocationRule> taskAllocationRuleRepository,
IRepository<ReadModule> readModuleRepository, IRepository<VisitTaskReReading> visitTaskReReadingRepository,
IRepository<TaskMedicalReview> taskMedicalReviewRepository,
IRepository<ReadingTaskQuestionAnswer> readingTaskQuestionAnswerRepository
, IRepository<ReadingQuestionCriterionTrial> trialReadingCriterionRepository,
IRepository<ReadingClinicalData> readingClinicalDataReposiotry,
IRepository<SubjectCriteriaEvaluation> subjectCriteriaEvaluationRepository,
IRepository<SubjectCriteriaEvaluationVisitFilter> subjectCriteriaEvaluationVisitFilterRepository,
IRepository<SubjectCriteriaEvaluationVisitStudyFilter> subjectCriteriaEvaluationVisitStudyFilterRepository
)
{
_readingClinicalDataReposiotry = readingClinicalDataReposiotry;
_taskAllocationRuleRepository = taskAllocationRuleRepository;
_visitTaskRepository = visitTaskRepository;
_trialRepository = trialRepository;
_subjectVisitRepository = subjectVisitRepository;
_subjectRepository = subjectRepository;
_subjectUserRepository = subjectUserRepository;
_readModuleRepository = readModuleRepository;
_visitTaskReReadingRepository = visitTaskReReadingRepository;
_taskMedicalReviewRepository = taskMedicalReviewRepository;
_readingTaskQuestionAnswerRepository = readingTaskQuestionAnswerRepository;
_trialReadingCriterionRepository = trialReadingCriterionRepository;
_subjectCriteriaEvaluationRepository = subjectCriteriaEvaluationRepository;
_subjectCriteriaEvaluationVisitFilterRepository = subjectCriteriaEvaluationVisitFilterRepository;
_subjectCriteriaEvaluationVisitStudyFilterRepository = subjectCriteriaEvaluationVisitStudyFilterRepository;
}
/// <summary>
/// 设置任务加急
@@ -73,13 +98,13 @@ namespace IRaCIS.Core.Application.Service.Allocation
TaskUrgentRemake = inDto.TaskUrgentRemake,
});
return await _visitTaskRepository.SaveChangesAsync();
}
public async Task<List<TrialReadingCriterionDto>> GetTrialCriterionList(Guid trialId, bool isHaveSigned = true, bool? isAutoCreate = null)
{
var list = await _readingQuestionCriterionTrialRepository.Where(t => t.TrialId == trialId && t.IsConfirm)
var list = await _repository.Where<ReadingQuestionCriterionTrial>(t => t.TrialId == trialId && t.IsConfirm)
.OrderBy(t => t.ShowOrder)
.Select(t => new TrialReadingCriterionDto()
@@ -121,35 +146,35 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IResponseOutput<PageOutput<SubjectAssignStat>>> GetSubjectAssignAndTaskStatList(SubjectAssignStatQuery inQuery)
public async Task<IResponseOutput<PageOutput<SubjectAssignStat>>> GetSubjectAssignAndTaskStatList(SubjectAssignStatQuery querySubjectAssign)
{
var isAddtinoarlCriterion = await _trialReadingCriterionRepository.AnyAsync(t => t.Id == inQuery.TrialReadingCriterionId && t.IsAutoCreate == false);
var isAddtinoarlCriterion = await _trialReadingCriterionRepository.AnyAsync(t => t.Id == querySubjectAssign.TrialReadingCriterionId && t.IsAutoCreate == false);
var subjectQuery = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId && t.SubjectVisitTaskList.Any())
.WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.Id == inQuery.SubjectId)
.WhereIf(inQuery.DoctorUserId != null, t => t.SubjectDoctorList.Any(t => t.DoctorUserId == inQuery.DoctorUserId && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => t.Code.Contains(inQuery.SubjectCode))
var subjectQuery = _subjectRepository.Where(t => t.TrialId == querySubjectAssign.TrialId && t.SubjectVisitTaskList.Any())
.WhereIf(querySubjectAssign.TrialSiteId != null, t => t.TrialSiteId == querySubjectAssign.TrialSiteId)
.WhereIf(querySubjectAssign.SubjectId != null, t => t.Id == querySubjectAssign.SubjectId)
.WhereIf(querySubjectAssign.DoctorUserId != null, t => t.SubjectDoctorList.Any(t => t.DoctorUserId == querySubjectAssign.DoctorUserId && t.TrialReadingCriterionId == querySubjectAssign.TrialReadingCriterionId))
.WhereIf(!string.IsNullOrEmpty(querySubjectAssign.SubjectCode), t => t.Code.Contains(querySubjectAssign.SubjectCode))
//未分配
.WhereIf(inQuery.SubjectAllocateState == 0, t => !t.SubjectDoctorList.Any(t => t.AssignTime != null && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId))
.WhereIf(querySubjectAssign.SubjectAllocateState == 0, t => !t.SubjectDoctorList.Any(t => t.AssignTime != null && t.TrialReadingCriterionId == querySubjectAssign.TrialReadingCriterionId))
//已分配
.WhereIf(inQuery.SubjectAllocateState == 1, t => t.SubjectDoctorList.Any(t => t.AssignTime != null && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId))
.WhereIf(querySubjectAssign.SubjectAllocateState == 1, t => t.SubjectDoctorList.Any(t => t.AssignTime != null && t.TrialReadingCriterionId == querySubjectAssign.TrialReadingCriterionId))
.WhereIf(inQuery.ArmList.Count > 0, t => !inQuery.ArmList.Except(t.SubjectDoctorList.Where(t => t.AssignTime != null && t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).Select(c => c.ArmEnum)).Any())
.WhereIf(querySubjectAssign.ArmList.Count > 0, t => !querySubjectAssign.ArmList.Except(t.SubjectDoctorList.Where(t => t.AssignTime != null && t.TrialReadingCriterionId == querySubjectAssign.TrialReadingCriterionId).Select(c => c.ArmEnum)).Any())
.WhereIf(isAddtinoarlCriterion, t => t.SubjectCriteriaEvaluationList.Where(t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId).Any(t => t.IsJoinEvaluation))
.WhereIf(isAddtinoarlCriterion, t => t.SubjectCriteriaEvaluationList.Where(t => t.TrialReadingCriterionId == querySubjectAssign.TrialReadingCriterionId).Any(t => t.IsJoinEvaluation))
.ProjectTo<SubjectAssignStat>(_mapper.ConfigurationProvider, new { trialReadingCriterionId = inQuery.TrialReadingCriterionId });
.ProjectTo<SubjectAssignStat>(_mapper.ConfigurationProvider, new { trialReadingCriterionId = querySubjectAssign.TrialReadingCriterionId });
var pageList = await subjectQuery.ToPagedListAsync(inQuery,nameof(SubjectAssignStat.SubjectId));
var pageList = await subjectQuery.ToPagedListAsync(querySubjectAssign.PageIndex, querySubjectAssign.PageSize, string.IsNullOrWhiteSpace(querySubjectAssign.SortField) ? nameof(querySubjectAssign.SubjectId) : querySubjectAssign.SortField, querySubjectAssign.Asc);
var criterionConfig = (await _trialReadingCriterionRepository.Where(x => x.Id == inQuery.TrialReadingCriterionId).Select(x => new { x.ReadingTool, x.IsReadingTaskViewInOrder, x.ReadingType, x.IsArbitrationReading, x.IsOncologyReading, x.IsGlobalReading }).FirstOrDefaultAsync()).IfNullThrowException();
var criterionConfig = (await _trialReadingCriterionRepository.Where(x => x.Id == querySubjectAssign.TrialReadingCriterionId).Select(x => new { x.ReadingTool, x.IsReadingTaskViewInOrder, x.ReadingType, x.IsArbitrationReading, x.IsOncologyReading, x.IsGlobalReading }).FirstOrDefaultAsync()).IfNullThrowException();
return ResponseOutput.Ok(pageList, criterionConfig);
}
@@ -266,7 +291,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
{
foreach (var command in cancelCommand.CancelList.Where(t => t.IsCancelAssign))
{
if (await _visitTaskRepository.AnyAsync(t => t.TaskState == TaskState.Effect && t.TrialReadingCriterionId == cancelCommand.TrialReadingCriterionId && t.SubjectId == command.SubjectId && t.DoctorUserId == command.DoctorUserId && t.ArmEnum == command.ArmEnum && t.ReadingTaskState != ReadingTaskState.WaitReading))
if (await _visitTaskRepository.AnyAsync(t => t.TrialReadingCriterionId == cancelCommand.TrialReadingCriterionId && t.SubjectId == command.SubjectId && t.DoctorUserId == command.DoctorUserId && t.ArmEnum == command.ArmEnum && t.ReadingTaskState != ReadingTaskState.WaitReading))
{
//---当前医生已开始做该Subject 该标准的任务,不允许取消分配
throw new BusinessValidationFailedException(_localizer["VisitTask_DoctorConfigNotFound"]);
@@ -285,7 +310,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
var subjectId = cancelCommand.CancelList.First().SubjectId;
await _subjectCanceDoctorRepository.AddAsync(new SubjectCanceDoctor() { SubjectId = subjectId, Note = cancelCommand.Note, TrialReadingCriterionId = cancelCommand.TrialReadingCriterionId });
await _repository.AddAsync(new SubjectCanceDoctor() { SubjectId = subjectId, Note = cancelCommand.Note, TrialReadingCriterionId = cancelCommand.TrialReadingCriterionId });
await _visitTaskRepository.SaveChangesAsync();
@@ -394,32 +419,32 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<SubjectAssignView>> GetSubjectAssignList(SubjectAssignQuery inQuery)
public async Task<PageOutput<SubjectAssignView>> GetSubjectAssignList(SubjectAssignQuery querySubjectAssign)
{
var subjectQuery = _subjectRepository.Where(t => t.TrialId == inQuery.TrialId)
.WhereIf(inQuery.IsJudgeDoctor == false, t => t.SubjectVisitTaskList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(inQuery.IsJudgeDoctor, t => t.SubjectVisitTaskList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
var subjectQuery = _subjectRepository.Where(t => t.TrialId == querySubjectAssign.TrialId)
.WhereIf(querySubjectAssign.IsJudgeDoctor == false, t => t.SubjectVisitTaskList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(querySubjectAssign.IsJudgeDoctor, t => t.SubjectVisitTaskList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
.WhereIf(inQuery.TrialSiteId != null, t => t.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.Id == inQuery.SubjectId)
.WhereIf(querySubjectAssign.TrialSiteId != null, t => t.TrialSiteId == querySubjectAssign.TrialSiteId)
.WhereIf(querySubjectAssign.SubjectId != null, t => t.Id == querySubjectAssign.SubjectId)
.WhereIf(inQuery.IsHaveAssigned != null && inQuery.IsHaveAssigned == true && inQuery.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(inQuery.IsHaveAssigned != null && inQuery.IsHaveAssigned == true && inQuery.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
.WhereIf(inQuery.IsHaveAssigned != null && inQuery.IsHaveAssigned == false && inQuery.IsJudgeDoctor == false, t => !t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(inQuery.IsHaveAssigned != null && inQuery.IsHaveAssigned == false && inQuery.IsJudgeDoctor, t => !t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
.WhereIf(querySubjectAssign.IsHaveAssigned != null && querySubjectAssign.IsHaveAssigned == true && querySubjectAssign.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(querySubjectAssign.IsHaveAssigned != null && querySubjectAssign.IsHaveAssigned == true && querySubjectAssign.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
.WhereIf(querySubjectAssign.IsHaveAssigned != null && querySubjectAssign.IsHaveAssigned == false && querySubjectAssign.IsJudgeDoctor == false, t => !t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any())
.WhereIf(querySubjectAssign.IsHaveAssigned != null && querySubjectAssign.IsHaveAssigned == false && querySubjectAssign.IsJudgeDoctor, t => !t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any())
.WhereIf(inQuery.IsAssignConfirmed != null && inQuery.IsAssignConfirmed == true && inQuery.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).All(u => u.IsConfirmed))
.WhereIf(inQuery.IsAssignConfirmed != null && inQuery.IsAssignConfirmed == true && inQuery.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).All(u => u.IsConfirmed))
.WhereIf(querySubjectAssign.IsAssignConfirmed != null && querySubjectAssign.IsAssignConfirmed == true && querySubjectAssign.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).All(u => u.IsConfirmed))
.WhereIf(querySubjectAssign.IsAssignConfirmed != null && querySubjectAssign.IsAssignConfirmed == true && querySubjectAssign.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).All(u => u.IsConfirmed))
.WhereIf(inQuery.IsAssignConfirmed != null && inQuery.IsAssignConfirmed == false && inQuery.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any(u => u.IsConfirmed == false))
.WhereIf(inQuery.IsAssignConfirmed != null && inQuery.IsAssignConfirmed == false && inQuery.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any(u => u.IsConfirmed == false))
.WhereIf(querySubjectAssign.IsAssignConfirmed != null && querySubjectAssign.IsAssignConfirmed == false && querySubjectAssign.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any(u => u.IsConfirmed == false))
.WhereIf(querySubjectAssign.IsAssignConfirmed != null && querySubjectAssign.IsAssignConfirmed == false && querySubjectAssign.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any(u => u.IsConfirmed == false))
.WhereIf(inQuery.DoctorUserId != null && inQuery.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any(t => t.DoctorUserId == inQuery.DoctorUserId))
.WhereIf(inQuery.DoctorUserId != null && inQuery.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any(t => t.DoctorUserId == inQuery.DoctorUserId))
.ProjectTo<SubjectAssignView>(_mapper.ConfigurationProvider, new { isJudgeDoctor = inQuery.IsJudgeDoctor });
.WhereIf(querySubjectAssign.DoctorUserId != null && querySubjectAssign.IsJudgeDoctor == false, t => t.SubjectDoctorList.Where(t => t.ArmEnum != Arm.JudgeArm).Any(t => t.DoctorUserId == querySubjectAssign.DoctorUserId))
.WhereIf(querySubjectAssign.DoctorUserId != null && querySubjectAssign.IsJudgeDoctor, t => t.SubjectDoctorList.Where(t => t.ArmEnum == Arm.JudgeArm).Any(t => t.DoctorUserId == querySubjectAssign.DoctorUserId))
.ProjectTo<SubjectAssignView>(_mapper.ConfigurationProvider, new { isJudgeDoctor = querySubjectAssign.IsJudgeDoctor });
var pageList = await subjectQuery.ToPagedListAsync(inQuery);
var pageList = await subjectQuery.ToPagedListAsync(querySubjectAssign.PageIndex, querySubjectAssign.PageSize, string.IsNullOrWhiteSpace(querySubjectAssign.SortField) ? nameof(querySubjectAssign.SubjectId) : querySubjectAssign.SortField, querySubjectAssign.Asc);
return pageList;
}
@@ -645,43 +670,43 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// 访视任务
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <param name="_visitTaskCommonService"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<VisitTaskView>> GetVisitTaskList(VisitTaskQuery inQuery, [FromServices] IVisitTaskHelpeService _visitTaskCommonService)
public async Task<PageOutput<VisitTaskView>> GetVisitTaskList(VisitTaskQuery queryVisitTask, [FromServices] IVisitTaskHelpeService _visitTaskCommonService)
{
//以前访视未产生任务的,在查询这里要产生
var svIdList = await _subjectVisitRepository.Where(t => t.TrialId == inQuery.TrialId && t.CheckState == CheckStateEnum.CVPassed && t.IsVisitTaskGenerated == false).Select(t => t.Id).ToListAsync();
var svIdList = await _subjectVisitRepository.Where(t => t.TrialId == queryVisitTask.TrialId && t.CheckState == CheckStateEnum.CVPassed && t.IsVisitTaskGenerated == false).Select(t => t.Id).ToListAsync();
//之前没有生成任务的逻辑 但是现在加了,任务要自动生成
await _visitTaskCommonService.GenerateVisitTaskAsync(inQuery.TrialId, svIdList);
await _visitTaskCommonService.GenerateVisitTaskAsync(queryVisitTask.TrialId, svIdList);
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.ReadingCategory == null, t => t.ReadingCategory != ReadingCategory.Judge)
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId && t.IsAnalysisCreate == false)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.ReadingCategory == null, t => t.ReadingCategory != ReadingCategory.Judge)
.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
.WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.TaskName.Contains(queryVisitTask.TaskName) || t.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.Subject.Code.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.ProjectTo<VisitTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
//var trialTaskConfig = _trialRepository.Where(t => t.Id == queryVisitTask.TrialId).ProjectTo<TrialTaskConfigView>(_mapper.ConfigurationProvider).FirstOrDefault();
return pageList;
@@ -692,35 +717,35 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// 裁判任务
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<JudgeVisitTaskView>/*, object)*/> GetJudgeVisitTaskList(VisitTaskQuery inQuery)
public async Task<PageOutput<JudgeVisitTaskView>/*, object)*/> GetJudgeVisitTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false)
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId && t.IsAnalysisCreate == false)
.Where(t => t.ReadingCategory == ReadingCategory.Judge)
.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.Subject.Code.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.TaskName.Contains(queryVisitTask.TaskName) || t.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.ProjectTo<JudgeVisitTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTaskView.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
return pageList;
//var trialTaskConfig = _trialRepository.Where(t => t.Id == queryVisitTask.TrialId).ProjectTo<TrialTaskConfig>(_mapper.ConfigurationProvider).FirstOrDefault();
@@ -732,45 +757,45 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// PM阅片跟踪
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<IResponseOutput<PageOutput<ReadingTaskView>>> GetReadingTaskList(VisitTaskQuery inQuery)
public async Task<IResponseOutput<PageOutput<ReadingTaskView>>> GetReadingTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId && t.IsAnalysisCreate == false)
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId && t.IsAnalysisCreate == false)
//.Where(t => t.IsAnalysisCreate == false && t.DoctorUserId != null)
.WhereIf(inQuery.IsEffect == true, t => t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze)
.WhereIf(inQuery.IsEffect == false, t => t.TaskState == TaskState.Adbandon || t.TaskState == TaskState.HaveReturned)
.WhereIf(queryVisitTask.IsEffect == true, t => t.TaskState == TaskState.Effect || t.TaskState == TaskState.Freeze)
.WhereIf(queryVisitTask.IsEffect == false, t => t.TaskState == TaskState.Adbandon || t.TaskState == TaskState.HaveReturned)
.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
.WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.ReadingTaskState != null, t => t.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(inQuery.ReReadingApplyState != null, t => t.ReReadingApplyState == inQuery.ReReadingApplyState)
.WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(queryVisitTask.ReReadingApplyState != null, t => t.ReReadingApplyState == queryVisitTask.ReReadingApplyState)
.WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.Complete, t => t.IsClinicalDataSign && t.IsNeedClinicalDataSign == true)
.WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NotComplete, t => t.IsClinicalDataSign == false && t.IsNeedClinicalDataSign == true)
.WhereIf(inQuery.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NA, t => t.IsNeedClinicalDataSign == false)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.Subject.Code.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate)
.WhereIf(inQuery.BeginSignTime != null, t => t.SignTime > inQuery.BeginSignTime)
.WhereIf(inQuery.EndSignTime != null, t => t.SignTime < inQuery.EndSignTime)
.WhereIf(queryVisitTask.CompleteClinicalDataEnum == CompleteClinicalDataEnum.Complete, t => t.IsClinicalDataSign && t.IsNeedClinicalDataSign == true)
.WhereIf(queryVisitTask.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NotComplete, t => t.IsClinicalDataSign == false && t.IsNeedClinicalDataSign == true)
.WhereIf(queryVisitTask.CompleteClinicalDataEnum == CompleteClinicalDataEnum.NA, t => t.IsNeedClinicalDataSign == false)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.TaskName.Contains(queryVisitTask.TaskName) || t.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.AllocateTime < queryVisitTask.EndAllocateDate)
.WhereIf(queryVisitTask.BeginSignTime != null, t => t.SignTime > queryVisitTask.BeginSignTime)
.WhereIf(queryVisitTask.EndSignTime != null, t => t.SignTime < queryVisitTask.EndSignTime)
.ProjectTo<ReadingTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
var trialTaskConfig = _trialRepository.Where(t => t.Id == inQuery.TrialId).ProjectTo<TrialUrgentConfig>(_mapper.ConfigurationProvider).FirstOrDefault();
var trialTaskConfig = _trialRepository.Where(t => t.Id == queryVisitTask.TrialId).ProjectTo<TrialUrgentConfig>(_mapper.ConfigurationProvider).FirstOrDefault();
return ResponseOutput.Ok(pageList, trialTaskConfig);
}
@@ -779,43 +804,43 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// PM 重阅追踪
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<ReReadingTaskView>> GetReReadingTaskList(VisitTaskQuery inQuery)
public async Task<PageOutput<ReReadingTaskView>> GetReReadingTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskReReadingRepository
.Where(t => t.OriginalReReadingTask.TrialId == inQuery.TrialId /*&& t.OriginalReReadingTask.IsAnalysisCreate == false*/)
.WhereIf(inQuery.RootReReadingTaskId != null, t => t.RootReReadingTaskId == inQuery.RootReReadingTaskId || t.OriginalReReadingTaskId == inQuery.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(inQuery.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(inQuery.TaskCode!))
.WhereIf(inQuery.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.TaskState != null, t => t.OriginalReReadingTask.TaskState == inQuery.TaskState)
.WhereIf(inQuery.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == inQuery.ReReadingApplyState)
.WhereIf(inQuery.RequestReReadingType != null, t => t.RequestReReadingType == inQuery.RequestReReadingType)
.WhereIf(inQuery.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ArmEnum != null, t => t.OriginalReReadingTask.ArmEnum == inQuery.ArmEnum)
.WhereIf(inQuery.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(inQuery.ReadingCategory != null, t => t.OriginalReReadingTask.ReadingCategory == inQuery.ReadingCategory)
.Where(t => t.OriginalReReadingTask.TrialId == queryVisitTask.TrialId /*&& t.OriginalReReadingTask.IsAnalysisCreate == false*/)
.WhereIf(queryVisitTask.RootReReadingTaskId != null, t => t.RootReReadingTaskId == queryVisitTask.RootReReadingTaskId || t.OriginalReReadingTaskId == queryVisitTask.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!))
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.TaskState != null, t => t.OriginalReReadingTask.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == queryVisitTask.ReReadingApplyState)
.WhereIf(queryVisitTask.RequestReReadingType != null, t => t.RequestReReadingType == queryVisitTask.RequestReReadingType)
.WhereIf(queryVisitTask.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ArmEnum != null, t => t.OriginalReReadingTask.ArmEnum == queryVisitTask.ArmEnum)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.OriginalReReadingTask.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(!string.IsNullOrEmpty(inQuery.RequestReReadingReason), t => t.RequestReReadingReason.Contains(inQuery.RequestReReadingReason))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.RequestReReadingReason), t => t.RequestReReadingReason.Contains(queryVisitTask.RequestReReadingReason))
.WhereIf(inQuery.RequestReReadingResultEnum != null, t => t.RequestReReadingResultEnum == inQuery.RequestReReadingResultEnum)
.WhereIf(queryVisitTask.RequestReReadingResultEnum != null, t => t.RequestReReadingResultEnum == queryVisitTask.RequestReReadingResultEnum)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(inQuery.TaskName) || t.OriginalReReadingTask.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => ((t.OriginalReReadingTask.Subject.Code.Contains(inQuery.SubjectCode) || t.OriginalReReadingTask.Subject.MedicalNo.Contains(inQuery.SubjectCode)) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(queryVisitTask.TaskName) || t.OriginalReReadingTask.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => ((t.OriginalReReadingTask.Subject.Code.Contains(queryVisitTask.SubjectCode) || t.OriginalReReadingTask.Subject.MedicalNo.Contains(queryVisitTask.SubjectCode)) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.WhereIf(inQuery.BeginRequestReReadingTime != null, t => t.RequestReReadingTime >= inQuery.BeginRequestReReadingTime)
.WhereIf(inQuery.EndRequestReReadingTime != null, t => t.RequestReReadingTime <= inQuery.EndRequestReReadingTime!.Value.AddDays(1))
.WhereIf(queryVisitTask.BeginRequestReReadingTime != null, t => t.RequestReReadingTime >= queryVisitTask.BeginRequestReReadingTime)
.WhereIf(queryVisitTask.EndRequestReReadingTime != null, t => t.RequestReReadingTime <= queryVisitTask.EndRequestReReadingTime!.Value.AddDays(1))
.ProjectTo<ReReadingTaskView>(_mapper.ConfigurationProvider);
@@ -829,7 +854,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
return pageList;
}
@@ -838,43 +863,43 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// 获取IR 重阅影像阅片列表
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<ReReadingTaskView>> GetIRReReadingTaskList(VisitTaskQuery inQuery)
public async Task<PageOutput<ReReadingTaskView>> GetIRReReadingTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskReReadingRepository
.Where(t => t.RequestReReadingType == RequestReReadingType.DocotorApply)
.Where(t => t.OriginalReReadingTask.DoctorUserId == _userInfo.Id)
.Where(t => t.OriginalReReadingTask.TrialId == inQuery.TrialId)
.WhereIf(inQuery.RequestReReadingResultEnum != null, t => t.RequestReReadingResultEnum == inQuery.RequestReReadingResultEnum)
.WhereIf(inQuery.RootReReadingTaskId != null, t => t.RootReReadingTaskId == inQuery.RootReReadingTaskId || t.OriginalReReadingTaskId == inQuery.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(inQuery.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(inQuery.TaskCode!))
.WhereIf(inQuery.TaskState != null, t => t.OriginalReReadingTask.TaskState == inQuery.TaskState)
.WhereIf(inQuery.ReadingCategory != null, t => t.OriginalReReadingTask.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == inQuery.ReReadingApplyState)
.WhereIf(inQuery.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.Where(t => t.OriginalReReadingTask.TrialId == queryVisitTask.TrialId)
.WhereIf(queryVisitTask.RequestReReadingResultEnum != null, t => t.RequestReReadingResultEnum == queryVisitTask.RequestReReadingResultEnum)
.WhereIf(queryVisitTask.RootReReadingTaskId != null, t => t.RootReReadingTaskId == queryVisitTask.RootReReadingTaskId || t.OriginalReReadingTaskId == queryVisitTask.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!))
.WhereIf(queryVisitTask.TaskState != null, t => t.OriginalReReadingTask.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.OriginalReReadingTask.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.ReReadingApplyState != null, t => t.OriginalReReadingTask.ReReadingApplyState == queryVisitTask.ReReadingApplyState)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(inQuery.TaskName) || t.NewReReadingTask.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.OriginalReReadingTask.Subject.Code.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(queryVisitTask.TaskName) || t.NewReReadingTask.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.OriginalReReadingTask.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.ProjectTo<ReReadingTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.IsUrgent) + " desc", nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.SubjectId), nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
return pageList;
}
@@ -882,34 +907,34 @@ namespace IRaCIS.Core.Application.Service.Allocation
//SPM 能看到项目组申请记录
[HttpPost]
public async Task<PageOutput<ReReadingTaskView>> GetSPMReReadingTaskList(VisitTaskQuery inQuery)
public async Task<PageOutput<ReReadingTaskView>> GetSPMReReadingTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskReReadingRepository.Where(t => t.RequestReReadingType == RequestReReadingType.TrialGroupApply && t.OriginalReReadingTask.IsAnalysisCreate == false)
.Where(t => t.OriginalReReadingTask.TrialId == inQuery.TrialId)
.WhereIf(inQuery.RootReReadingTaskId != null, t => t.RootReReadingTaskId == inQuery.RootReReadingTaskId || t.OriginalReReadingTaskId == inQuery.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(inQuery.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(inQuery.TaskCode!))
.WhereIf(inQuery.TaskState != null, t => t.OriginalReReadingTask.TaskState == inQuery.TaskState)
.WhereIf(inQuery.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == inQuery.DoctorUserId)
.WhereIf(inQuery.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == inQuery.ReadingTaskState)
.WhereIf(inQuery.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.Where(t => t.OriginalReReadingTask.TrialId == queryVisitTask.TrialId)
.WhereIf(queryVisitTask.RootReReadingTaskId != null, t => t.RootReReadingTaskId == queryVisitTask.RootReReadingTaskId || t.OriginalReReadingTaskId == queryVisitTask.RootReReadingTaskId)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskCode), t => t.OriginalReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!) || t.RootReReadingTask.TaskCode.Contains(queryVisitTask.TaskCode!))
.WhereIf(queryVisitTask.TaskState != null, t => t.OriginalReReadingTask.TaskState == queryVisitTask.TaskState)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.OriginalReReadingTask.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.OriginalReReadingTask.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.OriginalReReadingTask.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.DoctorUserId != null, t => t.OriginalReReadingTask.DoctorUserId == queryVisitTask.DoctorUserId)
.WhereIf(queryVisitTask.ReadingTaskState != null, t => t.OriginalReReadingTask.ReadingTaskState == queryVisitTask.ReadingTaskState)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.OriginalReReadingTask.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.OriginalReReadingTask.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.OriginalReReadingTask.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate) || (t.OriginalReReadingTask.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.OriginalReReadingTask.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(inQuery.TaskName) || t.NewReReadingTask.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.OriginalReReadingTask.Subject.Code.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.OriginalReReadingTask.TaskName.Contains(queryVisitTask.TaskName) || t.NewReReadingTask.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.OriginalReReadingTask.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate == false) || (t.OriginalReReadingTask.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.OriginalReReadingTask.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.OriginalReReadingTask.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.ProjectTo<ReReadingTaskView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(ReReadingTaskView.RequestReReadingTime) };
//var defalutSortArray = new string[] { nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.IsUrgent) + " desc", nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.SubjectId), nameof(ReReadingTaskView.OriginalReReadingTask) + "." + nameof(ReReadingTaskView.OriginalReReadingTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
return pageList;
}
@@ -1206,7 +1231,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
.ToList()
}).Where(x => x.UnReadCanReadTaskCount > 0);
var pageList = await visitTaskQuery.ToPagedListAsync(inQuery, nameof(IRUnReadSubjectView.UnReadCanReadTaskCount) );
var pageList = await visitTaskQuery.ToPagedListAsync(inQuery.PageIndex, inQuery.PageSize, string.IsNullOrWhiteSpace(inQuery.SortField) ? nameof(IRUnReadSubjectView.UnReadCanReadTaskCount) : inQuery.SortField, inQuery.Asc);
return pageList;
}
@@ -1217,36 +1242,36 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <summary>
/// IR 已阅片任务
/// </summary>
/// <param name="inQuery"></param>
/// <param name="queryVisitTask"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<IRHaveReadView>> GetIRHaveReadTaskList(VisitTaskQuery inQuery)
public async Task<PageOutput<IRHaveReadView>> GetIRHaveReadTaskList(VisitTaskQuery queryVisitTask)
{
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == inQuery.TrialId)
var visitTaskQueryable = _visitTaskRepository.Where(t => t.TrialId == queryVisitTask.TrialId)
.Where(t => t.DoctorUserId == _userInfo.Id && t.ReadingTaskState == ReadingTaskState.HaveSigned)//该医生 已经签名的数据
.WhereIf(inQuery.TrialSiteId != null, t => t.Subject.TrialSiteId == inQuery.TrialSiteId)
.WhereIf(inQuery.SubjectId != null, t => t.SubjectId == inQuery.SubjectId)
.WhereIf(inQuery.IsUrgent != null, t => t.IsUrgent == inQuery.IsUrgent)
.WhereIf(inQuery.ReadingCategory != null, t => t.ReadingCategory == inQuery.ReadingCategory)
.WhereIf(inQuery.TaskAllocationState != null, t => t.TaskAllocationState == inQuery.TaskAllocationState)
.WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)
.WhereIf(queryVisitTask.TrialSiteId != null, t => t.Subject.TrialSiteId == queryVisitTask.TrialSiteId)
.WhereIf(queryVisitTask.SubjectId != null, t => t.SubjectId == queryVisitTask.SubjectId)
.WhereIf(queryVisitTask.IsUrgent != null, t => t.IsUrgent == queryVisitTask.IsUrgent)
.WhereIf(queryVisitTask.ReadingCategory != null, t => t.ReadingCategory == queryVisitTask.ReadingCategory)
.WhereIf(queryVisitTask.TaskAllocationState != null, t => t.TaskAllocationState == queryVisitTask.TaskAllocationState)
.WhereIf(queryVisitTask.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == queryVisitTask.TrialReadingCriterionId)
.WhereIf(inQuery.TaskState != null, t => t.TaskState == inQuery.TaskState)
.WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(inQuery.TaskName), t => t.TaskName.Contains(inQuery.TaskName) || t.TaskBlindName.Contains(inQuery.TaskName))
.WhereIf(!string.IsNullOrEmpty(inQuery.SubjectCode), t => (t.Subject.Code.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(inQuery.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(inQuery.BeginAllocateDate != null, t => t.AllocateTime > inQuery.BeginAllocateDate)
.WhereIf(inQuery.EndAllocateDate != null, t => t.AllocateTime < inQuery.EndAllocateDate!.Value.AddDays(1))
.WhereIf(queryVisitTask.TaskState != null, t => t.TaskState == queryVisitTask.TaskState)
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TrialSiteCode), t => (t.BlindTrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate) || (t.Subject.TrialSite.TrialSiteCode.Contains(queryVisitTask.TrialSiteCode!) && t.IsAnalysisCreate == false))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.TaskName), t => t.TaskName.Contains(queryVisitTask.TaskName) || t.TaskBlindName.Contains(queryVisitTask.TaskName))
.WhereIf(!string.IsNullOrEmpty(queryVisitTask.SubjectCode), t => (t.Subject.Code.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate == false) || (t.BlindSubjectCode.Contains(queryVisitTask.SubjectCode) && t.IsAnalysisCreate))
.WhereIf(queryVisitTask.BeginAllocateDate != null, t => t.AllocateTime > queryVisitTask.BeginAllocateDate)
.WhereIf(queryVisitTask.EndAllocateDate != null, t => t.AllocateTime < queryVisitTask.EndAllocateDate!.Value.AddDays(1))
.ProjectTo<IRHaveReadView>(_mapper.ConfigurationProvider);
var defalutSortArray = new string[] { nameof(VisitTask.IsUrgent) + " desc", nameof(VisitTask.SubjectId), nameof(VisitTask.VisitTaskNum) };
var pageList = await visitTaskQueryable.ToPagedListAsync(inQuery, defalutSortArray);
var pageList = await visitTaskQueryable.ToPagedListAsync(queryVisitTask.PageIndex, queryVisitTask.PageSize, queryVisitTask.SortField, queryVisitTask.Asc, string.IsNullOrWhiteSpace(queryVisitTask.SortField), defalutSortArray);
return pageList;
}
@@ -1349,7 +1374,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
if (IsPMOrAPm())
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager)
{
if (criterionConfig.IsAutoCreate == false)
{
@@ -1439,7 +1464,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
throw new BusinessValidationFailedException(_localizer["VisitTask_LastReading"]);
}
if (task.ReadingCategory == ReadingCategory.Oncology && await _visitTaskRepository.AnyAsync(filterExpression.And(t => t.ReadingCategory == ReadingCategory.Oncology && t.ReadingTaskState == ReadingTaskState.HaveSigned)))
if (task.ReadingCategory == ReadingCategory.Oncology && await _visitTaskRepository.AnyAsync(filterExpression.And(t => t.ReadingCategory == ReadingCategory.Oncology && t.ReadingTaskState==ReadingTaskState.HaveSigned)))
{
//---有序阅片,只允许申请该受试者阅片人最后一次完成肿瘤学任务重阅
throw new BusinessValidationFailedException(_localizer["VisitTask_LastOncologistRecheck"]);
@@ -1460,8 +1485,8 @@ namespace IRaCIS.Core.Application.Service.Allocation
var originalTask = pmApply.OriginalReReadingTask;
//PM 无序影响列表
if (await _visitTaskRepository.Where(t => t.TrialId == originalTask.TrialId && t.SubjectId == originalTask.SubjectId && t.TaskState == TaskState.Effect && t.TaskAllocationState == TaskAllocationState.Allocated && t.IsAnalysisCreate == false && t.TrialReadingCriterionId == originalTask.TrialReadingCriterionId)
.Where(t => t.Id == originalTask.Id || t.Id == originalTask.JudgeVisitTaskId)
if (await _visitTaskRepository.Where(t => t.TrialId == originalTask.TrialId && t.SubjectId == originalTask.SubjectId && t.TaskState == TaskState.Effect && t.TaskAllocationState == TaskAllocationState.Allocated && t.IsAnalysisCreate == false && t.TrialReadingCriterionId == originalTask.TrialReadingCriterionId )
.Where(t=>t.Id==originalTask.Id||t.Id==originalTask.JudgeVisitTaskId)
.AnyAsync(t => t.VisitTaskNum == task.VisitTaskNum))
{
//---当前为无序阅片,影像存在问题,项目组已申请回退,暂不能申请重阅
@@ -1563,9 +1588,9 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <returns></returns>
private async Task PMReReadingConfirmOrBackInfluenceAnalysisAsync(Guid subjectId)
{
if (await _visitTaskRepository.AnyAsync(t => t.IsAnalysisCreate && t.SubjectId == subjectId))
if (await _repository.AnyAsync<VisitTask>(t => t.IsAnalysisCreate && t.SubjectId == subjectId))
{
await _subjectRepository.UpdatePartialFromQueryAsync(t => t.Id == subjectId, u => new Subject() { IsReReadingOrBackInfluenceAnalysis = true });
await _repository.UpdatePartialFromQueryAsync<Subject>(t => t.Id == subjectId, u => new Subject() { IsReReadingOrBackInfluenceAnalysis = true });
}
@@ -1605,7 +1630,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
await _visitTaskReReadingRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.Id, u => new VisitTaskReReading() { RequestReReadingConfirmUserId = _userInfo.Id, RequestReReadingResultEnum = RequestReReadingResult.Invalid });
//---当前申请重阅任务的状态,已被其他任务重阅已影响,不允许对该状态下的任务进行重阅同意与否操作
return ResponseOutput.Ok(string.Empty, msg: _localizer["VisitTask_ReapplyStatusConflict"]);
return ResponseOutput.Ok(string.Empty, msg:_localizer["VisitTask_ReapplyStatusConflict"]);
}
@@ -1632,7 +1657,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
if (criterionConfig.CriterionType == CriterionType.RECIST1Point1 && criterionConfig.IsAdditionalAssessment)
{
// PM申请 SPM / CPM审批
if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.TrialGroupApply && (IsSpmOrCPM()))
if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.TrialGroupApply && (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM))
{
filterExpression = filterExpression.And(t => t.TrialReadingCriterionId == origenalTask.TrialReadingCriterionId || t.TrialReadingCriterion.CriterionType == CriterionType.RECIST1Pointt1_MB);
}
@@ -1641,7 +1666,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
{
// 1.1 基线任务影响BM任务
if ((IsPMOrAPm()) && _subjectVisitRepository.Any(t => t.Id == origenalTask.SourceSubjectVisitId && t.IsBaseLine == true))
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager && _subjectVisitRepository.Any(t => t.Id == origenalTask.SourceSubjectVisitId && t.IsBaseLine == true))
{
isIR1Point1AdditionalAssessmentBaseline = true;
@@ -1664,7 +1689,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
if (agreeReReadingCommand.RequestReReadingResultEnum == RequestReReadingResult.Agree)
{
//PM申请 SPM / CPM审批 回退访视,因此这里不生成访视任务 影响多个标准的任务
if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.TrialGroupApply && (IsSpmOrCPM()))
if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.TrialGroupApply && (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM))
{
// 不管有序 无序 都会 回退访视
@@ -1784,7 +1809,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
}
//IR申请 PM 审批 注意这里有一致性分析的申请同意 不会回退访视,在此要生成影响的访视任务
else if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.DocotorApply && (IsPMOrAPm() || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.AIR))
else if (visitTaskReReadingAppply.RequestReReadingType == RequestReReadingType.DocotorApply && (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.AIR))
{
@@ -2160,7 +2185,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
{
//自定义
var readingCustomTagList = _readingCustomTagRepository.Where(t => t.VisitTaskId == origenalTask.Id).ToList();
var readingCustomTagList = _repository.Where<ReadingCustomTag>(t => t.VisitTaskId == origenalTask.Id).ToList();
foreach (var item in readingCustomTagList)
{
@@ -2168,10 +2193,10 @@ namespace IRaCIS.Core.Application.Service.Allocation
item.VisitTaskId = newTask.Id;
}
_ = _readingCustomTagRepository.AddRangeAsync(readingCustomTagList).Result;
_ = _repository.AddRangeAsync(readingCustomTagList).Result;
var readingTaskQuestionMarkList = _readingTaskQuestionMarkRepository.Where(t => t.VisitTaskId == origenalTask.Id).ToList();
var readingTaskQuestionMarkList = _repository.Where<ReadingTaskQuestionMark>(t => t.VisitTaskId == origenalTask.Id).ToList();
foreach (var item in readingTaskQuestionMarkList)
{
@@ -2179,21 +2204,21 @@ namespace IRaCIS.Core.Application.Service.Allocation
item.VisitTaskId = newTask.Id;
}
_ = _readingTaskQuestionMarkRepository.AddRangeAsync(readingTaskQuestionMarkList).Result;
_ = _repository.AddRangeAsync(readingTaskQuestionMarkList).Result;
var readingTaskQuestionAnswerList = _readingTaskQuestionAnswerRepository.Where(t => t.VisitTaskId == origenalTask.Id).ToList();
var readingTaskQuestionAnswerList = _repository.Where<ReadingTaskQuestionAnswer>(t => t.VisitTaskId == origenalTask.Id).ToList();
foreach (var item in readingTaskQuestionAnswerList)
{
item.Id = Guid.Empty;
item.VisitTaskId = newTask.Id;
}
_ = _readingTaskQuestionAnswerRepository.AddRangeAsync(readingTaskQuestionAnswerList).Result;
_ = _repository.AddRangeAsync(readingTaskQuestionAnswerList).Result;
//ReadingTableAnswerRowInfo ReadingTableQuestionAnswer 一起加
var readingTableAnswerRowInfoList = _readingTableAnswerRowInfoRepository.Where(t => t.VisitTaskId == origenalTask.Id).Include(t => t.LesionAnswerList).ToList();
var readingTableAnswerRowInfoList = _repository.Where<ReadingTableAnswerRowInfo>(t => t.VisitTaskId == origenalTask.Id).Include(t => t.LesionAnswerList).ToList();
foreach (var item in readingTableAnswerRowInfoList)
{
@@ -2216,7 +2241,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
}
}
_ = _readingTableAnswerRowInfoRepository.AddRangeAsync(readingTableAnswerRowInfoList).Result;
_ = _repository.AddRangeAsync(readingTableAnswerRowInfoList).Result;
@@ -2289,7 +2314,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
//PM 才允许操作
if (IsPMOrAPm())
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager)
{
#region
@@ -2545,25 +2570,15 @@ namespace IRaCIS.Core.Application.Service.Allocation
//await _repository.AddAsync(new CheckChallengeDialog() { SubjectVisitId = subjectVisitId, TalkContent = "PM/APM同意一致性核查回退。", UserTypeEnum = (UserTypeEnum)_userInfo.UserTypeEnumInt });
await _trialQCQuestionAnswerRepository.BatchDeleteNoTrackingAsync(t => t.SubjectVisitId == subjectVisitId);
await _dicomInstanceRepository.BatchDeleteNoTrackingAsync(t => t.DicomSerie.IsDeleted);
await _dicomSeriesRepository.BatchDeleteNoTrackingAsync(t => t.IsDeleted);
await _repository.BatchDeleteAsync<TrialQCQuestionAnswer>(t => t.SubjectVisitId == subjectVisitId);
await _repository.BatchDeleteAsync<DicomInstance>(t => t.DicomSerie.IsDeleted);
await _repository.BatchDeleteAsync<DicomSeries>(t => t.IsDeleted);
var success = await _subjectVisitRepository.SaveChangesAsync();
}
private bool IsPMOrAPm()
{
return _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM;
}
private bool IsSpmOrCPM()
{
return _userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM;
}
/// <summary>
/// 影响提示列表 重阅仅仅针对已完成的任务申请 退回针对的是未完成的(退回仅仅针对是访视类型的)
/// </summary>
@@ -2595,12 +2610,12 @@ namespace IRaCIS.Core.Application.Service.Allocation
{
// IR 申请 PM 同意
if (((IsPMOrAPm() && applyId != null && await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && t.CreateUser.UserTypeEnum == UserTypeEnum.IndependentReviewer))
if (((_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager && applyId != null && await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && t.CreateUser.UserTypeEnum == UserTypeEnum.IndependentReviewer))
|| (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer && applyId == null)))
{
// 1.1 基线任务影响BM任务
if (IsPMOrAPm() && _subjectVisitRepository.Any(t => t.Id == filterObj.SourceSubjectVisitId && t.IsBaseLine == true))
if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager && _subjectVisitRepository.Any(t => t.Id == filterObj.SourceSubjectVisitId && t.IsBaseLine == true))
{
isIR1Point1AdditionalAssessmentBaseline = true;
@@ -2638,7 +2653,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
//IR 申请 PM 同意 仅仅影响自己
if ((IsPMOrAPm() && applyId != null && await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && t.CreateUser.UserTypeEnum == UserTypeEnum.IndependentReviewer))
if ((_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager && applyId != null && await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && t.CreateUser.UserTypeEnum == UserTypeEnum.IndependentReviewer))
|| (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer && applyId == null))
{
@@ -2756,9 +2771,8 @@ namespace IRaCIS.Core.Application.Service.Allocation
}
//PM 影响所有阅片人 仅仅针对访视 SPM CPM 调用
else if (((IsSpmOrCPM()) && applyId != null &&
await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && (t.CreateUser.UserTypeEnum == UserTypeEnum.ProjectManager || t.CreateUser.UserTypeEnum == UserTypeEnum.APM)) && filterObj.IsAnalysisCreate == false && filterObj.ReadingCategory == ReadingCategory.Visit)
|| (IsPMOrAPm() && applyId == null))
else if (((_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM) && applyId != null && await _visitTaskReReadingRepository.AnyAsync(t => t.Id == applyId && t.CreateUser.UserTypeEnum == UserTypeEnum.ProjectManager) && filterObj.IsAnalysisCreate == false && filterObj.ReadingCategory == ReadingCategory.Visit)
|| (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager && applyId == null))
{
@@ -2821,7 +2835,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
throw new BusinessValidationFailedException(_localizer["VisitTask_NoConsistencyReturn"]);
}
if (filterObj.ReadingCategory == ReadingCategory.Visit && IsPMOrAPm())
if (filterObj.ReadingCategory == ReadingCategory.Visit && _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager)
{
//有序
if (criterionConfig.IsReadingTaskViewInOrder == ReadingOrder.InOrder)
@@ -2880,7 +2894,7 @@ namespace IRaCIS.Core.Application.Service.Allocation
/// <returns></returns>
public async Task<List<InfluenceTaskInfo>> GetInfluencedTaskList(Guid taskId)
{
var list = await _taskInfluenceRepository.Where(t => t.OriginalTaskId == taskId)/*.Select(t => t.InfluenceTask)*/.ProjectTo<InfluenceTaskInfo>(_mapper.ConfigurationProvider).ToListAsync();
var list = await _repository.Where<TaskInfluence>(t => t.OriginalTaskId == taskId)/*.Select(t => t.InfluenceTask)*/.ProjectTo<InfluenceTaskInfo>(_mapper.ConfigurationProvider).ToListAsync();
return list;
}
@@ -104,7 +104,7 @@ namespace IRaCIS.Core.Application.Service
CreateMap<SubjectUser, SubjectUserDTO>().IncludeBase<SubjectUser, SubjectUserView>()
.ForMember(o => o.IsHaveReading, t => t.MapFrom(u => u.Subject.SubjectVisitTaskList.Any(t => t.ReadingTaskState != ReadingTaskState.WaitReading && t.TrialReadingCriterionId==u.TrialReadingCriterionId && t.DoctorUserId==u.DoctorUserId && t.TaskState == TaskState.Effect)));
.ForMember(o => o.IsHaveReading, t => t.MapFrom(u => u.Subject.SubjectVisitTaskList.Any(t => t.ReadingTaskState != ReadingTaskState.WaitReading && t.TrialReadingCriterionId==u.TrialReadingCriterionId && t.DoctorUserId==u.DoctorUserId)));
CreateMap<SubjectVisit, VisitGenerataTaskDTO>();
@@ -145,8 +145,7 @@ namespace IRaCIS.Core.Application.Service
.ForMember(o => o.HistoryReadingDoctorUserList, t => t.MapFrom(u => u.JudgeVisitList));
CreateMap<VisitTask, ReadingTaskView>().IncludeBase<VisitTask, VisitTaskView>()
.ForMember(o=>o.IsManualGeneration,t=> t.MapFrom(u => !u.TrialReadingCriterion.IsAutoCreate))
.ForMember(o => o.IsHaveFeedBack, t => t.MapFrom(u => u.UserFeedBackList.Any(t=>t.State==0)))
;
CreateMap<VisitTask, AnalysisTaskView>().IncludeBase<VisitTask, VisitTaskView>()
@@ -239,7 +238,7 @@ namespace IRaCIS.Core.Application.Service
.ForMember(o => o.TrialReadingCriterionName, t => t.MapFrom(u => u.TrialReadingCriterion.CriterionName))
.ForMember(o => o.TrialSiteCode, t => t.MapFrom(u => /*u.IsAnalysisCreate == true ? u.BlindTrialSiteCode :*/ u.Subject.TrialSite.TrialSiteCode))
.ForMember(o => o.SubjectCode, t => t.MapFrom(u => /*u.IsAnalysisCreate == true ? u.BlindSubjectCode :*/ u.Subject.Code))
.ForMember(o => o.GeneratedMedicalReviewCount, t => t.MapFrom(u => u.TaskMedicalReviewList.Count(t=>t.MedicalManagerUserId!=null)))
.ForMember(o => o.GeneratedMedicalReviewCount, t => t.MapFrom(u => u.TaskMedicalReviewList.Count()))
.ForMember(o => o.MedicalNo, t => t.MapFrom(u => u.Subject.MedicalNo))
.ForMember(o => o.IsGeneratedJudge, t => t.MapFrom(u => u.JudgeVisitTaskId != null))
.ForMember(o => o.ReadingDurationTimeSpan, t => t.MapFrom(u => u.SignTime - u.FirstReadingTime))
@@ -319,9 +318,6 @@ namespace IRaCIS.Core.Application.Service
CreateMap<ReadingClinicalData, ReadingConsistentClinicalData>().ReverseMap();
CreateMap<ReadingClinicalDataPDF, ReadingConsistentClinicalDataPDF>().ReverseMap();
}
}
@@ -17,9 +17,17 @@ namespace IRaCIS.Core.Application.Service
/// 系统模板文档配置表
/// </summary>
[ApiExplorerSettings(GroupName = "Common")]
public class CommonDocumentService(IRepository<CommonDocument> _commonDocumentRepository) : BaseService, ICommonDocumentService
public class CommonDocumentService : BaseService, ICommonDocumentService
{
private readonly IRepository<CommonDocument> _commonDocumentRepository;
public CommonDocumentService(IRepository<CommonDocument> commonDocumentRepository)
{
_commonDocumentRepository = commonDocumentRepository;
}
[HttpPost]
public async Task<PageOutput<CommonDocumentView>> GetCommonDocumentList(CommonDocumentQuery queryCommonDocument)
{
@@ -29,11 +37,11 @@ namespace IRaCIS.Core.Application.Service
.WhereIf(queryCommonDocument.CriterionTypeEnum != null, t => t.CriterionTypeEnum == queryCommonDocument.CriterionTypeEnum)
.WhereIf(queryCommonDocument.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == queryCommonDocument.BusinessScenarioEnum)
.WhereIf(!string.IsNullOrEmpty(queryCommonDocument.Code), t => t.Code.Contains(queryCommonDocument.Code))
.WhereIf(!string.IsNullOrEmpty(queryCommonDocument.Name), t => t.Name.Contains(queryCommonDocument.Name))
.WhereIf(string.IsNullOrEmpty(queryCommonDocument.Code), t => t.Code.Contains(queryCommonDocument.Code))
.WhereIf(string.IsNullOrEmpty(queryCommonDocument.Name), t => t.Name.Contains(queryCommonDocument.Name))
.ProjectTo<CommonDocumentView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });
return await commonDocumentQueryable.ToPagedListAsync(queryCommonDocument);
return await commonDocumentQueryable.ToPagedListAsync(queryCommonDocument.PageIndex, queryCommonDocument.PageSize, String.IsNullOrEmpty(queryCommonDocument.SortField) ? nameof(CommonDocument.Code) : queryCommonDocument.SortField, queryCommonDocument.Asc); ;
}
@@ -111,7 +119,7 @@ namespace IRaCIS.Core.Application.Service
var filePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, dbbeforeEntity.Path);
if (File.Exists(filePath) && dbbeforeEntity.Path!=addOrEditCommonDocument.Path)
if (File.Exists(filePath))
{
File.Delete(filePath);
}
@@ -48,8 +48,6 @@ namespace IRaCIS.Core.Application.ViewModel
{
public Guid? Id { get; set; }
public string Name { get; set; } = String.Empty;
public string NameCN { get; set; } = String.Empty;
public string Path { get; set; } = String.Empty;
public string Description { get; set; } = String.Empty;
public bool IsDeleted { get; set; }
@@ -63,8 +63,6 @@ namespace IRaCIS.Core.Application.Contracts
public bool? IsDistinguishCriteria { get; set; }
public SysEmailLevel? SystemLevel { get; set; }
}
///<summary> EmailNoticeConfigAddOrEdit 列表查询参数模型</summary>
@@ -128,9 +126,6 @@ namespace IRaCIS.Core.Application.Contracts
public List<UserTypeEnum> ToUserTypeList { get; set; }
public List<UserTypeEnum> CopyUserTypeList { get; set; }
public SysEmailLevel SystemLevel { get; set; }
}
@@ -1,61 +0,0 @@
//--------------------------------------------------------------------
// 此代码由T4模板自动生成 byzhouhang 20210918
// 生成时间 2024-07-02 09:29:36
// 对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//--------------------------------------------------------------------
using System;
using IRaCIS.Core.Domain.Share;
using System.Collections.Generic;
namespace IRaCIS.Core.Application.ViewModel
{
/// <summary> ExploreRecommendView 列表视图模型 </summary>
public class ExploreRecommendView: ExploreRecommendAddOrEdit
{
public DateTime CreateTime { get; set; }
public Guid CreateUserId { get; set; }
public Guid UpdateUserId { get; set; }
public DateTime UpdateTime { get; set; }
public DateTime? DeleteTime { get; set; }
public Guid? DeleteUserId { get; set; }
}
///<summary>ExploreRecommendQuery 列表查询参数模型</summary>
public class ExploreRecommendQuery:PageInput
{
public string? Version { get; set; }
public string? Title { get; set; }
public string? DownloadUrl { get; set; }
public string? FileName { get; set; }
public bool? IsDeleted { get; set; }
}
///<summary> ExploreRecommendAddOrEdit 列表查询参数模型</summary>
public class ExploreRecommendAddOrEdit
{
public Guid? Id { get; set; }
public string ExploreType { get; set; }
public string Version { get; set; }
public string Title { get; set; }
public bool IsDeleted { get; set; }
public string DownloadUrl { get; set; }
public string Path { get; set; }
public string FileName { get; set; }
}
}
@@ -150,11 +150,6 @@ namespace IRaCIS.Core.Application.ViewModel
public DateTime UpdateTime { get; set; }
public Guid UpdateUserId { get; set; }
public string Code { get; set; } = string.Empty;
/// <summary>
/// 字段的英文值
/// </summary>
public string CodeEn { get; set; } = string.Empty;
public Guid? ParentId { get; set; }
public bool IsEnable { get; set; }
public Guid? ModuleTypeId { get; set; }
@@ -225,12 +220,6 @@ namespace IRaCIS.Core.Application.ViewModel
public string ChildDataLabel { get; set; }
/// <summary>
/// 前端渲染数组 数组名 和数组值 英文名称
/// </summary>
public string ChildDataEnLabel { get; set; } = string.Empty;
/// <summary>
/// 子数据Value
/// </summary>
@@ -279,15 +268,6 @@ namespace IRaCIS.Core.Application.ViewModel
public string ForeignKeyText { get; set; } = string.Empty;
/// <summary>
/// 英文的翻译
/// </summary>
public string ForeignKeyEnText { get; set; } = string.Empty;
/// <summary>
/// 接口名
/// </summary>
@@ -17,9 +17,6 @@ namespace IRaCIS.Core.Application.ViewModel
public DateTime UpdateTime { get; set; }
public Guid UpdateUserId { get; set; }
public string Version { get; set; }
}
///<summary>InternationalizationQuery 列表查询参数模型</summary>
@@ -33,10 +30,6 @@ namespace IRaCIS.Core.Application.ViewModel
public string? ValueCN { get; set; }
public string? Module { get; set; }
//关联版本历史记录表Id
public Guid? PublishLogId { get; set; }
}
///<summary> InternationalizationAddOrEdit 列表查询参数模型</summary>
@@ -52,9 +45,6 @@ namespace IRaCIS.Core.Application.ViewModel
public string FrontType { get; set; } = string.Empty;
public int InternationalizationType { get; set; }
public string Module { get; set; } = string.Empty;
//关联版本历史记录表Id
public Guid? PublishLogId { get; set; }
}
public class BatchAddInternationalization
@@ -74,28 +64,16 @@ namespace IRaCIS.Core.Application.ViewModel
public string Value { get; set; } = string.Empty;
public string FrontType { get; set; } = string.Empty;
public string ValueCN { get; set; } = string.Empty;
public string Module { get; set; } = string.Empty;
}
public class BatchAddInternationalizationDto : BatchInternationalizationDto
{
}
public class InternationalizationSimpleDto : BatchInternationalizationDto
public class InternationalizationSimpleDto: BatchInternationalizationDto
{
}
public class BatchUpdateInfoCommand
{
public List<Guid> IdList { get; set; }
public Guid? PublishLogId { get; set; }
public int State { get; set; }
}
}
@@ -26,8 +26,6 @@ namespace IRaCIS.Core.Application.ViewModel
public string? UpdateContent { get; set; }
public int? State { get; set; }
}
///<summary> PublishLogAddOrEdit 列表查询参数模型</summary>
@@ -35,24 +33,9 @@ namespace IRaCIS.Core.Application.ViewModel
{
public Guid? Id { get; set; }
public string Version { get; set; }
public DateTime? PublishTime { get; set; }
public DateTime PublishTime { get; set; }
public string UpdateContent { get; set; }
//0 开发中 ,已发布
public int State { get; set; }
public bool IsCurrentVersion { get; set; }
}
public class PublishVersionSelect
{
public Guid Id { get; set; }
public string Version { get; set; }
public int State { get; set; }
public DateTime? PublishTime { get; set; }
public bool IsCurrentVersion { get; set; }
}
@@ -1,30 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Service.Common
{
/// <summary>
/// 开始时候一些帮助 比如根据配置的字典生成枚举
/// </summary>
/// <param name="_dictionaryRepository"></param>
[ApiExplorerSettings(GroupName = "Common")]
public class DevelopService(IRepository<Dictionary> _dictionaryRepository) : BaseService
{
/// <summary>
/// 根据配置的字典名生成后端枚举
/// </summary>
/// <param name="dicName"></param>
/// <returns></returns>
[HttpPost]
public async Task<IResponseOutput> BackDicGenerateEnum(string dicName)
{
return ResponseOutput.Ok();
}
}
}
@@ -13,21 +13,48 @@ namespace IRaCIS.Application.Services
/// </summary>
[ApiExplorerSettings(GroupName = "Common")]
public class DictionaryService (IRepository<Dictionary> _dicRepository,
IRepository<DoctorDictionary> _doctorDictionaryRepository,
IRepository<TrialDictionary> _trialDictionaryRepository,
IRepository<Doctor> _doctorRepository,
IRepository<Trial> _trialRepository,
IRepository<SystemCriterionDictionaryCode> _systemCriterionDictionaryCodeRepository,
IRepository<TrialCriterionDictionaryCode> _trialCriterionDictionaryCodeRepository,
IRepository<ReadingTrialCriterionDictionary> _readingTrialCriterionDictionaryRepository,
IRepository<ReadingSystemCriterionDictionary> _readingSystemCriterionDictionaryRepository,
IRepository<ReadingSystemCriterionDictionary> _readingCriterionDictionaryRepository,
IRepository<ReadingQuestionCriterionSystem> _readingQuestionCriterionSystem,
IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrial
) : BaseService, IDictionaryService
public class DictionaryService : BaseService, IDictionaryService
{
private readonly IRepository<Dictionary> _dicRepository;
private readonly IRepository<DoctorDictionary> _doctorDictionaryRepository;
private readonly IRepository<TrialDictionary> _trialDictionaryRepository;
private readonly IRepository<Doctor> _doctorRepository;
private readonly IRepository<Trial> _trialRepository;
private readonly IRepository<SystemCriterionDictionaryCode> _systemCriterionDictionaryCodeRepository;
private readonly IRepository<TrialCriterionDictionaryCode> _trialCriterionDictionaryCodeRepository;
private readonly IRepository<ReadingTrialCriterionDictionary> _readingTrialCriterionDictionaryRepository;
private readonly IRepository<ReadingSystemCriterionDictionary> _readingSystemCriterionDictionaryRepository;
private readonly IRepository<ReadingSystemCriterionDictionary> _readingCriterionDictionaryRepository;
private readonly IRepository<ReadingQuestionCriterionSystem> _readingQuestionCriterionSystem;
private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrial;
public DictionaryService(IRepository<Dictionary> sysDicRepository, IRepository<DoctorDictionary> doctorDictionaryRepository, IRepository<TrialDictionary> trialDictionaryRepository,
IRepository<Doctor> doctorRepository, IRepository<Trial> trialRepository,
IRepository<SystemCriterionDictionaryCode> systemCriterionDictionaryCodeRepository,
IRepository<TrialCriterionDictionaryCode> trialCriterionDictionaryCodeRepository,
IRepository<ReadingTrialCriterionDictionary> readingTrialCriterionDictionaryRepository,
IRepository<ReadingSystemCriterionDictionary> readingSystemCriterionDictionaryRepository,
IRepository<ReadingSystemCriterionDictionary> readingCriterionDictionaryRepository,
IRepository<ReadingQuestionCriterionSystem> readingQuestionCriterionSystem,
IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrial
)
{
_dicRepository = sysDicRepository;
_doctorDictionaryRepository = doctorDictionaryRepository;
_trialDictionaryRepository = trialDictionaryRepository;
_doctorRepository = doctorRepository;
_trialRepository = trialRepository;
this._systemCriterionDictionaryCodeRepository = systemCriterionDictionaryCodeRepository;
this._trialCriterionDictionaryCodeRepository = trialCriterionDictionaryCodeRepository;
this._readingTrialCriterionDictionaryRepository = readingTrialCriterionDictionaryRepository;
this._readingSystemCriterionDictionaryRepository = readingSystemCriterionDictionaryRepository;
this._readingCriterionDictionaryRepository = readingCriterionDictionaryRepository;
this._readingQuestionCriterionSystem = readingQuestionCriterionSystem;
this._readingQuestionCriterionTrial = readingQuestionCriterionTrial;
}
/// <summary>
/// 添加bool
@@ -88,14 +115,6 @@ namespace IRaCIS.Application.Services
IsVerify = true
};
if((addBasicDicAndChild.DataTypeEnum == DicDataTypeEnum.Enum || addBasicDicAndChild.DataTypeEnum == DicDataTypeEnum.Bool))
{
if(addBasicDicAndChild.ChildList.GroupBy(t => t.Code).Where(g => g.Count() > 1).Any())
{
return ResponseOutput.NotOk(_localizer["Dictionary_RepeateCode"]);
}
}
var entity = await _dicRepository.InsertFromDTOAsync(addBasicDicAndChild, false, verifyExp1);
@@ -116,27 +135,27 @@ namespace IRaCIS.Application.Services
/// <summary>
/// New 查询条件
/// </summary>
/// <param name="inQuery"></param>
/// <param name="basicDicQuery"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageOutput<BasicDicView>> GetBasicDicList(BasicDicQuery inQuery)
public async Task<PageOutput<BasicDicView>> GetBasicDicList(BasicDicQuery basicDicQuery)
{
var systemBasicDataQueryable = _dicRepository.Where(t => t.ParentId == null)
.WhereIf(!string.IsNullOrEmpty(inQuery.Code), t => t.Code.Contains(inQuery.Code!))
.WhereIf(!string.IsNullOrEmpty(inQuery.keyInfo), t => t.Description.Contains(inQuery.keyInfo!)
|| t.Code.Contains(inQuery.keyInfo!)
|| t.ChildList.Any(u => u.ValueCN.Contains(inQuery.keyInfo!))
|| t.ChildList.Any(u => u.Description.Contains(inQuery.keyInfo!))
|| t.ChildList.Any(u => u.Value.Contains(inQuery.keyInfo!)))
.WhereIf(!string.IsNullOrEmpty(basicDicQuery.Code), t => t.Code.Contains(basicDicQuery.Code!))
.WhereIf(!string.IsNullOrEmpty(basicDicQuery.keyInfo), t => t.Description.Contains(basicDicQuery.keyInfo!)
|| t.Code.Contains(basicDicQuery.keyInfo!)
|| t.ChildList.Any(u => u.ValueCN.Contains(basicDicQuery.keyInfo!))
|| t.ChildList.Any(u => u.Description.Contains(basicDicQuery.keyInfo!))
|| t.ChildList.Any(u => u.Value.Contains(basicDicQuery.keyInfo!)))
.WhereIf(inQuery.ConfigTypeId != null, t => t.ConfigTypeId == inQuery.ConfigTypeId!)
.WhereIf(inQuery.DataTypeEnum != null, t => t.DataTypeEnum == inQuery.DataTypeEnum)
.WhereIf(inQuery.DataTypeEnum == null, t => t.DataTypeEnum != DicDataTypeEnum.Config)
.WhereIf(basicDicQuery.ConfigTypeId != null, t => t.ConfigTypeId == basicDicQuery.ConfigTypeId!)
.WhereIf(basicDicQuery.DataTypeEnum != null, t => t.DataTypeEnum == basicDicQuery.DataTypeEnum)
.WhereIf(basicDicQuery.DataTypeEnum == null, t => t.DataTypeEnum != DicDataTypeEnum.Config)
.ProjectTo<BasicDicView>(_mapper.ConfigurationProvider);
return await systemBasicDataQueryable.ToPagedListAsync(inQuery, new[] { nameof(BasicDicView.ConfigType), nameof(BasicDicView.ShowOrder) });
return await systemBasicDataQueryable.ToPagedListAsync(basicDicQuery.PageIndex, basicDicQuery.PageSize, String.IsNullOrEmpty(basicDicQuery.SortField) ? nameof(BasicDicView.ConfigType) : basicDicQuery.SortField, basicDicQuery.Asc, String.IsNullOrEmpty(basicDicQuery.SortField), new[] { nameof(BasicDicView.ConfigType), nameof(BasicDicView.ShowOrder) });
}
@@ -156,15 +175,16 @@ namespace IRaCIS.Application.Services
IsVerify = addOrEditBasic.ParentId == null
};
var verifyExp2 = new EntityVerifyExp<Dictionary>()
{
VerifyExp = t => t.Code == addOrEditBasic.Code && t.ParentId == addOrEditBasic.ParentId && t.Code==addOrEditBasic.Code,
VerifyMsg = _localizer["Dictionary_RepeateCode"],
IsVerify = addOrEditBasic.ParentId != null && (addOrEditBasic.DataTypeEnum == DicDataTypeEnum.Enum || addOrEditBasic.DataTypeEnum == DicDataTypeEnum.Bool)
};
//// 验证阅片标准是否可禁用
//if (!addOrEditBasic.IsEnable&&addOrEditBasic.Id!=null)
//{
// var result = await _readingQuestionService.SetSystemCriterionDisable(addOrEditBasic.Id.Value,addOrEditBasic.ParentId);
// if (!result.IsSuccess)
// {
// return result;
// }
//}
if (addOrEditBasic.Id != null && addOrEditBasic.ParentId == null)
@@ -174,7 +194,7 @@ namespace IRaCIS.Application.Services
//await _dicRepository.BatchUpdateNoTrackingAsync(t => t.ParentId == addOrEditBasic.Id, c => new Dictionary() { DataTypeEnum = addOrEditBasic.DataTypeEnum });
}
var entity = await _dicRepository.InsertOrUpdateAsync(addOrEditBasic, true, verifyExp1, verifyExp2);
var entity = await _dicRepository.InsertOrUpdateAsync(addOrEditBasic, true, verifyExp1);
@@ -7,7 +7,6 @@
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;
namespace IRaCIS.Core.Application.Contracts
{
@@ -15,47 +14,34 @@ namespace IRaCIS.Core.Application.Contracts
/// 系统邮件配置表
/// </summary>
[ApiExplorerSettings(GroupName = "Common")]
public class EmailNoticeConfigService(IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
IRepository<EmailNoticeUserType> _emailNoticeUserTypeRepository) : BaseService, IEmailNoticeConfigService
public class EmailNoticeConfigService : BaseService, IEmailNoticeConfigService
{
private readonly IRepository<EmailNoticeConfig> _emailNoticeConfigrepository;
private readonly IRepository<EmailNoticeUserType> _emailNoticeUserTypeRepository;
public EmailNoticeConfigService(IRepository<EmailNoticeConfig> repository, IRepository<EmailNoticeUserType> emailNoticeUserTypeRepository)
{
_emailNoticeConfigrepository = repository;
_emailNoticeUserTypeRepository = emailNoticeUserTypeRepository;
}
[HttpPost]
public async Task<PageOutput<EmailNoticeConfigView>> GetEmailNoticeConfigList(EmailNoticeConfigQuery inQuery)
public async Task<PageOutput<EmailNoticeConfigView>> GetEmailNoticeConfigList(EmailNoticeConfigQuery queryEmailNoticeConfig)
{
var emailNoticeConfigQueryable = _emailNoticeConfigrepository
.WhereIf(inQuery.SystemLevel == null, t => t.SystemLevel == SysEmailLevel.not_sys)
.WhereIf(inQuery.SystemLevel!=null, t =>t.SystemLevel == inQuery.SystemLevel)
.WhereIf(inQuery.IsDistinguishCriteria != null, t => t.IsDistinguishCriteria == inQuery.IsDistinguishCriteria)
.WhereIf(inQuery.CriterionTypeEnum != null, t => t.CriterionTypeEnum == inQuery.CriterionTypeEnum)
.WhereIf(inQuery.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == inQuery.BusinessScenarioEnum)
.WhereIf(inQuery.IsReturnRequired != null, t => t.IsReturnRequired == inQuery.IsReturnRequired)
.WhereIf(inQuery.IsEnable != null, t => t.IsEnable == inQuery.IsEnable)
.WhereIf(queryEmailNoticeConfig.IsDistinguishCriteria != null, t => t.IsDistinguishCriteria == queryEmailNoticeConfig.IsDistinguishCriteria)
.WhereIf(queryEmailNoticeConfig.CriterionTypeEnum != null, t => t.CriterionTypeEnum == queryEmailNoticeConfig.CriterionTypeEnum)
.WhereIf(queryEmailNoticeConfig.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == queryEmailNoticeConfig.BusinessScenarioEnum)
.WhereIf(queryEmailNoticeConfig.IsReturnRequired != null, t => t.IsReturnRequired == queryEmailNoticeConfig.IsReturnRequired)
.WhereIf(queryEmailNoticeConfig.IsEnable != null, t => t.IsEnable == queryEmailNoticeConfig.IsEnable)
.ProjectTo<EmailNoticeConfigView>(_mapper.ConfigurationProvider);
return await emailNoticeConfigQueryable.ToPagedListAsync(inQuery);
return await emailNoticeConfigQueryable.ToPagedListAsync(queryEmailNoticeConfig.PageIndex, queryEmailNoticeConfig.PageSize, queryEmailNoticeConfig.SortField, queryEmailNoticeConfig.Asc);
}
public async Task<IResponseOutput> AddOrUpdateEmailNoticeConfig(EmailNoticeConfigAddOrEdit addOrEditEmailNoticeConfig)
{
var verifyExp1 = new EntityVerifyExp<EmailNoticeConfig>()
{
VerifyExp = t => t.BusinessScenarioEnum == addOrEditEmailNoticeConfig.BusinessScenarioEnum,
VerifyMsg = _localizer["EmailNoticeConfig_RepeatEmailScenario"]
};
// 匹配所有占位符的正则表达式,允许包含空格的占位符
var regex = new Regex(@"\{\s*\d+\s*\}");
if (regex.Matches($"{addOrEditEmailNoticeConfig.EmailTopic}{addOrEditEmailNoticeConfig.EmailTopicCN}{addOrEditEmailNoticeConfig.EmailHtmlContent}{addOrEditEmailNoticeConfig.EmailHtmlContentCN}" )
.Any(t=>t.Value.Contains(" ")))
{
//邮件模板占位符不允许有空格,请核查占位符的地方
return ResponseOutput.NotOk("EmailNoticeConfig_ContainEmpty");
}
if (addOrEditEmailNoticeConfig.Id == null)
{
@@ -75,7 +61,7 @@ namespace IRaCIS.Core.Application.Contracts
}
await _emailNoticeConfigrepository.AddAsync(entity, true, verifyExp1);
await _emailNoticeConfigrepository.AddAsync(entity, true);
return ResponseOutput.Ok(entity.Id.ToString());
}
@@ -98,7 +84,7 @@ namespace IRaCIS.Core.Application.Contracts
}
var entity = await _emailNoticeConfigrepository.UpdateFromDTOAsync(addOrEditEmailNoticeConfig, true, false,verifyExp1);
var entity = await _emailNoticeConfigrepository.UpdateFromDTOAsync(addOrEditEmailNoticeConfig, true);
return ResponseOutput.Ok(entity.Id.ToString());
File diff suppressed because it is too large Load Diff
@@ -1,86 +0,0 @@
//--------------------------------------------------------------------
// 此代码由T4模板自动生成 byzhouhang 20210918
// 生成时间 2024-07-02 09:26:59
// 对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//--------------------------------------------------------------------
using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using Microsoft.AspNetCore.Authorization;
namespace IRaCIS.Core.Application.Service
{
/// <summary>
/// ExploreRecommendService
/// </summary>
[ApiExplorerSettings(GroupName = "Common")]
public class ExploreRecommendService(IRepository<ExploreRecommend> _exploreRecommendRepository) : BaseService, IExploreRecommendService
{
[HttpPost]
public async Task<PageOutput<ExploreRecommendView>> GetExploreRecommendList(ExploreRecommendQuery inQuery)
{
var exploreRecommendQueryable =
_exploreRecommendRepository.Where().IgnoreQueryFilters()
.WhereIf(string.IsNullOrEmpty(inQuery.Title), t => t.Title.Contains(inQuery.Title))
.WhereIf(string.IsNullOrEmpty(inQuery.FileName), t => t.Title.Contains(inQuery.FileName))
.WhereIf(string.IsNullOrEmpty(inQuery.DownloadUrl), t => t.Title.Contains(inQuery.DownloadUrl))
.WhereIf(string.IsNullOrEmpty(inQuery.Version), t => t.Title.Contains(inQuery.Version))
.WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == t.IsDeleted)
.ProjectTo<ExploreRecommendView>(_mapper.ConfigurationProvider);
var pageList = await exploreRecommendQueryable
.ToPagedListAsync(inQuery);
return pageList;
}
public async Task<IResponseOutput> AddOrUpdateExploreRecommend(ExploreRecommendAddOrEdit addOrEditExploreRecommend)
{
var verifyExp2 = new EntityVerifyExp<ExploreRecommend>()
{
VerifyExp = u => u.IsDeleted == addOrEditExploreRecommend.IsDeleted && u.ExploreType == addOrEditExploreRecommend.ExploreType,
// "当前类型浏览器启用版本只允许有一个"
VerifyMsg = _localizer["ExploreRecommend_OnlyOneTypePerType"] ,
IsVerify = addOrEditExploreRecommend.IsDeleted == false
};
var entity = await _exploreRecommendRepository.InsertOrUpdateAsync(addOrEditExploreRecommend, true, verifyExp2);
return ResponseOutput.Ok(entity.Id.ToString());
}
[HttpDelete("{exploreRecommendId:guid}")]
public async Task<IResponseOutput> DeleteExploreRecommend(Guid exploreRecommendId)
{
var success = await _exploreRecommendRepository.DeleteFromQueryAsync(t => t.Id == exploreRecommendId, true,true);
return ResponseOutput.Ok();
}
[AllowAnonymous]
public async Task<List<ExploreRecommendView> > GetExploreRecommentInfo()
{
var result = await _exploreRecommendRepository.Where(t => t.IsDeleted == false).ProjectTo<ExploreRecommendView>(_mapper.ConfigurationProvider).ToListAsync();
if (result .Count==0)
{ //"系统浏览器版本推荐未维护,请联系维护人员"
throw new QueryBusinessObjectNotExistException(_localizer["ExploreRecommend_NoExporeRecord"]);
}
return result;
}
}
}

Some files were not shown because too many files have changed in this diff Show More