From c4e53d5654f44e51de184c5599aea5ac56b11ee8 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Mon, 9 Oct 2023 11:27:35 +0800 Subject: [PATCH 01/13] =?UTF-8?q?study-=E9=82=AE=E4=BB=B6=E5=8F=91?= =?UTF-8?q?=E9=80=81=E4=BF=AE=E6=94=B9-=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/IRaCIS.Core.API.csproj | 4 +- .../Properties/launchSettings.json | 17 +- IRaCIS.Core.API/Startup.cs | 4 +- .../Hangfire/HangfireConfig.cs | 40 -- .../_PipelineExtensions/HangfireConfig.cs | 66 +++ .../_ServiceExtensions/hangfireSetup.cs | 16 +- .../appsettings.CenterImageDev.json | 35 -- .../appsettings.CertificateApply.json | 33 -- IRaCIS.Core.API/appsettings.Development.json | 4 +- IRaCIS.Core.API/appsettings.Production.json | 3 +- IRaCIS.Core.API/appsettings.Staging.json | 3 +- .../Helper/HangfireJobHelper.cs | 92 ++++ .../IRaCIS.Core.Application.csproj | 4 +- .../IRaCIS.Core.Application.xml | 83 +++- .../Common/DTO/CommonDocumentViewModel.cs | 4 +- .../Common/DTO/EmailNoticeConfigViewModel.cs | 87 +++- .../Common/EmailNoticeConfigService.cs | 58 ++- .../Service/Common/_MapConfig.cs | 8 +- .../DTO/TrialEmailNoticeConfigViewModel.cs | 97 +++-- .../Service/Document/EmailSendService.cs | 403 ++++++++++++++++++ .../Document/TrialEmailNoticeConfigService.cs | 283 +++++++++--- .../Management/DTO/UserTypeRoleModel.cs | 16 +- .../Common/EmailScenarioEnum.cs | 8 +- IRaCIS.Core.Domain/Common/CommonDocument.cs | 2 +- .../Common/EmailNoticeConfig.cs | 79 +++- .../Document/TrialEmailNoticeConfig.cs | 213 +++++---- IRaCIS.Core.Domain/Trial/Trial.cs | 2 +- IRaCIS.Core.Domain/_Config/_AppSettings.cs | 4 +- .../Context/IRaCISDBContext.cs | 3 +- .../_IRaCIS/Output/ResponseOutput.cs | 2 +- 30 files changed, 1314 insertions(+), 359 deletions(-) delete mode 100644 IRaCIS.Core.API/_PipelineExtensions/Hangfire/HangfireConfig.cs create mode 100644 IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs delete mode 100644 IRaCIS.Core.API/appsettings.CenterImageDev.json delete mode 100644 IRaCIS.Core.API/appsettings.CertificateApply.json create mode 100644 IRaCIS.Core.Application/Helper/HangfireJobHelper.cs create mode 100644 IRaCIS.Core.Application/Service/Document/EmailSendService.cs diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index c6af611a4..eccd92242 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -78,7 +78,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + + + diff --git a/IRaCIS.Core.API/Properties/launchSettings.json b/IRaCIS.Core.API/Properties/launchSettings.json index 5993ff67d..aed031839 100644 --- a/IRaCIS.Core.API/Properties/launchSettings.json +++ b/IRaCIS.Core.API/Properties/launchSettings.json @@ -45,22 +45,7 @@ "ASPNETCORE_ENVIRONMENT": "Production" }, "applicationUrl": "http://localhost:6300" - }, - "IRaCIS.CertificateApply": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "CertificateApply" - }, - "applicationUrl": "http://localhost:6400" - }, - "IRaCIS.CenterImageDev": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "CenterImageDev" - }, - "applicationUrl": "http://localhost:6500" } + } } \ No newline at end of file diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index 886e443fc..705f5ad87 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -114,7 +114,7 @@ namespace IRaCIS.Core.API //services.AddDistributedMemoryCache(); // hangfire 定时任务框架 有界面,更友好~ - //services.AddhangfireSetup(_configuration); + services.AddhangfireSetup(_configuration); // QuartZ 定时任务框架 使用了hangfire 暂时不用,后续需要可以打开,已经配好 services.AddQuartZSetup(_configuration); @@ -181,7 +181,7 @@ namespace IRaCIS.Core.API app.UseLogDashboard("/LogDashboard"); //hangfire - //app.UseHangfireConfig(env); + app.UseHangfireConfig(env); ////暂时废弃 //app.UseHttpReports(); diff --git a/IRaCIS.Core.API/_PipelineExtensions/Hangfire/HangfireConfig.cs b/IRaCIS.Core.API/_PipelineExtensions/Hangfire/HangfireConfig.cs deleted file mode 100644 index 48423534d..000000000 --- a/IRaCIS.Core.API/_PipelineExtensions/Hangfire/HangfireConfig.cs +++ /dev/null @@ -1,40 +0,0 @@ -锘縰sing Hangfire; -using Hangfire.Dashboard; -using IRaCIS.Application.Services.BackGroundJob; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; - -namespace IRaCIS.Core.API -{ - - - public static class HangfireConfig - { - - public static void UseHangfireConfig(this IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseHangfireDashboard("/api/hangfire", new DashboardOptions() - { - //鐩存帴璁块棶锛屾病鏈夊甫token 鑾峰彇涓嶅埌鐢ㄦ埛韬唤淇℃伅锛屾墍浠ヨ繖绉嶈嚜瀹氫箟鎺堟潈鏆傛椂娌℃硶浣跨敤 - //Authorization = new[] { new hangfireAuthorizationFilter() } - - //鏈湴璇锋眰 鎵嶈兘鐪 - Authorization = new[] { new LocalRequestsOnlyAuthorizationFilter() } - - }); - - #region hangfire - //// 寤惰繜浠诲姟鎵ц 1绉掍箣鍚庢墽琛 鏈夋椂鍚姩娌¤繍琛 鎹㈡垚娣诲姞鍒伴槦鍒椾腑 - //BackgroundJob.Schedule(t => t.MemoryCacheTrialStatus(), TimeSpan.FromSeconds(1)); - ////娣诲姞鍒板悗鍙颁换鍔¢槦鍒楋紝 - //BackgroundJob.Enqueue(t => t.MemoryCacheTrialStatus()); - - //鍛ㄦ湡鎬т换鍔★紝1澶╂墽琛屼竴娆 - - RecurringJob.AddOrUpdate(t => t.ProjectStartCache(), Cron.Daily); - - #endregion - - } - } -} diff --git a/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs b/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs new file mode 100644 index 000000000..3b9cb8b7a --- /dev/null +++ b/IRaCIS.Core.API/_PipelineExtensions/HangfireConfig.cs @@ -0,0 +1,66 @@ +锘縰sing Hangfire; +using Hangfire.Dashboard; +using Hangfire.Dashboard.BasicAuthorization; +using IRaCIS.Application.Services.BackGroundJob; +using IRaCIS.Core.API.Filter; +using IRaCIS.Core.Application.Helper; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; + +namespace IRaCIS.Core.API +{ + + + public static class HangfireConfig + { + + public static void UseHangfireConfig(this IApplicationBuilder app, IWebHostEnvironment env) + { + + + app.UseHangfireDashboard("/back/hangfire", new DashboardOptions() + { + + + + Authorization = new IDashboardAuthorizationFilter[] { /*new hangfireAuthorizationFilter(),*/ + + new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions(){ + SslRedirect=false, + RequireSsl=false, + Users=new BasicAuthAuthorizationUser[]{ + new BasicAuthAuthorizationUser(){ + Login="admin", + PasswordClear="admin", + + } + } + + }) + }, + + DashboardTitle ="鍚庡彴浠诲姟绠$悊", + + + //Authorization = new BasicAuthAuthorizationFilter[] { + // new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions(){ + // SslRedirect=false, + // RequireSsl=false, + // Users=new BasicAuthAuthorizationUser[]{ + // new BasicAuthAuthorizationUser(){ + // Login="admin", + // PasswordClear="test", + + // } + // } + + // }) + //} + + }); + + + + } + } +} \ No newline at end of file diff --git a/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs index a5dd1fc09..00b718e2c 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/hangfireSetup.cs @@ -1,13 +1,12 @@ 锘縰sing Hangfire; using Hangfire.SqlServer; -using Hangfire.Tags.SqlServer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; namespace IRaCIS.Core.API { - public static class hangfireSetup + public static class hangfireSetup { public static void AddhangfireSetup(this IServiceCollection services, IConfiguration configuration) { @@ -15,24 +14,29 @@ namespace IRaCIS.Core.API services.AddHangfire(hangFireConfig => { + + //hangFireConfig.UseInMemoryStorage(); + //鎸囧畾瀛樺偍浠嬭川 hangFireConfig.UseSqlServerStorage(hangFireConnStr, new SqlServerStorageOptions() { - SchemaName = "hangfire", + SchemaName = "dbo", CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, - UsePageLocksOnDequeue = true, DisableGlobalLocks = true }); - hangFireConfig.UseTagsWithSql(); //nuget寮曞叆Hangfire.Tags.SqlServer + //hangFireConfig.UseTagsWithSql(); //nuget寮曞叆Hangfire.Tags.SqlServer //.UseHangfireHttpJob(); }); - services.AddHangfireServer(); + services.AddHangfireServer(option => + { + option.Queues = new[] { "immediately_once", "default", "sys_init", "not_immediately_once" }; + }); } } diff --git a/IRaCIS.Core.API/appsettings.CenterImageDev.json b/IRaCIS.Core.API/appsettings.CenterImageDev.json deleted file mode 100644 index 948b3dacd..000000000 --- a/IRaCIS.Core.API/appsettings.CenterImageDev.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "ConnectionStrings": { - "RemoteNew": "Server=123.56.94.154,1433\\MSSQLSERVER;Database=CenterImage_Test;User ID=sa;Password=dev123456DEV;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@extimaging.com", - "FromName": "Test_IRC", - "AuthorizationCode": "SHzyyl2021" - } - -} diff --git a/IRaCIS.Core.API/appsettings.CertificateApply.json b/IRaCIS.Core.API/appsettings.CertificateApply.json deleted file mode 100644 index 2c04ce923..000000000 --- a/IRaCIS.Core.API/appsettings.CertificateApply.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "ConnectionStrings": { - "RemoteNew": "Server=123.56.94.154,1433\\MSSQLSERVER;Database=IRaCIS_Certificate;User ID=sa;Password=dev123456DEV;TrustServerCertificate=true", - "Hangfire": "Server=123.56.94.154,1433\\MSSQLSERVER;Database=Hangfire_IRaCIS;User ID=sa;Password=dev123456DEV;TrustServerCertificate=true" - - }, - "BasicSystemConfig": { - - "OpenUserComplexPassword": false, - - "OpenSignDocumentBeforeWork": false, - - "OpenTrialRelationDelete": true, - - "OpenLoginLimit": false - }, - - "SystemEmailSendConfig": { - "Port": 465, - "Host": "smtp.qiye.aliyun.com", - "FromEmail": "test@extimaging.com", - "FromName": "Test_IRC", - "AuthorizationCode": "SHzyyl2021" - } - -} diff --git a/IRaCIS.Core.API/appsettings.Development.json b/IRaCIS.Core.API/appsettings.Development.json index 076ddb95f..3f816a12f 100644 --- a/IRaCIS.Core.API/appsettings.Development.json +++ b/IRaCIS.Core.API/appsettings.Development.json @@ -38,7 +38,9 @@ "Host": "smtp.qiye.aliyun.com", "FromEmail": "test@extimaging.com", "FromName": "Test_IRC", - "AuthorizationCode": "SHzyyl2021" + "AuthorizationCode": "SHzyyl2021", + + "SiteUrl": "http://test.extimaging.com/login" } } diff --git a/IRaCIS.Core.API/appsettings.Production.json b/IRaCIS.Core.API/appsettings.Production.json index 91ca65025..442c3a8d1 100644 --- a/IRaCIS.Core.API/appsettings.Production.json +++ b/IRaCIS.Core.API/appsettings.Production.json @@ -35,7 +35,8 @@ "Host": "smtp.qiye.aliyun.com", "FromEmail": "IRC@extimaging.com", "FromName": "IRC", - "AuthorizationCode": "ExtImg@2022" + "AuthorizationCode": "ExtImg@2022", + "SiteUrl": "http://irc.extimaging.com/login" } diff --git a/IRaCIS.Core.API/appsettings.Staging.json b/IRaCIS.Core.API/appsettings.Staging.json index c40e2367e..708834b73 100644 --- a/IRaCIS.Core.API/appsettings.Staging.json +++ b/IRaCIS.Core.API/appsettings.Staging.json @@ -27,7 +27,8 @@ "Host": "smtp.qiye.aliyun.com", "FromEmail": "uat@extimaging.com", "FromName": "UAT_IRC", - "AuthorizationCode": "SHzyyl2021" + "AuthorizationCode": "SHzyyl2021", + "SiteUrl": "http://uat.extimaging.com/login" } diff --git a/IRaCIS.Core.Application/Helper/HangfireJobHelper.cs b/IRaCIS.Core.Application/Helper/HangfireJobHelper.cs new file mode 100644 index 000000000..69eaf410d --- /dev/null +++ b/IRaCIS.Core.Application/Helper/HangfireJobHelper.cs @@ -0,0 +1,92 @@ +锘縰sing Hangfire; +using IRaCIS.Core.Application.Service; +using IRaCIS.Core.Domain.Share; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NPOI.SS.Formula.Functions; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace IRaCIS.Core.Application.Helper +{ + public static class HangfireJobHelper + { + + + + //public static void AddOrUpdateCronJob(string jobId, string queueName, Expression methodCall, string cron) + //{ + // RecurringJob.AddOrUpdate(jobId, queueName, methodCall, cron); + //} + + + + //娣诲姞 鎴栬呮洿鏂板畾鏃朵换鍔 Id 瑕佸敮涓鏍囪瘑涓涓畾涔変换鍔 + public static void AddOrUpdateCronJob(string jobId, Expression> methodCall, string cron, string queueName = "default") + { + RecurringJob.AddOrUpdate(jobId, queueName, methodCall, cron); + } + + public static void AddOrUpdateInitCronJob(string jobId, Expression> methodCall, string cron) + { + RecurringJob.AddOrUpdate(jobId, "sys_init", methodCall, cron); + } + + public static void RemoveCronJob(string jobId) + { + RecurringJob.RemoveIfExists(jobId); + + } + + + + public static void ImmediatelyOnceOnlyJob(Expression methodCall) + { + BackgroundJob.Enqueue("immediately_once", methodCall); + } + + public static void ImmediatelyOnceOnlyJob(Expression> methodCall) + { + BackgroundJob.Enqueue("immediately_once", methodCall); + } + + public static void NotImmediatelyOnceOnlyJob(Expression methodCall, TimeSpan timeSpan) + { + BackgroundJob.Schedule("not_immediately_once", methodCall, timeSpan); + } + + public static void NotImmediatelyOnceOnlyJob(Expression> methodCall, TimeSpan timeSpan) + { + BackgroundJob.Schedule("not_immediately_once", methodCall, timeSpan); + } + + + public static void AddOrUpdateTrialCronJob (string jobId, Guid trialId, EmailBusinessScenario businessScenario, string emailCron) + { + + switch (businessScenario) + { + + case EmailBusinessScenario.QCTask: + HangfireJobHelper.AddOrUpdateCronJob(jobId, t => t.SendTrialImageQCTaskEmailAsync(trialId), emailCron); + break; + case EmailBusinessScenario.QCQuestion: + HangfireJobHelper.AddOrUpdateCronJob(jobId, t => t.SendTrialQCQuestionEmailAsync(trialId), emailCron); + break; + case EmailBusinessScenario.ImageQuestion: + HangfireJobHelper.AddOrUpdateCronJob(jobId, t => t.SendTrialImageQuestionAsync(trialId), emailCron); + break; + + default: + break; + } + + } + } +} + + diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj index 247ed6016..ece94b800 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj @@ -64,6 +64,7 @@ + @@ -76,9 +77,6 @@ - - true - true diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml index 5b5d1d667..56def288d 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml @@ -685,6 +685,27 @@ PublishLogService + + + 褰卞儚璐ㄦ帶 + + + + + + + QC璐ㄧ枒 + + + + + + + 褰卞儚璐ㄧ枒 + + + + TrialEmailNoticeConfigService @@ -706,7 +727,7 @@ - 鍚屾绯荤粺閰嶇疆鐨勬枃妗e埌鎯抽」鐩腑 + 鍚屾绯荤粺閰嶇疆鐨勬枃妗e埌鎯抽」鐩腑 ---搴熷純 @@ -756,6 +777,27 @@ + + + 榛戝悕鍗曠敤鎴稩d 鍒楄〃 + + + + + + + 鑾峰彇绯荤粺 閭欢閰嶇疆 鍕鹃夊垪琛 + + + + + + + 鎵归噺鍕鹃 浼犻掑垪琛ㄦ瘡琛屾暟鎹紝鍚庡彴杩涜澶勭悊杞崲锛屽缓绔嬪叧鑱斿叧绯 + + + + 鎸囧畾璧勬簮Id锛屾覆鏌揇icom妫鏌ョ殑Jpeg棰勮鍥惧儚 Dicom妫鏌ョ殑Id @@ -8922,6 +8964,27 @@ TrialEmailNoticeConfigQuery 鍒楄〃鏌ヨ鍙傛暟妯″瀷 + + 涓氬姟妯″潡 /// + + + 涓氬姟灞傜骇 /// + + + 閭欢绫诲瀷 /// + + + 閭欢鍔犳ョ被鍨 /// + + + 瀹氭椂鍛ㄦ湡 /// + + + 閭欢涓婚 /// + + + 闄勪欢 /// + TrialEmailNoticeConfigAddOrEdit 鍒楄〃鏌ヨ鍙傛暟妯″瀷 @@ -9816,6 +9879,24 @@ 鏄惁鍖哄垎鏍囧噯 + + 涓氬姟妯″潡 /// + + + 涓氬姟灞傜骇 /// + + + 閭欢绫诲瀷 /// + + + 閭欢鍔犳ョ被鍨 /// + + + 瀹氭椂鍛ㄦ湡 /// + + + 閭欢涓婚 /// + SystemBasicDataView 鍒楄〃瑙嗗浘妯″瀷 diff --git a/IRaCIS.Core.Application/Service/Common/DTO/CommonDocumentViewModel.cs b/IRaCIS.Core.Application/Service/Common/DTO/CommonDocumentViewModel.cs index 25a9212ac..77e41901d 100644 --- a/IRaCIS.Core.Application/Service/Common/DTO/CommonDocumentViewModel.cs +++ b/IRaCIS.Core.Application/Service/Common/DTO/CommonDocumentViewModel.cs @@ -35,7 +35,7 @@ namespace IRaCIS.Core.Application.ViewModel { public CriterionType? CriterionTypeEnum { get; set; } public CommonDocumentFileType? FileTypeEnum { get; set; } - public CommonDocumentBusinessScenario? BusinessScenarioEnum { get; set; } + public EmailBusinessScenario? BusinessScenarioEnum { get; set; } public string Name { get; set; } = String.Empty; @@ -55,7 +55,7 @@ namespace IRaCIS.Core.Application.ViewModel public CriterionType? CriterionTypeEnum { get; set; } public CommonDocumentFileType FileTypeEnum { get; set; } - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } //public Guid FileTypeId { get; set; } diff --git a/IRaCIS.Core.Application/Service/Common/DTO/EmailNoticeConfigViewModel.cs b/IRaCIS.Core.Application/Service/Common/DTO/EmailNoticeConfigViewModel.cs index ae2bfca4b..691b1e8bf 100644 --- a/IRaCIS.Core.Application/Service/Common/DTO/EmailNoticeConfigViewModel.cs +++ b/IRaCIS.Core.Application/Service/Common/DTO/EmailNoticeConfigViewModel.cs @@ -3,10 +3,16 @@ // 鐢熸垚鏃堕棿 2022-02-15 11:55:57 // 瀵规鏂囦欢鐨勬洿鏀瑰彲鑳戒細瀵艰嚧涓嶆纭殑琛屼负锛屽苟涓斿鏋滈噸鏂扮敓鎴愪唬鐮侊紝杩欎簺鏇存敼灏嗕細涓㈠け銆 //-------------------------------------------------------------------- +using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Domain.Share; using Newtonsoft.Json; namespace IRaCIS.Core.Application.Contracts { + public class TrialSelectEmailNoticeConfigView : EmailNoticeConfigView + { + public bool IsHaveSelected { get; set; } + } + /// EmailNoticeConfigView 鍒楄〃瑙嗗浘妯″瀷 public class EmailNoticeConfigView : EmailNoticeConfigAddOrEdit { @@ -19,6 +25,12 @@ namespace IRaCIS.Core.Application.Contracts + public List EmailNoticeUserList { get; set; } + + + public new List ToUserTypeList => EmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.To).Select(t => t.UserType).ToList(); + public new List CopyUserTypeList => EmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.Copy).Select(t => t.UserType).ToList(); + //[JsonIgnore] //public SystemBasicDataSelect Scenario { get; set; } ////public Guid? ScenarioParentId => Scenario.ParentId; @@ -28,17 +40,29 @@ namespace IRaCIS.Core.Application.Contracts } + public class EmailUserTypeDto + { + public UserTypeEnum UserType { get; set; } + + public EmailUserType EmailUserType { get; set; } + } + ///EmailNoticeConfigQuery 鍒楄〃鏌ヨ鍙傛暟妯″瀷 - public class EmailNoticeConfigQuery:PageInput + public class EmailNoticeConfigQuery : PageInput { //public Guid? ScenarioId { get; set; } - public CommonDocumentBusinessScenario? BusinessScenarioEnum { get; set; } + public EmailBusinessScenario? BusinessScenarioEnum { get; set; } public bool? IsReturnRequired { get; set; } - public bool? IsUrgent { get; set; } public bool? IsEnable { get; set; } + public CriterionType? CriterionTypeEnum { get; set; } + + public Guid? TrialId { get; set; } + + public bool? IsDistinguishCriteria { get; set; } + } /// EmailNoticeConfigAddOrEdit 鍒楄〃鏌ヨ鍙傛暟妯″瀷 @@ -47,31 +71,66 @@ namespace IRaCIS.Core.Application.Contracts public Guid? Id { get; set; } public string Code { get; set; } = String.Empty; - - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } /// /// 鏄惁鍖哄垎鏍囧噯 /// public bool IsDistinguishCriteria { get; set; } - - //public string AuthorizationCode { get; set; } = String.Empty; - //public Guid ScenarioId { get; set; } - //public string Title { get; set; } = String.Empty; - //public string Body { get; set; } = String.Empty; - //public string FromEmail { get; set; } = String.Empty; - //public string ReceiveEmail { get; set; } = String.Empty; - //public string CopyEmail { get; set; } = String.Empty; public bool IsReturnRequired { get; set; } - public bool IsUrgent { get; set; } public bool IsEnable { get; set; } public bool IsAutoSend { get; set; } public bool IsDeleted { get; set; } + + + + public CriterionType? CriterionTypeEnum { get; set; } + + /// 涓氬姟妯″潡 /// + public int BusinessModuleEnum { get; set; } + + /// 涓氬姟灞傜骇 /// + public int BusinessLevelEnum { get; set; } + + /// 閭欢绫诲瀷 /// + public int EmailTypeEnum { get; set; } + + /// 閭欢鍔犳ョ被鍨 /// + public int EmailUrgentEnum { get; set; } + public string Description { get; set; } = string.Empty; + + + /// 瀹氭椂鍛ㄦ湡 /// + public string EmailCron { get; set; } = string.Empty; + + /// 閭欢涓婚 /// + public string EmailTopic { get; set; } = string.Empty; + + public string EmailTopicCN { get; set; } = string.Empty; + + + public string AttachPath { get; set; } = string.Empty; + + public string AttachCNPath { get; set; } = string.Empty; + + public string EmailHtmlContent { get; set; } = string.Empty; + + public string EmailHtmlContentCN { get; set; } = string.Empty; + + public string AttachName { get; set; } + public string AttachNameCN { get; set; } + + + public List ToUserTypeList { get; set; } + public List CopyUserTypeList { get; set; } + } + + } diff --git a/IRaCIS.Core.Application/Service/Common/EmailNoticeConfigService.cs b/IRaCIS.Core.Application/Service/Common/EmailNoticeConfigService.cs index 27adfc3be..aa07c35c1 100644 --- a/IRaCIS.Core.Application/Service/Common/EmailNoticeConfigService.cs +++ b/IRaCIS.Core.Application/Service/Common/EmailNoticeConfigService.cs @@ -17,19 +17,22 @@ namespace IRaCIS.Core.Application.Contracts public class EmailNoticeConfigService : BaseService, IEmailNoticeConfigService { private readonly IRepository _emailNoticeConfigrepository; + private readonly IRepository _emailNoticeUserTypeRepository; - public EmailNoticeConfigService(IRepository repository) + public EmailNoticeConfigService(IRepository repository, IRepository emailNoticeUserTypeRepository) { _emailNoticeConfigrepository = repository; + _emailNoticeUserTypeRepository = emailNoticeUserTypeRepository; } [HttpPost] public async Task> GetEmailNoticeConfigList(EmailNoticeConfigQuery queryEmailNoticeConfig) { var emailNoticeConfigQueryable = _emailNoticeConfigrepository + .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.IsUrgent != null, t => t.IsUrgent == queryEmailNoticeConfig.IsUrgent) .WhereIf(queryEmailNoticeConfig.IsEnable != null, t => t.IsEnable == queryEmailNoticeConfig.IsEnable) .ProjectTo(_mapper.ConfigurationProvider); @@ -39,10 +42,55 @@ namespace IRaCIS.Core.Application.Contracts public async Task AddOrUpdateEmailNoticeConfig(EmailNoticeConfigAddOrEdit addOrEditEmailNoticeConfig) { - - var entity = await _emailNoticeConfigrepository.InsertOrUpdateAsync(addOrEditEmailNoticeConfig, true); + if (addOrEditEmailNoticeConfig.Id == null) + { + + var entity = _mapper.Map(addOrEditEmailNoticeConfig); + + + foreach (var item in addOrEditEmailNoticeConfig.ToUserTypeList) + { + entity.EmailNoticeUserTypeList.Add(new EmailNoticeUserType() { EmailUserType = EmailUserType.To, UserType = item }); + + } + + foreach (var item in addOrEditEmailNoticeConfig.CopyUserTypeList) + { + entity.EmailNoticeUserTypeList.Add(new EmailNoticeUserType() { EmailUserType = EmailUserType.Copy, UserType = item }); + + } + + + await _emailNoticeConfigrepository.AddAsync(entity, true); + + return ResponseOutput.Ok(entity.Id.ToString()); + } + else + { + var emailNoticeConfigId = addOrEditEmailNoticeConfig.Id; + await _emailNoticeUserTypeRepository.BatchDeleteNoTrackingAsync(t => t.EmailNoticeConfigId == emailNoticeConfigId); + + + foreach (var item in addOrEditEmailNoticeConfig.ToUserTypeList) + { + await _emailNoticeUserTypeRepository.AddAsync(new EmailNoticeUserType() { EmailUserType = EmailUserType.To, UserType = item, EmailNoticeConfigId = (Guid)emailNoticeConfigId }); + + } + + foreach (var item in addOrEditEmailNoticeConfig.CopyUserTypeList) + { + await _emailNoticeUserTypeRepository.AddAsync(new EmailNoticeUserType() { EmailUserType = EmailUserType.Copy, UserType = item, EmailNoticeConfigId = (Guid)emailNoticeConfigId }); + + } + + + var entity = await _emailNoticeConfigrepository.UpdateFromDTOAsync(addOrEditEmailNoticeConfig, true); + + return ResponseOutput.Ok(entity.Id.ToString()); + + + } - return ResponseOutput.Ok(entity.Id.ToString()); } diff --git a/IRaCIS.Core.Application/Service/Common/_MapConfig.cs b/IRaCIS.Core.Application/Service/Common/_MapConfig.cs index 4077d674a..bff993ccd 100644 --- a/IRaCIS.Core.Application/Service/Common/_MapConfig.cs +++ b/IRaCIS.Core.Application/Service/Common/_MapConfig.cs @@ -20,7 +20,13 @@ namespace IRaCIS.Core.Application.Service CreateMap().ReverseMap(); CreateMap().ReverseMap(); - CreateMap(); + var trialId = Guid.Empty; + CreateMap().IncludeBase() + .ForMember(o => o.IsHaveSelected, t => t.MapFrom(u => u.TrialEmailNoticeConfigList.Any(c => c.TrialId == trialId && c.SysEmailNoticeConfigId == u.Id))) + ; + + CreateMap() + .ForMember(t => t.EmailNoticeUserList, u => u.MapFrom(c => c.EmailNoticeUserTypeList)); CreateMap(); diff --git a/IRaCIS.Core.Application/Service/Document/DTO/TrialEmailNoticeConfigViewModel.cs b/IRaCIS.Core.Application/Service/Document/DTO/TrialEmailNoticeConfigViewModel.cs index 8ecdc76e8..652d381a6 100644 --- a/IRaCIS.Core.Application/Service/Document/DTO/TrialEmailNoticeConfigViewModel.cs +++ b/IRaCIS.Core.Application/Service/Document/DTO/TrialEmailNoticeConfigViewModel.cs @@ -36,7 +36,7 @@ namespace IRaCIS.Core.Application.ViewModel } - public class EmailUserInfoDto + public class EmailUserInfoDto { public Guid TrialEmailNoticeConfigId { get; set; } @@ -77,7 +77,7 @@ namespace IRaCIS.Core.Application.ViewModel /// /// SMTP绔彛 /// - public int? EmailSMTPServerPort { get; set; } + public int EmailSMTPServerPort { get; set; } /// /// 鏄惁閰嶇疆杩囬偖绠 @@ -87,7 +87,7 @@ namespace IRaCIS.Core.Application.ViewModel public class SetTrialEmailInDto : GetTrialEmailSetOutDto { - + } public class GetTrialEmailSetInDto { @@ -100,7 +100,7 @@ namespace IRaCIS.Core.Application.ViewModel [NotDefault] public Guid TrialId { get; set; } - public CommonDocumentBusinessScenario? BusinessScenarioEnum { get; set; } + public EmailBusinessScenario? BusinessScenarioEnum { get; set; } //public CriterionType? CriterionTypeEnum { get; set; } @@ -117,51 +117,98 @@ namespace IRaCIS.Core.Application.ViewModel public Guid TrialReadingCriterionId { get; set; } - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } } - /// TrialEmailNoticeConfigAddOrEdit 鍒楄〃鏌ヨ鍙傛暟妯″瀷 - public class TrialEmailNoticeConfigAddOrEdit + public class BatchAddTrialEmailNoticeConfig { + + + public Guid? Id { get; set; } - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } public string Code { get; set; } = string.Empty; - public Guid? TrialReadingCriterionId { get; set; } + public Guid TrialId { get; set; } - public string AuthorizationCode { get; set; } = string.Empty; - public string SMTPServerAddress { get; set; } = string.Empty; - - public int SMTPServerPort { get; set; } - - public CriterionType CriterionTypeEnum { get; set; } - - public string FromName { get; set; } = string.Empty; - - public string FromEmail { get; set; } = string.Empty; + public CriterionType? CriterionTypeEnum { get; set; } - public List? ToUserTypeList { get; set; } + public List ToUserTypeList { get; set; } public List CopyUserTypeList { get; set; } - - public bool IsUrgent { get; set; } - + public bool IsEnable { get; set; } public bool IsAutoSend { get; set; } public bool IsReturnRequired { get; set; } - public string FilePath { get; set; } = string.Empty; - public string FileName { get; set; } = string.Empty; + /// 涓氬姟妯″潡 /// + public int BusinessModuleEnum { get; set; } + + /// 涓氬姟灞傜骇 /// + public int BusinessLevelEnum { get; set; } + + /// 閭欢绫诲瀷 /// + public int EmailTypeEnum { get; set; } + + /// 閭欢鍔犳ョ被鍨 /// + public int EmailUrgentEnum { get; set; } + + /// 瀹氭椂鍛ㄦ湡 /// + public string EmailCron { get; set; } = string.Empty; + + /// 閭欢涓婚 /// + public string EmailTopic { get; set; } = string.Empty; + + public string EmailTopicCN { get; set; } = string.Empty; + + /// 闄勪欢 /// + public string AttachPath { get; set; } = string.Empty; + + public string AttachCNPath { get; set; } = string.Empty; + + public string Description { get; set; } = string.Empty; + + + public string AttachName { get; set; } = string.Empty; + public string AttachNameCN { get; set; } = string.Empty; + + + public string EmailHtmlContent { get; set; } = string.Empty; + public string EmailHtmlContentCN { get; set; } = string.Empty; + + } + + + /// TrialEmailNoticeConfigAddOrEdit 鍒楄〃鏌ヨ鍙傛暟妯″瀷 + public class TrialEmailNoticeConfigAddOrEdit : BatchAddTrialEmailNoticeConfig + { + + public Guid? TrialReadingCriterionId { get; set; } + + + public string AuthorizationCode { get; set; } = string.Empty; + + public string SMTPServerAddress { get; set; } = string.Empty; + + public int SMTPServerPort { get; set; } + + + public string FromName { get; set; } = string.Empty; + + public string FromEmail { get; set; } = string.Empty; + + public List BlackUserIdList { get; set; } + } diff --git a/IRaCIS.Core.Application/Service/Document/EmailSendService.cs b/IRaCIS.Core.Application/Service/Document/EmailSendService.cs new file mode 100644 index 000000000..fae472eec --- /dev/null +++ b/IRaCIS.Core.Application/Service/Document/EmailSendService.cs @@ -0,0 +1,403 @@ +锘縰sing DocumentFormat.OpenXml.EMMA; +using DocumentFormat.OpenXml.Spreadsheet; +using IRaCIS.Application.Contracts; +using IRaCIS.Application.Interfaces; +using IRaCIS.Core.Application.Contracts; +using IRaCIS.Core.Application.Helper; +using IRaCIS.Core.Application.Service.Reading.Dto; +using IRaCIS.Core.Domain.Models; +using IRaCIS.Core.Domain.Share; +using IRaCIS.Core.Infrastructure; +using MailKit; +using Microsoft.Extensions.Options; +using Microsoft.VisualBasic; +using MimeKit; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mail; +using System.Text; +using System.Threading.Tasks; + +namespace IRaCIS.Core.Application.Service +{ + + public interface IEmailSendService + { + Task SendEnrollOrPdEmail(Guid visitTaskId, bool? isEnrollment, bool? isPDConfirm); + Task SendTrialImageQCTaskEmailAsync(Guid trialId); + + Task SendTrialQCQuestionEmailAsync(Guid trialId); + Task SendTrialImageQuestionAsync(Guid trialId); + } + + public class EmailSendService : BaseService, IEmailSendService + { + private readonly IRepository _trialEmailNoticeConfigRepository; + + private readonly IRepository _emailNoticeConfigRepository; + + private readonly IRepository _trialRepository; + + private readonly IDictionaryService _dictionaryService; + private readonly IOptionsMonitor _SystemEmailSendConfig; + + public readonly static string EmailNamePlaceholder = "EmailNamePlaceholder"; + + public EmailSendService(IRepository trialEmailNoticeConfigRepository, IRepository emailNoticeConfigRepository, IRepository trialRepository, IOptionsMonitor systemEmailSendConfig, IDictionaryService dictionaryService) + { + _trialEmailNoticeConfigRepository = trialEmailNoticeConfigRepository; + _emailNoticeConfigRepository = emailNoticeConfigRepository; + _trialRepository = trialRepository; + _SystemEmailSendConfig = systemEmailSendConfig; + _dictionaryService = dictionaryService; + } + + //鍏ョ粍纭/PD纭 + + public async Task SendEnrollOrPdEmail(Guid visitTaskId, bool? isEnrollment, bool? isPDConfirm) + { + EmailBusinessScenario businessScenarioEnum; + + bool? result = null; + + if (isEnrollment != null && isPDConfirm == null) + { + businessScenarioEnum = EmailBusinessScenario.EnrollConfirmed; + + result = isEnrollment; + } + else + { + businessScenarioEnum = EmailBusinessScenario.PDConfirmed; + + result = isPDConfirm; + } + + var taskInfo = await _repository.Where(t => t.Id == visitTaskId).Select(t => new + { + t.Subject.SiteId, + t.Trial.ResearchProgramNo, + t.Subject.TrialSite.TrialSiteCode, + SubjectCode = t.Subject.Code, + t.Trial.Sponsor.SponsorName, + t.SourceSubjectVisit.VisitName, + t.TrialId, + + }).FirstNotNullAsync(); + + var isEn_us = _userInfo.IsEn_Us; + + var resultStr = isEn_us ? (result == true ? "Yes" : "No") : (result == true ? "鏄" : "鍚"); + + if (isEnrollment == true) + { + Func topicAndHtmlFunc = trialEmailConfig => + { + var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, taskInfo.ResearchProgramNo, taskInfo.SubjectCode); + + var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN, + EmailNamePlaceholder, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, resultStr); + return (topicStr, htmlBodyStr, isEn_us, null); + }; + + await SendTrialEmailAsync(taskInfo.TrialId, businessScenarioEnum, topicAndHtmlFunc, taskInfo.SiteId); + } + else + { + Func topicAndHtmlFunc = trialEmailConfig => + { + var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, taskInfo.VisitName); + + var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN, + EmailNamePlaceholder, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, taskInfo.VisitName, resultStr); + + return (topicStr, htmlBodyStr, isEn_us, null); + }; + + await SendTrialEmailAsync(taskInfo.TrialId, businessScenarioEnum, topicAndHtmlFunc, taskInfo.SiteId); + } + + + } + + /// + /// 褰卞儚璐ㄦ帶 + /// + /// + /// + public async Task SendTrialImageQCTaskEmailAsync(Guid trialId) + { + var isEn_us = false; + var trialInfo = await _repository.Where(t => t.Id == trialId).Select(t => new { t.ResearchProgramNo, t.ExperimentName, t.TrialCode, t.TrialStatusStr }).FirstNotNullAsync(); + + //鎵惧埌 璇ラ」鐩殑IQC 鐢ㄦ埛Id + var userList = await _repository.Where(t => t.TrialId == trialId).Where(t => t.User.UserTypeEnum == UserTypeEnum.IQC).Select(t => new { t.UserId, t.User.FullName }).ToListAsync(); + + //鍒ゆ柇鏄惁浠诲姟鍙互棰嗗彇 锛屽彲浠ョ殑璇 鍙戦侀偖浠 + var userIdList = userList.Select(t => t.UserId).ToList(); + + foreach (var user in userList) + { + var userId = user.UserId; + + //杩囨护椤圭洰 骞朵笖 灏 _userInfo.Id 鎹綅 褰撳墠鍙戦侀偖浠剁殑Id + var query = _trialRepository.Where(t => t.Id == trialId) + .Where(t => t.QCProcessEnum != TrialQCProcess.NotAudit) + .Select(t => new + { + //寰呴鍙栭噺 + ToBeClaimedCount = t.SubjectVisitList.Where(u => u.SubmitState == SubmitStateEnum.Submitted && u.CurrentActionUserId == null && (u.PreliminaryAuditUserId == null || (u.PreliminaryAuditUserId != userId && u.ReviewAuditUserId == null))).Count(), + + //寰呭鏍搁氳繃锛岀粺璁′粠宸查鍙栧埌QC鎻愪氦涔嬮棿鐨 宸查鍙 寰呭鏍 瀹℃牳涓 (瀹℃牳瀹屾垚 棰嗗彇浜哄氨浼氭竻鐞 鎵浠ュ彧鐢ㄦ煡璇㈠綋鍓嶉鍙栦汉鏄嚜宸辩殑灏卞ソ浜) + ToBeReviewedCount = t.SubjectVisitList.Where(u => u.CurrentActionUserId == userId).Count() + + }); + + var sendStat = await query.FirstOrDefaultAsync(); + + //褰撳墠浜 鏈夊緟棰嗗彇鐨勬垨鑰呮湁寰呭鏍哥殑鎵嶅彂閭欢 + if (sendStat != null && (sendStat.ToBeClaimedCount > 0 || sendStat.ToBeReviewedCount > 0)) + { + + Func topicAndHtmlFunc = trialEmailConfig => + { + var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, trialInfo.ResearchProgramNo); + var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN, + user.FullName, DateTime.Now, sendStat.ToBeClaimedCount, sendStat.ToBeReviewedCount, _SystemEmailSendConfig.CurrentValue.SiteUrl); + return (topicStr, htmlBodyStr, false, userId); + }; + + await SendTrialEmailAsync(trialId, EmailBusinessScenario.QCTask, topicAndHtmlFunc); + } + } + } + + /// + /// QC璐ㄧ枒 + /// + /// + /// + public async Task SendTrialQCQuestionEmailAsync(Guid trialId) + { + var isEn_us = false; + var trialInfo = _repository.Where(t => t.Id == trialId).Select(t => new { t.ResearchProgramNo, t.ExperimentName, t.TrialCode, t.TrialStatusStr, t.DeclarationTypeEnumList }).FirstOrDefault(); + + //鎵惧埌 璇ラ」鐩殑IQC 鐢ㄦ埛Id + var userList = await _repository.Where(t => t.TrialId == trialId).Where(t => t.User.UserTypeEnum == UserTypeEnum.IQC).Select(t => new { t.UserId, t.User.FullName }).ToListAsync(); + + //鍒ゆ柇鏄惁浠诲姟鍙互棰嗗彇 锛屽彲浠ョ殑璇 鍙戦侀偖浠 + + foreach (var user in userList) + { + var userId = user.UserId; + + //杩囨护椤圭洰 骞朵笖 灏 _userInfo.Id 鎹綅 褰撳墠鍙戦侀偖浠剁殑Id + var query = _trialRepository + .Where(t => t.Id == trialId) + .Select(t => new + { + ReUploadTobeDealedCount = t.SubjectVisitList.SelectMany(c => c.QCChallengeList) + .Where(u => u.CreateUserId == userId && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator && u.ReuploadEnum == QCChanllengeReuploadEnum.CRCRequestReupload).Count(), + + //璐ㄧ枒寰呭鐞 鍙戦侀偖浠剁殑鏃跺 闇瑕佸噺鍘籖eUploadTobeDealedCount + ToBeDealedCount = t.SubjectVisitList.SelectMany(c => c.QCChallengeList) + .Where(u => u.CreateUserId == userId && u.IsClosed == false && u.LatestReplyUser.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Count(), + }); + + var sendStat = await query.FirstOrDefaultAsync(); + + //褰撳墠浜 + if (sendStat != null && (sendStat.ToBeDealedCount > 0 || sendStat.ReUploadTobeDealedCount > 0)) + { + + Func topicAndHtmlFunc = trialEmailConfig => + { + var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, trialInfo.ResearchProgramNo); + var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN, + + user.FullName, DateTime.Now, sendStat.ToBeDealedCount - sendStat.ReUploadTobeDealedCount, sendStat.ReUploadTobeDealedCount, _SystemEmailSendConfig.CurrentValue.SiteUrl); + return (topicStr, htmlBodyStr, false, userId); + }; + + await SendTrialEmailAsync(trialId, EmailBusinessScenario.QCQuestion, topicAndHtmlFunc); + } + } + } + + /// + /// 褰卞儚璐ㄧ枒 + /// + /// + /// + public async Task SendTrialImageQuestionAsync(Guid trialId) + { + var isEn_us = false; + + var trialInfo = _repository.Where(t => t.Id == trialId).Select(t => new { t.ResearchProgramNo, t.ExperimentName, t.TrialCode, t.TrialStatusStr }).FirstOrDefault(); + + //鎵惧埌 璇ラ」鐩殑CRC 鐢ㄦ埛Id + var userList = await _repository.Where(t => t.TrialId == trialId).Where(t => t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Select(t => new { t.UserId, t.User.FullName }).ToListAsync(); + + //鍒ゆ柇鏄惁浠诲姟鍙互棰嗗彇 锛屽彲浠ョ殑璇 鍙戦侀偖浠 + + foreach (var user in userList) + { + var userId = user.UserId; + //杩囨护椤圭洰 骞朵笖 灏 _userInfo.Id 鎹綅 褰撳墠鍙戦侀偖浠剁殑Id + var query = _trialRepository.Where(t => t.Id == trialId) + + .Select(t => new + { + //璐ㄧ枒寰呭鐞 + ToBeDealedCount = t.SubjectVisitList.Where(t => t.TrialSite.CRCUserList.Any(t => t.UserId == userId)).SelectMany(c => c.QCChallengeList) + .Where(u => u.IsClosed == false && (u.LatestReplyUser.UserTypeEnum == UserTypeEnum.IQC || u.LatestReplyUserId == null)).Count(), + + }); + + var sendStat = await query.FirstOrDefaultAsync(); + + //褰撳墠浜 + if (sendStat != null && (sendStat.ToBeDealedCount > 0)) + { + + Func topicAndHtmlFunc = trialEmailConfig => + { + var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, trialInfo.ResearchProgramNo); + var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN, + user.FullName, DateTime.Now, sendStat.ToBeDealedCount, _SystemEmailSendConfig.CurrentValue.SiteUrl); + return (topicStr, htmlBodyStr, isEn_us, userId); + }; + + await SendTrialEmailAsync(trialId, EmailBusinessScenario.ImageQuestion, topicAndHtmlFunc); + } + } + } + + + + + public async Task SendTrialEmailAsync(Guid trialId, EmailBusinessScenario businessScenario, Func topicAndHtmlFunc, Guid? siteId = null, Guid? trialReadingCriterionId = null) + { + //鎵惧埌閰嶇疆 + var trialEmailConfig = await _trialEmailNoticeConfigRepository.Where(t => t.TrialId == trialId && t.TrialReadingCriterionId == trialReadingCriterionId && t.BusinessScenarioEnum == businessScenario, ignoreQueryFilters: true) + .Include(t => t.TrialEmailNoticeUserList).Include(t => t.TrialEmailBlackUserList).FirstOrDefaultAsync(); + + + if (trialEmailConfig == null || trialEmailConfig.IsAutoSend == false) + { + return; + } + else + { + var sendEmailConfig = new SMTPEmailConfig(); + + var (topicStr, htmlBodyStr, isEn_us, onlyToUserId) = topicAndHtmlFunc(trialEmailConfig); + + + sendEmailConfig.TopicDescription = topicStr; + sendEmailConfig.HtmlBodyStr = htmlBodyStr; + + + var blackUserIdList = trialEmailConfig.TrialEmailBlackUserList.Select(t => t.UserId).ToList(); + + + var toUserTypeEnumList = trialEmailConfig.TrialEmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.To).Select(c => c.UserType).ToList(); + + var copyUserTypeEnumList = trialEmailConfig.TrialEmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.Copy).Select(c => c.UserType).ToList(); + + var allUserTypeEnumList = toUserTypeEnumList.Union(copyUserTypeEnumList).Distinct().ToList(); + + var allUserList = await _repository.Where(t => t.TrialId == trialId && allUserTypeEnumList.Contains(t.User.UserTypeEnum)).Select(t => new { t.UserId, t.User.EMail, t.User.FullName, t.User.UserTypeEnum }).ToListAsync(); + + + var toUserList = allUserList.Where(t => toUserTypeEnumList.Contains(t.UserTypeEnum)) + .ToList(); + + //鏀朵欢浜 鏈塁RC CRA 锛 CRC CRA鐨勮处鎴疯鎸夌収涓績鍙戦 + if (siteId == null && toUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA) && onlyToUserId == null) + { + throw new BusinessValidationFailedException("褰撳墠鍦烘櫙鏀朵欢浜哄寘鍚獵RC CRA,浣嗘槸娌℃湁siteId,璇疯仈绯诲悗绔紑鍙"); + } + if (siteId != null && toUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA)) + { + var curentSiteUserIdList = _repository.Where(t => t.TrialId == trialId && t.SiteId == siteId).Select(t => t.UserId).ToList(); + + toUserList = toUserList.Where(t => (t.UserTypeEnum != UserTypeEnum.CRA && t.UserTypeEnum != UserTypeEnum.ClinicalResearchCoordinator) || curentSiteUserIdList.Contains(t.UserId)).ToList(); + } + + + //鍘婚櫎榛戝悕鍗 + toUserList = toUserList.Where(t => !blackUserIdList.Contains(t.UserId)).ToList(); + + var copyUserList = allUserList.Where(t => copyUserTypeEnumList.Contains(t.UserTypeEnum)) + .Where(t => !blackUserIdList.Contains(t.UserId)).ToList(); + + if (siteId != null && copyUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA)) + { + var curentSiteUserIdList = _repository.Where(t => t.TrialId == trialId && t.SiteId == siteId).Select(t => t.UserId).ToList(); + + copyUserList = copyUserList.Where(t => (t.UserTypeEnum != UserTypeEnum.CRA && t.UserTypeEnum != UserTypeEnum.ClinicalResearchCoordinator) || curentSiteUserIdList.Contains(t.UserId)).ToList(); + } + + if (onlyToUserId != null) + { + toUserList = toUserList.Where(t => t.UserId == onlyToUserId).ToList(); + } + else + { + sendEmailConfig.HtmlBodyStr = htmlBodyStr.Replace(EmailNamePlaceholder, string.Join(isEn_us ? ", " : "銆", toUserList.Select(t => t.FullName).ToList())); + } + + if (toUserList.Count() == 0) + { + //---娌℃湁鏀朵欢浜猴紝鏃犳硶鍙戦侀偖浠 + throw new BusinessValidationFailedException(_localizer["TrialEmailN_NoRecipient"]); + } + + + if (trialEmailConfig.FromEmail.Contains("@") && !string.IsNullOrEmpty(trialEmailConfig.FromEmail)) + { + + sendEmailConfig.FromEmailAddress = new MimeKit.MailboxAddress(trialEmailConfig.FromName, trialEmailConfig.FromEmail); + sendEmailConfig.AuthorizationCode = trialEmailConfig.AuthorizationCode; + sendEmailConfig.UserName = trialEmailConfig.FromEmail; + + sendEmailConfig.Host = trialEmailConfig.SMTPServerAddress; + sendEmailConfig.Port = trialEmailConfig.SMTPServerPort; + } + else + { + //---椤圭洰鍙戜欢閭閰嶇疆鏈夎锛岃鏍稿疄 + throw new BusinessValidationFailedException(_localizer["TrialEmailN_InvalidEmailConfig"]); + } + + foreach (var item in toUserList) + { + + if (item.EMail.Contains("@") && !string.IsNullOrEmpty(item.EMail)) + { + + sendEmailConfig.ToMailAddressList.Add(new MimeKit.MailboxAddress(item.FullName, item.EMail)); + + } + } + foreach (var item in copyUserList) + { + + if (item.EMail.Contains("@") && !string.IsNullOrEmpty(item.EMail)) + { + + sendEmailConfig.CopyToMailAddressList.Add(new MimeKit.MailboxAddress(item.FullName, item.EMail)); + + } + } + + await SendEmailHelper.SendEmailAsync(sendEmailConfig); + + } + } + + + } +} diff --git a/IRaCIS.Core.Application/Service/Document/TrialEmailNoticeConfigService.cs b/IRaCIS.Core.Application/Service/Document/TrialEmailNoticeConfigService.cs index 5289dea1d..7a68d55ef 100644 --- a/IRaCIS.Core.Application/Service/Document/TrialEmailNoticeConfigService.cs +++ b/IRaCIS.Core.Application/Service/Document/TrialEmailNoticeConfigService.cs @@ -32,30 +32,41 @@ namespace IRaCIS.Core.Application.Service { private readonly IRepository _trialEmailNoticeConfigRepository; + private readonly IRepository _trialEmailBlackUserRepository; + private readonly IRepository _emailNoticeConfigRepository; + private readonly IRepository _trialRepository; - private readonly IRepository _taskMedicalReviewRepository; + private readonly IRepository _visitTaskRepository; + private readonly IRepository _trialUserRepository; + private readonly IRepository _subjectRepository; + private readonly IRepository _subjectVisitRepository; - public IRepository _visitTaskRepository { get; } - public IRepository _trialUserRepository { get; } - public IRepository _subjectRepository { get; } - public IRepository _subjectVisitRepository { get; } - public TrialEmailNoticeConfigService(IRepository trialEmailNoticeConfigRepository, IRepository visitTaskRepository, + public TrialEmailNoticeConfigService( + IRepository trialEmailNoticeConfigRepository, + IRepository visitTaskRepository, IRepository trialRepository, - IRepository trialUserRepository, IRepository taskMedicalReviewRepository, IRepository subjectRepository, IRepository subjectVisitRepository) + IRepository trialUserRepository, + IRepository taskMedicalReviewRepository, + IRepository subjectRepository, + IRepository subjectVisitRepository, + IRepository trialEmailBlackUserRepository, + IRepository emailNoticeConfigRepository + ) { _trialEmailNoticeConfigRepository = trialEmailNoticeConfigRepository; _visitTaskRepository = visitTaskRepository; - this._trialRepository = trialRepository; + _trialRepository = trialRepository; _trialUserRepository = trialUserRepository; _taskMedicalReviewRepository = taskMedicalReviewRepository; _subjectRepository = subjectRepository; - _subjectVisitRepository = subjectVisitRepository; + _trialEmailBlackUserRepository = trialEmailBlackUserRepository; + _emailNoticeConfigRepository = emailNoticeConfigRepository; } /// @@ -66,7 +77,7 @@ namespace IRaCIS.Core.Application.Service [HttpPost] public async Task GetTrialEmail(GetTrialEmailSetInDto inDto) { - return await _trialRepository.Where(x => x.Id == inDto.TrialId).Select(x => new GetTrialEmailSetOutDto() + return await _trialRepository.Where(x => x.Id == inDto.TrialId, ignoreQueryFilters: true).Select(x => new GetTrialEmailSetOutDto() { TrialId = inDto.TrialId, EmailAuthorizationCode = x.EmailAuthorizationCode, @@ -76,7 +87,7 @@ namespace IRaCIS.Core.Application.Service IsConfigureEmail = x.IsConfigureEmail, EmailSMTPServerPort = x.EmailSMTPServerPort - }).FirstNotNullAsync(); + }).FirstOrDefaultAsync(); } /// @@ -94,7 +105,7 @@ namespace IRaCIS.Core.Application.Service FromEmail = inDto.EmailFromEmail, FromName = inDto.EmailFromName, SMTPServerAddress = inDto.EmailSMTPServerAddress, - SMTPServerPort = inDto.EmailSMTPServerPort.Value, + SMTPServerPort = inDto.EmailSMTPServerPort, TrialId = inDto.TrialId, }); @@ -117,7 +128,7 @@ namespace IRaCIS.Core.Application.Service FromEmail = inDto.EmailFromEmail, FromName = inDto.EmailFromName, SMTPServerAddress = inDto.EmailSMTPServerAddress, - SMTPServerPort = inDto.EmailSMTPServerPort.Value, + SMTPServerPort = inDto.EmailSMTPServerPort, }); await _trialRepository.SaveChangesAsync(); @@ -125,7 +136,7 @@ namespace IRaCIS.Core.Application.Service } /// - /// 鍚屾绯荤粺閰嶇疆鐨勬枃妗e埌鎯抽」鐩腑 + /// 鍚屾绯荤粺閰嶇疆鐨勬枃妗e埌鎯抽」鐩腑 ---搴熷純 /// /// /// @@ -139,7 +150,7 @@ namespace IRaCIS.Core.Application.Service { //鍙鏈夌郴缁熸爣鍑嗙殑鏂囨。 璇存槑鍚屾杩囦簡 - var trialDocCount = _trialEmailNoticeConfigRepository.Where(t =>/* t.CriterionTypeEnum == criterionTypeEnum &&*/ t.TrialId == trialId && t.TrialReadingCriterionId != null).Count(); + var trialDocCount = _trialEmailNoticeConfigRepository.Where(t => t.TrialId == trialId).Count(); if (trialDocCount == 0) { @@ -148,7 +159,10 @@ namespace IRaCIS.Core.Application.Service var confirmedCriterionTypeList = list.Select(t => (CriterionType?)t.CriterionType).ToList(); - var docmentList = _repository.Where(t => confirmedCriterionTypeList.Contains(t.CriterionTypeEnum)).Select(t => new { t.Path, t.Name, t.Code, t.BusinessScenarioEnum, t.CriterionTypeEnum }).ToList(); + var docmentList = _repository.Where(t => t.BusinessScenarioEnum == EmailBusinessScenario.EnrollConfirmed || t.BusinessScenarioEnum == EmailBusinessScenario.PDConfirmed) + //.Where(t => (confirmedCriterionTypeList.Contains(t.CriterionTypeEnum)) || t.CriterionTypeEnum == null).Select(t => new { t.Path, t.Name, t.Code, t.BusinessScenarioEnum, t.CriterionTypeEnum }) + .ToList(); + foreach (var item in docmentList) @@ -157,8 +171,8 @@ namespace IRaCIS.Core.Application.Service { TrialId = trialId, TrialReadingCriterionId = list.Where(t => t.CriterionType == item.CriterionTypeEnum).FirstOrDefault()?.TrialReadingCriterionId, - FileName = item.Name, - FilePath = item.Path, + //FileName = item.Name, + //FilePath = item.Path, BusinessScenarioEnum = item.BusinessScenarioEnum, Code = item.Code }); @@ -176,6 +190,7 @@ namespace IRaCIS.Core.Application.Service + private async Task DealMedicalReviewTasKGenerateAndIsSendAsync(Guid trialId, bool? isHandSend, string pdAnswer, List taskIdList, List minUserIdList) { @@ -241,7 +256,7 @@ namespace IRaCIS.Core.Application.Service public async Task BaseBusinessScenarioSendEmailAsync(Guid visitTaskId, bool? isHandSend, EmailStoreSendMode emailStoreMode, string sendFileRelativePath) { - CommonDocumentBusinessScenario? businessScenarioEnum = null; + EmailBusinessScenario? businessScenarioEnum = null; #region 浠诲姟鍏宠仈鐨勯」鐩厤缃 鏍囧噯淇℃伅鍙婇厤缃紝subject 淇℃伅 var taskInfo = await _visitTaskRepository.Where(t => t.Id == visitTaskId).Select(t => new @@ -309,7 +324,7 @@ namespace IRaCIS.Core.Application.Service //鍏ョ粍纭鍦烘櫙 if (taskInfo.IsEnrollmentConfirm == true && taskInfo.IsEnrollementQualificationConfirm == true && taskInfo.IsBaseline == true) { - businessScenarioEnum = CommonDocumentBusinessScenario.EnrollConfirmed; + businessScenarioEnum = EmailBusinessScenario.EnrollConfirmed; } @@ -318,7 +333,7 @@ namespace IRaCIS.Core.Application.Service (taskInfo.PDState == PDStateEnum.PDProgress && taskInfo.SourceSubjectVisitId != null) || (taskInfo.SouceReadModuleId != null && taskInfo.MoudulePDState == PDStateEnum.PDProgress)) { - businessScenarioEnum = CommonDocumentBusinessScenario.PDConfirmed; + businessScenarioEnum = EmailBusinessScenario.PDConfirmed; } else { @@ -344,7 +359,7 @@ namespace IRaCIS.Core.Application.Service .Include(t => t.TrialEmailNoticeUserList).FirstOrDefaultAsync(); - if (emailConfig == null || (emailConfig.IsAutoSend == false && isHandSend==null)) + if (emailConfig == null || (emailConfig.IsAutoSend == false && isHandSend == null)) { //throw new BusinessValidationFailedException("鎵句笉鍒拌椤圭洰鏍囧噯鍦烘櫙涓嬮偖浠剁殑閰嶇疆"); @@ -418,7 +433,7 @@ namespace IRaCIS.Core.Application.Service #region 纭繚 閭欢Html瀛樺湪 //閭欢闄勪欢 - var path = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, emailConfig.FilePath); + var path = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, _userInfo.IsEn_Us ? emailConfig.AttachPath : emailConfig.AttachCNPath); if (!File.Exists(path)) { @@ -431,7 +446,7 @@ namespace IRaCIS.Core.Application.Service + Path.DirectorySeparatorChar.ToString() + "EmailTemplate" + Path.DirectorySeparatorChar.ToString() - //+ "SubjectEnrollConfirmOrPDProgress.html"; + //+ "SubjectEnrollConfirmOrPDProgress.html"; + (_userInfo.IsEn_Us ? "SubjectEnrollConfirmOrPDProgress_US.html" : "SubjectEnrollConfirmOrPDProgress.html"); #endregion @@ -439,7 +454,7 @@ namespace IRaCIS.Core.Application.Service #region 涓嶅悓鍦烘櫙 Tile 璁剧疆 - if (businessScenarioEnum == CommonDocumentBusinessScenario.EnrollConfirmed) + if (businessScenarioEnum == EmailBusinessScenario.EnrollConfirmed) { sendEmailConfig.TopicDescription = _localizer["TrialEmailN_EnrollmentConfirmation", taskInfo.ResearchProgramNo, taskInfo.SubjectCode]; @@ -454,7 +469,7 @@ namespace IRaCIS.Core.Application.Service ); } } - else if (businessScenarioEnum == CommonDocumentBusinessScenario.PDConfirmed) + else if (businessScenarioEnum == EmailBusinessScenario.PDConfirmed) { sendEmailConfig.TopicDescription = _localizer["TrialEmailN_PDReport", taskInfo.ResearchProgramNo, taskInfo.SubjectCode]; @@ -464,7 +479,7 @@ namespace IRaCIS.Core.Application.Service sendEmailConfig.HtmlBodyStr = string.Format(templateInfo, - //--- 闄勪欢涓虹柧鐥呰繘灞曠‘璁ゆ姤鍛婏紝璇锋煡鏀 + //--- 闄勪欢涓虹柧鐥呰繘灞曠‘璁ゆ姤鍛婏紝璇锋煡鏀 _localizer["TrialEmailN_SubjectDiseaseProgression"] ); } @@ -486,7 +501,7 @@ namespace IRaCIS.Core.Application.Service //鍏ョ粍纭 鏍规嵁姣忎釜鏍囧噯閰嶇疆鐨勬槸鍚﹁嚜鍔ㄥ彂閫侊紝鍙戦侀偖浠朵笌鍚 - if (businessScenarioEnum == CommonDocumentBusinessScenario.EnrollConfirmed) + if (businessScenarioEnum == EmailBusinessScenario.EnrollConfirmed) { if (await _repository.Where().AnyAsync(x => x.VisitTaskId == visitTaskId && x.Answer == TargetState.Exist.GetEnumInt() && x.ReadingTableQuestionTrial.QuestionMark == QuestionMark.State && x.ReadingQuestionTrial.LesionType == LesionType.TargetLesion)) @@ -531,7 +546,7 @@ namespace IRaCIS.Core.Application.Service } - else if (businessScenarioEnum == CommonDocumentBusinessScenario.PDConfirmed) + else if (businessScenarioEnum == EmailBusinessScenario.PDConfirmed) { @@ -629,7 +644,7 @@ namespace IRaCIS.Core.Application.Service } else { - //---鍙戦丳D 杩涘睍閭欢涓彂鐜颁换鍔℃暟鎹湁闂锛 + //---鍙戦丳D 杩涘睍閭欢涓彂鐜颁换鍔℃暟鎹湁闂锛 throw new BusinessValidationFailedException(_localizer["TrialEmailN_PDProgressEmailTask"]); } @@ -639,13 +654,13 @@ namespace IRaCIS.Core.Application.Service else { - //---鍙岄噸鏈夊簭闃呯墖 娌℃湁瀹氫箟璇ヤ徊瑁佽鍒欏鐞嗛昏緫锛岃鑱旂郴涓氬姟鍜屽悗鍙板紑鍙戞牳鏌ワ紒 + //---鍙岄噸鏈夊簭闃呯墖 娌℃湁瀹氫箟璇ヤ徊瑁佽鍒欏鐞嗛昏緫锛岃鑱旂郴涓氬姟鍜屽悗鍙板紑鍙戞牳鏌ワ紒 throw new BusinessValidationFailedException(_localizer["TrialEmailN_DoubleBlindedError"]); } } - + //灞忚斀鍗曢噸闃呯墖娣诲姞 else { @@ -661,7 +676,7 @@ namespace IRaCIS.Core.Application.Service // if (taskInfo.ArbitrationRule != ArbitrationRule.None) // { - //---鍗曢噸鏈夊簭闃呯墖閰嶇疆鏈夎(涓嶅簲璇ユ湁浠茶瀵硅薄閰嶇疆)锛岃鏍告煡锛 + //---鍗曢噸鏈夊簭闃呯墖閰嶇疆鏈夎(涓嶅簲璇ユ湁浠茶瀵硅薄閰嶇疆)锛岃鏍告煡锛 // throw new BusinessValidationFailedException(_localizer["TrialEmailN_SingleBlindedSet"]); // } @@ -687,7 +702,7 @@ namespace IRaCIS.Core.Application.Service // } // else // { - //---鍗曢噸鏈夊簭闃呯墖 璇ョ被鍨嬬殑浠诲姟涓嶅簲杩涘叆姝ゅ閫昏緫锛岃鑱旂郴鍚庡彴寮鍙戞牳鏌ワ紒 + //---鍗曢噸鏈夊簭闃呯墖 璇ョ被鍨嬬殑浠诲姟涓嶅簲杩涘叆姝ゅ閫昏緫锛岃鑱旂郴鍚庡彴寮鍙戞牳鏌ワ紒 // throw new BusinessValidationFailedException(_localizer["TrialEmailN_SingleBlindedSequenced"]); // } @@ -697,7 +712,7 @@ namespace IRaCIS.Core.Application.Service //} //else //{ - //---鏈夊簭闃呯墖閰嶇疆鏈夎(搴斾负鍗曢噸鎴栬呭弻閲嶉槄鐗)锛岃鏍告煡锛 + //---鏈夊簭闃呯墖閰嶇疆鏈夎(搴斾负鍗曢噸鎴栬呭弻閲嶉槄鐗)锛岃鏍告煡锛 // throw new BusinessValidationFailedException(_localizer["TrialEmailN_BlindedSequencedReading"]); //} @@ -788,7 +803,7 @@ namespace IRaCIS.Core.Application.Service //鍏堥鍏堢敓鎴愪簡閭欢锛屽彂閫侀鍏堢敓鎴愮殑閭欢 sendEmailConfig.EmailAttachMentConfigList.Add(new EmailAttachMentConfig() { - FileName = $"{taskInfo.SubjectCode}_{Path.GetFileNameWithoutExtension(emailConfig.FileName)}.pdf", + FileName = $"{taskInfo.SubjectCode}_{Path.GetFileNameWithoutExtension(_userInfo.IsEn_Us ? emailConfig.AttachName : emailConfig.AttachNameCN)}.pdf", FileStream = File.OpenRead(phyPath), }); @@ -812,7 +827,7 @@ namespace IRaCIS.Core.Application.Service }; - var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetSubjectEnrollConfirmOrPDEmailPath(_hostEnvironment, Path.GetFileName(path), taskInfo.TrialId, taskInfo.SiteId, taskInfo.SubjectId,true); + var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetSubjectEnrollConfirmOrPDEmailPath(_hostEnvironment, Path.GetFileName(path), taskInfo.TrialId, taskInfo.SiteId, taskInfo.SubjectId, true); if (emailStoreMode == EmailStoreSendMode.StoreLocalSend || emailStoreMode == EmailStoreSendMode.OnlyStoreLocalNotSentEmail) { @@ -823,7 +838,7 @@ namespace IRaCIS.Core.Application.Service MiniSoftware.MiniWord.SaveAsByTemplate(wordMemoryStream, path, value); - document.LoadFromStream(wordMemoryStream,FileFormat.Docx); + document.LoadFromStream(wordMemoryStream, FileFormat.Docx); document.SaveToFile(serverFilePath, FileFormat.PDF); @@ -856,7 +871,7 @@ namespace IRaCIS.Core.Application.Service sendEmailConfig.EmailAttachMentConfigList.Add(new EmailAttachMentConfig() { - FileName = $"{taskInfo.SubjectCode}_{Path.GetFileNameWithoutExtension(emailConfig.FileName)}.pdf", + FileName = $"{taskInfo.SubjectCode}_{Path.GetFileNameWithoutExtension(_userInfo.IsEn_Us ? emailConfig.AttachName : emailConfig.AttachNameCN)}.pdf", FileStream = pdfMemoryStream }); @@ -900,19 +915,19 @@ namespace IRaCIS.Core.Application.Service //鎵惧埌鍏ョ粍纭 鎴栬匬d 杩涘睍 宸茬敓鎴愪换鍔$殑 璁胯 var subjectVisitList = await _subjectVisitRepository.Where(t => t.SubjectId == subjectId & t.CheckState == CheckStateEnum.CVPassed && (t.IsEnrollmentConfirm == true || t.PDState == PDStateEnum.PDProgress)).ToListAsync(); - if (businessScenarioEnum == CommonDocumentBusinessScenario.EnrollConfirmed) + if (businessScenarioEnum == EmailBusinessScenario.EnrollConfirmed) { if (trialConfig.IsEnrollementQualificationConfirm == false) { - //---椤圭洰鏈厤缃叆缁勭‘璁わ紒 + //---椤圭洰鏈厤缃叆缁勭‘璁わ紒 return ResponseOutput.NotOk(_localizer["TrialEmailN_InCons"]); } var exisitBaseline = subjectVisitList.FirstOrDefault(t => t.IsEnrollmentConfirm); if (exisitBaseline == null) { - //---涓嶅瓨鍦ㄩ厤缃簡鍏ョ粍纭鐨勫苟涓旂敓鎴愪换鍔$殑鍩虹嚎璁胯 + //---涓嶅瓨鍦ㄩ厤缃簡鍏ョ粍纭鐨勫苟涓旂敓鎴愪换鍔$殑鍩虹嚎璁胯 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoBaseLine"]); } else @@ -933,7 +948,7 @@ namespace IRaCIS.Core.Application.Service if (task == null) { - //---鍋氬叆缁勭‘璁ょ殑闃呯墖浜哄熀绾夸换鍔℃病鏈夐槄鐗囧畬锛 + //---鍋氬叆缁勭‘璁ょ殑闃呯墖浜哄熀绾夸换鍔℃病鏈夐槄鐗囧畬锛 return ResponseOutput.NotOk(_localizer["TrialEmailN_IncompBase"]); } else @@ -942,7 +957,7 @@ namespace IRaCIS.Core.Application.Service if (string.IsNullOrEmpty(filePath)) { - //---閭欢鎵嬪姩鐢熸垚澶辫触锛岃鑱旂郴寮鍙戞牳瀹炶鍦烘櫙澶辫触鍘熷洜 + //---閭欢鎵嬪姩鐢熸垚澶辫触锛岃鑱旂郴寮鍙戞牳瀹炶鍦烘櫙澶辫触鍘熷洜 return ResponseOutput.NotOk(_localizer["TrialEmailN_EmailFail"]); } else @@ -956,7 +971,7 @@ namespace IRaCIS.Core.Application.Service } else { - //---褰撳墠鏈湁闃呯墖浜鸿瀹屽熀绾夸换鍔★紒 + //---褰撳墠鏈湁闃呯墖浜鸿瀹屽熀绾夸换鍔★紒 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoReader"]); } @@ -967,12 +982,12 @@ namespace IRaCIS.Core.Application.Service } } - else if (businessScenarioEnum == CommonDocumentBusinessScenario.PDConfirmed) + else if (businessScenarioEnum == EmailBusinessScenario.PDConfirmed) { if (trialConfig.IsPDProgressView == false) { - //---椤圭洰鏈厤缃甈D杩涘睍锛 + //---椤圭洰鏈厤缃甈D杩涘睍锛 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoPDConfig"]); } @@ -982,7 +997,7 @@ namespace IRaCIS.Core.Application.Service if (pdSubjectVisitIdList.Count == 0) { - //---涓嶅瓨鍦ㄩ厤缃簡PD杩涘睍鐨勫苟涓旂敓鎴愪换鍔$殑璁胯 + //---涓嶅瓨鍦ㄩ厤缃簡PD杩涘睍鐨勫苟涓旂敓鎴愪换鍔$殑璁胯 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoPDTasks"]); } @@ -1027,7 +1042,7 @@ namespace IRaCIS.Core.Application.Service } else { - //---褰撳墠鍙楄瘯鑰呮渶鏂癙D璁胯闃呯墖浠诲姟瀹屾垚鐘舵佷笉绗﹀悎鍙戦佹潯浠 + //---褰撳墠鍙楄瘯鑰呮渶鏂癙D璁胯闃呯墖浠诲姟瀹屾垚鐘舵佷笉绗﹀悎鍙戦佹潯浠 return ResponseOutput.NotOk(_localizer["TrialEmailN_PDNotFinished"]); } @@ -1040,7 +1055,7 @@ namespace IRaCIS.Core.Application.Service if (existReadModule == null) { - //---椤圭洰閰嶇疆浜嗛槄鐗囨湡浠茶锛屼絾鏄綋鍓嶅彈璇曡呮渶鏂癙D璁胯娌℃湁褰卞儚瀛﹂槄鐗囨湡 + //---椤圭洰閰嶇疆浜嗛槄鐗囨湡浠茶锛屼絾鏄綋鍓嶅彈璇曡呮渶鏂癙D璁胯娌℃湁褰卞儚瀛﹂槄鐗囨湡 return ResponseOutput.NotOk(_localizer["TrialEmailN_PDNoImaging"]); } else @@ -1075,7 +1090,7 @@ namespace IRaCIS.Core.Application.Service else { - //---褰撳墠鍙楄瘯鑰呮渶鏂癙D璁胯闃呯墖鏈熶换鍔″畬鎴愮姸鎬佷笉绗﹀悎鍙戦佹潯浠 + //---褰撳墠鍙楄瘯鑰呮渶鏂癙D璁胯闃呯墖鏈熶换鍔″畬鎴愮姸鎬佷笉绗﹀悎鍙戦佹潯浠 return ResponseOutput.NotOk(_localizer["TrialEmailN_PDPhaseNotFinished"]); } } @@ -1084,7 +1099,7 @@ namespace IRaCIS.Core.Application.Service } else { - //---鏈畾涔夎浠茶瑙勫垯鍙戦佷笟鍔¢昏緫锛 + //---鏈畾涔夎浠茶瑙勫垯鍙戦佷笟鍔¢昏緫锛 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoRuleDefined"]); } } @@ -1143,7 +1158,7 @@ namespace IRaCIS.Core.Application.Service else { - //---褰撳墠椤圭洰閰嶇疆锛屼笉婊¤冻鍙岄噸鏈夊簭闃呯墖锛屼笉婊¤冻鍙戦佹潯浠讹紒 + //---褰撳墠椤圭洰閰嶇疆锛屼笉婊¤冻鍙岄噸鏈夊簭闃呯墖锛屼笉婊¤冻鍙戦佹潯浠讹紒 return ResponseOutput.NotOk(_localizer["TrialEmailN_NoDoubleOrder"]); } @@ -1233,7 +1248,7 @@ namespace IRaCIS.Core.Application.Service //} else { - //---涓嶅簲鏈 闄よ瑙嗐佽鍒ゃ佸叏灞鍏朵粬绫诲瀷鐨勪换鍔¤繘琛屽彂閫侀偖浠讹紝璇锋牳鏌ヤ笟鍔¢昏緫 + //---涓嶅簲鏈 闄よ瑙嗐佽鍒ゃ佸叏灞鍏朵粬绫诲瀷鐨勪换鍔¤繘琛屽彂閫侀偖浠讹紝璇锋牳鏌ヤ笟鍔¢昏緫 throw new BusinessValidationFailedException(_localizer["TrialEmailN_InvalidTaskTypeForEmailSending"]); } @@ -1273,7 +1288,7 @@ namespace IRaCIS.Core.Application.Service //} else { - //---涓嶅簲鏈 闄よ瑙嗐佽鍒ゃ佸叏灞鍏朵粬绫诲瀷鐨勪换鍔¤繘琛屽彂閫侀偖浠讹紝璇锋牳鏌ヤ笟鍔¢昏緫 + //---涓嶅簲鏈 闄よ瑙嗐佽鍒ゃ佸叏灞鍏朵粬绫诲瀷鐨勪换鍔¤繘琛屽彂閫侀偖浠讹紝璇锋牳鏌ヤ笟鍔¢昏緫 throw new BusinessValidationFailedException(_localizer["TrialEmailN_InvalidTaskTypeForEmailSending"]); } @@ -1311,7 +1326,7 @@ namespace IRaCIS.Core.Application.Service case CriterionType.IMWG2016: default: - //---璇ユ爣鍑嗕换鍔¤繕鏈畾涔塒D鑾峰彇閫昏緫锛岃仈绯讳笟鍔″拰鍚庡彴寮鍙戝崗鍟嗗悗琛ュ厖 + //---璇ユ爣鍑嗕换鍔¤繕鏈畾涔塒D鑾峰彇閫昏緫锛岃仈绯讳笟鍔″拰鍚庡彴寮鍙戝崗鍟嗗悗琛ュ厖 throw new BusinessValidationFailedException(_localizer["TrialEmailN_PDLogicNotDefined"]); } @@ -1335,19 +1350,127 @@ namespace IRaCIS.Core.Application.Service var query = _trialUserRepository.Where(t => t.TrialId == trialId, false, true).IgnoreQueryFilters().Select(t => t.User.UserTypeRole).Distinct() - .ProjectTo(_mapper.ConfigurationProvider); + .ProjectTo(_mapper.ConfigurationProvider); return await query.ToListAsync(); } + /// + /// 榛戝悕鍗曠敤鎴稩d 鍒楄〃 + /// + /// + /// + public async Task> GetTrialUserIdSelectList(Guid trialEmailNoticeConfigId) + { + + var trialEmailNoticeConfig = await _trialEmailNoticeConfigRepository.Where(t => t.Id == trialEmailNoticeConfigId).Include(t => t.TrialEmailNoticeUserList).FirstNotNullAsync(); + + var trialId = trialEmailNoticeConfig.TrialId; + + var userTypeList = trialEmailNoticeConfig.TrialEmailNoticeUserList.Select(t => t.UserType).ToList(); + + + var query = _trialUserRepository.Where(t => t.TrialId == trialId && userTypeList.Contains(t.User.UserTypeEnum), false, true).IgnoreQueryFilters() + .Select(t => new TrialSelectUser() + { + UserId = t.UserId, + UserName = t.User.UserName, + RealName = t.User.FullName, + UserTypeEnum = t.User.UserTypeEnum + }).Distinct(); + + return await query.ToListAsync(); + } + + /// + /// 鑾峰彇绯荤粺 閭欢閰嶇疆 鍕鹃夊垪琛 + /// + /// + /// + public async Task> GetSysEmailNoticeConfigList(EmailNoticeConfigQuery queryEmailNoticeConfig) + { + var emailNoticeConfigQueryable = _emailNoticeConfigRepository + .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(_mapper.ConfigurationProvider, new { trialId = queryEmailNoticeConfig.TrialId }); + + return await emailNoticeConfigQueryable.ToPagedListAsync(queryEmailNoticeConfig.PageIndex, queryEmailNoticeConfig.PageSize, queryEmailNoticeConfig.SortField, queryEmailNoticeConfig.Asc); + } + + /// + /// 鎵归噺鍕鹃 浼犻掑垪琛ㄦ瘡琛屾暟鎹紝鍚庡彴杩涜澶勭悊杞崲锛屽缓绔嬪叧鑱斿叧绯 + /// + /// + /// + public async Task BatchAddSysEmailConfig(List batchAddList) + { + + var first = batchAddList.First(); + var trialId = first.TrialId; + + var emailConfig = await _trialRepository.Where(t => t.Id == trialId).Select(x => new + { + TrialId = x.Id, + EmailAuthorizationCode = x.EmailAuthorizationCode, + EmailSMTPServerAddress = x.EmailSMTPServerAddress, + EmailFromEmail = x.EmailFromEmail, + EmailFromName = x.EmailFromName, + IsConfigureEmail = x.IsConfigureEmail, + EmailSMTPServerPort = x.EmailSMTPServerPort + + }).FirstNotNullAsync(); + + var list = await _repository.Where(t => t.TrialId == trialId && t.IsConfirm).Select(t => new { t.CriterionType, TrialReadingCriterionId = t.Id }).ToListAsync(); + + + var addList = _mapper.Map>(batchAddList); + + + foreach (var item in addList) + { + item.SysEmailNoticeConfigId = item.Id; + item.Id = Guid.Empty; + + item.AuthorizationCode = emailConfig.EmailAuthorizationCode; + item.FromEmail = emailConfig.EmailFromEmail; + item.SMTPServerAddress = emailConfig.EmailSMTPServerAddress; + item.FromName = emailConfig.EmailFromName; + item.SMTPServerPort = emailConfig.EmailSMTPServerPort; + item.IsAutoSend = false; + item.IsEnable = false; + + item.TrialReadingCriterionId = list.FirstOrDefault(t => t.CriterionType == item.CriterionTypeEnum)?.TrialReadingCriterionId; + + item.TrialEmailNoticeUserList.AddRange(batchAddList.Where(t => t.Id == item.SysEmailNoticeConfigId) + .SelectMany(t => t.ToUserTypeList).Select(t => new TrialEmailNoticeUser() { EmailUserType = EmailUserType.To, UserType = t })); + + item.TrialEmailNoticeUserList.AddRange(batchAddList.Where(t => t.Id == item.SysEmailNoticeConfigId) + .SelectMany(t => t.CopyUserTypeList).Select(t => new TrialEmailNoticeUser() { EmailUserType = EmailUserType.Copy, UserType = t })); + + + await _trialEmailNoticeConfigRepository.AddAsync(item); + + } + + await _trialEmailNoticeConfigRepository.SaveChangesAsync(); + + return ResponseOutput.Ok(); + + + } + + [HttpPost] public async Task> GetTrialEmailNoticeConfigList(TrialEmailNoticeConfigQuery inQuery) { - await SyncSystemEmainCofigDocListAsync(inQuery.TrialId); + //await SyncSystemEmainCofigDocListAsync(inQuery.TrialId); var trialEmailNoticeConfigQueryable = _trialEmailNoticeConfigRepository.Where(t => t.TrialId == inQuery.TrialId) .WhereIf(inQuery.IsDistinguishCriteria == false, t => t.TrialReadingCriterionId == null) + .WhereIf(inQuery.IsDistinguishCriteria == true, t => t.CriterionTypeEnum != null) .WhereIf(inQuery.TrialReadingCriterionId != null, t => t.TrialReadingCriterionId == inQuery.TrialReadingCriterionId) .WhereIf(inQuery.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == inQuery.BusinessScenarioEnum) .ProjectTo(_mapper.ConfigurationProvider); @@ -1355,6 +1478,7 @@ namespace IRaCIS.Core.Application.Service return await trialEmailNoticeConfigQueryable.ToListAsync(); } + [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] public async Task AddOrUpdateTrialEmailNoticeConfig(TrialEmailNoticeConfigAddOrEdit addOrEditTrialEmailNoticeConfig) { @@ -1379,6 +1503,10 @@ namespace IRaCIS.Core.Application.Service } + foreach (var userid in addOrEditTrialEmailNoticeConfig.BlackUserIdList) + { + entity.TrialEmailBlackUserList.Add(new TrialEmailBlackUser() { UserId = userid }); + } await _trialEmailNoticeConfigRepository.AddAsync(entity, true); @@ -1387,10 +1515,10 @@ namespace IRaCIS.Core.Application.Service } else { + var id = (Guid)addOrEditTrialEmailNoticeConfig.Id; + await _repository.BatchDeleteAsync(t => t.TrialEmailNoticeConfigId == addOrEditTrialEmailNoticeConfig.Id); - - - var entity = (await _trialEmailNoticeConfigRepository.Where(t => t.Id == addOrEditTrialEmailNoticeConfig.Id, true, true).Include(t => t.TrialEmailNoticeUserList).FirstOrDefaultAsync()).IfNullThrowException(); + await _repository.BatchDeleteAsync(t => t.TrialEmailNoticeConfigId == addOrEditTrialEmailNoticeConfig.Id); List trialEmailNoticeUsers = new List(); @@ -1398,31 +1526,51 @@ namespace IRaCIS.Core.Application.Service foreach (var item in addOrEditTrialEmailNoticeConfig.ToUserTypeList) { - trialEmailNoticeUsers.Add(new TrialEmailNoticeUser() { EmailUserType = EmailUserType.To, UserType = item, TrialEmailNoticeConfigId = entity.Id }); + trialEmailNoticeUsers.Add(new TrialEmailNoticeUser() { EmailUserType = EmailUserType.To, UserType = item, TrialEmailNoticeConfigId = id }); } foreach (var item in addOrEditTrialEmailNoticeConfig.CopyUserTypeList) { - trialEmailNoticeUsers.Add(new TrialEmailNoticeUser() { EmailUserType = EmailUserType.Copy, UserType = item, TrialEmailNoticeConfigId = entity.Id }); + trialEmailNoticeUsers.Add(new TrialEmailNoticeUser() { EmailUserType = EmailUserType.Copy, UserType = item, TrialEmailNoticeConfigId = id }); } await _repository.AddRangeAsync(trialEmailNoticeUsers); + foreach (var userid in addOrEditTrialEmailNoticeConfig.BlackUserIdList) + { + await _trialEmailBlackUserRepository.AddAsync(new TrialEmailBlackUser() { UserId = userid, TrialEmailNoticeConfigId = id }); + + } + await _trialEmailNoticeConfigRepository.UpdateFromDTOAsync(addOrEditTrialEmailNoticeConfig); await _trialEmailNoticeConfigRepository.SaveChangesAsync(); + var jobId = $"{addOrEditTrialEmailNoticeConfig.TrialId}_{id}"; + + if (addOrEditTrialEmailNoticeConfig.IsAutoSend) + { + HangfireJobHelper.AddOrUpdateTrialCronJob(jobId, addOrEditTrialEmailNoticeConfig.TrialId, addOrEditTrialEmailNoticeConfig.BusinessScenarioEnum, addOrEditTrialEmailNoticeConfig.EmailCron); + + } + else + { + HangfireJobHelper.RemoveCronJob(jobId); + } + return ResponseOutput.Ok(); } } + + private async Task TestEmailConfigAsync(TrialEmailNoticeConfigAddOrEdit config) { - + if (!config.FromEmail.Contains("@") || string.IsNullOrEmpty(config.FromEmail)) { @@ -1449,7 +1597,7 @@ namespace IRaCIS.Core.Application.Service throw new BusinessValidationFailedException(_localizer["TrialEmailN_InvalidSenderEmailConfig"] + ex.Message); } - + #region 浜哄憳杩樻湭鍔犲叆锛屽彲浠ュ厛閰嶇疆閭欢 鍘嗗彶搴熷純 @@ -1522,6 +1670,11 @@ namespace IRaCIS.Core.Application.Service [HttpDelete("{trialEmailNoticeConfigId:guid}")] public async Task DeleteTrialEmailNoticeConfig(Guid trialEmailNoticeConfigId) { + var trialId = await _trialEmailNoticeConfigRepository.Where(t => t.Id == trialEmailNoticeConfigId).Select(t => t.TrialId).FirstOrDefaultAsync(); + var jobId = $"{trialId}_{trialEmailNoticeConfigId}"; + + HangfireJobHelper.RemoveCronJob(jobId); + var success = await _trialEmailNoticeConfigRepository.DeleteFromQueryAsync(t => t.Id == trialEmailNoticeConfigId, true); return ResponseOutput.Ok(); diff --git a/IRaCIS.Core.Application/Service/Management/DTO/UserTypeRoleModel.cs b/IRaCIS.Core.Application/Service/Management/DTO/UserTypeRoleModel.cs index 3a059e4bd..a68328309 100644 --- a/IRaCIS.Core.Application/Service/Management/DTO/UserTypeRoleModel.cs +++ b/IRaCIS.Core.Application/Service/Management/DTO/UserTypeRoleModel.cs @@ -12,7 +12,7 @@ namespace IRaCIS.Core.Application.Contracts public UserTypeEnum UserTypeEnum { get; set; } public List UserTypeGroupList { get; set; } = new List(); - public new List UserTypeGroupIdList => UserTypeGroupList.Select(t=>t.DictionaryId).ToList(); + public new List UserTypeGroupIdList => UserTypeGroupList.Select(t => t.DictionaryId).ToList(); } @@ -22,7 +22,7 @@ namespace IRaCIS.Core.Application.Contracts public Guid DictionaryId { get; set; } - public string GroupName { get; set; }=string.Empty; + public string GroupName { get; set; } = string.Empty; public string GroupNameCN { get; set; } = string.Empty; } @@ -36,7 +36,7 @@ namespace IRaCIS.Core.Application.Contracts } - public class UserTypeMenuAddOrEdit: UserTypeRoleAddOrEdit + public class UserTypeMenuAddOrEdit : UserTypeRoleAddOrEdit { public UserTypeEnum UserTypeEnum { get; set; } @@ -64,6 +64,16 @@ namespace IRaCIS.Core.Application.Contracts } + public class TrialSelectUser + { + public Guid UserId { get; set; } + + public string UserName { get; set; } + + public string RealName { get; set; } + + public UserTypeEnum UserTypeEnum { get; set; } + } public class TrialUserType { diff --git a/IRaCIS.Core.Domain.Share/Common/EmailScenarioEnum.cs b/IRaCIS.Core.Domain.Share/Common/EmailScenarioEnum.cs index d14ccc540..b46f6ac5c 100644 --- a/IRaCIS.Core.Domain.Share/Common/EmailScenarioEnum.cs +++ b/IRaCIS.Core.Domain.Share/Common/EmailScenarioEnum.cs @@ -34,7 +34,7 @@ namespace IRaCIS.Core.Domain.Share } - public enum CommonDocumentBusinessScenario + public enum EmailBusinessScenario { EnrollConfirmed = 1, @@ -44,6 +44,12 @@ namespace IRaCIS.Core.Domain.Share Trial=3, Reviewer=4, + + QCTask = 5, + + QCQuestion = 6, + + ImageQuestion = 7 } diff --git a/IRaCIS.Core.Domain/Common/CommonDocument.cs b/IRaCIS.Core.Domain/Common/CommonDocument.cs index be9a95fa5..451b0f51c 100644 --- a/IRaCIS.Core.Domain/Common/CommonDocument.cs +++ b/IRaCIS.Core.Domain/Common/CommonDocument.cs @@ -72,7 +72,7 @@ namespace IRaCIS.Core.Domain.Models public CriterionType? CriterionTypeEnum { get; set; } public CommonDocumentFileType FileTypeEnum { get; set; } - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } //[Required] diff --git a/IRaCIS.Core.Domain/Common/EmailNoticeConfig.cs b/IRaCIS.Core.Domain/Common/EmailNoticeConfig.cs index dd1a99f11..74ab2ac60 100644 --- a/IRaCIS.Core.Domain/Common/EmailNoticeConfig.cs +++ b/IRaCIS.Core.Domain/Common/EmailNoticeConfig.cs @@ -16,11 +16,59 @@ namespace IRaCIS.Core.Domain.Models ///EmailNoticeConfig /// [Table("EmailNoticeConfig")] - public class EmailNoticeConfig : Entity, IAuditUpdate, IAuditAdd,ISoftDelete + public class EmailNoticeConfig : Entity, IAuditUpdate, IAuditAdd, ISoftDelete { + [JsonIgnore] + public List TrialEmailNoticeConfigList { get; set; } + + [JsonIgnore] + public List EmailNoticeUserTypeList { get; set; } = new List(); public string Code { get; set; } = String.Empty; - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } + public EmailBusinessScenario BusinessScenarioEnum { get; set; } + + /// 鏍囧噯绫诲瀷 /// + public CriterionType? CriterionTypeEnum { get; set; } + + /// 涓氬姟妯″潡 /// + public int BusinessModuleEnum { get; set; } + + /// 涓氬姟灞傜骇 /// + public int BusinessLevelEnum { get; set; } + + /// 閭欢绫诲瀷 /// + public int EmailTypeEnum { get; set; } + + /// 閭欢鍔犳ョ被鍨 /// + public int EmailUrgentEnum { get; set; } + + /// 瀹氭椂鍛ㄦ湡 /// + public string EmailCron { get; set; } = string.Empty; + + /// 閭欢涓婚 /// + public string EmailTopic { get; set; } = string.Empty; + + public string EmailTopicCN { get; set; } = string.Empty; + + /// 闄勪欢 /// + public string AttachPath { get; set; } = string.Empty; + + public string AttachCNPath { get; set; } = string.Empty; + + public string EmailHtmlContent { get; set; } = string.Empty; + + public string EmailHtmlContentCN { get; set; } = string.Empty; + + public string Description { get; set; } = string.Empty; + + + public string AttachName { get; set; } = string.Empty; + public string AttachNameCN { get; set; } = string.Empty; + + + + + /// /// 鏄惁鍖哄垎鏍囧噯 @@ -34,10 +82,6 @@ namespace IRaCIS.Core.Domain.Models [Required] public bool IsReturnRequired { get; set; } - - [Required] - public bool IsUrgent { get; set; } - public bool IsAutoSend { get; set; } public bool IsEnable { get; set; } @@ -61,14 +105,21 @@ namespace IRaCIS.Core.Domain.Models public Guid? DeleteUserId { get; set; } - - - - - - - - } + + [Table("EmailNoticeUserType")] + + public class EmailNoticeUserType : Entity + { + [JsonIgnore] + public EmailNoticeConfig EmailNoticeConfig { get; set; } + + public Guid EmailNoticeConfigId { get; set; } + + + public UserTypeEnum UserType { get; set; } + + public EmailUserType EmailUserType { get; set; } + } } diff --git a/IRaCIS.Core.Domain/Document/TrialEmailNoticeConfig.cs b/IRaCIS.Core.Domain/Document/TrialEmailNoticeConfig.cs index 5b3bf06b4..2a221071d 100644 --- a/IRaCIS.Core.Domain/Document/TrialEmailNoticeConfig.cs +++ b/IRaCIS.Core.Domain/Document/TrialEmailNoticeConfig.cs @@ -12,93 +12,138 @@ using System.Linq; namespace IRaCIS.Core.Domain.Models { - /// - ///TrialEmailNoticeConfig - /// - [Table("TrialEmailNoticeConfig")] - public class TrialEmailNoticeConfig : Entity, IAuditUpdate, IAuditAdd - { + /// + ///TrialEmailNoticeConfig + /// + [Table("TrialEmailNoticeConfig")] + public class TrialEmailNoticeConfig : Entity, IAuditUpdate, IAuditAdd, ISoftDelete + { + [JsonIgnore] - [Required] - public Guid TrialId { get; set; } - - - public string SMTPServerAddress { get; set; } = string.Empty; - - public int SMTPServerPort { get; set; } - - [Required] - public string AuthorizationCode { get; set; } = string.Empty; - - - public string FromName { get; set; } = string.Empty; - public List TrialEmailNoticeUserList { get; set; } = new List(); - - - //[Required] - - //public string ReceiveEmailsStr { get; set; } = string.Empty; - //public string CopyEmailsStr { get; set; } = string.Empty; - - //[NotMapped] - //public List ReceiveEmailList => ReceiveEmailsStr.Split('|', StringSplitOptions.RemoveEmptyEntries).Where(t => !string.IsNullOrEmpty(t)).Select(t=>t.Trim()).ToList(); - - //[NotMapped] - //public List CopyEmailList => CopyEmailsStr.Split('|', StringSplitOptions.RemoveEmptyEntries).Where(t=> !string.IsNullOrEmpty(t)).Select(t => t.Trim()).ToList(); - - - - public string FromEmail { get; set; } = string.Empty; - - [Required] - public bool IsUrgent { get; set; } - - - [Required] - public string Code { get; set; } = string.Empty; - - - - [Required] - public bool IsReturnRequired { get; set; } - - - - [Required] - public bool IsAutoSend { get; set; } - - - - public CommonDocumentBusinessScenario BusinessScenarioEnum { get; set; } - - public CriterionType? CriterionTypeEnum { get; set; } - - - public Guid? TrialReadingCriterionId { get; set; } - - [ForeignKey("TrialReadingCriterionId")] - [JsonIgnore] - public ReadingQuestionCriterionTrial TrialReadingCriterion { get; set; } + public Trial Trial { get; set; } [Required] - public string FilePath { get; set; } = string.Empty; - - [Required] - public string FileName { get; set; } = string.Empty; - - [Required] - public Guid CreateUserId { get; set; } - - [Required] - public DateTime CreateTime { get; set; } - - [Required] - public Guid UpdateUserId { get; set; } - - [Required] - public DateTime UpdateTime { get; set; } + public Guid TrialId { get; set; } - } + public string SMTPServerAddress { get; set; } = string.Empty; -} + public int SMTPServerPort { get; set; } + + [Required] + public string AuthorizationCode { get; set; } = string.Empty; + + + public string FromName { get; set; } = string.Empty; + + + public string FromEmail { get; set; } = string.Empty; + + [JsonIgnore] + public List TrialEmailNoticeUserList { get; set; } = new List(); + + public List TrialEmailBlackUserList { get; set; } = new List(); + + + /// 涓氬姟妯″潡 /// + public int BusinessModuleEnum { get; set; } + + /// 涓氬姟灞傜骇 /// + public int BusinessLevelEnum { get; set; } + + /// 閭欢绫诲瀷 /// + public int EmailTypeEnum { get; set; } + + /// 閭欢鍔犳ョ被鍨 /// + public int EmailUrgentEnum { get; set; } + + /// 瀹氭椂鍛ㄦ湡 /// + public string EmailCron { get; set; } = string.Empty; + + /// 閭欢涓婚 /// + public string EmailTopic { get; set; } = string.Empty; + + public string EmailTopicCN { get; set; } = string.Empty; + + /// 闄勪欢 /// + public string AttachPath { get; set; } = string.Empty; + + public string AttachCNPath { get; set; } = string.Empty; + + public string Description { get; set; } = string.Empty; + + + public string AttachName { get; set; } + public string AttachNameCN { get; set; } + + + public string EmailHtmlContent { get; set; } = string.Empty; + public string EmailHtmlContentCN { get; set; } = string.Empty; + + + + [JsonIgnore] + + public EmailNoticeConfig SysEmailNoticeConfig { get; set; } + public Guid? SysEmailNoticeConfigId { get; set; } + + + [Required] + public string Code { get; set; } = string.Empty; + + [Required] + public bool IsReturnRequired { get; set; } + [Required] + public bool IsAutoSend { get; set; } + + public bool IsEnable { get; set; } + + + public EmailBusinessScenario BusinessScenarioEnum { get; set; } + + public CriterionType? CriterionTypeEnum { get; set; } + + + public Guid? TrialReadingCriterionId { get; set; } + + [ForeignKey("TrialReadingCriterionId")] + [JsonIgnore] + public ReadingQuestionCriterionTrial TrialReadingCriterion { get; set; } + + [Required] + public Guid CreateUserId { get; set; } + + [Required] + public DateTime CreateTime { get; set; } + + [Required] + public Guid UpdateUserId { get; set; } + + [Required] + public DateTime UpdateTime { get; set; } + + public bool IsDeleted { get; set; } + + public DateTime? DeletedTime { get; set; } + + public Guid? DeleteUserId { get; set; } + + + } + + public class TrialEmailBlackUser : Entity + { + [JsonIgnore] + public TrialEmailNoticeConfig TrialEmailNoticeConfig { get; set; } + + [JsonIgnore] + public User User { get; set; } + + + public Guid TrialEmailNoticeConfigId { get; set; } + + + public Guid UserId { get; set; } + } + +} diff --git a/IRaCIS.Core.Domain/Trial/Trial.cs b/IRaCIS.Core.Domain/Trial/Trial.cs index 705ca584b..68f77bc56 100644 --- a/IRaCIS.Core.Domain/Trial/Trial.cs +++ b/IRaCIS.Core.Domain/Trial/Trial.cs @@ -383,7 +383,7 @@ namespace IRaCIS.Core.Domain.Models /// /// SMTP端口 /// - public int? EmailSMTPServerPort { get; set; } + public int EmailSMTPServerPort { get; set; } /// /// 是否配置过邮箱 diff --git a/IRaCIS.Core.Domain/_Config/_AppSettings.cs b/IRaCIS.Core.Domain/_Config/_AppSettings.cs index 4bda63fec..698f8a10b 100644 --- a/IRaCIS.Core.Domain/_Config/_AppSettings.cs +++ b/IRaCIS.Core.Domain/_Config/_AppSettings.cs @@ -34,7 +34,9 @@ namespace IRaCIS.Core.Domain.Share public string FromName { get; set; } - public string AuthorizationCode { get; set; } + public string AuthorizationCode { get; set; } + + public string SiteUrl { get; set; } } diff --git a/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs b/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs index 3720a409d..b98df40d8 100644 --- a/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs +++ b/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs @@ -513,7 +513,8 @@ namespace IRaCIS.Core.Infra.EFCore public virtual DbSet UserLog { get; set; } - + public virtual DbSet EmailNoticeUserType { get; set; } + public virtual DbSet TrialEmailBlackUser { get; set; } #region 搴熷純 diff --git a/IRaCIS.Core.Infrastructure/_IRaCIS/Output/ResponseOutput.cs b/IRaCIS.Core.Infrastructure/_IRaCIS/Output/ResponseOutput.cs index b0ae8448b..0b6e8ea93 100644 --- a/IRaCIS.Core.Infrastructure/_IRaCIS/Output/ResponseOutput.cs +++ b/IRaCIS.Core.Infrastructure/_IRaCIS/Output/ResponseOutput.cs @@ -169,7 +169,7 @@ namespace IRaCIS.Core.Infrastructure.Extention public static IResponseOutput DBNotExistIfNUll(object businessObject) { - return new ResponseOutput().NotOk("The business object{businessObject.GetType().Name} does not exist in the database, or was deleted by someone else, or an incorrect parameter query caused"); + return new ResponseOutput().NotOk($"The business object{businessObject.GetType().Name} does not exist in the database, or was deleted by someone else, or an incorrect parameter query caused"); } From 9ade3a7c3930604cff70e239b3cfc206409bc43f Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 09:40:00 +0800 Subject: [PATCH 02/13] =?UTF-8?q?=E5=BC=95=E5=85=A5=E5=88=86=E5=B8=83?= =?UTF-8?q?=E5=BC=8F=E9=94=81=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.Application/IRaCIS.Core.Application.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj index 247ed6016..7e0318c0f 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj @@ -70,6 +70,8 @@ + + true From 3218be613d81576835d7a2f06ff7a43f70fae981 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Wed, 11 Oct 2023 17:38:34 +0800 Subject: [PATCH 03/13] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=94=81=20?= =?UTF-8?q?=20sqlserver=20=E6=B5=8B=E8=AF=95=2003?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs | 13 ++++++++- IRaCIS.Core.Application/TestService.cs | 27 ++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs index c1d2c31cc..3a7df5742 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/EFSetup.cs @@ -1,8 +1,12 @@ -锘縰sing IRaCIS.Core.Application.Triggers; +锘縰sing Hangfire.SqlServer; +using IRaCIS.Core.Application.Triggers; using IRaCIS.Core.Infra.EFCore; +using Medallion.Threading; +using Medallion.Threading.SqlServer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; namespace IRaCIS.Core.API { @@ -55,6 +59,13 @@ namespace IRaCIS.Core.API }); + //娉ㄦ剰鍖哄垎 easy caching 涔熸湁 IDistributedLockProvider + services.AddSingleton(sp => + { + //var connection = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]!); + + return new SqlDistributedSynchronizationProvider(configuration.GetSection("ConnectionStrings:RemoteNew").Value); + }); //services.AddAssemblyTriggers(typeof(SubjectVisitImageDateTrigger).Assembly); } diff --git a/IRaCIS.Core.Application/TestService.cs b/IRaCIS.Core.Application/TestService.cs index c3e953a73..b72556137 100644 --- a/IRaCIS.Core.Application/TestService.cs +++ b/IRaCIS.Core.Application/TestService.cs @@ -3,6 +3,8 @@ using IRaCIS.Core.Application.Service; using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infrastructure; +using MassTransit; +using Medallion.Threading; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -10,6 +12,7 @@ using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Options; using MiniExcelLibs; using System.Linq.Expressions; +using System.Reflection.Metadata; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; @@ -20,6 +23,8 @@ namespace IRaCIS.Application.Services [ApiExplorerSettings(GroupName = "Institution")] public class TestService : BaseService { + + public static int IntValue = 100; private readonly IRepository _dicRepository; private readonly IRepository _trialRepository; @@ -30,10 +35,11 @@ namespace IRaCIS.Application.Services private readonly IOptionsMonitor _basicConfig; private readonly IRepository _visitTaskRepositoryy; + private readonly IDistributedLockProvider _distributedLockProvider; public TestService(IRepository dicRepository, IRepository trialRepository/*, IDistributedCache cache*/ - , IOptionsMonitor systemEmailConfig, IOptionsMonitor basicConfig, IRepository visitTaskRepository) + , IOptionsMonitor systemEmailConfig, IOptionsMonitor basicConfig, IRepository visitTaskRepository, IDistributedLockProvider distributedLockProvider) { _visitTaskRepositoryy = visitTaskRepository; @@ -42,11 +48,30 @@ namespace IRaCIS.Application.Services _dicRepository = dicRepository; _trialRepository = trialRepository; + + _distributedLockProvider= distributedLockProvider; //_cache = cache; } + [AllowAnonymous] + public async Task TestDistributedLock( ) + { + Console.WriteLine($"鎴戣繘鏉ヤ簡褰撳墠鍊兼槸锛" + IntValue); + + var @lock = _distributedLockProvider.CreateLock($"UserAccount"); + + using (await @lock.AcquireAsync()) + { + await Task.Delay(3); + IntValue--; + Console.WriteLine(IntValue); + } + + return ResponseOutput.Ok(IntValue); + } + [AllowAnonymous] public async Task InternationazitionInit() From 5d7beb71e6467e176c440dd14711d80c967a24f9 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Wed, 11 Oct 2023 17:44:13 +0800 Subject: [PATCH 04/13] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=94=81=20?= =?UTF-8?q?=20sqlserver=20=E6=B5=8B=E8=AF=95=2004=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.Application/TestService.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/IRaCIS.Core.Application/TestService.cs b/IRaCIS.Core.Application/TestService.cs index b72556137..46153bca6 100644 --- a/IRaCIS.Core.Application/TestService.cs +++ b/IRaCIS.Core.Application/TestService.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MiniExcelLibs; using System.Linq.Expressions; @@ -37,7 +38,9 @@ namespace IRaCIS.Application.Services private readonly IDistributedLockProvider _distributedLockProvider; - public TestService(IRepository dicRepository, IRepository trialRepository/*, IDistributedCache cache*/ + private readonly ILogger _logger; + + public TestService(IRepository dicRepository, IRepository trialRepository,ILogger logger , IOptionsMonitor systemEmailConfig, IOptionsMonitor basicConfig, IRepository visitTaskRepository, IDistributedLockProvider distributedLockProvider) { @@ -50,6 +53,8 @@ namespace IRaCIS.Application.Services _trialRepository = trialRepository; _distributedLockProvider= distributedLockProvider; + + _logger= logger; //_cache = cache; } @@ -59,13 +64,16 @@ namespace IRaCIS.Application.Services public async Task TestDistributedLock( ) { Console.WriteLine($"鎴戣繘鏉ヤ簡褰撳墠鍊兼槸锛" + IntValue); + _logger.LogWarning($"鎴戣繘鏉ヤ簡褰撳墠鍊兼槸锛" + IntValue); var @lock = _distributedLockProvider.CreateLock($"UserAccount"); using (await @lock.AcquireAsync()) { - await Task.Delay(3); + await Task.Delay(4); IntValue--; + + _logger.LogWarning( IntValue.ToString()); Console.WriteLine(IntValue); } From a565282a94f2ca7c5af81399c44b346ec830ab1e Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 09:34:09 +0800 Subject: [PATCH 05/13] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=94=81=20?= =?UTF-8?q?=20sqlserver=2005=20=E9=A1=B9=E7=9B=AE=E8=BF=81=E7=A7=BB?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRaCIS.Core.Application.csproj | 1 - .../Service/Common/MailService.cs | 2 - .../ImageAndDoc/DicomArchiveService.cs | 25 ++- .../Service/ImageAndDoc/StudyService.cs | 32 +-- .../Service/Institution/SiteService.cs | 14 +- .../Service/Management/UserService.cs | 42 ++-- .../Service/QC/NoneDicomStudyService.cs | 12 +- .../Service/QC/QCOperationService.cs | 13 +- .../SiteSurvey/TrialSiteSurveyService.cs | 5 +- .../TrialSiteUser/TrialExternalUserService.cs | 196 +++++++++--------- 10 files changed, 181 insertions(+), 161 deletions(-) diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj index 7e0318c0f..4f74c24fb 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj @@ -101,7 +101,6 @@ true - diff --git a/IRaCIS.Core.Application/Service/Common/MailService.cs b/IRaCIS.Core.Application/Service/Common/MailService.cs index 5f6e58120..bf195994b 100644 --- a/IRaCIS.Core.Application/Service/Common/MailService.cs +++ b/IRaCIS.Core.Application/Service/Common/MailService.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Hosting; using IRaCIS.Core.Application.Auth; using AutoMapper; using IRaCIS.Application.Contracts; -using Nito.AsyncEx; using Microsoft.Extensions.Options; namespace IRaCIS.Application.Services @@ -55,7 +54,6 @@ namespace IRaCIS.Application.Services private readonly IRepository _doctorTypeRepository; - private readonly AsyncLock _mutex = new AsyncLock(); private readonly SystemEmailSendConfig _systemEmailConfig; diff --git a/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs b/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs index f797c8ca4..9b990c306 100644 --- a/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs +++ b/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs @@ -8,10 +8,11 @@ using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Helper; using Microsoft.AspNetCore.Hosting; using IRaCIS.Core.Infrastructure; +using Medallion.Threading; namespace IRaCIS.Core.Application.Services { - public class DicomArchiveService :BaseService, IDicomArchiveService + public class DicomArchiveService : BaseService, IDicomArchiveService { private readonly IRepository _studyRepository; private readonly IRepository _seriesRepository; @@ -21,7 +22,7 @@ namespace IRaCIS.Core.Application.Services private readonly IWebHostEnvironment _hostEnvironment; - private static object lockCodeGenerate = new object(); + private readonly IDistributedLockProvider _distributedLockProvider; private List _instanceIdList = new List(); @@ -31,8 +32,9 @@ namespace IRaCIS.Core.Application.Services IRepository instanceRepository, IWebHostEnvironment hostEnvironment, IRepository dictionaryRepository, - IEasyCachingProvider provider) + IEasyCachingProvider provider, IDistributedLockProvider distributedLockProvider) { + _distributedLockProvider = distributedLockProvider; _hostEnvironment = hostEnvironment; _studyRepository = studyRepository; @@ -50,7 +52,7 @@ namespace IRaCIS.Core.Application.Services return success; } - + public async Task<(Guid StudyId, string StudyCode)> ArchiveDicomStreamAsync(Stream dicomStream, @@ -129,7 +131,7 @@ namespace IRaCIS.Core.Application.Services DicomStudy dicomStudy = CreateDicomStudy(dataset, addtionalInfo, out bool isStudyNeedAdd); DicomSeries dicomSeries = CreateDicomSeries(dataset, dicomStudy, out bool isSeriesNeedAdd); - DicomInstance dicomInstance = CreateDicomInstance(dataset, dicomStudy, dicomSeries,out bool isInstanceNeedAdd); + DicomInstance dicomInstance = CreateDicomInstance(dataset, dicomStudy, dicomSeries, out bool isInstanceNeedAdd); dicomSeries.DicomStudy = dicomStudy; @@ -183,7 +185,7 @@ namespace IRaCIS.Core.Application.Services //姝e父淇濆瓨 涓嶅仛澶勭悊 await dicomFile.SaveAsync(physicalPath); } - else + else { //RLELossless 淇濆瓨 await dicomFile.Clone(DicomTransferSyntax.RLELossless).SaveAsync(physicalPath); //RLELossless @@ -235,7 +237,7 @@ namespace IRaCIS.Core.Application.Services { modalityForEdit = "PET"; } - if(modality== "PT銆丆T") + if (modality == "PT銆丆T") { modalityForEdit = "PET-CT"; } @@ -282,9 +284,10 @@ namespace IRaCIS.Core.Application.Services dicomStudy.PatientBirthDate = $"{dicomStudy.PatientBirthDate[0]}{dicomStudy.PatientBirthDate[1]}{dicomStudy.PatientBirthDate[2]}{dicomStudy.PatientBirthDate[3]}-{dicomStudy.PatientBirthDate[4]}{dicomStudy.PatientBirthDate[5]}-{dicomStudy.PatientBirthDate[6]}{dicomStudy.PatientBirthDate[7]}"; } - lock (lockCodeGenerate) - { + var @lock = _distributedLockProvider.CreateLock($"StudyCode"); + using (@lock.Acquire()) + { //鏌ヨ鏁版嵁搴撹幏鍙栨渶澶х殑Code 娌℃湁璁板綍鍒欎负0 var dbStudyCodeIntMax = _studyRepository.Where(s => s.TrialId == addtionalInfo.TrialId).Select(t => t.Code).DefaultIfEmpty().Max(); @@ -298,9 +301,9 @@ namespace IRaCIS.Core.Application.Services dicomStudy.StudyCode = AppSettings.GetCodeStr(currentNextCodeInt, nameof(DicomStudy)); _provider.Set($"{addtionalInfo.TrialId}_{StaticData.CacheKey.StudyMaxCode}", dicomStudy.Code, TimeSpan.FromMinutes(30)); - } + #region Setting Code old //var studyCode = _studyRepository.Where(s => s.TrialId == addtionalInfo.TrialId).Select(t => t.StudyCode).OrderByDescending(c => c).FirstOrDefault(); @@ -468,7 +471,7 @@ namespace IRaCIS.Core.Application.Services _instanceIdList.Add(instanceId); } - + return dicomInstance; } diff --git a/IRaCIS.Core.Application/Service/ImageAndDoc/StudyService.cs b/IRaCIS.Core.Application/Service/ImageAndDoc/StudyService.cs index 0e3e5c184..adb1f224a 100644 --- a/IRaCIS.Core.Application/Service/ImageAndDoc/StudyService.cs +++ b/IRaCIS.Core.Application/Service/ImageAndDoc/StudyService.cs @@ -14,16 +14,13 @@ using IRaCIS.Core.Application.MediatR.Handlers; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Threading; -using Nito.AsyncEx; +using Medallion.Threading; namespace IRaCIS.Core.Application.Service.ImageAndDoc { [ApiExplorerSettings(GroupName = "Image")] public class StudyService : BaseService, IStudyService { - private static object lockObj = new object(); - private static readonly AsyncLock _mutex = new AsyncLock(); - private static readonly AsyncLock _mutex2 = new AsyncLock(); private readonly IEasyCachingProvider _provider; @@ -35,12 +32,12 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc private readonly IRepository _dictionaryRepository; private readonly IRepository _studyMonitorRepository; - + private readonly IDistributedLockProvider _distributedLockProvider; public StudyService(IEasyCachingProvider provider , IRepository subjectVisitRepository, IRepository dicomInstanceRepository, - IRepository dicomSeriesRepository, IRepository dicomstudyRepository, IRepository dictionaryRepository, IRepository studyMonitorRepository) + IRepository dicomSeriesRepository, IRepository dicomstudyRepository, IRepository dictionaryRepository, IRepository studyMonitorRepository, IDistributedLockProvider distributedLockProvider) { _provider = provider; _subjectVisitRepository = subjectVisitRepository; @@ -49,6 +46,7 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc _dicomstudyRepository = dicomstudyRepository; _dictionaryRepository = dictionaryRepository; _studyMonitorRepository = studyMonitorRepository; + _distributedLockProvider = distributedLockProvider; } @@ -160,7 +158,9 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc { var study = _mapper.Map(incommand.Study); - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"StudyCode"); + + using (await @lock.AcquireAsync()) { //鏌ヨ鏁版嵁搴撹幏鍙栨渶澶х殑Code 娌℃湁璁板綍鍒欎负0 var dbStudyCodeIntMax = _dicomstudyRepository.Where(s => s.TrialId == trialId).Select(t => t.Code).DefaultIfEmpty().Max(); @@ -306,11 +306,11 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc } - using (await _mutex2.LockAsync()) + var @lock2 = _distributedLockProvider.CreateLock($"StudyCommit"); + + using (await @lock2.AcquireAsync()) { await _dicomInstanceRepository.SaveChangesAsync(); - - } } catch (Exception ex) @@ -826,22 +826,22 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc } result.StudyInstanceUid = studyInstanceUid; + var @lock = _distributedLockProvider.CreateLock($"StudyUpload"); - if (result.AllowReUpload || result.AllowUpload) + using (@lock.Acquire()) { - lock (lockObj) + if (result.AllowReUpload || result.AllowUpload) { _provider.Set($"StudyUid_{trialId}_{studyInstanceUid}", _userInfo.Id, TimeSpan.FromSeconds(30)); } - } - else - { - lock (lockObj) + else { _provider.Remove($"StudyUid_{trialId}_{studyInstanceUid}"); } } + + return result; } diff --git a/IRaCIS.Core.Application/Service/Institution/SiteService.cs b/IRaCIS.Core.Application/Service/Institution/SiteService.cs index ce240e222..b65b2379f 100644 --- a/IRaCIS.Core.Application/Service/Institution/SiteService.cs +++ b/IRaCIS.Core.Application/Service/Institution/SiteService.cs @@ -3,7 +3,7 @@ using IRaCIS.Application.Contracts; using IRaCIS.Core.Infra.EFCore; using Microsoft.AspNetCore.Mvc; using IRaCIS.Core.Domain.Share; -using Nito.AsyncEx; +using Medallion.Threading; namespace IRaCIS.Application.Services { @@ -12,13 +12,13 @@ namespace IRaCIS.Application.Services { private readonly IRepository _siteRepository; private readonly IRepository _trialSiteUserRepository; + private readonly IDistributedLockProvider _distributedLockProvider; - private readonly AsyncLock _mutex = new AsyncLock(); - - public SiteService(IRepository siteRepository, IRepository trialSiteUserRepository) + public SiteService(IRepository siteRepository, IRepository trialSiteUserRepository, IDistributedLockProvider distributedLockProvider) { _siteRepository = siteRepository; - this._trialSiteUserRepository = trialSiteUserRepository; + _trialSiteUserRepository = trialSiteUserRepository; + _distributedLockProvider = distributedLockProvider; } /// 鍒嗛〉鑾峰彇鐮旂┒涓績鍒楄〃 @@ -58,7 +58,9 @@ namespace IRaCIS.Application.Services VerifyMsg = _localizer["Site_DupName"] }; - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"SiteAdd"); + + using (await @lock.AcquireAsync()) { if (siteCommand.Id == null) { diff --git a/IRaCIS.Core.Application/Service/Management/UserService.cs b/IRaCIS.Core.Application/Service/Management/UserService.cs index ef581d115..8b6b968e3 100644 --- a/IRaCIS.Core.Application/Service/Management/UserService.cs +++ b/IRaCIS.Core.Application/Service/Management/UserService.cs @@ -12,6 +12,7 @@ using IRaCIS.Core.Infra.Common.Cache; using Microsoft.Identity.Client; using static IRaCIS.Core.Domain.Share.StaticData; using IRaCIS.Core.Application.ViewModel; +using Medallion.Threading; namespace IRaCIS.Application.Services { @@ -25,7 +26,7 @@ namespace IRaCIS.Application.Services private readonly IRepository _userTrialRepository; private readonly IRepository _userLogRepository; - + private readonly IDistributedLockProvider _distributedLockProvider; private readonly IMemoryCache _cache; private readonly IOptionsMonitor _verifyConfig; @@ -40,7 +41,8 @@ namespace IRaCIS.Application.Services IRepository userTrialRepository, IOptionsMonitor verifyConfig, IRepository userLogRepository - ) +, + IDistributedLockProvider distributedLockProvider) { _userLogRepository = userLogRepository; @@ -52,6 +54,7 @@ namespace IRaCIS.Application.Services _doctorRepository = doctorRepository; _userTrialRepository = userTrialRepository; _userLogRepository = userLogRepository; + _distributedLockProvider = distributedLockProvider; } @@ -504,29 +507,32 @@ namespace IRaCIS.Application.Services var saveItem = _mapper.Map(userAddModel); - saveItem.Code = await _userRepository.Select(t => t.Code).DefaultIfEmpty().MaxAsync() + 1; + var @lock = _distributedLockProvider.CreateLock($"UserAccount"); - saveItem.UserCode = AppSettings.GetCodeStr(saveItem.Code, nameof(User)); - - if (saveItem.IsZhiZhun) + using (await @lock.AcquireAsync()) { - saveItem.OrganizationName = AppSettings.DefaultInternalOrganizationName; + saveItem.Code = await _userRepository.Select(t => t.Code).DefaultIfEmpty().MaxAsync() + 1; + + saveItem.UserCode = AppSettings.GetCodeStr(saveItem.Code, nameof(User)); + + if (saveItem.IsZhiZhun) + { + saveItem.OrganizationName = AppSettings.DefaultInternalOrganizationName; + } + + + saveItem.Password = MD5Helper.Md5("123456"); + + await _userRepository.AddAsync(saveItem); + + var success = await _userRepository.SaveChangesAsync(); } - - saveItem.Password = MD5Helper.Md5("123456"); - - await _userRepository.AddAsync(saveItem); - - var success = await _userRepository.SaveChangesAsync(); - - + await _mailVerificationService.AddUserSendEmailAsync(saveItem.Id, userAddModel.BaseUrl, userAddModel.RouteUrl); - - - return ResponseOutput.Result(success, new UserAddedReturnDTO { Id = saveItem.Id, UserCode = saveItem.UserCode }); + return ResponseOutput.Ok( new UserAddedReturnDTO { Id = saveItem.Id, UserCode = saveItem.UserCode }); } diff --git a/IRaCIS.Core.Application/Service/QC/NoneDicomStudyService.cs b/IRaCIS.Core.Application/Service/QC/NoneDicomStudyService.cs index fa912838f..e6a40c3bf 100644 --- a/IRaCIS.Core.Application/Service/QC/NoneDicomStudyService.cs +++ b/IRaCIS.Core.Application/Service/QC/NoneDicomStudyService.cs @@ -5,10 +5,10 @@ //-------------------------------------------------------------------- using Microsoft.AspNetCore.Mvc; using IRaCIS.Core.Application.Filter; -using Nito.AsyncEx; using System.ComponentModel.DataAnnotations; using IRaCIS.Core.Application.Service; using IRaCIS.Core.Domain.Share; +using Medallion.Threading; namespace IRaCIS.Core.Application.Contracts { @@ -20,19 +20,19 @@ namespace IRaCIS.Core.Application.Contracts { private readonly IRepository _noneDicomStudyRepository; private readonly IRepository _noneDicomStudyFileRepository; - private readonly AsyncLock _mutex = new AsyncLock(); + private readonly IDistributedLockProvider _distributedLockProvider; private readonly QCCommon _qCCommon; public NoneDicomStudyService(IRepository noneDicomStudyRepository, QCCommon qCCommon, - IRepository noneDicomStudyFileRepository) + IRepository noneDicomStudyFileRepository, IDistributedLockProvider distributedLockProvider) { _qCCommon = qCCommon; _noneDicomStudyRepository = noneDicomStudyRepository; _noneDicomStudyFileRepository = noneDicomStudyFileRepository; - + _distributedLockProvider = distributedLockProvider; } @@ -62,7 +62,9 @@ namespace IRaCIS.Core.Application.Contracts } NoneDicomStudy? optEntity = null; - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"NoneDicomCode"); + + using (await @lock.AcquireAsync()) { if (addOrEditNoneDicomStudy.Id == Guid.Empty || addOrEditNoneDicomStudy.Id == null) { diff --git a/IRaCIS.Core.Application/Service/QC/QCOperationService.cs b/IRaCIS.Core.Application/Service/QC/QCOperationService.cs index 207e9c30c..b714730ae 100644 --- a/IRaCIS.Core.Application/Service/QC/QCOperationService.cs +++ b/IRaCIS.Core.Application/Service/QC/QCOperationService.cs @@ -10,13 +10,13 @@ using WinSCP; using Newtonsoft.Json; using IRaCIS.Core.Infrastructure; using IRaCIS.Core.Application.Service.Inspection.DTO; -using Nito.AsyncEx; using System.ComponentModel.DataAnnotations; using IRaCIS.Core.Application.Auth; using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Application.Service; +using Medallion.Threading; namespace IRaCIS.Core.Application.Image.QA { @@ -35,8 +35,7 @@ namespace IRaCIS.Core.Application.Image.QA private readonly IRepository _trialRepository; private readonly IRepository _visitTaskRepository; private readonly IVisitTaskHelpeService _IVisitTaskHelpeService; - - private readonly AsyncLock _mutex = new AsyncLock(); + private readonly IDistributedLockProvider _distributedLockProvider; public QCOperationService(IRepository subjectVisitRepository, IRepository qcChallengeRepository, @@ -48,7 +47,8 @@ namespace IRaCIS.Core.Application.Image.QA IRepository readingClinicalDataRepository, IRepository qCChallengeDialogrepository, IRepository checkChallengeDialogrepository, - IVisitTaskHelpeService visitTaskHelpeService + IVisitTaskHelpeService visitTaskHelpeService, + IDistributedLockProvider distributedLockProvider ) { _subjectVisitRepository = subjectVisitRepository; @@ -62,6 +62,7 @@ namespace IRaCIS.Core.Application.Image.QA _trialRepository = trialRepository; this._visitTaskRepository = visitTaskRepository; _IVisitTaskHelpeService = visitTaskHelpeService; + _distributedLockProvider = distributedLockProvider; } #region QC璐ㄧ枒 浠ュ強鍥炲 鍏抽棴 @@ -108,9 +109,9 @@ namespace IRaCIS.Core.Application.Image.QA var trialConfig = (await _trialRepository.Where(t => t.Id == trialId).Select(t => new { TrialId = t.Id, t.QCProcessEnum, t.IsImageConsistencyVerification }).FirstOrDefaultAsync()).IfNullThrowException(); + var @lock = _distributedLockProvider.CreateLock($"QCChallengeCode"); - - using (await _mutex.LockAsync()) + using (await @lock.AcquireAsync()) { //鑾峰彇缂栧彿 var code = _qcChallengeRepository.Where(t => t.TrialId == trialId).Select(t => t.Code).DefaultIfEmpty().Max(); diff --git a/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs b/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs index 09a8225d9..2c6e899d9 100644 --- a/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs +++ b/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs @@ -49,7 +49,6 @@ namespace IRaCIS.Core.Application.Contracts _mailVerificationService = mailVerificationService; } - private object lockObj { get; set; } = new object(); /// /// 鍙戦侀獙璇佺爜 @@ -801,7 +800,9 @@ namespace IRaCIS.Core.Application.Contracts if (sysUserInfo == null) { - lock (lockObj) + var @lock = _distributedLockProvider.CreateLock($"UserCode"); + + using (await @lock.AcquireAsync()) { var saveItem = _mapper.Map(item); diff --git a/IRaCIS.Core.Application/Service/TrialSiteUser/TrialExternalUserService.cs b/IRaCIS.Core.Application/Service/TrialSiteUser/TrialExternalUserService.cs index 94bb318c3..309cbdd1d 100644 --- a/IRaCIS.Core.Application/Service/TrialSiteUser/TrialExternalUserService.cs +++ b/IRaCIS.Core.Application/Service/TrialSiteUser/TrialExternalUserService.cs @@ -16,6 +16,7 @@ using Panda.DynamicWebApi.Attributes; using IRaCIS.Core.Application.Auth; using IRaCIS.Application.Services; using IRaCIS.Core.Application.Filter; +using Medallion.Threading; namespace IRaCIS.Core.Application.Service { @@ -31,10 +32,11 @@ namespace IRaCIS.Core.Application.Service private readonly IRepository _trialSiteSurveyUserRepository; private readonly IRepository _trialSiteUserRepository; private readonly IMailVerificationService _mailVerificationService; + private readonly IDistributedLockProvider _distributedLockProvider; public TrialExternalUserService(IRepository trialExternalUseRepository, IRepository userRepository, IRepository trialUserRepository, IRepository trialSiteSurveyUserRepository, IRepository trialSiteUserRepository, - IMailVerificationService mailVerificationService) + IMailVerificationService mailVerificationService, IDistributedLockProvider distributedLockProvider) { _trialExternalUseRepository = trialExternalUseRepository; _userRepository = userRepository; @@ -43,6 +45,7 @@ namespace IRaCIS.Core.Application.Service _trialSiteUserRepository = trialSiteUserRepository; _mailVerificationService = mailVerificationService; + _distributedLockProvider = distributedLockProvider; } @@ -75,121 +78,125 @@ namespace IRaCIS.Core.Application.Service if (addOrEditTrialExternalUser.Id == null) { - var existSysUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId); + var @lock = _distributedLockProvider.CreateLock($"UserCode"); - if (existSysUser != null) + using (await @lock.AcquireAsync()) { - if (existSysUser.LastName != addOrEditTrialExternalUser.LastName || existSysUser.FirstName != addOrEditTrialExternalUser.FirstName) + var existSysUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId); + + if (existSysUser != null) { - //$"璇ョ敤鎴峰湪绯荤粺涓殑鐢ㄦ埛鍚嶄负锛歿existSysUser.LastName + " / " + existSysUser.FirstName} 鐢佃瘽锛歿existSysUser.Phone}锛屼笌濉啓淇℃伅瀛樺湪涓嶄竴鑷撮」, 璇峰皢鐣岄潰淇℃伅淇敼涓轰笌绯荤粺涓鑷达紝鍐嶈繘琛屼繚瀛", - return ResponseOutput.NotOk(_localizer["TrialExternalUser_Inconsistency", existSysUser.LastName + " / " + existSysUser.FirstName, existSysUser.Phone], new { existSysUser.LastName, existSysUser.FirstName, existSysUser.Phone, existSysUser.IsZhiZhun, existSysUser.IsTestUser }, ApiResponseCodeEnum.NeedTips); + if (existSysUser.LastName != addOrEditTrialExternalUser.LastName || existSysUser.FirstName != addOrEditTrialExternalUser.FirstName) + { + //$"璇ョ敤鎴峰湪绯荤粺涓殑鐢ㄦ埛鍚嶄负锛歿existSysUser.LastName + " / " + existSysUser.FirstName} 鐢佃瘽锛歿existSysUser.Phone}锛屼笌濉啓淇℃伅瀛樺湪涓嶄竴鑷撮」, 璇峰皢鐣岄潰淇℃伅淇敼涓轰笌绯荤粺涓鑷达紝鍐嶈繘琛屼繚瀛", + return ResponseOutput.NotOk(_localizer["TrialExternalUser_Inconsistency", existSysUser.LastName + " / " + existSysUser.FirstName, existSysUser.Phone], new { existSysUser.LastName, existSysUser.FirstName, existSysUser.Phone, existSysUser.IsZhiZhun, existSysUser.IsTestUser }, ApiResponseCodeEnum.NeedTips); + } + } - } + //澶勭悊 鐢熸垚璐︽埛 - //澶勭悊 鐢熸垚璐︽埛 - - if (await _trialExternalUseRepository.AnyAsync(t => - t.Email == addOrEditTrialExternalUser.Email && - t.UserTypeId == addOrEditTrialExternalUser.UserTypeId && t.TrialId == addOrEditTrialExternalUser.TrialId)) - { - //---绯荤粺宸茬粡瀛樺湪涓庡垪琛ㄤ腑濉啓鐨勯偖绠卞拰鐢ㄦ埛绫诲瀷鐩稿悓鐨勮处鎴凤紝璇风‘璁ゃ - return ResponseOutput.NotOk(_localizer["TrialExternalUser_EmailTypeDuplicate"]); - } + if (await _trialExternalUseRepository.AnyAsync(t => + t.Email == addOrEditTrialExternalUser.Email && + t.UserTypeId == addOrEditTrialExternalUser.UserTypeId && t.TrialId == addOrEditTrialExternalUser.TrialId)) + { + //---绯荤粺宸茬粡瀛樺湪涓庡垪琛ㄤ腑濉啓鐨勯偖绠卞拰鐢ㄦ埛绫诲瀷鐩稿悓鐨勮处鎴凤紝璇风‘璁ゃ + return ResponseOutput.NotOk(_localizer["TrialExternalUser_EmailTypeDuplicate"]); + } - var addEntity = _mapper.Map(addOrEditTrialExternalUser); + var addEntity = _mapper.Map(addOrEditTrialExternalUser); - await _trialExternalUseRepository.AddAsync(addEntity); + await _trialExternalUseRepository.AddAsync(addEntity); - var existUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId); - var trialType = await _repository.Where(t => t.Id == addOrEditTrialExternalUser.TrialId).Select(t => t.TrialType).FirstOrDefaultAsync(); + var existUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId); + var trialType = await _repository.Where(t => t.Id == addOrEditTrialExternalUser.TrialId).Select(t => t.TrialType).FirstOrDefaultAsync(); - if (existUser != null) - { - addEntity.IsSystemUser = true; - addEntity.SystemUserId = existUser.Id; + if (existUser != null) + { + addEntity.IsSystemUser = true; + addEntity.SystemUserId = existUser.Id; - } - else - { + } + else + { - //鐢熸垚璐︽埛 骞舵彃鍏 + //鐢熸垚璐︽埛 骞舵彃鍏 - var generateUser = _mapper.Map(addOrEditTrialExternalUser); + var generateUser = _mapper.Map(addOrEditTrialExternalUser); + + if (trialType == TrialType.NoneOfficial) + { + generateUser.IsTestUser = true; + } + + // 澶栭儴浜哄憳鐢熸垚璐﹀彿 閮芥槸澶栭儴鐨 + generateUser.IsZhiZhun = false; + + generateUser.Code = _userRepository.Select(t => t.Code).DefaultIfEmpty().Max() + 1; + + + generateUser.UserCode = AppSettings.GetCodeStr(generateUser.Code, nameof(User)); + + generateUser.UserName = generateUser.UserCode; + + generateUser.UserTypeEnum = _repository.Where(t => t.Id == generateUser.UserTypeId).Select(t => t.UserTypeEnum).First(); + + generateUser.Password = MD5Helper.Md5("123456"); + + generateUser.Status = UserStateEnum.Disable; + + var newAddUser = await _repository.AddAsync(generateUser); + + + addEntity.IsSystemUser = false; + addEntity.SystemUserId = newAddUser.Id; + + + existUser = newAddUser; + + } + + #region 楠岃瘉鐢ㄦ埛 鑳藉惁鍔犲叆 + + if (trialType == TrialType.OfficialTrial || trialType == TrialType.Training) + { + + if (existUser.IsTestUser) + { + //---姝e紡绫诲瀷 銆佸煿璁被鍨嬬殑椤圭洰 涓嶅厑璁稿姞鍏ユ祴璇曠敤鎴 + throw new BusinessValidationFailedException(_localizer["TrialExternalUser_TestUserNotAllowed"]); + + } + } if (trialType == TrialType.NoneOfficial) { - generateUser.IsTestUser = true; + + if (existUser.IsTestUser == false) + { + //---娴嬭瘯椤圭洰 涓嶅厑璁稿姞鍏ユ寮忕敤鎴 + throw new BusinessValidationFailedException(_localizer["TrialExternalUser_FormalUserNotAllowed"]); + } } - // 澶栭儴浜哄憳鐢熸垚璐﹀彿 閮芥槸澶栭儴鐨 - generateUser.IsZhiZhun = false; - - generateUser.Code = _userRepository.Select(t => t.Code).DefaultIfEmpty().Max() + 1; + #endregion - generateUser.UserCode = AppSettings.GetCodeStr(generateUser.Code, nameof(User)); - - generateUser.UserName = generateUser.UserCode; - - generateUser.UserTypeEnum = _repository.Where(t => t.Id == generateUser.UserTypeId).Select(t => t.UserTypeEnum).First(); - - generateUser.Password = MD5Helper.Md5("123456"); - - generateUser.Status = UserStateEnum.Disable; - - var newAddUser = await _repository.AddAsync(generateUser); + await _trialExternalUseRepository.SaveChangesAsync(); - addEntity.IsSystemUser = false; - addEntity.SystemUserId = newAddUser.Id; - - - existUser = newAddUser; - - } - - #region 楠岃瘉鐢ㄦ埛 鑳藉惁鍔犲叆 - - if (trialType == TrialType.OfficialTrial || trialType == TrialType.Training) - { - - if (existUser.IsTestUser) + //娣诲姞鐨勬椂鍊欏氨鍙戦偖浠 鐜板湪鐪佺暐 + if (addOrEditTrialExternalUser.IsSendEmail) { - //---姝e紡绫诲瀷 銆佸煿璁被鍨嬬殑椤圭洰 涓嶅厑璁稿姞鍏ユ祴璇曠敤鎴 - throw new BusinessValidationFailedException(_localizer["TrialExternalUser_TestUserNotAllowed"]); - - } - } - - if (trialType == TrialType.NoneOfficial) - { - - if (existUser.IsTestUser == false ) - { - //---娴嬭瘯椤圭洰 涓嶅厑璁稿姞鍏ユ寮忕敤鎴 - throw new BusinessValidationFailedException(_localizer["TrialExternalUser_FormalUserNotAllowed"]); - } - } - - #endregion - - - await _trialExternalUseRepository.SaveChangesAsync(); - - - //娣诲姞鐨勬椂鍊欏氨鍙戦偖浠 鐜板湪鐪佺暐 - if (addOrEditTrialExternalUser.IsSendEmail) - { - await SendExternalUserJoinEmail(new TrialExternalUserSendEmail() - { - BaseUrl = addOrEditTrialExternalUser.BaseUrl, - RouteUrl = addOrEditTrialExternalUser.RouteUrl, - TrialId = addOrEditTrialExternalUser.TrialId, - SendUsers = new List() + await SendExternalUserJoinEmail(new TrialExternalUserSendEmail() + { + BaseUrl = addOrEditTrialExternalUser.BaseUrl, + RouteUrl = addOrEditTrialExternalUser.RouteUrl, + TrialId = addOrEditTrialExternalUser.TrialId, + SendUsers = new List() { new UserEmail() { @@ -199,12 +206,13 @@ namespace IRaCIS.Core.Application.Service SystemUserId=addEntity.SystemUserId } } - }); + }); + } + + + return ResponseOutput.Ok(addEntity.Id.ToString()); } - - return ResponseOutput.Ok(addEntity.Id.ToString()); - } else { From 8436a319f83905fec306e8c874874fb49d94da1a Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 09:59:06 +0800 Subject: [PATCH 06/13] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=94=81?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Allocation/TaskConsistentRuleService.cs | 15 ++- .../Service/Common/MailService.cs | 11 +- .../SiteSurvey/TrialSiteSurveyService.cs | 118 +----------------- 3 files changed, 22 insertions(+), 122 deletions(-) diff --git a/IRaCIS.Core.Application/Service/Allocation/TaskConsistentRuleService.cs b/IRaCIS.Core.Application/Service/Allocation/TaskConsistentRuleService.cs index 1f8480a21..14ded501a 100644 --- a/IRaCIS.Core.Application/Service/Allocation/TaskConsistentRuleService.cs +++ b/IRaCIS.Core.Application/Service/Allocation/TaskConsistentRuleService.cs @@ -13,9 +13,9 @@ using IRaCIS.Core.Domain.Share; using System.Linq.Expressions; using IRaCIS.Core.Infra.EFCore.Common; using System.Linq; -using Nito.AsyncEx; using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Filter; +using Medallion.Threading; namespace IRaCIS.Core.Application.Service { @@ -31,16 +31,17 @@ namespace IRaCIS.Core.Application.Service private readonly IRepository _subjectUserRepository; private readonly IRepository _subjectRepository; private readonly IRepository _enrollRepository; + private readonly IDistributedLockProvider _distributedLockProvider; - private readonly AsyncLock _mutex = new AsyncLock(); - public TaskConsistentRuleService(IRepository visitTaskRepository, IRepository enrollRepository, IRepository taskConsistentRuleRepository, IRepository subjectUserRepository, IRepository subjectRepository) + public TaskConsistentRuleService(IRepository visitTaskRepository, IRepository enrollRepository, IRepository taskConsistentRuleRepository, IRepository subjectUserRepository, IRepository subjectRepository, IDistributedLockProvider distributedLockProvider) { _taskConsistentRuleRepository = taskConsistentRuleRepository; _visitTaskRepository = visitTaskRepository; _subjectUserRepository = subjectUserRepository; _subjectRepository = subjectRepository; _enrollRepository = enrollRepository; + _distributedLockProvider = distributedLockProvider; } /// @@ -142,7 +143,9 @@ namespace IRaCIS.Core.Application.Service //var list = query.OrderByDescending(t => t.IsHaveGeneratedTask).ToList(); - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"VisitTaskCode"); + + using (await @lock.AcquireAsync()) { int maxCodeInt = 0; @@ -293,7 +296,9 @@ namespace IRaCIS.Core.Application.Service var configDoctorUserIdList = await doctorUserIdQuery.ToListAsync(); - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"VisitTaskCode"); + + using (await @lock.AcquireAsync()) { int maxCodeInt = 0; diff --git a/IRaCIS.Core.Application/Service/Common/MailService.cs b/IRaCIS.Core.Application/Service/Common/MailService.cs index bf195994b..7fac78714 100644 --- a/IRaCIS.Core.Application/Service/Common/MailService.cs +++ b/IRaCIS.Core.Application/Service/Common/MailService.cs @@ -7,6 +7,7 @@ using IRaCIS.Core.Application.Auth; using AutoMapper; using IRaCIS.Application.Contracts; using Microsoft.Extensions.Options; +using Medallion.Threading; namespace IRaCIS.Application.Services { @@ -53,7 +54,7 @@ namespace IRaCIS.Application.Services private readonly IRepository _userTypeRepository; private readonly IRepository _doctorTypeRepository; - + private readonly IDistributedLockProvider _distributedLockProvider; private readonly SystemEmailSendConfig _systemEmailConfig; @@ -67,7 +68,7 @@ namespace IRaCIS.Application.Services IRepository trialRepository, IRepository userTypeRepository, IRepository doctorTypeRepository, - IMapper mapper, IOptionsMonitor systemEmailConfig) + IMapper mapper, IOptionsMonitor systemEmailConfig, IDistributedLockProvider distributedLockProvider) { _systemEmailConfig = systemEmailConfig.CurrentValue; _verificationCodeRepository = verificationCodeRepository; @@ -83,7 +84,7 @@ namespace IRaCIS.Application.Services _userTypeRepository = userTypeRepository; _doctorTypeRepository = doctorTypeRepository; - + _distributedLockProvider = distributedLockProvider; } //閲嶇疆閭 @@ -604,7 +605,9 @@ namespace IRaCIS.Application.Services var userType = await _userTypeRepository.FirstAsync(t => t.UserTypeEnum == UserTypeEnum.IndependentReviewer); - using (await _mutex.LockAsync()) + var @lock = _distributedLockProvider.CreateLock($"UserCode"); + + using (await @lock.AcquireAsync()) { var isDoctorHaveAccount = await _userRepository.AnyAsync(t => t.DoctorId == doctorId); diff --git a/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs b/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs index 2c6e899d9..522885748 100644 --- a/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs +++ b/IRaCIS.Core.Application/Service/SiteSurvey/TrialSiteSurveyService.cs @@ -15,6 +15,7 @@ using MailKit.Security; using MimeKit; using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Application.Filter; +using Medallion.Threading; namespace IRaCIS.Core.Application.Contracts { @@ -32,21 +33,23 @@ namespace IRaCIS.Core.Application.Contracts private readonly IRepository _trialUserRepository; private readonly ITokenService _tokenService; private readonly IMailVerificationService _mailVerificationService; + private readonly IDistributedLockProvider _distributedLockProvider; public TrialSiteSurveyService(IRepository trialSiteSurveyRepository, IRepository trialUserRepository, IRepository trialSiteUserSurveyRepository, IRepository userRepository, IRepository trialSiteRepository, IRepository doctorRepository, ITokenService tokenService, - IMailVerificationService mailVerificationService) + IMailVerificationService mailVerificationService, IDistributedLockProvider distributedLockProvider) { _trialSiteSurveyRepository = trialSiteSurveyRepository; _trialSiteUserSurveyRepository = trialSiteUserSurveyRepository; _userRepository = userRepository; _trialUserRepository = trialUserRepository; _trialSiteRepository = trialSiteRepository; - this._doctorRepository = doctorRepository; + _doctorRepository = doctorRepository; _tokenService = tokenService; _mailVerificationService = mailVerificationService; + _distributedLockProvider = distributedLockProvider; } @@ -903,118 +906,7 @@ namespace IRaCIS.Core.Application.Contracts - #region 搴熷純 - //Site 璋冪爺閭璇 - public async Task SendInviteEmail(InviteEmailCommand inviteEmailCommand) - { - var trialInfo = await _repository.FirstOrDefaultAsync(t => t.Id == inviteEmailCommand.TrialId); - - - foreach (var item in inviteEmailCommand.UserList) - { - - var messageToSend = new MimeMessage(); - //鍙戜欢鍦板潃 - messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com")); - //鏀朵欢鍦板潃 - messageToSend.To.Add(new MailboxAddress(String.Empty, item.Email)); - //涓婚 - //$"[鏉ヨ嚜灞曞奖IRC] [{trialInfo.ResearchProgramNo}] 閭璇蜂俊"; - messageToSend.Subject = _localizer["TrialSiteSurvey_IRCInvitation", trialInfo.ResearchProgramNo]; - - var builder = new BodyBuilder(); - - //鎵句笅绯荤粺涓槸鍚﹀瓨鍦ㄨ鐢ㄦ埛绫诲瀷鐨 骞朵笖閭 鎴栬呮墜鏈虹殑璐︽埛 - var sysUserInfo = await _userRepository.Where(t => t.UserTypeId == item.UserTypeId && t.EMail == item.Email).Include(t => t.UserTypeRole).FirstOrDefaultAsync(); - - //int verificationCode = new Random().Next(100000, 1000000); - - //var baseApiUrl = baseUrl.Remove(baseUrl.IndexOf("#")) + "api"; - - - if (sysUserInfo == null) - { - - lock (lockObj) - { - var saveItem = _mapper.Map(item); - - saveItem.Code = _userRepository.Select(t => t.Code).DefaultIfEmpty().Max() + 1; - - saveItem.UserCode = AppSettings.GetCodeStr(saveItem.Code, nameof(User)); ; - - saveItem.UserName = saveItem.UserCode; - - saveItem.UserTypeEnum = _repository.Where(t => t.Id == saveItem.UserTypeId).Select(t => t.UserTypeEnum).First(); - - //saveItem.Password = MD5Helper.Md5(verificationCode.ToString()); - - _ = _repository.AddAsync(saveItem).Result; - - _ = _repository.SaveChangesAsync().Result; - - - sysUserInfo = saveItem; - } - - } - - - - builder.HtmlBody = @$" -
-
-
- {sysUserInfo.LastName + "/" + sysUserInfo.FirstName}: -
-
- {_localizer["TrialSiteSurvey_IRCInvitationContent", trialInfo.ResearchProgramNo]} -
- - - 鏌ョ湅骞剁‘璁 - -
-
- "; - - - - messageToSend.Body = builder.ToMessageBody(); - - using (var smtp = new MailKit.Net.Smtp.SmtpClient()) - { - - smtp.ServerCertificateValidationCallback = (s, c, h, e) => true; - - smtp.MessageSent += (sender, args) => - { - - _ = _trialSiteUserSurveyRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.Id, u => new TrialSiteUserSurvey() { IsGenerateSuccess = true, InviteState = TrialSiteUserStateEnum.HasSend, ConfirmTime = null, RejectReason = String.Empty, SystemUserId = sysUserInfo.Id, ExpireTime = DateTime.Now.AddDays(7) }).Result; - - }; - - - await smtp.ConnectAsync("smtp.163.com", 465, SecureSocketOptions.StartTls); - - - await smtp.AuthenticateAsync("iracis_grr@163.com", "XLWVQKZAEKLDWOAH"); - - - await smtp.SendAsync(messageToSend); - - - await smtp.DisconnectAsync(true); - } - - } - - - return ResponseOutput.Ok(); - } - - #endregion From 86a486b0605ebfca35e04e6963dc46ee8c14d9db Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 10:09:32 +0800 Subject: [PATCH 07/13] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E7=BB=84=E4=BB=B6=E5=87=86=E5=A4=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/IRaCIS.Core.API.csproj | 3 +- IRaCIS.Core.API/Startup.cs | 2 +- .../_ServiceExtensions/EasyCachingSetup.cs | 13 ++++- IRaCIS.Core.API/appsettings.json | 20 ++++++++ .../IRaCIS.Core.Application.csproj | 4 +- .../IRaCIS.Core.Application.xml | 5 -- .../Interface/JsonPatchUserRequestExample.cs | 51 ------------------- 7 files changed, 36 insertions(+), 62 deletions(-) delete mode 100644 IRaCIS.Core.Application/Service/SiteSurvey/Interface/JsonPatchUserRequestExample.cs diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index c6af611a4..dbda38d25 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -70,7 +70,8 @@ - + + diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index 886e443fc..f8aca4e66 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -109,7 +109,7 @@ namespace IRaCIS.Core.API // MediatR 进程内消息 事件解耦 从程序集中 注册命令和handler对应关系 services.AddMediatR(typeof(ConsistencyVerificationHandler).Assembly); // EasyCaching 缓存 - services.AddEasyCachingSetup(); + services.AddEasyCachingSetup(_configuration); //services.AddDistributedMemoryCache(); diff --git a/IRaCIS.Core.API/_ServiceExtensions/EasyCachingSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/EasyCachingSetup.cs index 7d7a28c6a..6f9e53bcc 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/EasyCachingSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/EasyCachingSetup.cs @@ -1,17 +1,26 @@ 锘縰sing EasyCaching.Core; +using EasyCaching.Core.Configurations; using EasyCaching.Interceptor.Castle; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace IRaCIS.Core.API { - public static class EasyCachingSetup + public static class EasyCachingSetup { - public static void AddEasyCachingSetup(this IServiceCollection services) + public static void AddEasyCachingSetup(this IServiceCollection services, IConfiguration configuration) { services.AddEasyCaching(options => { options.UseInMemory(); + + //options.UseRedis(configuration, EasyCachingConstValue.DefaultRedisName).WithMessagePack(EasyCachingConstValue.DefaultRedisName); + + }); + + //services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultRedisName); + services.ConfigureCastleInterceptor(options => options.CacheProviderName = EasyCachingConstValue.DefaultInMemoryName); } } diff --git a/IRaCIS.Core.API/appsettings.json b/IRaCIS.Core.API/appsettings.json index f142d1f51..242ea4da5 100644 --- a/IRaCIS.Core.API/appsettings.json +++ b/IRaCIS.Core.API/appsettings.json @@ -55,6 +55,26 @@ "EnableReadDeepClone": true, "EnableWriteDeepClone": false } + }, + "redis": { + "MaxRdSecond": 120, + "EnableLogging": false, + "LockMs": 5000, + "SleepMs": 300, + "dbconfig": { + "Password": "xc@123456", + "IsSsl": false, + "SslHost": null, + "ConnectionTimeout": 5000, + "AllowAdmin": true, + "Endpoints": [ + { + "Host": "47.117.164.182", + "Port": 6379 + } + ], + "Database": 0 + } } }, "IRaCISImageStore": { diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj index 4f74c24fb..1ea467582 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj @@ -67,7 +67,8 @@ - + + @@ -91,7 +92,6 @@ - true diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml index ce7fb263e..b510fcf9e 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml @@ -10274,11 +10274,6 @@ TrialSiteUserSurveyAddOrEdit 鍒楄〃鏌ヨ鍙傛暟妯″瀷 - - - 瀹炴祴 鏍囨敞鍦ㄦ湇鍔℃柟娉曚笂 娌$敤 - - TrialSiteEquipmentSurveyService diff --git a/IRaCIS.Core.Application/Service/SiteSurvey/Interface/JsonPatchUserRequestExample.cs b/IRaCIS.Core.Application/Service/SiteSurvey/Interface/JsonPatchUserRequestExample.cs deleted file mode 100644 index 0fa6ff834..000000000 --- a/IRaCIS.Core.Application/Service/SiteSurvey/Interface/JsonPatchUserRequestExample.cs +++ /dev/null @@ -1,51 +0,0 @@ -锘縰sing Microsoft.AspNetCore.JsonPatch.Operations; -using Swashbuckle.AspNetCore.Filters; - -namespace IRaCIS.Core.Application.Contracts -{ - /// - /// 瀹炴祴 鏍囨敞鍦ㄦ湇鍔℃柟娉曚笂 娌$敤 - /// - public class JsonPatchUserRequestExample : IExamplesProvider - { - public Operation[] GetExamples() - { - return new[] - { - new Operation - { - op = "replace", - path = "/name", - value = "Gordon" - }, - new Operation - { - op = "replace", - path = "/surname", - value = "Freeman" - } - }; - } - - object IExamplesProvider.GetExamples() - { - return new[] - { - new Operation - { - op = "replace", - path = "/name", - value = "Gordon" - }, - new Operation - { - op = "replace", - path = "/surname", - value = "Freeman" - } - }; - } - } - - -} From a1d8e2237cbef9e8c6d22d9796e7b03f3f392760 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 10:12:22 +0800 Subject: [PATCH 08/13] =?UTF-8?q?=E5=88=A0=E9=99=A4JsonPatch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/IRaCIS.Core.API.csproj | 1 - IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index dbda38d25..ffbbb41b1 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -69,7 +69,6 @@ - diff --git a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs index 4a16162e7..44bbb60f4 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs @@ -18,7 +18,6 @@ namespace IRaCIS.Core.API { public static void AddSwaggerSetup(this IServiceCollection services) { - services.AddSwaggerExamplesFromAssemblyOf(); services.AddSwaggerGen(options => { From 09acd125866f9c75b00c71e1a6b5be34a0c7d780 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 10:26:41 +0800 Subject: [PATCH 09/13] =?UTF-8?q?Study=20=E4=B8=8A=E4=BC=A0=20=E8=BF=81?= =?UTF-8?q?=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/ExtraController.cs | 45 +++++++ .../Controllers/UploadDownLoadController.cs | 53 ++++++++ IRaCIS.Core.API/IRaCIS.Core.API.csproj | 1 + IRaCIS.Core.API/Startup.cs | 3 +- IRaCIS.Core.API/appsettings.Development.json | 14 +- .../Helper/FileStoreHelper.cs | 45 +++++++ IRaCIS.Core.Application/Helper/OSSService.cs | 120 ++++++++++++++++++ IRaCIS.Core.Domain/_Config/_StaticData.cs | 5 + 8 files changed, 280 insertions(+), 6 deletions(-) create mode 100644 IRaCIS.Core.Application/Helper/OSSService.cs diff --git a/IRaCIS.Core.API/Controllers/ExtraController.cs b/IRaCIS.Core.API/Controllers/ExtraController.cs index de3d78b2c..15ec0a88b 100644 --- a/IRaCIS.Core.API/Controllers/ExtraController.cs +++ b/IRaCIS.Core.API/Controllers/ExtraController.cs @@ -24,6 +24,13 @@ using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Infrastructure; 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; namespace IRaCIS.Api.Controllers { @@ -203,6 +210,44 @@ namespace IRaCIS.Api.Controllers } + [HttpGet("user/GenerateSTS")] + public IResponseOutput GenerateSTS(IOptionsMonitor options ) + { + var ossOptions = options.CurrentValue; + + + IClientProfile profile = DefaultProfile.GetProfile(ossOptions.RegionId, ossOptions.AccessKeyId, ossOptions.AccessKeySecret); + DefaultAcsClient client = new DefaultAcsClient(profile); + + + // 鍒涘缓涓涓猄TS璇锋眰 + 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); + + } diff --git a/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs b/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs index c96d9b1c2..f8a017c5b 100644 --- a/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs +++ b/IRaCIS.Core.API/Controllers/UploadDownLoadController.cs @@ -1222,6 +1222,59 @@ namespace IRaCIS.Core.API.Controllers } + public enum UploadFileType + { + DataUpload = 1, + + DataDownload = 2, + + EmailAttachment = 3, + + EmailBodyHtml = 4, + + Other = 5 + } + + /// + /// 1锛氭暟鎹笂浼 2锛氬鍑恒 3锛氶偖浠堕檮浠 4锛氶偖浠禜tml 閫氳繃 ----new + /// + /// + [HttpPost("SystemFile/Upload")] + [DisableRequestSizeLimit] + [DisableFormValueModelBinding] + public async Task Upload(UploadFileType fileType) + { + IResponseOutput result = null; + + switch (fileType) + { + case UploadFileType.DataUpload: + result = await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemFileUploadPath(_hostEnvironment, StaticData.Folder.DataTemplate, fileName)); + + break; + case UploadFileType.DataDownload: + result = await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemFileUploadPath(_hostEnvironment, StaticData.Folder.DataTemplate, fileName)); + + break; + case UploadFileType.EmailAttachment: + result = await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemFileUploadPath(_hostEnvironment, StaticData.Folder.EmailTemplate, fileName)); + + break; + + case UploadFileType.EmailBodyHtml: + result = await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemFileUploadPath(_hostEnvironment, StaticData.Folder.EmailTemplate, fileName)); + break; + + default: + result = await SingleFileUploadAsync((fileName) => FileStoreHelper.GetOtherFileUploadPath(_hostEnvironment, StaticData.Folder.TempFile, fileName)); + + break; + } + + return result; + + } + } #endregion diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index eccd92242..ba3a2d4e0 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -66,6 +66,7 @@ + diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index 705f5ad87..2d5f19e41 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -24,6 +24,7 @@ using Invio.Extensions.Authentication.JwtBearer; using Microsoft.AspNetCore.SignalR; using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.StaticFiles; +using IRaCIS.Core.Application.Helper; namespace IRaCIS.Core.API { @@ -91,7 +92,7 @@ namespace IRaCIS.Core.API services.AddOptions().Configure( _configuration.GetSection("SystemEmailSendConfig")); services.AddOptions().Configure(_configuration.GetSection("BasicSystemConfig")); - + services.AddOptions().Configure(_configuration.GetSection("AliyunOSS")); //动态WebApi + UnifiedApiResultFilter 省掉控制器代码 diff --git a/IRaCIS.Core.API/appsettings.Development.json b/IRaCIS.Core.API/appsettings.Development.json index 3f816a12f..a71d2d214 100644 --- a/IRaCIS.Core.API/appsettings.Development.json +++ b/IRaCIS.Core.API/appsettings.Development.json @@ -13,10 +13,14 @@ }, "AliyunOSS": { - "endpoint": "https://zyypacs-code.oss-cn-shanghai.aliyuncs.com", - "accessKeyId": "mpXG7Nu6zTpsDrI1", - "accessKeySecret": "yNINcEb099SkNfF6vYKaoP8TZNI3xZ", - "bucketName": "zyypacs-code" + "RegionId": "cn-shanghai", + "Endpoint": "https://oss-cn-shanghai.aliyuncs.com", + "AccessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ", + "AccessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio", + "BucketName": "zy-sir-test-store", + "RoleArn": "acs:ram::1899121822495495:role/oss-upload", + "ViewEndpoint": "https://zy-sir-test-store.oss-cn-shanghai.aliyuncs.com", + "Region": "oss-cn-shanghai" }, "BasicSystemConfig": { @@ -30,7 +34,7 @@ "LoginMaxFailCount": 5, - "LoginFailLockMinutes":1 + "LoginFailLockMinutes": 1 }, "SystemEmailSendConfig": { diff --git a/IRaCIS.Core.Application/Helper/FileStoreHelper.cs b/IRaCIS.Core.Application/Helper/FileStoreHelper.cs index 0089d3e9a..c0797b1fe 100644 --- a/IRaCIS.Core.Application/Helper/FileStoreHelper.cs +++ b/IRaCIS.Core.Application/Helper/FileStoreHelper.cs @@ -116,6 +116,51 @@ public static class FileStoreHelper return physicalFilePath; } + + #region 淇敼鍚庣暀瀛 + + + public static (string PhysicalPath, string RelativePath) GetSystemFileUploadPath(IWebHostEnvironment _hostEnvironment, string templateFolderName, string fileName) + { + var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment); + + //鏂囦欢绫诲瀷璺緞澶勭悊 + var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.SystemDataFolder, templateFolderName); + if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath); + + + var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName); + + + var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.SystemDataFolder}/{templateFolderName}/{trustedFileNameForFileStorage}"; + + var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage); + + return (serverFilePath, relativePath); + } + + public static (string PhysicalPath, string RelativePath) GetOtherFileUploadPath(IWebHostEnvironment _hostEnvironment, string templateFolderName, string fileName) + { + var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment); + + //鏂囦欢绫诲瀷璺緞澶勭悊 + var uploadFolderPath = Path.Combine(rootPath, StaticData.Folder.OtherDataFolder, templateFolderName); + if (!Directory.Exists(uploadFolderPath)) Directory.CreateDirectory(uploadFolderPath); + + + var (trustedFileNameForFileStorage, fileRealName) = FileStoreHelper.GetStoreFileName(fileName); + + + var relativePath = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.OtherDataFolder}/{templateFolderName}/{trustedFileNameForFileStorage}"; + + var serverFilePath = Path.Combine(uploadFolderPath, trustedFileNameForFileStorage); + + return (serverFilePath, relativePath); + } + + + #endregion + /// /// /// diff --git a/IRaCIS.Core.Application/Helper/OSSService.cs b/IRaCIS.Core.Application/Helper/OSSService.cs new file mode 100644 index 000000000..1fba59176 --- /dev/null +++ b/IRaCIS.Core.Application/Helper/OSSService.cs @@ -0,0 +1,120 @@ +锘縰sing Aliyun.OSS; +using IRaCIS.Core.Infrastructure; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using NPOI.HPSF; +using SharpCompress.Common; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Security.AccessControl; +using System.Text; +using System.Threading.Tasks; + +namespace IRaCIS.Core.Application.Helper +{ + + public class AliyunOssOptions + { + public string RegionId { get; set; } + public string AccessKeyId { get; set; } + public string AccessKeySecret { 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 interface IOSSService + { + + } + + public class OSSService : IOSSService + { + + public AliyunOssOptions _OSSConfig { get; set; } + + public OssClient _ossClient { get; set; } + + + + public OSSService(IOptionsMonitor options) + { + var ossOptions = options.CurrentValue; + + _OSSConfig = new AliyunOssOptions() + { + RegionId = ossOptions.RegionId, + AccessKeyId = ossOptions.AccessKeyId, + AccessKeySecret = ossOptions.AccessKeySecret, + EndPoint = ossOptions.EndPoint, + BucketName = ossOptions.BucketName, + RoleArn = ossOptions.RoleArn, + Region = ossOptions.Region, + ViewEndpoint = ossOptions.ViewEndpoint + }; + + _ossClient = new OssClient(_OSSConfig.EndPoint, _OSSConfig.AccessKeyId, _OSSConfig.AccessKeySecret); + + } + + + public string UploadToOSS(string localFilePath, string oosFolderPath) + { + var localFileName = Path.GetFileName(localFilePath); + + var ossRelativePath = oosFolderPath + "/" + localFileName; + + + try + { + // 涓婁紶鏂囦欢 + var result = _ossClient.PutObject(_OSSConfig.BucketName, ossRelativePath, localFilePath); + + return ossRelativePath; + } + catch (Exception ex) + { + throw new BusinessValidationFailedException("oss涓婁紶澶辫触" + ex.Message); + + } + } + + public void DownLoadFromOSS(string ossRelativePath, string localFilePath) + { + try + { + var result = _ossClient.GetObject(_OSSConfig.BucketName, ossRelativePath); + + // 灏嗕笅杞界殑鏂囦欢娴佷繚瀛樺埌鏈湴鏂囦欢 + using (var fs = File.OpenWrite(localFilePath)) + { + result.Content.CopyTo(fs); + fs.Close(); + } + } + catch (Exception ex) + { + + throw new BusinessValidationFailedException("oss涓嬭浇澶辫触!" + ex.Message); + } + + + } + + + + + } + + +} diff --git a/IRaCIS.Core.Domain/_Config/_StaticData.cs b/IRaCIS.Core.Domain/_Config/_StaticData.cs index daf810d2b..d6ca83588 100644 --- a/IRaCIS.Core.Domain/_Config/_StaticData.cs +++ b/IRaCIS.Core.Domain/_Config/_StaticData.cs @@ -87,6 +87,11 @@ public static class StaticData public static readonly string SignDocumentFolder = "SignDocument"; public static readonly string DataTemplate = "DataTemplate"; + public static readonly string EmailTemplate = "EmailTemplate"; + + public static readonly string CommonFile = "CommonFile"; + + public static readonly string TempFile = "TempFile"; public static readonly string NoticeAttachment = "NoticeAttachment"; From ed89bc652e62a9b27b07e36b5ebdaca9d0807c36 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 10:51:21 +0800 Subject: [PATCH 10/13] =?UTF-8?q?=E5=AE=9A=E6=97=B6=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/AnonymizeTagSetting.json | 106 --------- IRaCIS.Core.API/IRaCIS.Core.API.csproj | 3 - IRaCIS.Core.API/IRaCIS.Core.API.xml | 6 + IRaCIS.Core.API/NLog.config | 18 -- IRaCIS.Core.API/Program.cs | 37 +-- IRaCIS.Core.API/Startup.cs | 7 +- .../BackGroundJob/IRaCISCHangfireJob.cs | 213 ++++++++++++++++++ .../BackGroundJob/IRaCISCacheHangfireJob.cs | 99 -------- .../IRaCIS.Core.Application.xml | 6 + IRaCIS.Core.Domain/_Config/_StaticData.cs | 2 +- 10 files changed, 234 insertions(+), 263 deletions(-) delete mode 100644 IRaCIS.Core.API/AnonymizeTagSetting.json delete mode 100644 IRaCIS.Core.API/NLog.config create mode 100644 IRaCIS.Core.Application/BackGroundJob/IRaCISCHangfireJob.cs delete mode 100644 IRaCIS.Core.Application/BackGroundJob/IRaCISCacheHangfireJob.cs diff --git a/IRaCIS.Core.API/AnonymizeTagSetting.json b/IRaCIS.Core.API/AnonymizeTagSetting.json deleted file mode 100644 index 6576ca04a..000000000 --- a/IRaCIS.Core.API/AnonymizeTagSetting.json +++ /dev/null @@ -1,106 +0,0 @@ -锘縶 - "needAnonymizeTag": [ - { //PatientsName - "Group": "0010", - "Element": "0010", - "ReplaceValue": "", - "Enable": true - }, - { // PatientID - "Group": "0010", - "Element": "0020", - "ReplaceValue": "", - "Enable": true - }, - { // IssuerOfPatientID - "Group": "0010", - "Element": "0021", - "ReplaceValue": "", - "Enable": true - }, - { // PatientsBirthDate - "Group": "0010", - "Element": "0030", - "ReplaceValue": "", - "Enable": true - }, - { // PatientsBirthTime - "Group": "0010", - "Element": "0032", - "ReplaceValue": "", - "Enable": false - }, - { // PatientsSex - "Group": "0010", - "Element": "0040", - "ReplaceValue": "", - "Enable": false - }, - { // OtherPatientIDs - "Group": "0010", - "Element": "1000", - "ReplaceValue": "", - "Enable": false - }, - { // OtherPatientNames - "Group": "0010", - "Element": "1001", - "ReplaceValue": "", - "Enable": false - }, - { // OtherPatientNames - "Group": "0010", - "Element": "1005", - "ReplaceValue": "", - "Enable": true - }, - { // PatientBirthName - "Group": "0010", - "Element": "1005", - "ReplaceValue": "", - "Enable": true - }, - { // PatientsAge - "Group": "0010", - "Element": "1010", - "ReplaceValue": "", - "Enable": true - }, - { // PatientsAddress - "Group": "0010", - "Element": "1040", - "ReplaceValue": "", - "Enable": true - }, - { // PatientsMothersBirthName - "Group": "0010", - "Element": "1060", - "ReplaceValue": "", - "Enable": true - }, - { - "Group": "0010", - "Element": "2150", - "ReplaceValue": "", - "Enable": true - }, - { - "Group": "0010", - "Element": "2152", - "ReplaceValue": "", - "Enable": true - }, - { - "Group": "0010", - "Element": "2154", - "ReplaceValue": "", - "Enable": true - }, - { - "Group": "0012", - "Element": "0040", - "ReplaceValue": "XXX", - "Enable": true - } - ] -} \ No newline at end of file diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index a6bbf319e..843813572 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -108,9 +108,6 @@ - - Always - Always diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.xml b/IRaCIS.Core.API/IRaCIS.Core.API.xml index ed6960728..50413058f 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.xml +++ b/IRaCIS.Core.API/IRaCIS.Core.API.xml @@ -429,6 +429,12 @@ + + + 1锛氭暟鎹笂浼 2锛氬鍑恒 3锛氶偖浠堕檮浠 4锛氶偖浠禜tml 閫氳繃 ----new + + + IPLimit闄愭祦 鍚姩鏈嶅姟 diff --git a/IRaCIS.Core.API/NLog.config b/IRaCIS.Core.API/NLog.config deleted file mode 100644 index bf1dbbb1b..000000000 --- a/IRaCIS.Core.API/NLog.config +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/IRaCIS.Core.API/Program.cs b/IRaCIS.Core.API/Program.cs index b771b7a5f..ad2c3f425 100644 --- a/IRaCIS.Core.API/Program.cs +++ b/IRaCIS.Core.API/Program.cs @@ -53,24 +53,12 @@ namespace IRaCIS.Core.API }) .Build(); - //// Serilog SerilogExtension.AddSerilogSetup(enviromentName, host.Services); Log.Logger.Warning($"当前环境:{enviromentName}"); - - NewId.SetProcessIdProvider(new CurrentProcessIdProvider()); - - - //缓存项目的状态 匿名化数据 - await InitCache(host); - - - - - - + host.Run(); @@ -100,28 +88,7 @@ namespace IRaCIS.Core.API webBuilder.UseStartup(); }).UseSerilog() .UseServiceProviderFactory(new AutofacServiceProviderFactory()); - - - private static async Task InitCache(IHost host) - { - var _repository = host.Services.GetService(typeof(IRepository)) as IRepository; - - //初始化 国际化数据,并且监测国际化文件变更 - await InternationalizationHelper.InitInternationlizationDataAndWatchJsonFileAsync(_repository); - - var _mediator = host.Services.GetService(typeof(IMediator)) as IMediator; - - await _mediator.Send(new AnonymizeCacheRequest()); - - await _mediator.Send(new TrialStateCacheRequest()); - - - - } - - - - + } } diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index c157a1d94..06851f87d 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -25,6 +25,7 @@ using Microsoft.AspNetCore.SignalR; using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.StaticFiles; using IRaCIS.Core.Application.Helper; +using IRaCIS.Application.Services.BackGroundJob; namespace IRaCIS.Core.API { @@ -162,7 +163,7 @@ namespace IRaCIS.Core.API } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //本地化 app.UseLocalization(); @@ -236,6 +237,10 @@ namespace IRaCIS.Core.API endpoints.MapHub("/UploadHub"); }); + var hangfireJobService = app.ApplicationServices.GetRequiredService(); + + await hangfireJobService.InitHangfireJobTaskAsync(); + } } } diff --git a/IRaCIS.Core.Application/BackGroundJob/IRaCISCHangfireJob.cs b/IRaCIS.Core.Application/BackGroundJob/IRaCISCHangfireJob.cs new file mode 100644 index 000000000..f62423549 --- /dev/null +++ b/IRaCIS.Core.Application/BackGroundJob/IRaCISCHangfireJob.cs @@ -0,0 +1,213 @@ +锘縰sing EasyCaching.Core; +using Hangfire; +using Hangfire.Storage; +using IRaCIS.Core.Application.Helper; +using IRaCIS.Core.Application.Service; +using IRaCIS.Core.Domain.Share; +using IRaCIS.Core.Infrastructure; +using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; + +namespace IRaCIS.Application.Services.BackGroundJob +{ + + public interface IIRaCISHangfireJob + { + + Task MemoryCacheTrialStatusAsync(); + + Task InitHangfireJobTaskAsync(); + + } + public class IRaCISCHangfireJob : IIRaCISHangfireJob + { + public static string JsonFileFolder = Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources); + + private readonly IRepository _trialRepository; + private readonly IEasyCachingProvider _provider; + private readonly ILogger _logger; + private readonly IRepository _systemAnonymizationRepository; + private readonly IRepository _trialEmailNoticeConfigRepository; + private readonly IRepository _internationalizationRepository; + + + + public IRaCISCHangfireJob(IRepository trialRepository, ILogger logger, IEasyCachingProvider provider, IRepository trialEmailNoticeConfigRepository, IRepository internationalizationRepository, IRepository systemAnonymizationRepository) + { + _trialRepository = trialRepository; + _provider = provider; + _logger = logger; + _trialEmailNoticeConfigRepository = trialEmailNoticeConfigRepository; + _internationalizationRepository = internationalizationRepository; + _systemAnonymizationRepository = systemAnonymizationRepository; + } + + public async Task InitHangfireJobTaskAsync() + { + _logger.LogInformation("椤圭洰鍚姩 hangfire 浠诲姟鍒濆鍖 鎵ц寮濮媬"); + + + //椤圭洰鐘舵 绔嬪嵆鍔犺浇鍒扮紦瀛樹腑 + await MemoryCacheTrialStatusAsync(); + + await MemoryCacheAnonymizeData(); + + + //鍒涘缓椤圭洰缂撳瓨 瀹氭椂浠诲姟 + HangfireJobHelper.AddOrUpdateInitCronJob("RecurringJob_Cache_TrialState", t => t.MemoryCacheTrialStatusAsync(), Cron.Daily()); + + //鍒濆鍖 + + await InitInternationlizationDataAndWatchJsonFileAsync(); + + //鍒涘缓閭欢瀹氭椂浠诲姟 + await InitSysAndTrialCronJobAsync(); + + + _logger.LogInformation("椤圭洰鍚姩 hangfire 浠诲姟鍒濆鍖 鎵ц缁撴潫"); + } + + /// + /// 缂撳瓨椤圭洰鐘舵 + /// + /// + 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(); + + //缁勭粐鎴恓son 鏂囦欢 + + 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鏂囦欢鍙樻洿 瀹炴椂鍒锋柊鏁版嵁 + WatchJsonFile(usJsonPath); + WatchJsonFile(cnJsonPath); + + } + + public void WatchJsonFile(string filePath) + { + if (!File.Exists(filePath)) + { + throw new BusinessValidationFailedException(StaticData.International("IRaCISCHangfireJob_FileNotFound")); + } + + FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath), Path.GetFileName(filePath)); + watcher.Changed += (sender, e) => LoadJsonFile(filePath); + watcher.EnableRaisingEvents = true; + + } + + + private void LoadJsonFile(string filePath) + { + + IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(filePath); + + 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() + { + //var deleteJobIdList = await _trialEmailNoticeConfigRepository.Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialOngoing && t.EmailCron != string.Empty && t.IsAutoSend) + // .Select(t => t.TrialId + "_" + t.Id) + // .ToListAsync(); + + //foreach (var jobId in deleteJobIdList) + //{ + // HangfireJobHelper.RemoveCronJob(jobId); + //} + + + var taskInfoList = await _trialEmailNoticeConfigRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing && t.EmailCron != string.Empty && t.IsAutoSend) + .Select(t => new { t.Id, t.Code, t.EmailCron, t.BusinessScenarioEnum, t.TrialId }) + .ToListAsync(); + + foreach (var task in taskInfoList) + { + //鍒╃敤涓婚敭浣滀负浠诲姟Id + var jobId = $"{task.TrialId}_{task.Id}"; + + HangfireJobHelper.AddOrUpdateTrialCronJob(jobId, task.TrialId, task.BusinessScenarioEnum, task.EmailCron); + } + + var addOrUpdateJobIdList = taskInfoList.Select(t => $"{t.TrialId}_{t.Id}").ToList(); + + var list = JobStorage.Current.GetConnection().GetRecurringJobs().ToList(); + + //椤圭洰瀹氭椂浠诲姟閮藉湪default 闃熷垪 + //var dbJobIdList = JobStorage.Current.GetConnection().GetRecurringJobs().Where(t => t.Queue == "default").Select(t => t.Id).ToList(); + + //var deleteList= dbJobIdList.Except(addOrUpdateJobIdList).ToList(); + + // foreach (var jobId in deleteList) + // { + // HangfireJobHelper.RemoveCronJob(jobId); + // } + + + } + } + + +} diff --git a/IRaCIS.Core.Application/BackGroundJob/IRaCISCacheHangfireJob.cs b/IRaCIS.Core.Application/BackGroundJob/IRaCISCacheHangfireJob.cs deleted file mode 100644 index 80a3d16ac..000000000 --- a/IRaCIS.Core.Application/BackGroundJob/IRaCISCacheHangfireJob.cs +++ /dev/null @@ -1,99 +0,0 @@ -锘縰sing EasyCaching.Core; -using IRaCIS.Core.Domain.Share; -using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal; -using Microsoft.Extensions.Logging; - -namespace IRaCIS.Application.Services.BackGroundJob -{ - - public interface IIRaCISCacheHangfireJob - { - - Task ProjectStartCache(); - Task MemoryCacheTrialStatus(); - - Task MemoryCacheAnonymizeData(); - - Task CacheUserTypePermission(Guid? cacheUserTypeId); - } - public class IRaCISCacheHangfireJob: IIRaCISCacheHangfireJob - { - private readonly IRepository _trialRepository; - private readonly IEasyCachingProvider _provider; - private readonly ILogger _logger; - private readonly IRepository _systemAnonymizationRepository; - - private readonly IRepository _userTypeMenuRepository; - - public IRaCISCacheHangfireJob(IRepository trialRepository, - IRepository systemAnonymizationRepository, IRepository userTypeMenuRepository, - IEasyCachingProvider provider,ILogger logger) - { - _trialRepository = trialRepository; - _provider = provider; - _logger = logger; - _systemAnonymizationRepository = systemAnonymizationRepository; - _userTypeMenuRepository = userTypeMenuRepository; - } - - - public async Task ProjectStartCache() - { - _logger.LogInformation("hangfire 瀹氭椂缂撳瓨椤圭洰鐘舵佷换鍔″紑濮媬"); - try - { - await MemoryCacheTrialStatus(); - - await MemoryCacheAnonymizeData(); - - await CacheUserTypePermission(); - } - catch (Exception e) - { - _logger.LogError("hangfire 瀹氭椂浠诲姟鎵ц澶辫触" + e.Message); - - } - - _logger.LogInformation("hangfire 瀹氭椂浠诲姟鎵ц缁撴潫"); - } - - public async Task MemoryCacheTrialStatus() - { - 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)); - } - - public async Task CacheUserTypePermission(Guid? cacheUserTypeId=null) - { - - var permissionList = await _userTypeMenuRepository.Where(t => t.Menu.MenuType == "F") - .WhereIf(cacheUserTypeId != null, t => t.UserTypeId == cacheUserTypeId.Value).Select(t => new { t.UserTypeId, t.Menu.PermissionStr }).ToListAsync(); - - foreach (var userTypeGroup in permissionList.GroupBy(t => t.UserTypeId)) - { - _provider.Set($"{StaticData.CacheKey.UserTypeId}_{userTypeGroup.Key}", userTypeGroup.Select(t => t.PermissionStr).ToList(), TimeSpan.FromDays(7)); - } - } - - - } -} \ No newline at end of file diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml index 01b3b1464..38559fb74 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.xml +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.xml @@ -11927,6 +11927,12 @@ 鏋勯犲嚱鏁版敞鍏 + + + 缂撳瓨椤圭洰鐘舵 + + + 缁熶竴杩斿洖鍓嶇鏁版嵁鍖呰锛屼箣鍓嶅湪鎺у埗鍣ㄥ寘瑁咃紝鐜板湪淇敼涓哄姩鎬丄pi 鍦≧esultFilter杩欓噷鍖呰锛屽噺灏戦噸澶嶅啑浣欎唬鐮 diff --git a/IRaCIS.Core.Domain/_Config/_StaticData.cs b/IRaCIS.Core.Domain/_Config/_StaticData.cs index d6ca83588..5bfb2f3e5 100644 --- a/IRaCIS.Core.Domain/_Config/_StaticData.cs +++ b/IRaCIS.Core.Domain/_Config/_StaticData.cs @@ -78,7 +78,7 @@ public static class StaticData public static readonly string Resources = "Resources"; public static readonly string IRaCISDataFolder = "IRaCISData"; - + public static readonly string OtherDataFolder = "OtherData"; public static readonly string TrialDataFolder = "TrialData"; public static readonly string SystemDataFolder = "SystemData"; From 9ad4c96572945d805377d89a145e20c706e94dea Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 11:06:16 +0800 Subject: [PATCH 11/13] =?UTF-8?q?=E5=88=A0=E9=99=A4=20quartz?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API/IRaCIS.Core.API.csproj | 2 - IRaCIS.Core.API/Startup.cs | 3 +- .../_ServiceExtensions/QuartZSetup.cs | 45 ------------ .../CacheTrialStatusQuartZJob.cs | 72 ------------------- 4 files changed, 1 insertion(+), 121 deletions(-) delete mode 100644 IRaCIS.Core.API/_ServiceExtensions/QuartZSetup.cs delete mode 100644 IRaCIS.Core.Application/BackGroundJob/CacheTrialStatusQuartZJob.cs diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index 843813572..248060a76 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -89,8 +89,6 @@ - - diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index 06851f87d..83255d47a 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -117,8 +117,7 @@ namespace IRaCIS.Core.API // hangfire 定时任务框架 有界面,更友好~ services.AddhangfireSetup(_configuration); - // QuartZ 定时任务框架 使用了hangfire 暂时不用,后续需要可以打开,已经配好 - services.AddQuartZSetup(_configuration); + // 保护上传文件 //services.AddStaticFileAuthorizationSetup(); diff --git a/IRaCIS.Core.API/_ServiceExtensions/QuartZSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/QuartZSetup.cs deleted file mode 100644 index 2f42e8f7c..000000000 --- a/IRaCIS.Core.API/_ServiceExtensions/QuartZSetup.cs +++ /dev/null @@ -1,45 +0,0 @@ -锘 -using IRaCIS.Application.Services.BackGroundJob; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Quartz; - -namespace IRaCIS.Core.API -{ - public static class QuartZSetup - { - public static void AddQuartZSetup(this IServiceCollection services, IConfiguration configuration) - { - services.AddTransient(); - - services.AddQuartz(q => - { - // base quartz scheduler, job and trigger configuration - - // as of 3.3.2 this also injects scoped services (like EF DbContext) without problems - q.UseMicrosoftDependencyInjectionJobFactory(); - - // 鍩烘湰Quartz璋冨害鍣ㄣ佷綔涓氬拰瑙﹀彂鍣ㄩ厤缃 - var jobKey = new JobKey("RegularTrialWork", "regularWorkGroup"); - q.AddJob(jobKey, j => j - .WithDescription("Trial regular work") - ); - q.AddTrigger(t => t - .WithIdentity("TrialStatusTrigger") - .ForJob(jobKey) - - .WithCronSchedule("0 0 * * * ?") - .WithDescription("My regular trial work trigger") - ); - }); - - // ASP.NET Core hosting - services.AddQuartzHostedService(options => - { - // when shutting down we want jobs to complete gracefully - options.WaitForJobsToComplete = true; - }); - - } - } -} diff --git a/IRaCIS.Core.Application/BackGroundJob/CacheTrialStatusQuartZJob.cs b/IRaCIS.Core.Application/BackGroundJob/CacheTrialStatusQuartZJob.cs deleted file mode 100644 index e3be27479..000000000 --- a/IRaCIS.Core.Application/BackGroundJob/CacheTrialStatusQuartZJob.cs +++ /dev/null @@ -1,72 +0,0 @@ -锘縰sing System; -using System.Linq; -using System.Threading.Tasks; -using EasyCaching.Core; -using IRaCIS.Core.Domain; -using IRaCIS.Core.Infra.EFCore; -using IRaCIS.Core.Domain.Models; -using Microsoft.Extensions.Logging; -using Quartz; -using IRaCIS.Core.Domain.Share; - -namespace IRaCIS.Application.Services.BackGroundJob -{ - - public class CacheTrialStatusQuartZJob: IJob - { - - private readonly IRepository _trialRepository; - private readonly IEasyCachingProvider _provider; - private readonly ILogger _logger; - private readonly IRepository _systemAnonymizationRepository; - - public CacheTrialStatusQuartZJob(IRepository trialRepository, IEasyCachingProvider provider,ILogger logger, IRepository systemAnonymizationRepository) - { - _trialRepository = trialRepository; - _provider = provider; - _logger = logger; - _systemAnonymizationRepository = systemAnonymizationRepository; - } - - public async Task Execute(IJobExecutionContext context) - - { - _logger.LogInformation($"寮濮嬫墽琛孮uartZ瀹氭椂浠诲姟浣滀笟"); - try - { - await MemoryCacheTrialStatus(); - - await MemoryCacheAnonymizeData(); - - } - catch (Exception e) - { - _logger.LogError($" 鏌ヨ鍜岀紦瀛樿繃绋嬪嚭鐜板紓甯"+e.Message); - } - _logger.LogInformation("QuartZ瀹氭椂浠诲姟浣滀笟缁撴潫"); - } - - - public async Task MemoryCacheTrialStatus() - { - 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)); - } - - - - } -} \ No newline at end of file From 89d852f4ed75f427454f87383b783b777a99f1db Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 13:26:06 +0800 Subject: [PATCH 12/13] =?UTF-8?q?=E5=8D=87=E7=BA=A7efcore=20=20=E6=B8=85?= =?UTF-8?q?=E7=90=86=E4=B9=8B=E5=89=8D=E7=9A=84=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Serilog/SerilogSetup.cs | 2 +- .../Swagger/JsonPatchDocumentFilter.cs | 55 ------ .../Swagger/SwaggerSetup.cs | 1 - .../Service/Common/DictionaryService.cs | 2 +- .../Service/Common/_MapConfig.cs | 2 +- .../Service/Document/SystemDocumentService.cs | 2 +- .../Service/Document/TrialDocumentService.cs | 10 +- .../Service/Document/_MapConfig.cs | 3 +- .../Service/TrialSiteUser/TrialService.cs | 8 +- .../Service/TrialSiteUser/_MapConfig.cs | 8 +- IRaCIS.Core.Domain/Common/Dictionary.cs | 3 - .../Context/IRaCISDBContext.cs | 16 +- .../Extention/RequestExtension.cs | 158 ------------------ IRaCIS.Core.Infrastructure/Helper/IPHelper.cs | 43 ----- .../IRaCIS.Core.Infrastructure.csproj | 13 +- 15 files changed, 33 insertions(+), 293 deletions(-) delete mode 100644 IRaCIS.Core.API/_ServiceExtensions/Swagger/JsonPatchDocumentFilter.cs delete mode 100644 IRaCIS.Core.Infrastructure/Extention/RequestExtension.cs delete mode 100644 IRaCIS.Core.Infrastructure/Helper/IPHelper.cs diff --git a/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs index f0740dbbf..a27de1505 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Serilog/SerilogSetup.cs @@ -21,7 +21,7 @@ namespace IRaCIS.Core.API .MinimumLevel.Override("Hangfire", LogEventLevel.Warning) .MinimumLevel.Override("System.Net.Http.HttpClient.HttpReports", LogEventLevel.Warning) .Enrich.WithClientIp() - .Enrich.WithClientAgent() + .Enrich.FromLogContext() //鎺у埗鍙 鏂逛究璋冭瘯 闂 鎴戜滑鏄剧ず璁板綍鏃ュ織 鏃 鑾峰彇涓婁笅鏂囩殑ip 鍜岀敤鎴峰悕 鐢ㄦ埛绫诲瀷 diff --git a/IRaCIS.Core.API/_ServiceExtensions/Swagger/JsonPatchDocumentFilter.cs b/IRaCIS.Core.API/_ServiceExtensions/Swagger/JsonPatchDocumentFilter.cs deleted file mode 100644 index 9f3562072..000000000 --- a/IRaCIS.Core.API/_ServiceExtensions/Swagger/JsonPatchDocumentFilter.cs +++ /dev/null @@ -1,55 +0,0 @@ -锘縰sing Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; -using System.Collections.Generic; -using System.Linq; - -namespace IRaCIS.Core.API -{ - public class JsonPatchDocumentFilter : IDocumentFilter - { - public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) - { - var schemas = swaggerDoc.Components.Schemas.ToList(); - foreach (var item in schemas) - { - if (item.Key.StartsWith("Operation") || item.Key.StartsWith("JsonPatchDocument")) - swaggerDoc.Components.Schemas.Remove(item.Key); - } - - swaggerDoc.Components.Schemas.Add("Operation", new OpenApiSchema - { - Type = "object", - Properties = new Dictionary - { - { "op", new OpenApiSchema { Type = "string" } }, - {"value", new OpenApiSchema{ Type = "object", Nullable = true } }, - { "path", new OpenApiSchema { Type = "string" } } - } - }); - - swaggerDoc.Components.Schemas.Add("JsonPatchDocument", new OpenApiSchema - { - Type = "array", - Items = new OpenApiSchema - { - Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "Operation" } - }, - Description = "Array of operations to perform" - }); - - foreach (var path in swaggerDoc.Paths.SelectMany(p => p.Value.Operations) - .Where(p => p.Key == Microsoft.OpenApi.Models.OperationType.Patch)) - { - foreach (var item in path.Value.RequestBody.Content.Where(c => c.Key != "application/json-patch+json")) - path.Value.RequestBody.Content.Remove(item.Key); - - var response = path.Value.RequestBody.Content.SingleOrDefault(c => c.Key == "application/json-patch+json"); - - response.Value.Schema = new OpenApiSchema - { - Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "JsonPatchDocument" } - }; - } - } - } -} diff --git a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs index 44bbb60f4..a5c53cd7f 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/Swagger/SwaggerSetup.cs @@ -62,7 +62,6 @@ namespace IRaCIS.Core.API // 鍦╤eader涓坊鍔爐oken锛屼紶閫掑埌鍚庡彴 options.OperationFilter(); - options.DocumentFilter(); // 娣诲姞鐧诲綍鎸夐挳 options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme() diff --git a/IRaCIS.Core.Application/Service/Common/DictionaryService.cs b/IRaCIS.Core.Application/Service/Common/DictionaryService.cs index cc5bf300d..f41b6d3bc 100644 --- a/IRaCIS.Core.Application/Service/Common/DictionaryService.cs +++ b/IRaCIS.Core.Application/Service/Common/DictionaryService.cs @@ -259,7 +259,7 @@ namespace IRaCIS.Application.Services public async Task>> GetBasicDataSelect(string[] searchArray) { - var searchList = await _dicRepository.Where(t => searchArray.Contains(t.Parent.Code) && t.ParentId != null && t.IsEnable).ProjectTo(_mapper.ConfigurationProvider).ToListAsync(); + var searchList = await _dicRepository.Where(t => searchArray.Contains(t.Parent.Code) && t.ParentId != null && t.IsEnable).ProjectTo(_mapper.ConfigurationProvider,new { isEn_Us = _userInfo.IsEn_Us}).ToListAsync(); return searchList.GroupBy(t => t.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList()); diff --git a/IRaCIS.Core.Application/Service/Common/_MapConfig.cs b/IRaCIS.Core.Application/Service/Common/_MapConfig.cs index bff993ccd..cf8a3a95c 100644 --- a/IRaCIS.Core.Application/Service/Common/_MapConfig.cs +++ b/IRaCIS.Core.Application/Service/Common/_MapConfig.cs @@ -51,7 +51,7 @@ namespace IRaCIS.Core.Application.Service CreateMap() .ForMember(o => o.ParentChildCodeEnum, t => t.MapFrom(u => u.Parent.ChildCodeEnum)) - .ForMember(o => o.Value, t => t.MapFrom(u => u.MappedValue)) + .ForMember(o => o.Value, t => t.MapFrom(u => isEn_Us? u.Value : u.ValueCN )) .ForMember(o => o.ParentCode, t => t.MapFrom(u => u.Parent.Code)); CreateMap() diff --git a/IRaCIS.Core.Application/Service/Document/SystemDocumentService.cs b/IRaCIS.Core.Application/Service/Document/SystemDocumentService.cs index 4d3003ad9..21480bae3 100644 --- a/IRaCIS.Core.Application/Service/Document/SystemDocumentService.cs +++ b/IRaCIS.Core.Application/Service/Document/SystemDocumentService.cs @@ -170,7 +170,7 @@ namespace IRaCIS.Core.Application.Services SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes, Name = sysDoc.Name, Path = sysDoc.Path, - FileType = sysDoc.FileType.MappedValue, + FileType = _userInfo.IsEn_Us? sysDoc.FileType.Value: sysDoc.FileType.ValueCN, UpdateTime = sysDoc.UpdateTime, FullFilePath = sysDoc.Path , diff --git a/IRaCIS.Core.Application/Service/Document/TrialDocumentService.cs b/IRaCIS.Core.Application/Service/Document/TrialDocumentService.cs index d8818be71..eb34d3eb7 100644 --- a/IRaCIS.Core.Application/Service/Document/TrialDocumentService.cs +++ b/IRaCIS.Core.Application/Service/Document/TrialDocumentService.cs @@ -60,7 +60,7 @@ namespace IRaCIS.Core.Application.Services var trialDocumentQueryable = _trialDocumentRepository.AsQueryable(true).Where(t => t.TrialId == queryTrialDocument.TrialId) .WhereIf(!string.IsNullOrEmpty(queryTrialDocument.Name), t => t.Name.Contains(queryTrialDocument.Name)) .WhereIf(queryTrialDocument.FileTypeId != null, t => t.FileTypeId == queryTrialDocument.FileTypeId) - .ProjectTo(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken }); + .ProjectTo(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, isEn_Us=_userInfo.IsEn_Us }); return await trialDocumentQueryable.ToPagedListAsync(queryTrialDocument.PageIndex, queryTrialDocument.PageSize, queryTrialDocument.SortField, queryTrialDocument.Asc); } @@ -187,7 +187,7 @@ namespace IRaCIS.Core.Application.Services Name = needConfirmedUserType.SystemDocument.Name, Path = needConfirmedUserType.SystemDocument.Path, FileTypeId = needConfirmedUserType.SystemDocument.FileTypeId, - FileType = needConfirmedUserType.SystemDocument.FileType.MappedValue, + FileType = _userInfo.IsEn_Us? needConfirmedUserType.SystemDocument.FileType.Value: needConfirmedUserType.SystemDocument.FileType.ValueCN, UpdateTime = needConfirmedUserType.SystemDocument.UpdateTime, FullFilePath = needConfirmedUserType.SystemDocument.Path , @@ -219,7 +219,7 @@ namespace IRaCIS.Core.Application.Services Name = trialDoc.Name, Path = trialDoc.Path, FileTypeId = trialDoc.FileTypeId, - FileType = trialDoc.FileType.MappedValue, + FileType = _userInfo.IsEn_Us ? trialDoc.FileType.Value: trialDoc.FileType.ValueCN, UpdateTime = trialDoc.UpdateTime, SignViewMinimumMinutes = trialDoc.SignViewMinimumMinutes, @@ -333,7 +333,7 @@ namespace IRaCIS.Core.Application.Services Name = trialDocumentNeedConfirmedUserType.TrialDocument.Name, Path = trialDocumentNeedConfirmedUserType.TrialDocument.Path, FileTypeId = trialDocumentNeedConfirmedUserType.TrialDocument.FileTypeId, - FileType = trialDocumentNeedConfirmedUserType.TrialDocument.FileType.MappedValue, + FileType = _userInfo.IsEn_Us ? trialDocumentNeedConfirmedUserType.TrialDocument.FileType.Value : trialDocumentNeedConfirmedUserType.TrialDocument.FileType.ValueCN, UpdateTime = trialDocumentNeedConfirmedUserType.TrialDocument.UpdateTime, @@ -367,7 +367,7 @@ namespace IRaCIS.Core.Application.Services SignViewMinimumMinutes = needConfirmEdUserType.SystemDocument.SignViewMinimumMinutes, Name = needConfirmEdUserType.SystemDocument.Name, Path = needConfirmEdUserType.SystemDocument.Path, - FileType = needConfirmEdUserType.SystemDocument.FileType.MappedValue, + FileType = _userInfo.IsEn_Us ? needConfirmEdUserType.SystemDocument.FileType.Value : needConfirmEdUserType.SystemDocument.FileType.ValueCN, FileTypeId = needConfirmEdUserType.SystemDocument.FileTypeId, UpdateTime = needConfirmEdUserType.SystemDocument.UpdateTime, diff --git a/IRaCIS.Core.Application/Service/Document/_MapConfig.cs b/IRaCIS.Core.Application/Service/Document/_MapConfig.cs index 3cec4fc79..1116a7bf1 100644 --- a/IRaCIS.Core.Application/Service/Document/_MapConfig.cs +++ b/IRaCIS.Core.Application/Service/Document/_MapConfig.cs @@ -14,12 +14,13 @@ namespace IRaCIS.Core.Application.Service var userId = Guid.Empty; var token = string.Empty; + var isEn_Us = false; CreateMap() .ForMember(d => d.FileType, u => u.MapFrom(s => s.FileType.Value)) .ForMember(d => d.FullFilePath, u => u.MapFrom(s => s.Path)); CreateMap() - .ForMember(d => d.FileType, u => u.MapFrom(s => s.FileType.MappedValue)) + .ForMember(d => d.FileType, u => u.MapFrom(s => isEn_Us ? s.FileType.Value : s.FileType.ValueCN )) .ForMember(d => d.IsSomeUserSigned, u => u.MapFrom(s => s.TrialDocConfirmedUserList.Any(t=>t.ConfirmTime!=null))) .ForMember(d => d.FullFilePath, u => u.MapFrom(s => s.Path )); diff --git a/IRaCIS.Core.Application/Service/TrialSiteUser/TrialService.cs b/IRaCIS.Core.Application/Service/TrialSiteUser/TrialService.cs index 76f6cdacc..69f46a855 100644 --- a/IRaCIS.Core.Application/Service/TrialSiteUser/TrialService.cs +++ b/IRaCIS.Core.Application/Service/TrialSiteUser/TrialService.cs @@ -92,7 +92,7 @@ namespace IRaCIS.Application.Services .WhereIf(multiCriteriaSelectCount > 0, t => t.TrialDicList.Count(t => t.KeyName == StaticData.Criterion) == multiCriteriaSelectCount) .WhereIf(multiReviewTypeSelectCount > 0, t => t.TrialDicList.Count(t => t.KeyName == StaticData.ReviewType) == multiReviewTypeSelectCount) .WhereIf(_userInfo.UserTypeEnumInt != (int)UserTypeEnum.SuperAdmin, t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id && t.IsDeleted == false) && t.IsDeleted == false) - .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id }); + .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id , isEn_Us= _userInfo.IsEn_Us }); return await query.ToPagedListAsync(searchParam.PageIndex, searchParam.PageSize, string.IsNullOrWhiteSpace(searchParam.SortField) ? "CreateTime" : searchParam.SortField, searchParam.Asc); @@ -118,7 +118,7 @@ namespace IRaCIS.Application.Services [HttpGet("{projectId:guid}")] public async Task GetTrialInfoAndLockState(Guid projectId) { - return (await _trialRepository.Where(o => o.Id == projectId).IgnoreQueryFilters().ProjectTo(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException(); + return (await _trialRepository.Where(o => o.Id == projectId).IgnoreQueryFilters().ProjectTo(_mapper.ConfigurationProvider, new {isEn_Us = _userInfo.IsEn_Us }).FirstOrDefaultAsync()).IfNullThrowException(); } @@ -609,7 +609,7 @@ namespace IRaCIS.Application.Services .WhereIf(param.Status == 8, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.InviteIntoGroup)) .WhereIf(param.Status == 10, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.DoctorReading)) .WhereIf(param.Status == 14, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.Finished)) - .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id }); + .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id, isEn_Us = _userInfo.IsEn_Us }); return await query.ToPagedListAsync(param.PageIndex, param.PageSize, string.IsNullOrWhiteSpace(param.SortField) ? "CreateTime" : param.SortField, param.Asc); @@ -644,7 +644,7 @@ namespace IRaCIS.Application.Services .WhereIf(!string.IsNullOrEmpty(searchModel.Code), o => o.TrialCode.Contains(searchModel.Code)) .WhereIf(!string.IsNullOrWhiteSpace(searchModel.Indication), o => o.Indication.Contains(searchModel.Indication)) .WhereIf(_userInfo.UserTypeEnumInt != (int)UserTypeEnum.SuperAdmin, t => t.TrialUserList.Any(t => t.UserId == _userInfo.Id)) - .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id }); + .ProjectTo(_mapper.ConfigurationProvider, new { userTypeEnumInt = _userInfo.UserTypeEnumInt, userId = _userInfo.Id ,isEn_Us = _userInfo.IsEn_Us }); return await query.ToPagedListAsync(searchModel.PageIndex, searchModel.PageSize, string.IsNullOrWhiteSpace(searchModel.SortField) ? "CreateTime" : searchModel.SortField, searchModel.Asc); diff --git a/IRaCIS.Core.Application/Service/TrialSiteUser/_MapConfig.cs b/IRaCIS.Core.Application/Service/TrialSiteUser/_MapConfig.cs index f5861e37e..200b6f4c3 100644 --- a/IRaCIS.Core.Application/Service/TrialSiteUser/_MapConfig.cs +++ b/IRaCIS.Core.Application/Service/TrialSiteUser/_MapConfig.cs @@ -65,16 +65,17 @@ namespace IRaCIS.Core.Application.Service var userId = Guid.Empty; var userTypeEnumInt = 0; + var isEn_Us = false; CreateMap() .ForMember(x=>x.CriterionList,y=>y.MapFrom(z=>z.ReadingQuestionCriterionTrialList.Where(n=>n.IsConfirm).Select(m=>m.CriterionName))) .ForMember(d => d.DictionaryList, u => u.MapFrom(s => s.TrialDicList.Select(t => t.Dictionary).OrderBy(t => t.ShowOrder))) //.ForMember(d => d.Code, u => u.MapFrom(s => s.TrialCode)) .ForMember(d => d.Sponsor, u => u.MapFrom(s => s.Sponsor.SponsorName)) - .ForMember(d => d.Phase, u => u.MapFrom(s => s.Phase.MappedValue)) + .ForMember(d => d.Phase, u => u.MapFrom(s => isEn_Us? s.Phase.Value: s.Phase.ValueCN)) //.ForMember(d => d.DeclarationType, u => u.MapFrom(s => s.DeclarationType.MappedValue)) - .ForMember(d => d.IndicationType, u => u.MapFrom(s => s.IndicationType.MappedValue)) + .ForMember(d => d.IndicationType, u => u.MapFrom(s => isEn_Us ? s.IndicationType.Value:s.IndicationType.ValueCN)) .ForMember(d => d.CRO, u => u.MapFrom(s => s.CRO.CROName)) - .ForMember(d => d.ReviewMode, u => u.MapFrom(s => s.ReviewMode.MappedValue)) + .ForMember(d => d.ReviewMode, u => u.MapFrom(s => isEn_Us ? s.ReviewMode.Value:s.ReviewMode.ValueCN)) //.ForMember(d => d.ReviewType, u => u.MapFrom(s => s.ReviewType.Value)) .ForMember(d => d.IsLocked, u => u.MapFrom(s => s.WorkloadList.Any(u => u.DataFrom == (int)WorkLoadFromStatus.FinalConfirm))) //.ForMember(d => d.SiteCount, u => u.MapFrom(s => userTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator ? s.TrialSiteUserList.Count(k => k.UserId == userId) : s.TrialSiteList.Count())) @@ -111,7 +112,6 @@ namespace IRaCIS.Core.Application.Service .ForMember(d => d.HospitalName, u => u.MapFrom(s => s.Hospital.HospitalName)); //trial site 閫夋嫨鍒楄〃 subjectVisit pannel 妯″紡娣诲姞鐨勬椂鍊 - var isEn_Us = false; CreateMap() .ForMember(d => d.IsSelect, u => u.MapFrom(s => s.TrialSiteList.Any(k => k.TrialId == trialId))) diff --git a/IRaCIS.Core.Domain/Common/Dictionary.cs b/IRaCIS.Core.Domain/Common/Dictionary.cs index 6b518574a..f178c6154 100644 --- a/IRaCIS.Core.Domain/Common/Dictionary.cs +++ b/IRaCIS.Core.Domain/Common/Dictionary.cs @@ -59,9 +59,6 @@ namespace IRaCIS.Core.Domain.Models public List ChildList { get; set; } = new List(); - [NotMapped] - public string MappedValue { get; set; } - [Projectable] public string TranslateValue( string value, string valueCN,bool isCN) => isCN?valueCN:value; diff --git a/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs b/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs index b98df40d8..068df0e6d 100644 --- a/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs +++ b/IRaCIS.Core.Infra.EFCore/Context/IRaCISDBContext.cs @@ -123,14 +123,14 @@ namespace IRaCIS.Core.Infra.EFCore modelBuilder.Entity().HasMany(t => t.ChildList).WithOne(t => t.Parent); modelBuilder.Entity().HasMany(t => t.EarlierSubjectUserList).WithOne(t => t.OrignalSubjectUser); - if (_userInfo.IsEn_Us) - { - modelBuilder.Entity().Property(t => t.MappedValue).HasColumnName(nameof(Domain.Models.Dictionary.Value)); - } - else - { - modelBuilder.Entity().Property(t => t.MappedValue).HasColumnName(nameof(Domain.Models.Dictionary.ValueCN)); - } + //if (_userInfo.IsEn_Us) + //{ + // modelBuilder.Entity().Property(t => t.MappedValue).HasColumnName(nameof(Domain.Models.Dictionary.Value)); + //} + //else + //{ + // modelBuilder.Entity().Property(t => t.MappedValue).HasColumnName(nameof(Domain.Models.Dictionary.ValueCN)); + //} //閬嶅巻瀹炰綋妯″瀷鎵嬪姩閰嶇疆 diff --git a/IRaCIS.Core.Infrastructure/Extention/RequestExtension.cs b/IRaCIS.Core.Infrastructure/Extention/RequestExtension.cs deleted file mode 100644 index 1aecdeb67..000000000 --- a/IRaCIS.Core.Infrastructure/Extention/RequestExtension.cs +++ /dev/null @@ -1,158 +0,0 @@ -锘縰sing Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace IRaCIS.Core.Infrastructure.Extention -{ - public static class HttpContextExtension - { - - public static T GetService(this HttpContext context) where T : class - { - return context.RequestServices.GetService(typeof(T)) as T; - } - - - public static string GetUserIp(this HttpContext context) - { - string realIP = null; - string forwarded = null; - string remoteIpAddress = context.Connection.RemoteIpAddress.ToString(); - if (context.Request.Headers.ContainsKey("X-Real-IP")) - { - realIP = context.Request.Headers["X-Real-IP"].ToString(); - if (realIP != remoteIpAddress) - { - remoteIpAddress = realIP; - } - } - if (context.Request.Headers.ContainsKey("X-Forwarded-For")) - { - forwarded = context.Request.Headers["X-Forwarded-For"].ToString(); - if (forwarded != remoteIpAddress) - { - remoteIpAddress = forwarded; - } - } - return remoteIpAddress; - } - - - - /// - /// 鑾峰彇Request鍊 - /// - /// - /// - /// - public static string Request(this HttpContext context, string parameter) - { - try - { - if (context == null) - return null; - if (context.Request.Method == "POST") - return context.Request.Form[parameter].ToString(); - else - return context.Request.Query[parameter].ToString(); - } - catch (System.Exception ex) - { - Console.Write(ex.Message + ex.InnerException); - return context.RequestString(parameter); - } - } - - public static T Request(this HttpContext context, string parameter) where T : class - { - return context.RequestString(parameter)?.DeserializeObject(); - } - public static string RequestString(this HttpContext context, string parameter) - { - string requestParam = context.GetRequestParameters(); - if (string.IsNullOrEmpty(requestParam)) return null; - Dictionary keyValues = requestParam.DeserializeObject>(); - if (keyValues == null || keyValues.Count == 0) return null; - if (keyValues.TryGetValue(parameter, out object value)) - { - if (value == null) return null; - if (value.GetType() == typeof(string)) - { - return value?.ToString(); - } - return value.Serialize(); - } - return null; - } - /// - /// 鏄惁涓篴jax璇锋眰 - /// - /// - /// - public static bool IsAjaxRequest(this HttpContext context) - { - return context.Request("X-Requested-With") == "XMLHttpRequest" - || (context.Request.Headers != null - && context.Request.Headers["X-Requested-With"] == "XMLHttpRequest"); - } - - public static UserAgent GetAgentType(this HttpContext context) - { - string agent = context.Request.Headers["User-Agent"].ToString().ToLower(); - - if (agent.Contains("ios") || agent.Contains("ipod") || agent.Contains("ipad")) - { - return UserAgent.IOS; - } - if (agent.Contains("windows")) - { - return UserAgent.Windows; - } - return UserAgent.Android; - - } - - /// - /// 鑾峰彇璇锋眰鐨勫弬鏁 - /// net core 2.0宸插鍔犲洖璇绘柟娉 context.Request.EnableRewind(); - /// - /// - /// - /// - - public static string GetRequestParameters(this HttpContext context) - { - if (context.Request.Body == null || !context.Request.Body.CanRead || !context.Request.Body.CanSeek) - return null; - if (context.Request.Body.Length == 0) - return null; - if (context.Request.Body.Position > 0) - context.Request.Body.Position = 0; - - string prarameters = null; - var bodyStream = context.Request.Body; - - using (var buffer = new MemoryStream()) - { - bodyStream.CopyToAsync(buffer); - buffer.Position = 0L; - bodyStream.Position = 0L; - using (var reader = new StreamReader(buffer, Encoding.UTF8)) - { - buffer.Seek(0, SeekOrigin.Begin); - prarameters = reader.ReadToEnd(); - } - } - return prarameters; - } - } - public enum UserAgent - { - IOS = 0, - Android = 1, - Windows = 2, - Linux - } -} diff --git a/IRaCIS.Core.Infrastructure/Helper/IPHelper.cs b/IRaCIS.Core.Infrastructure/Helper/IPHelper.cs deleted file mode 100644 index c8827eab0..000000000 --- a/IRaCIS.Core.Infrastructure/Helper/IPHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -锘縰sing System.Linq; -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Http; - -namespace IRaCIS.Core.Infrastructure -{ - public class IPHelper - { - /// - /// 鏄惁涓篿p - /// - /// - /// - public static bool IsIP(string ip) - { - return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); - } - - public static string GetIP(HttpRequest request) - { - if (request == null) - { - return ""; - } - - string ip = request.Headers["X-Real-IP"].FirstOrDefault(); - if (string.IsNullOrEmpty(ip)) - { - ip = request.Headers["X-Forwarded-For"].FirstOrDefault(); - } - if (string.IsNullOrEmpty(ip)) - { - ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString(); - } - if (string.IsNullOrEmpty(ip) || !IsIP(ip)) - { - ip = "127.0.0.1"; - } - - return ip; - } - } -} \ No newline at end of file diff --git a/IRaCIS.Core.Infrastructure/IRaCIS.Core.Infrastructure.csproj b/IRaCIS.Core.Infrastructure/IRaCIS.Core.Infrastructure.csproj index 152693792..9976f5251 100644 --- a/IRaCIS.Core.Infrastructure/IRaCIS.Core.Infrastructure.csproj +++ b/IRaCIS.Core.Infrastructure/IRaCIS.Core.Infrastructure.csproj @@ -9,13 +9,12 @@ - - - - - - - + + + + + + From 27e9cadf919bd7606b625af7ad1c37ad81979fe1 Mon Sep 17 00:00:00 2001 From: hang <872297557@qq.com> Date: Thu, 12 Oct 2023 13:26:30 +0800 Subject: [PATCH 13/13] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=8C=85=EF=BC=8C=E6=B8=85=E7=90=86=E6=97=A0?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IRaCIS.Core.API.sln | 30 ----- .../Controllers/ExtraController.cs | 3 - IRaCIS.Core.API/IRaCIS.Core.API.csproj | 29 ++--- IRaCIS.Core.API/IRaCIS.Core.API.xml | 108 ------------------ IRaCIS.Core.API/Startup.cs | 4 +- .../_ServiceExtensions/AutofacModuleSetup.cs | 20 +--- .../MiniProfilerConfigure.cs | 81 ------------- .../IRaCIS.Core.Application.csproj | 43 ++++--- .../ImageAndDoc/DicomArchiveService.cs | 6 +- .../Reading/Dto/ReadingMedicalReviewDto.cs | 8 +- .../Allocation/TaskMedicalReview.cs | 10 +- IRaCIS.Core.Domain/IRaCIS.Core.Domain.csproj | 6 +- .../ReadingMedicalReviewDialog.cs | 8 +- IRaCIS.Core.Domain/Visit/SubjectVisit.cs | 2 +- .../ClinicalFromConfigration.cs | 27 ----- .../EntityConfigration/DoctorConfigration.cs | 20 +--- .../IRaCIS.Core.Infra.EFCore.csproj | 10 +- IRaCIS.Core.Test/IRaCIS.Core.Test.csproj | 1 - 18 files changed, 63 insertions(+), 353 deletions(-) delete mode 100644 IRaCIS.Core.API/_ServiceExtensions/MiniProfilerConfigure.cs delete mode 100644 IRaCIS.Core.Infra.EFCore/EntityConfigration/ClinicalFromConfigration.cs diff --git a/IRaCIS.Core.API.sln b/IRaCIS.Core.API.sln index cb23da7dd..d5afa55fa 100644 --- a/IRaCIS.Core.API.sln +++ b/IRaCIS.Core.API.sln @@ -11,25 +11,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Application", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Domain.Share", "IRaCIS.Core.Domain.Share\IRaCIS.Core.Domain.Share.csproj", "{7CBC76F5-3817-46B7-8D9D-79253A89B578}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.JWT.RS256", "ZhiZhunAuthenticationCenter\IRaCIS.JWT.RS256.csproj", "{3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Test", "IRaCIS.Core.Test\IRaCIS.Core.Test.csproj", "{3292B2B4-6E8A-43AA-84C0-AB4A391E8A2A}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Infra.EFCore", "IRaCIS.Core.Infra.EFCore\IRaCIS.Core.Infra.EFCore.csproj", "{6D8115E5-84D6-424B-8F8D-0C2D40347A8C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.Infrastructure", "IRaCIS.Core.Infrastructure\IRaCIS.Core.Infrastructure.csproj", "{07EED0F8-08E6-46F3-ACBE-17BC1391BD4C}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IRaCIS.AuthenticationCenter", "IRaCIS.AuthenticationCenter", "{481329D6-B8A0-491F-A398-1DF66A0FBB62}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.IdentityServer4", "IRaCIS.Core.IdentityServer4\IRaCIS.Core.IdentityServer4.csproj", "{C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IRaCIS.Core.IdentityServer4.MVC", "IRaCIS.Core.IdentityServer4.MVC\IRaCIS.Core.IdentityServer4.MVC.csproj", "{F621ADD6-94E8-4A4B-998E-25B8EF15D39C}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F852ABFB-88AC-48BE-B876-2228BE2373D6}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - EndProjectSection -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -52,10 +39,6 @@ Global {7CBC76F5-3817-46B7-8D9D-79253A89B578}.Debug|Any CPU.Build.0 = Debug|Any CPU {7CBC76F5-3817-46B7-8D9D-79253A89B578}.Release|Any CPU.ActiveCfg = Release|Any CPU {7CBC76F5-3817-46B7-8D9D-79253A89B578}.Release|Any CPU.Build.0 = Release|Any CPU - {3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39}.Release|Any CPU.Build.0 = Release|Any CPU {3292B2B4-6E8A-43AA-84C0-AB4A391E8A2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3292B2B4-6E8A-43AA-84C0-AB4A391E8A2A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3292B2B4-6E8A-43AA-84C0-AB4A391E8A2A}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -68,23 +51,10 @@ 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 - {C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674}.Release|Any CPU.Build.0 = Release|Any CPU - {F621ADD6-94E8-4A4B-998E-25B8EF15D39C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F621ADD6-94E8-4A4B-998E-25B8EF15D39C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F621ADD6-94E8-4A4B-998E-25B8EF15D39C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F621ADD6-94E8-4A4B-998E-25B8EF15D39C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {3EF210EE-D5D1-4C93-A8FA-E0DB1852BD39} = {481329D6-B8A0-491F-A398-1DF66A0FBB62} - {C3DD48CF-B8B3-40F6-9BDB-B7C7F0851674} = {481329D6-B8A0-491F-A398-1DF66A0FBB62} - {F621ADD6-94E8-4A4B-998E-25B8EF15D39C} = {481329D6-B8A0-491F-A398-1DF66A0FBB62} - EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BCC2EB19-3914-489B-B1D7-B7303E0218A3} EndGlobalSection diff --git a/IRaCIS.Core.API/Controllers/ExtraController.cs b/IRaCIS.Core.API/Controllers/ExtraController.cs index 15ec0a88b..ca49c5e0b 100644 --- a/IRaCIS.Core.API/Controllers/ExtraController.cs +++ b/IRaCIS.Core.API/Controllers/ExtraController.cs @@ -1,9 +1,6 @@ 锘縰sing System; using System.Net.Http; using EasyCaching.Core; -using gRPC.ZHiZHUN.AuthServer.protos; -using Grpc.Net.Client; -using Grpc.Net.Client.Configuration; using IRaCIS.Application.Interfaces; using IRaCIS.Application.Contracts; using IRaCIS.Core.Application.Auth; diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.csproj b/IRaCIS.Core.API/IRaCIS.Core.API.csproj index 248060a76..787cd194b 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.csproj +++ b/IRaCIS.Core.API/IRaCIS.Core.API.csproj @@ -66,34 +66,27 @@ - - + + - + - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + true + - - - - - - + + + + - + diff --git a/IRaCIS.Core.API/IRaCIS.Core.API.xml b/IRaCIS.Core.API/IRaCIS.Core.API.xml index 50413058f..d07789653 100644 --- a/IRaCIS.Core.API/IRaCIS.Core.API.xml +++ b/IRaCIS.Core.API/IRaCIS.Core.API.xml @@ -490,113 +490,5 @@ - - Holder for reflection information generated from Protos/GrpcToken.proto - - - File descriptor for Protos/GrpcToken.proto - - - - 鏂板鐢ㄦ埛鏃堕渶瑕佷紶閫掓暟鎹秷鎭紝 鍙悊瑙d负涓涓被 - - - - Field number for the "id" field. - - - Field number for the "userName" field. - - - Field number for the "realName" field. - - - Field number for the "reviewerCode" field. - - - Field number for the "userTypeEnumInt" field. - - - Field number for the "userTypeShortName" field. - - - Field number for the "isAdmin" field. - - - - 鏂板鏃惰繑鍥炵殑娑堟伅鏍煎紡 - - - - Field number for the "code" field. - - - Field number for the "token" field. - - - - service 鐢ㄦ爣璇嗗畾涔夋湇鍔$殑锛岄噷闈㈠啓瀵瑰簲鐨勬柟娉 - - - - Service descriptor - - - Client for TokenGrpcService - - - Creates a new client for TokenGrpcService - The channel to use to make remote calls. - - - Creates a new client for TokenGrpcService that uses a custom CallInvoker. - The callInvoker to use to make remote calls. - - - Protected parameterless constructor to allow creation of test doubles. - - - Protected constructor to allow creation of configured clients. - The client configuration. - - - - 鑾峰彇token - - The request to send to the server. - The initial metadata to send with the call. This parameter is optional. - An optional deadline for the call. The call will be cancelled if deadline is hit. - An optional token for canceling the call. - The response received from the server. - - - - 鑾峰彇token - - The request to send to the server. - The options for the call. - The response received from the server. - - - - 鑾峰彇token - - The request to send to the server. - The initial metadata to send with the call. This parameter is optional. - An optional deadline for the call. The call will be cancelled if deadline is hit. - An optional token for canceling the call. - The call object. - - - - 鑾峰彇token - - The request to send to the server. - The options for the call. - The call object. - - - Creates a new instance of client from given ClientBaseConfiguration. - diff --git a/IRaCIS.Core.API/Startup.cs b/IRaCIS.Core.API/Startup.cs index 83255d47a..21772cf98 100644 --- a/IRaCIS.Core.API/Startup.cs +++ b/IRaCIS.Core.API/Startup.cs @@ -108,8 +108,10 @@ namespace IRaCIS.Core.API services.AddSwaggerSetup(); //JWT Token 验证 services.AddJWTAuthSetup(_configuration); + + // MediatR 进程内消息 事件解耦 从程序集中 注册命令和handler对应关系 - services.AddMediatR(typeof(ConsistencyVerificationHandler).Assembly); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); // EasyCaching 缓存 services.AddEasyCachingSetup(_configuration); diff --git a/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs b/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs index fd321596e..3435a738a 100644 --- a/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs +++ b/IRaCIS.Core.API/_ServiceExtensions/AutofacModuleSetup.cs @@ -31,10 +31,6 @@ namespace IRaCIS.Core.API containerBuilder.RegisterType().As().InstancePerLifetimeScope(); - //containerBuilder.RegisterType().As().InstancePerLifetimeScope(); - - //containerBuilder.RegisterGeneric(typeof(EFUnitOfWork<>)) - // .As(typeof(IEFUnitOfWork<>)).InstancePerLifetimeScope();//娉ㄥ唽浠撳偍 #endregion @@ -50,8 +46,7 @@ namespace IRaCIS.Core.API #endregion - //containerBuilder.RegisterType().As().PropertiesAutowired().InstancePerLifetimeScope(); - //containerBuilder.RegisterType().As().InstancePerLifetimeScope(); + @@ -59,22 +54,13 @@ namespace IRaCIS.Core.API containerBuilder.RegisterAssemblyTypes(application).Where(t => t.FullName.Contains("Service")) .PropertiesAutowired().AsImplementedInterfaces().EnableClassInterceptors(); - //Assembly infrastructure = Assembly.Load("IRaCIS.Core.Infra.EFCore"); - //containerBuilder.RegisterAssemblyTypes(infrastructure).AsImplementedInterfaces(); + containerBuilder.RegisterType().As().SingleInstance(); containerBuilder.RegisterType().As().InstancePerLifetimeScope(); - //containerBuilder.RegisterType().InstancePerLifetimeScope(); - //Autofac 娉ㄥ唽鎷︽埅鍣 闇瑕佹敞鎰忕殑鏄敓鎴恆pi涓婃湇鍔′笂鐨勫姩鎬佷唬鐞咥OP澶辨晥 闂存帴鎺夌敤涓嶅奖鍝 - //containerBuilder.RegisterType(); - //containerBuilder.RegisterType(); - //containerBuilder.RegisterType(); - //containerBuilder.RegisterType().As().SingleInstance(); - - - //娉ㄥ唽hangfire浠诲姟 渚濊禆娉ㄥ叆 + //娉ㄥ唽hangfire浠诲姟 渚濊禆娉ㄥ叆 containerBuilder.RegisterType().As().InstancePerDependency(); diff --git a/IRaCIS.Core.API/_ServiceExtensions/MiniProfilerConfigure.cs b/IRaCIS.Core.API/_ServiceExtensions/MiniProfilerConfigure.cs deleted file mode 100644 index f08e27aae..000000000 --- a/IRaCIS.Core.API/_ServiceExtensions/MiniProfilerConfigure.cs +++ /dev/null @@ -1,81 +0,0 @@ -锘//using System; -//using Microsoft.Extensions.DependencyInjection; -//using StackExchange.Profiling.Storage; - -//namespace IRaCIS.Core.API -//{ -// public class MiniProfilerConfigure -// { -// public static void ConfigureMiniProfiler(IServiceCollection services) -// { - -// services.AddMiniProfiler(options => -// { -// // All of this is optional. You can simply call .AddMiniProfiler() for all defaults - -// // (Optional) Path to use for profiler URLs, default is /mini-profiler-resources -// options.RouteBasePath = "/profiler"; - -// //// (Optional) Control storage -// //// (default is 30 minutes in MemoryCacheStorage) -// (options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(10); - -// //// (Optional) Control which SQL formatter to use, InlineFormatter is the default -// //options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(); - -// //// (Optional) To control authorization, you can use the Func options: -// //// (default is everyone can access profilers) -// //options.ResultsAuthorize = request => MyGetUserFunction(request).CanSeeMiniProfiler; -// //options.ResultsListAuthorize = request => MyGetUserFunction(request).CanSeeMiniProfiler; -// //// Or, there are async versions available: -// //options.ResultsAuthorizeAsync = async request => (await MyGetUserFunctionAsync(request)).CanSeeMiniProfiler; -// //options.ResultsAuthorizeListAsync = async request => (await MyGetUserFunctionAsync(request)).CanSeeMiniProfilerLists; - -// //// (Optional) To control which requests are profiled, use the Func option: -// //// (default is everything should be profiled) -// //options.ShouldProfile = request => MyShouldThisBeProfiledFunction(request); - -// //// (Optional) Profiles are stored under a user ID, function to get it: -// //// (default is null, since above methods don't use it by default) -// //options.UserIdProvider = request => MyGetUserIdFunction(request); - -// //// (Optional) Swap out the entire profiler provider, if you want -// //// (default handles async and works fine for almost all applications) -// //options.ProfilerProvider = new MyProfilerProvider(); - -// //// (Optional) You can disable "Connection Open()", "Connection Close()" (and async variant) tracking. -// //// (defaults to true, and connection opening/closing is tracked) -// //options.TrackConnectionOpenClose = true; - -// //// (Optional) Use something other than the "light" color scheme. -// //// (defaults to "light") -// //options.ColorScheme = StackExchange.Profiling.ColorScheme.Auto; - -// //// The below are newer options, available in .NET Core 3.0 and above: - -// //// (Optional) You can disable MVC filter profiling -// //// (defaults to true, and filters are profiled) -// //options.EnableMvcFilterProfiling = true; -// //// ...or only save filters that take over a certain millisecond duration (including their children) -// //// (defaults to null, and all filters are profiled) -// //// options.MvcFilterMinimumSaveMs = 1.0m; - -// //// (Optional) You can disable MVC view profiling -// //// (defaults to true, and views are profiled) -// //options.EnableMvcViewProfiling = true; -// //// ...or only save views that take over a certain millisecond duration (including their children) -// //// (defaults to null, and all views are profiled) -// //// options.MvcViewMinimumSaveMs = 1.0m; - -// //// (Optional) listen to any errors that occur within MiniProfiler itself -// //// options.OnInternalError = e => MyExceptionLogger(e); - -// //// (Optional - not recommended) You can enable a heavy debug mode with stacks and tooltips when using memory storage -// //// It has a lot of overhead vs. normal profiling and should only be used with that in mind -// //// (defaults to false, debug/heavy mode is off) -// ////options.EnableDebugMode = true; -// }); -// //.AddEntityFramework(); -// } -// } -//} \ No newline at end of file diff --git a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj index 7a5d93102..aa9a82bba 100644 --- a/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj +++ b/IRaCIS.Core.Application/IRaCIS.Core.Application.csproj @@ -64,6 +64,9 @@ + + + @@ -74,37 +77,31 @@ + + true + + + true - - - - - + true - - true - - - - - - true - - - - + + + + + + true - - - - - - + + + + + diff --git a/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs b/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs index 9b990c306..9d9bd7cc6 100644 --- a/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs +++ b/IRaCIS.Core.Application/Service/ImageAndDoc/DicomArchiveService.cs @@ -1,6 +1,4 @@ -锘縰sing Dicom; -using Dicom.Imaging.Codec; -using EasyCaching.Core; +锘縰sing EasyCaching.Core; using IRaCIS.Core.Application.Contracts.Dicom; using IRaCIS.Core.Domain.Share; using System.Text; @@ -9,6 +7,8 @@ using IRaCIS.Core.Application.Helper; using Microsoft.AspNetCore.Hosting; using IRaCIS.Core.Infrastructure; using Medallion.Threading; +using FellowOakDicom; +using FellowOakDicom.Imaging.Codec; namespace IRaCIS.Core.Application.Services { diff --git a/IRaCIS.Core.Application/Service/Reading/Dto/ReadingMedicalReviewDto.cs b/IRaCIS.Core.Application/Service/Reading/Dto/ReadingMedicalReviewDto.cs index 95784d2ff..9cb77bc89 100644 --- a/IRaCIS.Core.Application/Service/Reading/Dto/ReadingMedicalReviewDto.cs +++ b/IRaCIS.Core.Application/Service/Reading/Dto/ReadingMedicalReviewDto.cs @@ -262,7 +262,7 @@ namespace IRaCIS.Core.Application.Service.Reading.Dto public string ImagePath { get; set; } = string.Empty; - public List FileList { get; set; } = new List(); + public List FileList { get; set; } = new List(); } @@ -310,7 +310,7 @@ namespace IRaCIS.Core.Application.Service.Reading.Dto - public List FileList { get; set; } = new List(); + public List FileList { get; set; } = new List(); @@ -451,7 +451,7 @@ namespace IRaCIS.Core.Application.Service.Reading.Dto public Guid TaskMedicalReviewId { get; set; } - public List FileList { get; set; } = new List(); + public List FileList { get; set; } = new List(); /// @@ -498,7 +498,7 @@ namespace IRaCIS.Core.Application.Service.Reading.Dto public string Questioning { get; set; } = string.Empty; - public List FileList { get; set; } = new List(); + public List FileList { get; set; } = new List(); /// /// 瀹℃牳寤鸿 diff --git a/IRaCIS.Core.Domain/Allocation/TaskMedicalReview.cs b/IRaCIS.Core.Domain/Allocation/TaskMedicalReview.cs index 7c77ea807..901e4c984 100644 --- a/IRaCIS.Core.Domain/Allocation/TaskMedicalReview.cs +++ b/IRaCIS.Core.Domain/Allocation/TaskMedicalReview.cs @@ -178,7 +178,7 @@ namespace IRaCIS.Core.Domain.Models /// 鏂囦欢 /// [NotMapped] - public List FileList + public List FileList { get { @@ -186,13 +186,13 @@ namespace IRaCIS.Core.Domain.Models try { - var result= JsonConvert.DeserializeObject>(this.ImagePath); - return result==null?new List() : result; + var result= JsonConvert.DeserializeObject>(this.ImagePath); + return result==null?new List() : result; } catch (Exception) { - return new List(); + return new List(); } } @@ -210,7 +210,7 @@ namespace IRaCIS.Core.Domain.Models #region 鏂囦欢瀵硅薄 - public class ImageInfo + public class OSSImageInfo { public string FileName { get; set; } diff --git a/IRaCIS.Core.Domain/IRaCIS.Core.Domain.csproj b/IRaCIS.Core.Domain/IRaCIS.Core.Domain.csproj index 5cbdf014a..f9c01aaf3 100644 --- a/IRaCIS.Core.Domain/IRaCIS.Core.Domain.csproj +++ b/IRaCIS.Core.Domain/IRaCIS.Core.Domain.csproj @@ -9,11 +9,7 @@ - - - - - + diff --git a/IRaCIS.Core.Domain/Reading/MedicalAudit/ReadingMedicalReviewDialog.cs b/IRaCIS.Core.Domain/Reading/MedicalAudit/ReadingMedicalReviewDialog.cs index c3f46259f..e00db79c7 100644 --- a/IRaCIS.Core.Domain/Reading/MedicalAudit/ReadingMedicalReviewDialog.cs +++ b/IRaCIS.Core.Domain/Reading/MedicalAudit/ReadingMedicalReviewDialog.cs @@ -113,7 +113,7 @@ namespace IRaCIS.Core.Domain.Models /// 鏂囦欢 /// [NotMapped] - public List FileList + public List FileList { get { @@ -121,13 +121,13 @@ namespace IRaCIS.Core.Domain.Models try { - var result = JsonConvert.DeserializeObject>(this.ImagePath); - return result == null ? new List() : result; + var result = JsonConvert.DeserializeObject>(this.ImagePath); + return result == null ? new List() : result; } catch (Exception) { - return new List(); + return new List(); } } diff --git a/IRaCIS.Core.Domain/Visit/SubjectVisit.cs b/IRaCIS.Core.Domain/Visit/SubjectVisit.cs index cf80c30b2..7b44926ef 100644 --- a/IRaCIS.Core.Domain/Visit/SubjectVisit.cs +++ b/IRaCIS.Core.Domain/Visit/SubjectVisit.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using IRaCIS.Core.Domain.Share; -using Microsoft.EntityFrameworkCore.Metadata.Internal; + namespace IRaCIS.Core.Domain.Models { diff --git a/IRaCIS.Core.Infra.EFCore/EntityConfigration/ClinicalFromConfigration.cs b/IRaCIS.Core.Infra.EFCore/EntityConfigration/ClinicalFromConfigration.cs deleted file mode 100644 index 98b711e7a..000000000 --- a/IRaCIS.Core.Infra.EFCore/EntityConfigration/ClinicalFromConfigration.cs +++ /dev/null @@ -1,27 +0,0 @@ -锘縰sing IRaCIS.Core.Domain.Models; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace IRaCIS.Core.Infra.EFCore.EntityConfigration -{ - //public class ClinicalFromConfigration : IEntityTypeConfiguration - //{ - - - // public void Configure(EntityTypeBuilder builder) - // { - // builder - // .HasOne(s => s.ReadingClinicalData) - // .WithMany(c => c.ClinicalFormList) - // .HasForeignKey(s => new { s.SubjectId, s.ReadingId }) - // .HasPrincipalKey(c => new { c.SubjectId, c.ReadingId }); - // } - - - //} -} diff --git a/IRaCIS.Core.Infra.EFCore/EntityConfigration/DoctorConfigration.cs b/IRaCIS.Core.Infra.EFCore/EntityConfigration/DoctorConfigration.cs index bac14118a..a0d0f1744 100644 --- a/IRaCIS.Core.Infra.EFCore/EntityConfigration/DoctorConfigration.cs +++ b/IRaCIS.Core.Infra.EFCore/EntityConfigration/DoctorConfigration.cs @@ -26,31 +26,17 @@ namespace IRaCIS.Core.Infra.EFCore.EntityConfigration } - //public class DoctorTaskConfigration : IEntityTypeConfiguration - //{ - // public void Configure(EntityTypeBuilder builder) - // { - // builder - // .HasOne(dd => dd.DoctorUser) - // .WithMany(p => p.VisitTaskList) - // .HasForeignKey(dd => dd.DoctorUserId); - - - // } - - - //} - public class DictionaryConfigration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { - builder.Property(e => e.MappedValue).Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore); - builder.Property(e => e.MappedValue).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + + //builder.Property(e => e.MappedValue).Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore); + // builder.Property(e => e.MappedValue).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); } } diff --git a/IRaCIS.Core.Infra.EFCore/IRaCIS.Core.Infra.EFCore.csproj b/IRaCIS.Core.Infra.EFCore/IRaCIS.Core.Infra.EFCore.csproj index df6df308d..ccebbacad 100644 --- a/IRaCIS.Core.Infra.EFCore/IRaCIS.Core.Infra.EFCore.csproj +++ b/IRaCIS.Core.Infra.EFCore/IRaCIS.Core.Infra.EFCore.csproj @@ -17,13 +17,13 @@ - - - + + - - + + + diff --git a/IRaCIS.Core.Test/IRaCIS.Core.Test.csproj b/IRaCIS.Core.Test/IRaCIS.Core.Test.csproj index 5f49abc87..16b11378d 100644 --- a/IRaCIS.Core.Test/IRaCIS.Core.Test.csproj +++ b/IRaCIS.Core.Test/IRaCIS.Core.Test.csproj @@ -15,7 +15,6 @@ - all