diff --git a/.dockerignore b/.dockerignore index a02c9edb..cd42ee34 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,2 +1,2 @@ -bin\ -obj\ \ No newline at end of file +bin/ +obj/ diff --git a/OpenImis.DB.SqlServer/DataHelper/DataHelper.cs b/OpenImis.DB.SqlServer/DataHelper/DataHelper.cs index 359e35f6..9902cc6c 100644 --- a/OpenImis.DB.SqlServer/DataHelper/DataHelper.cs +++ b/OpenImis.DB.SqlServer/DataHelper/DataHelper.cs @@ -11,19 +11,21 @@ namespace OpenImis.DB.SqlServer.DataHelper { public class DataHelper { - private readonly string ConnectionString; + private readonly string _connectionString; + private readonly int _commandTimeout = 30; public int ReturnValue { get; set; } public DataHelper(IConfiguration configuration) { - ConnectionString = configuration["ConnectionStrings:IMISDatabase"]; + _connectionString = configuration["ConnectionStrings:IMISDatabase"]; + if (configuration["ConnectionSettings:CommandTimeout"] != null) _commandTimeout = Int32.Parse(configuration["ConnectionSettings:CommandTimeout"]); } public DataSet FillDataSet(string SQL, SqlParameter[] parameters, CommandType commandType) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType, CommandTimeout = _commandTimeout }) using (var adapter = new SqlDataAdapter(command)) { DataSet ds = new DataSet(); @@ -48,8 +50,8 @@ public DataSet FillDataSet(string SQL, SqlParameter[] parameters, CommandType co public DataTable GetDataTable(string SQL, SqlParameter[] parameters, CommandType commandType) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType, CommandTimeout = _commandTimeout }) using (var adapter = new SqlDataAdapter(command)) { DataTable dt = new DataTable(); @@ -67,8 +69,8 @@ public DataTable GetDataTable(string SQL, SqlParameter[] parameters, CommandType public DataSet GetDataSet(string SQL, SqlParameter[] parameters, CommandType commandType) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType, CommandTimeout = _commandTimeout }) using (var adapter = new SqlDataAdapter(command)) { DataSet ds = new DataSet(); @@ -86,8 +88,8 @@ public DataSet GetDataSet(string SQL, SqlParameter[] parameters, CommandType com public void Execute(string SQL, SqlParameter[] parameters, CommandType commandType) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType, CommandTimeout = _commandTimeout }) { sqlConnection.Open(); @@ -102,8 +104,8 @@ public void Execute(string SQL, SqlParameter[] parameters, CommandType commandTy public async Task ExecuteAsync(string SQL, SqlParameter[] parameters, CommandType commandType) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(SQL, sqlConnection) { CommandType = commandType, CommandTimeout = _commandTimeout }) { if (command.Connection.State == 0) { @@ -121,8 +123,8 @@ public async Task ExecuteAsync(string SQL, SqlParameter[] parameters, CommandTyp public ProcedureOutPut Procedure(string StoredProcedure, SqlParameter[] parameters, int tableIndex = 0) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure, CommandTimeout = _commandTimeout }) using (var adapter = new SqlDataAdapter(command)) { DataSet dt = new DataSet(); @@ -155,8 +157,8 @@ public ProcedureOutPut Procedure(string StoredProcedure, SqlParameter[] paramete public IList ExecProcedure(string StoredProcedure, SqlParameter[] parameters) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure, CommandTimeout = _commandTimeout }) { SqlParameter returnParameter = new SqlParameter("@RV", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; @@ -181,8 +183,8 @@ public IList ExecProcedure(string StoredProcedure, SqlParameter[] public async Task> ExecProcedureAsync(string StoredProcedure, SqlParameter[] parameters) { - using (var sqlConnection = new SqlConnection(ConnectionString)) - using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure }) + using (var sqlConnection = new SqlConnection(_connectionString)) + using (var command = new SqlCommand(StoredProcedure, sqlConnection) { CommandType = CommandType.StoredProcedure, CommandTimeout = _commandTimeout }) { SqlParameter returnParameter = new SqlParameter("@RV", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; diff --git a/OpenImis.DB.SqlServer/ImisDB.cs b/OpenImis.DB.SqlServer/ImisDB.cs index 6cd8346e..1a2147ee 100644 --- a/OpenImis.DB.SqlServer/ImisDB.cs +++ b/OpenImis.DB.SqlServer/ImisDB.cs @@ -1,13 +1,29 @@ using System; +using System.Data; +using System.Data.Common; using System.IO; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.Configuration; namespace OpenImis.DB.SqlServer { public partial class ImisDB : IMISContext { + private int _commandTimeout = 30; + + public DbCommand CreateCommand() + { + var connection = Database.GetDbConnection(); + var command = connection.CreateCommand(); + command.CommandTimeout = _commandTimeout; + return command; + } + + public void CheckConnection() + { + var connection = Database.GetDbConnection(); + if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { @@ -19,8 +35,8 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) //.AddJsonFile("appsettings.json") .AddJsonFile(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != null ? $"{path}appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json" : $"{path}appsettings.Production.json", optional: false, reloadOnChange: true) .Build(); - - optionsBuilder.UseSqlServer(configuration.GetConnectionString("IMISDatabase")); + if (configuration["ConnectionSettings:CommandTimeout"] != null) _commandTimeout = Int32.Parse(configuration["ConnectionSettings:CommandTimeout"]); + optionsBuilder.UseSqlServer(configuration.GetConnectionString("IMISDatabase"), options => options.CommandTimeout(_commandTimeout)); } } } diff --git a/OpenImis.ModulesV2/InsureeModule/Repositories/InsureeRepository.cs b/OpenImis.ModulesV2/InsureeModule/Repositories/InsureeRepository.cs index 225ea5f0..6ac3e317 100644 --- a/OpenImis.ModulesV2/InsureeModule/Repositories/InsureeRepository.cs +++ b/OpenImis.ModulesV2/InsureeModule/Repositories/InsureeRepository.cs @@ -130,7 +130,7 @@ join G in imisContext.TblGender on I.Gender equals G.Code DOB = I.Dob.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), Gender = G.Gender, InsureeName = I.LastName + " " + I.OtherNames, - PhotoPath = P.PhotoFolder + P.PhotoFileName + PhotoPath = System.IO.Path.Combine(P.PhotoFolder, P.PhotoFileName) }) .FirstOrDefault(); } diff --git a/OpenImis.ModulesV3/ClaimModule/ClaimModule.cs b/OpenImis.ModulesV3/ClaimModule/ClaimModule.cs index be20928a..38532f98 100644 --- a/OpenImis.ModulesV3/ClaimModule/ClaimModule.cs +++ b/OpenImis.ModulesV3/ClaimModule/ClaimModule.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using OpenImis.ModulesV3.ClaimModule.Logic; namespace OpenImis.ModulesV3.ClaimModule @@ -8,20 +9,22 @@ public class ClaimModule { private IConfiguration _configuration; private readonly IHostingEnvironment _hostingEnvironment; + private readonly ILoggerFactory _loggerFactory; private ClaimLogic _claimLogic; - public ClaimModule(IConfiguration configuration, IHostingEnvironment hostingEnvironment) + public ClaimModule(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { _configuration = configuration; _hostingEnvironment = hostingEnvironment; + _loggerFactory = loggerFactory; } public ClaimLogic GetClaimLogic() { if (_claimLogic == null) { - _claimLogic = new ClaimLogic(_configuration, _hostingEnvironment); + _claimLogic = new ClaimLogic(_configuration, _hostingEnvironment, _loggerFactory); } return _claimLogic; } diff --git a/OpenImis.ModulesV3/ClaimModule/Logic/ClaimLogic.cs b/OpenImis.ModulesV3/ClaimModule/Logic/ClaimLogic.cs index 6470364a..eabef1ff 100644 --- a/OpenImis.ModulesV3/ClaimModule/Logic/ClaimLogic.cs +++ b/OpenImis.ModulesV3/ClaimModule/Logic/ClaimLogic.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using OpenImis.DB.SqlServer; using OpenImis.ModulesV3.ClaimModule.Models; using OpenImis.ModulesV3.ClaimModule.Models.RegisterClaim; @@ -12,14 +13,16 @@ public class ClaimLogic { private IConfiguration _configuration; private readonly IHostingEnvironment _hostingEnvironment; + private readonly ILoggerFactory _loggerFactory; protected ClaimRepository claimRepository; - public ClaimLogic(IConfiguration configuration, IHostingEnvironment hostingEnvironment) + public ClaimLogic(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { _configuration = configuration; _hostingEnvironment = hostingEnvironment; + _loggerFactory = loggerFactory; - claimRepository = new ClaimRepository(_configuration, _hostingEnvironment); + claimRepository = new ClaimRepository(_configuration, _hostingEnvironment, _loggerFactory); } public List Create(List claims) @@ -30,7 +33,7 @@ public List Create(List claims) foreach (var claim in claims) { result = claimRepository.Create(claim); - + Errors.Claim errorCode; string message; switch (result) @@ -77,16 +80,22 @@ public List Create(List claims) break; default: errorCode = Errors.Claim.UnexpectedException; - message = "Unhandled exception occured. Please contact the system administrator"; + message = $"Unhandled exception occured ({result}). Please contact the system administrator"; break; } + var rejectedItems = claimRepository.GetRejectedItems(claim.Details.HFCode, claim.Details.ClaimCode); + var rejectedServices = claimRepository.GetRejectedServices(claim.Details.HFCode, claim.Details.ClaimCode); + + claimResponse.Add( new SubmitClaimResponse { ClaimCode = claim.Details.ClaimCode, Response = (int)errorCode, - Message = message + Message = message, + RejectedItems = rejectedItems, + RejectedServices = rejectedServices }); } diff --git a/OpenImis.ModulesV3/ClaimModule/Models/ClaimOutPut.cs b/OpenImis.ModulesV3/ClaimModule/Models/ClaimOutPut.cs index 485446c1..77db97ea 100644 --- a/OpenImis.ModulesV3/ClaimModule/Models/ClaimOutPut.cs +++ b/OpenImis.ModulesV3/ClaimModule/Models/ClaimOutPut.cs @@ -1,9 +1,7 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace OpenImis.ModulesV3.ClaimModule.Models { diff --git a/OpenImis.ModulesV3/ClaimModule/Models/ClaimsModel.cs b/OpenImis.ModulesV3/ClaimModule/Models/ClaimsModel.cs index cdc15c29..50fea5db 100644 --- a/OpenImis.ModulesV3/ClaimModule/Models/ClaimsModel.cs +++ b/OpenImis.ModulesV3/ClaimModule/Models/ClaimsModel.cs @@ -1,11 +1,7 @@ -using Newtonsoft.Json; -using OpenImis.ModulesV3.Helpers.Validators; -using OpenImis.ModulesV3.Utils; +using Newtonsoft.Json; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; namespace OpenImis.ModulesV3.ClaimModule.Models { @@ -14,17 +10,13 @@ public class ClaimsModel [Required] public string claim_administrator_code { get; set; } public ClaimStatus status_claim { get; set; } - [ValidDate(ErrorMessage = "4:Wrong or missing enrolment date")] - [JsonConverter(typeof(IsoDateSerializer))] + [JsonConverter(typeof(IsoDateSerializer), "Invalid visit_date_from")] public DateTime? visit_date_from { get; set; } - [ValidDate(ErrorMessage = "4:Wrong or missing enrolment date")] - [JsonConverter(typeof(IsoDateSerializer))] + [JsonConverter(typeof(IsoDateSerializer), "Invalid visit_date_to")] public DateTime? visit_date_to { get; set; } - [ValidDate(ErrorMessage = "4:Wrong or missing enrolment date")] - [JsonConverter(typeof(IsoDateSerializer))] + [JsonConverter(typeof(IsoDateSerializer), "Invalid processed_date_from")] public DateTime? processed_date_from { get; set; } - [ValidDate(ErrorMessage = "4:Wrong or missing enrolment date")] - [JsonConverter(typeof(IsoDateSerializer))] + [JsonConverter(typeof(IsoDateSerializer), "Invalid processed_date_to")] public DateTime? processed_date_to { get; set; } } diff --git a/OpenImis.ModulesV3/ClaimModule/Models/DsiInputModel.cs b/OpenImis.ModulesV3/ClaimModule/Models/DsiInputModel.cs index ca2c4f70..d153f669 100644 --- a/OpenImis.ModulesV3/ClaimModule/Models/DsiInputModel.cs +++ b/OpenImis.ModulesV3/ClaimModule/Models/DsiInputModel.cs @@ -1,12 +1,7 @@  using Newtonsoft.Json; -using OpenImis.ModulesV3.Helpers.Validators; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; namespace OpenImis.ModulesV3.ClaimModule.Models { diff --git a/OpenImis.ModulesV3/ClaimModule/Models/RegisterClaim/Claim.cs b/OpenImis.ModulesV3/ClaimModule/Models/RegisterClaim/Claim.cs index cab8c0d6..d07b68c2 100644 --- a/OpenImis.ModulesV3/ClaimModule/Models/RegisterClaim/Claim.cs +++ b/OpenImis.ModulesV3/ClaimModule/Models/RegisterClaim/Claim.cs @@ -1,5 +1,5 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; using System.Collections.Generic; diff --git a/OpenImis.ModulesV3/ClaimModule/Models/SubmitClaimResponse.cs b/OpenImis.ModulesV3/ClaimModule/Models/SubmitClaimResponse.cs index 7983afde..c72cbd89 100644 --- a/OpenImis.ModulesV3/ClaimModule/Models/SubmitClaimResponse.cs +++ b/OpenImis.ModulesV3/ClaimModule/Models/SubmitClaimResponse.cs @@ -4,11 +4,30 @@ namespace OpenImis.ModulesV3.ClaimModule.Models { + public class RejectedItem + { + public string Code { get; set; } + public short? Error { get; set; } + public string Reason { get; set; } + } + + public class RejectedService + { + public string Code { get; set; } + public short? Error { get; set; } + public string Reason { get; set; } + } + public class SubmitClaimResponse { public string ClaimCode { get; set; } public int Response { get; set; } public string Message { get; set; } + + public List RejectedItems { get; set; } + + public List RejectedServices { get; set; } + } } diff --git a/OpenImis.ModulesV3/ClaimModule/Repositories/ClaimRepository.cs b/OpenImis.ModulesV3/ClaimModule/Repositories/ClaimRepository.cs index efaa7729..b4863b8e 100644 --- a/OpenImis.ModulesV3/ClaimModule/Repositories/ClaimRepository.cs +++ b/OpenImis.ModulesV3/ClaimModule/Repositories/ClaimRepository.cs @@ -3,13 +3,12 @@ using System.Data; using System.Data.Common; using System.Data.SqlClient; -using System.Diagnostics; using System.IO; using System.Linq; using System.Xml; using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using OpenImis.DB.SqlServer; using OpenImis.DB.SqlServer.DataHelper; using OpenImis.ModulesV3.ClaimModule.Models; @@ -22,11 +21,15 @@ public class ClaimRepository { private IConfiguration _configuration; private readonly IHostingEnvironment _hostingEnvironment; + private readonly ILoggerFactory _loggerFactory; + private readonly ILogger _logger; - public ClaimRepository(IConfiguration configuration, IHostingEnvironment hostingEnvironment) + public ClaimRepository(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { _configuration = configuration; _hostingEnvironment = hostingEnvironment; + _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } // TODO Change the RV assignment codes. It should be on the list for better understanding @@ -63,6 +66,7 @@ public int Create(Claim claim) } catch (Exception e) { + _logger.LogError("Error while saving claim file", e); return (int)Errors.Claim.UnexpectedException; } @@ -76,15 +80,13 @@ public int Create(Claim claim) var sql = "exec @RV = uspRestApiUpdateClaimFromPhone @XML, 0, @ClaimRejected OUTPUT"; - DbConnection connection = imisContext.Database.GetDbConnection(); - - using (DbCommand cmd = connection.CreateCommand()) + using (DbCommand cmd = imisContext.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(new[] { xmlParameter, returnParameter, claimRejectedParameter }); - if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + imisContext.CheckConnection(); using (var reader = cmd.ExecuteReader()) { @@ -93,7 +95,7 @@ public int Create(Claim claim) { while (reader.Read()) { - Debug.WriteLine("Error/Warning: " + reader.GetValue(0)); + _logger.LogDebug($"SP OUTPUT: {reader.GetValue(0)}"); } } while (reader.NextResult()); } @@ -104,7 +106,7 @@ public int Create(Claim claim) if ((RV == 0) && (isClaimRejected == false || isClaimRejected == null)) { - RV = 0; + RV = 0; } else if (RV == 0 && (isClaimRejected == true)) { @@ -113,10 +115,11 @@ public int Create(Claim claim) File.Move(fromPhoneClaimDir + fileName, fromPhoneClaimRejectedDir + fileName); } - RV = (int)Errors.Claim.Rejected; + RV = (int)Errors.Claim.Rejected; } else { + _logger.LogWarning($"Saving claim failed, RV: {RV}"); if (File.Exists(fromPhoneClaimDir + fileName)) { File.Delete(fromPhoneClaimDir + fileName); @@ -129,13 +132,89 @@ public int Create(Claim claim) return RV; } - catch (SqlException e) + catch (Exception e) { + _logger.LogError("Error while saving a claim", e); throw e; } - catch (Exception e) + } + + // Get Rejected Items + public List GetRejectedItems(string hfCode, string claimCode) + { + var rejectedItems = new List(); + + using (var imisContext = new ImisDB()) { - throw e; + var query = from c in imisContext.TblClaim + join hf in imisContext.TblHf on c.Hfid equals hf.HfId + join ci in imisContext.TblClaimItems on c.ClaimId equals ci.ClaimId + join i in imisContext.TblItems on ci.ItemId equals i.ItemId + where c.ClaimCode == claimCode && c.ValidityTo == null && hf.Hfcode == hfCode && ci.ValidityTo == null && ci.ClaimItemStatus == 2 + select new RejectedItem() { Code = i.ItemCode, Error = ci.RejectionReason}; + + rejectedItems = query.ToList(); + } + + foreach (var item in rejectedItems) + { + item.Reason = GetRejectionReason(item.Error); + } + + return rejectedItems; + + } + + // Get Rejected Services + public List GetRejectedServices(string hfCode, string claimCode) + { + var rejectedServices = new List(); + + using (var imisContext = new ImisDB()) + { + var query = from c in imisContext.TblClaim + join hf in imisContext.TblHf on c.Hfid equals hf.HfId + join cs in imisContext.TblClaimServices on c.ClaimId equals cs.ClaimId + join s in imisContext.TblServices on cs.ServiceId equals s.ServiceId + where c.ClaimCode == claimCode && c.ValidityTo == null && hf.Hfcode == hfCode && cs.ValidityTo == null && cs.ClaimServiceStatus == 2 + select new RejectedService() { Code = s.ServCode, Error = cs.RejectionReason}; + + rejectedServices = query.ToList(); + } + + foreach (var service in rejectedServices) + { + service.Reason = GetRejectionReason(service.Error); + } + + return rejectedServices; + + } + + public string GetRejectionReason(short? code) + { + switch (code) + { + case 1: return "Not in Registers"; + case 2: return "Not in HF Pricelist"; + case 3: return "Not in Covering Product/policy"; + case 4: return "Limitation Failed"; + case 5: return "Frequency Failed"; + case 6: return "Duplicated"; + case 7: return "CHFID Not valid/Family Not Valid"; + case 8: return "ICD Code not in current ICD list"; + case 9: return "Target date provision invalid"; + case 10: return "Care type not consistant with Facility"; + case 11: return "Maximum Hospital admissions"; + case 12: return "Maximim visits(OP)"; + case 13: return "Maximum consulations"; + case 14: return "Maximum Surgeries"; + case 15: return "Maximum Deliveries"; + case 16: return "Maximum provision"; + case 17: return "Waiting period violation"; + case 19: return "Maximum Antenatal"; + default: + return ""; } } diff --git a/OpenImis.ModulesV3/FeedbackModule/Models/Feedback.cs b/OpenImis.ModulesV3/FeedbackModule/Models/Feedback.cs index 1f649288..c795fb82 100644 --- a/OpenImis.ModulesV3/FeedbackModule/Models/Feedback.cs +++ b/OpenImis.ModulesV3/FeedbackModule/Models/Feedback.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.FeedbackModule.Models { diff --git a/OpenImis.ModulesV3/FeedbackModule/Models/FeedbackRequest.cs b/OpenImis.ModulesV3/FeedbackModule/Models/FeedbackRequest.cs index 47d61574..7598ffb0 100644 --- a/OpenImis.ModulesV3/FeedbackModule/Models/FeedbackRequest.cs +++ b/OpenImis.ModulesV3/FeedbackModule/Models/FeedbackRequest.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.FeedbackModule.Models { diff --git a/OpenImis.ModulesV3/FeedbackModule/Repositories/FeedbackRepository.cs b/OpenImis.ModulesV3/FeedbackModule/Repositories/FeedbackRepository.cs index a5dca706..0056fe63 100644 --- a/OpenImis.ModulesV3/FeedbackModule/Repositories/FeedbackRepository.cs +++ b/OpenImis.ModulesV3/FeedbackModule/Repositories/FeedbackRepository.cs @@ -96,15 +96,13 @@ public int Post(FeedbackRequest feedbackClaim) var sql = "exec @RV = uspInsertFeedback @XML"; - DbConnection connection = imisContext.Database.GetDbConnection(); - - using (DbCommand cmd = connection.CreateCommand()) + using (DbCommand cmd = imisContext.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(new[] { xmlParameter, returnParameter }); - if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + imisContext.CheckConnection(); using (var reader = cmd.ExecuteReader()) { diff --git a/OpenImis.RestApi/Util/ErrorHandling/BusinessException.cs b/OpenImis.ModulesV3/Helpers/BusinessException.cs similarity index 83% rename from OpenImis.RestApi/Util/ErrorHandling/BusinessException.cs rename to OpenImis.ModulesV3/Helpers/BusinessException.cs index 03c94585..6f4b1a90 100644 --- a/OpenImis.RestApi/Util/ErrorHandling/BusinessException.cs +++ b/OpenImis.ModulesV3/Helpers/BusinessException.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Threading.Tasks; -namespace OpenImis.RestApi.Util.ErrorHandling +namespace OpenImis.ModulesV3.Helpers { /// /// Exception for business related errors. It's error message will be included in the payload. diff --git a/OpenImis.ModulesV3/Helpers/DateTimeFormats.cs b/OpenImis.ModulesV3/Helpers/DateTimeFormats.cs new file mode 100644 index 00000000..241ffec7 --- /dev/null +++ b/OpenImis.ModulesV3/Helpers/DateTimeFormats.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenImis.ModulesV3.Helpers +{ + public static class DateTimeFormats + { + public const string IsoDateFormat = "yyyy-MM-dd"; + public const string IsoDateTimeFormat = "yyyy-MM-ddTHH:mm:ss"; + public const string FileNameDateTimeFormat = "yyyy-MM-ddTHH-mm-ss"; + } +} diff --git a/OpenImis.ModulesV3/Utils/DateTimeSerializers.cs b/OpenImis.ModulesV3/Helpers/DateTimeSerializers.cs similarity index 53% rename from OpenImis.ModulesV3/Utils/DateTimeSerializers.cs rename to OpenImis.ModulesV3/Helpers/DateTimeSerializers.cs index 7377e33c..070a26c3 100644 --- a/OpenImis.ModulesV3/Utils/DateTimeSerializers.cs +++ b/OpenImis.ModulesV3/Helpers/DateTimeSerializers.cs @@ -5,34 +5,42 @@ using System.Text; using System.Xml; -namespace OpenImis.ModulesV3.Utils +namespace OpenImis.ModulesV3.Helpers { - public static class DateTimeFormats - { - public static CultureInfo cultureInfo = CultureInfo.InvariantCulture; - public const string IsoDateFormat = "yyyy-MM-dd"; - public const string IsoDateTimeFormat = "yyyy-MM-ddTHH:mm:ss"; - public const string FileNameDateTimeFormat = "yyyy-MM-ddTHH-mm-ss"; - - } - - public class CustomFormatDatetimeSerializer : JsonConverter + public class CustomFormatDatetimeSerializer : JsonConverter { protected string format; + protected string errorMessage; public CustomFormatDatetimeSerializer(string format) { this.format = format; + this.errorMessage = "Invalid datetime field"; + } + + public CustomFormatDatetimeSerializer(string format, string errorMessage) + { + this.format = format; + this.errorMessage = errorMessage; } - public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer) + public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer) { - return DateTime.ParseExact(reader.Value.ToString(), this.format, DateTimeFormats.cultureInfo); + if (DateTime.TryParseExact(reader.Value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt)) + { + return dt; + } + else + { + throw new BusinessException(errorMessage); + } } - public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer) { - writer.WriteValue(value.ToString(this.format, DateTimeFormats.cultureInfo)); + DateTime dt = value ?? new DateTime(); + writer.WriteValue(dt.ToString(format, CultureInfo.InvariantCulture)); + } } @@ -41,11 +49,16 @@ public class IsoDateSerializer : CustomFormatDatetimeSerializer public IsoDateSerializer() : base(DateTimeFormats.IsoDateFormat) { } + + public IsoDateSerializer(string errorMessage) : base(DateTimeFormats.IsoDateFormat, errorMessage) + { + } } public class ImisSPXmlWriter : XmlTextWriter { - public ImisSPXmlWriter(TextWriter writer) : base(writer) { + public ImisSPXmlWriter(TextWriter writer) : base(writer) + { } public ImisSPXmlWriter(Stream stream, Encoding encoding) : base(stream, encoding) { } public ImisSPXmlWriter(string filename, Encoding encoding) : base(filename, encoding) { } @@ -55,7 +68,7 @@ public override void WriteRaw(string data) DateTime dt; if (DateTime.TryParse(data, out dt)) - base.WriteRaw(dt.ToString(DateTimeFormats.IsoDateFormat, DateTimeFormats.cultureInfo)); + base.WriteRaw(dt.ToString(DateTimeFormats.IsoDateFormat, CultureInfo.InvariantCulture)); else base.WriteRaw(data); } diff --git a/OpenImis.ModulesV3/Helpers/SelfRenewalHelper.cs b/OpenImis.ModulesV3/Helpers/SelfRenewalHelper.cs index 55b105d3..caff1ed4 100644 --- a/OpenImis.ModulesV3/Helpers/SelfRenewalHelper.cs +++ b/OpenImis.ModulesV3/Helpers/SelfRenewalHelper.cs @@ -247,7 +247,7 @@ private DataTable GetPolicyPeriod(int productId, DateTime enrolDate) private async Task GetControlNumber(IntentOfSinglePay intent) { - var result = await new PaymentController(_configuration, _hostingEnvironment, _loggerFactory).CHFRequestControlNumberForSimplePolicy(intent); + var result = await new PaymentController(_configuration, _hostingEnvironment, _loggerFactory, null).CHFRequestControlNumberForSimplePolicy(intent); var result1 = (OkObjectResult)result; var value = (GetControlNumberResp)result1.Value; diff --git a/OpenImis.ModulesV3/Helpers/Validators/ValidDateAttribute.cs b/OpenImis.ModulesV3/Helpers/Validators/ValidDateAttribute.cs deleted file mode 100644 index ef71ef7f..00000000 --- a/OpenImis.ModulesV3/Helpers/Validators/ValidDateAttribute.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using System.Globalization; - -namespace OpenImis.ModulesV3.Helpers.Validators -{ - [AttributeUsage(AttributeTargets.Property, Inherited = false)] - public class ValidDateAttribute : ValidationAttribute - { - public ValidDateAttribute() - { - } - - protected override ValidationResult IsValid(object value, ValidationContext validationContext) - { - if (value == null) - return ValidationResult.Success; - - try - { - DateTime date = Convert.ToDateTime(value.ToString()); - DateTime Odate; - - if (date.Year > 1753) - { - if (DateTime.TryParseExact(value.ToString(), "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out Odate)) - { - return ValidationResult.Success; - } - else - { - return new ValidationResult(null); - } - } - else - { - return new ValidationResult(null); - } - } - catch (Exception) - { - return new ValidationResult(null); - } - } - } -} diff --git a/OpenImis.ModulesV3/ImisModules.cs b/OpenImis.ModulesV3/ImisModules.cs index 2dbb121f..27e4c82c 100644 --- a/OpenImis.ModulesV3/ImisModules.cs +++ b/OpenImis.ModulesV3/ImisModules.cs @@ -80,7 +80,7 @@ public ClaimModule.ClaimModule GetClaimModule() { if (claimModule == null) { - claimModule = new ClaimModule.ClaimModule(_configuration, _hostingEnvironment); + claimModule = new ClaimModule.ClaimModule(_configuration, _hostingEnvironment, _loggerFactory); Type claimLogicType = CreateTypeFromConfiguration("ClaimModule", "ClaimLogic", "OpenImis.ModulesV3.ClaimModule.Logic.ClaimLogic"); claimModule.SetClaimLogic((ClaimModule.Logic.ClaimLogic)ActivatorUtilities.CreateInstance(_serviceProvider, claimLogicType)); diff --git a/OpenImis.ModulesV3/InsureeModule/InsureeModule.cs b/OpenImis.ModulesV3/InsureeModule/InsureeModule.cs index 7df2c385..fe7ddb41 100644 --- a/OpenImis.ModulesV3/InsureeModule/InsureeModule.cs +++ b/OpenImis.ModulesV3/InsureeModule/InsureeModule.cs @@ -44,7 +44,7 @@ public IInsureeLogic GetInsureeLogic() { if (_insureeLogic == null) { - _insureeLogic = new InsureeLogic(_configuration); + _insureeLogic = new InsureeLogic(_configuration, _loggerFactory); } return _insureeLogic; } diff --git a/OpenImis.ModulesV3/InsureeModule/Logic/FamilyLogic.cs b/OpenImis.ModulesV3/InsureeModule/Logic/FamilyLogic.cs index b9c13600..2a568d10 100644 --- a/OpenImis.ModulesV3/InsureeModule/Logic/FamilyLogic.cs +++ b/OpenImis.ModulesV3/InsureeModule/Logic/FamilyLogic.cs @@ -35,7 +35,11 @@ public FamilyModel GetByCHFID(string chfid, Guid userUUID) { foreach (var insure in response.Insurees) { - insure.PhotoBase64 = PhotoUtils.CreateBase64ImageFromFilepath(_configuration.GetValue("AppSettings:UpdatedFolder"), insure.PhotoPath); + insure.PhotoBase64 = PhotoUtils.CreateBase64ImageFromFilepath( + _configuration.GetValue("AppSettings:UpdatedFolder"), + insure.PhotoPath, + _loggerFactory.CreateLogger() + ); } } diff --git a/OpenImis.ModulesV3/InsureeModule/Logic/InsureeLogic.cs b/OpenImis.ModulesV3/InsureeModule/Logic/InsureeLogic.cs index c91a35bf..805a14b6 100644 --- a/OpenImis.ModulesV3/InsureeModule/Logic/InsureeLogic.cs +++ b/OpenImis.ModulesV3/InsureeModule/Logic/InsureeLogic.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using OpenImis.ModulesV3.InsureeModule.Models; using OpenImis.ModulesV3.InsureeModule.Repositories; using OpenImis.ModulesV3.Utils; @@ -11,10 +12,12 @@ public class InsureeLogic : IInsureeLogic { private IConfiguration _configuration; protected IInsureeRepository insureeRepository; + private readonly ILoggerFactory _loggerFactory; - public InsureeLogic(IConfiguration configuration) + public InsureeLogic(IConfiguration configuration, ILoggerFactory loggerFactory) { _configuration = configuration; + _loggerFactory = loggerFactory; insureeRepository = new InsureeRepository(_configuration); } @@ -25,9 +28,12 @@ public GetEnquireModel GetEnquire(string chfid) response = insureeRepository.GetEnquire(chfid); - if (response != null) + if (response != null && !string.IsNullOrEmpty(response.PhotoPath)) { - response.PhotoBase64 = PhotoUtils.CreateBase64ImageFromFilepath(_configuration.GetValue("AppSettings:UpdatedFolder"), response.PhotoPath); + response.PhotoBase64 = PhotoUtils.CreateBase64ImageFromFilepath( + _configuration.GetValue("AppSettings:UpdatedFolder"), + response.PhotoPath, + _loggerFactory.CreateLogger()); } return response; diff --git a/OpenImis.ModulesV3/InsureeModule/Models/DetailModel.cs b/OpenImis.ModulesV3/InsureeModule/Models/DetailModel.cs index ff420956..9cabd1e2 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/DetailModel.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/DetailModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.InsureeModule.Models { diff --git a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/EnrollFamilyModel.cs b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/EnrollFamilyModel.cs index 0f971665..20f5fadd 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/EnrollFamilyModel.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/EnrollFamilyModel.cs @@ -8,13 +8,15 @@ namespace OpenImis.ModulesV3.InsureeModule.Models.EnrollFamilyModels public class EnrolFamilyModel { public List Family { get; set; } + public string Source { get; set; } = "unknown"; + public string SourceVersion { get; set; } = ""; public Enrolment GetEnrolmentFromModel() { var enrolment = new Enrolment(); enrolment.FileInfo = new FileInfo(); - + foreach (Family f in Family) { // add the Family Family family = new Family() diff --git a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Enrolment.cs b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Enrolment.cs index 04b60fc4..646d903b 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Enrolment.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Enrolment.cs @@ -22,5 +22,6 @@ public Enrolment() public List Policies { get; set; } public List Premiums { get; set; } public List InsureePolicies { get; set; } + } } diff --git a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Insuree.cs b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Insuree.cs index 8ebcdd21..c3a391cc 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Insuree.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/EnrollFamilyModels/Insuree.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.InsureeModule.Models.EnrollFamilyModels { diff --git a/OpenImis.ModulesV3/InsureeModule/Models/GetEnquireModel.cs b/OpenImis.ModulesV3/InsureeModule/Models/GetEnquireModel.cs index 2dd1f6c8..1acdf6e8 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/GetEnquireModel.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/GetEnquireModel.cs @@ -16,6 +16,8 @@ public GetInsureeModel GetInsuree() DOB = DOB, Gender = Gender, InsureeName = InsureeName, + OtherNames = OtherNames, + LastName = LastName, PhotoPath = PhotoPath, PhotoBase64 = PhotoBase64 }; diff --git a/OpenImis.ModulesV3/InsureeModule/Models/GetInsureeModel.cs b/OpenImis.ModulesV3/InsureeModule/Models/GetInsureeModel.cs index d378e3ba..2c47c02a 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/GetInsureeModel.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/GetInsureeModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.Globalization; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; namespace OpenImis.ModulesV3.InsureeModule.Models { @@ -15,5 +13,7 @@ public class GetInsureeModel public DateTime? DOB { get; set; } public string Gender { get; set; } public string PhotoBase64 { get; set; } + public string OtherNames { get; set; } + public string LastName { get; set; } } } diff --git a/OpenImis.ModulesV3/InsureeModule/Models/InsureeModel.cs b/OpenImis.ModulesV3/InsureeModule/Models/InsureeModel.cs index 8d52d23f..9398a97e 100644 --- a/OpenImis.ModulesV3/InsureeModule/Models/InsureeModel.cs +++ b/OpenImis.ModulesV3/InsureeModule/Models/InsureeModel.cs @@ -1,10 +1,8 @@ using Newtonsoft.Json; using OpenImis.DB.SqlServer; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.Utils; using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Text; namespace OpenImis.ModulesV3.InsureeModule.Models { diff --git a/OpenImis.ModulesV3/InsureeModule/Repositories/FamilyRepository.cs b/OpenImis.ModulesV3/InsureeModule/Repositories/FamilyRepository.cs index 1d5105c9..c8555e92 100644 --- a/OpenImis.ModulesV3/InsureeModule/Repositories/FamilyRepository.cs +++ b/OpenImis.ModulesV3/InsureeModule/Repositories/FamilyRepository.cs @@ -31,12 +31,14 @@ public class FamilyRepository : IFamilyRepository private IConfiguration _configuration; private readonly IHostingEnvironment _hostingEnvironment; private readonly ILoggerFactory _loggerFactory; + private readonly ILogger _logger; public FamilyRepository(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { _configuration = configuration; _hostingEnvironment = hostingEnvironment; _loggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger(); } public FamilyModel GetByCHFID(string chfid, Guid userUUID) @@ -47,22 +49,22 @@ public FamilyModel GetByCHFID(string chfid, Guid userUUID) { var locationIds = (from UD in imisContext.TblUsersDistricts join U in imisContext.TblUsers on UD.UserId equals U.UserId - where U.UserUUID == userUUID && UD.ValidityTo == null + where U.UserUUID == userUUID && U.ValidityTo == null && UD.ValidityTo == null select UD.LocationId) .ToList(); var familyId = (from I in imisContext.TblInsuree join F in imisContext.TblFamilies on I.FamilyId equals F.FamilyId - join V in imisContext.TblVillages on F.LocationId equals V.VillageId - join W in imisContext.TblWards on V.WardId equals W.WardId - join D in imisContext.TblDistricts on W.DistrictId equals D.DistrictId + join LV in imisContext.TblLocations on F.LocationId equals LV.LocationId + join LW in imisContext.TblLocations on LV.ParentLocationId equals LW.LocationId + join LD in imisContext.TblLocations on LW.ParentLocationId equals LD.LocationId where (I.Chfid == chfid - && locationIds.Contains(D.DistrictId) - && F.ValidityTo == null && I.ValidityTo == null - && V.ValidityTo == null - && W.ValidityTo == null - && D.ValidityTo == null) + && F.ValidityTo == null + && LV.ValidityTo == null + && LW.ValidityTo == null + && LD.ValidityTo == null + && locationIds.Contains(LD.LocationId)) select F.FamilyId) .FirstOrDefault(); @@ -164,15 +166,18 @@ public NewFamilyResponse Create(EnrolFamilyModel model, int userId, int officerI var XML = enrolFamily.XMLSerialize(); var JSON = JsonConvert.SerializeObject(enrolFamily); - var EnrolmentDir = _configuration["AppSettings:Enrollment_Phone"] + Path.DirectorySeparatorChar; - var JsonDebugFolder = _configuration["AppSettings:JsonDebugFolder"] + Path.DirectorySeparatorChar; + var dateFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Day.ToString() + Path.DirectorySeparatorChar; + + var EnrolmentDir = _configuration["AppSettings:Enrollment_Phone"] + Path.DirectorySeparatorChar + dateFolder; + var UpdatedFolder = _configuration["AppSettings:UpdatedFolder"] + Path.DirectorySeparatorChar; var SubmittedFolder = _configuration["AppSettings:SubmittedFolder"] + Path.DirectorySeparatorChar; + var hof = enrolFamily.Families.Select(x => x.HOFCHFID).FirstOrDefault(); var FileName = string.Format("{0}_{1}_{2}.xml", hof, officerId.ToString(), DateTime.Now.ToString(DateTimeFormats.FileNameDateTimeFormat)); - var JsonFileName = string.Format("{0}_{1}_{2}.json", hof, officerId.ToString(), DateTime.Now.ToString(DateTimeFormats.FileNameDateTimeFormat)); + var xmldoc = new XmlDocument(); xmldoc.InnerXml = XML; @@ -181,9 +186,7 @@ public NewFamilyResponse Create(EnrolFamilyModel model, int userId, int officerI xmldoc.Save(EnrolmentDir + FileName); - if (!Directory.Exists(JsonDebugFolder)) Directory.CreateDirectory(JsonDebugFolder); - File.WriteAllText(JsonDebugFolder + JsonFileName, JSON); int RV = -99; int InsureeUpd; @@ -192,6 +195,8 @@ public NewFamilyResponse Create(EnrolFamilyModel model, int userId, int officerI using (var imisContext = new ImisDB()) { var xmlParameter = new SqlParameter("@XML", XML) { DbType = DbType.Xml }; + var source = new SqlParameter("@Source", model.Source) { DbType = DbType.String, Size = 50 }; + var sourceVersion = new SqlParameter("@SourceVersion", model.SourceVersion) { DbType = DbType.String, Size = 15 }; var returnParameter = OutputParameter.CreateOutputParameter("@RV", SqlDbType.Int); var familySentParameter = OutputParameter.CreateOutputParameter("@FamilySent", SqlDbType.Int); var familyImportedParameter = OutputParameter.CreateOutputParameter("@FamilyImported", SqlDbType.Int); @@ -208,24 +213,22 @@ public NewFamilyResponse Create(EnrolFamilyModel model, int userId, int officerI var premiumImportedParameter = OutputParameter.CreateOutputParameter("@PremiumImported", SqlDbType.Int); var premiumRejectedParameter = OutputParameter.CreateOutputParameter("@PremiumRejected", SqlDbType.Int); - var sql = "exec @RV = uspConsumeEnrollments @XML, @FamilySent OUT, @FamilyImported OUT, @FamiliesUpd OUT, @FamilyRejected OUT, " + + var sql = "exec @RV = uspConsumeEnrollments @XML, @Source, @SourceVersion, @FamilySent OUT, @FamilyImported OUT, @FamiliesUpd OUT, @FamilyRejected OUT, " + "@InsureeSent OUT, @InsureeUpd OUT, @InsureeImported OUT, " + "@PolicySent OUT, @PolicyImported OUT, @PolicyRejected OUT, @PolicyChanged OUT," + "@PremiumSent OUT, @PremiumImported OUT, @PremiumRejected OUT"; - DbConnection connection = imisContext.Database.GetDbConnection(); - - using (DbCommand cmd = connection.CreateCommand()) + using (DbCommand cmd = imisContext.CreateCommand()) { cmd.CommandText = sql; - cmd.Parameters.AddRange(new[] { xmlParameter, returnParameter, familySentParameter, familyImportedParameter, familiesUpdParameter, + cmd.Parameters.AddRange(new[] { xmlParameter, source, sourceVersion, returnParameter, familySentParameter, familyImportedParameter, familiesUpdParameter, familyRejectedParameter, insureeSentParameter, insureeUpdParameter, insureeImportedParameter, policySentParameter, policyImportedParameter, policyRejectedParameter, policyChangedParameter, premiumSentParameter, premiumImportedParameter, premiumRejectedParameter }); - if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + imisContext.CheckConnection(); using (var reader = cmd.ExecuteReader()) { @@ -278,8 +281,6 @@ public NewFamilyResponse Create(EnrolFamilyModel model, int userId, int officerI // Create Premium CreatePremium(model); - - } return newFamily; @@ -326,14 +327,16 @@ public int UpdateControlNumber(EnrolFamilyModel familyModel, NewFamilyResponse s foreach (var family in familyModel.Family) { - foreach (var policy in family.Policies) + if (family.Policies != null) { - if (policy.ControlNumber.Length == 0) - continue; + foreach (var policy in family.Policies) + { + if (String.IsNullOrEmpty(policy.ControlNumber)) + continue; - var policyId = serverResponse.Family.Where(f => f.FamilyId == family.FamilyId).FirstOrDefault().Policies.Where(p => p.PolicyId == policy.PolicyId).Select(p => p.PolicyDBId).FirstOrDefault(); + var policyId = serverResponse.Family.Where(f => f.FamilyId == family.FamilyId).FirstOrDefault().Policies.Where(p => p.PolicyId == policy.PolicyId).Select(p => p.PolicyDBId).FirstOrDefault(); - var sSQL = @"UPDATE PD SET InsuranceNumber = I.CHFID, PremiumID = PR.PremiumId, PolicyStage = Pol.PolicyStage, enrollmentDate = Pol.EnrollDate, ValidityFrom = GETDATE() + var sSQL = @"UPDATE PD SET InsuranceNumber = I.CHFID, PremiumID = PR.PremiumId, PolicyStage = Pol.PolicyStage, enrollmentDate = Pol.EnrollDate, ValidityFrom = GETDATE() FROM tblControlNumber CN INNER JOIN tblPaymentDetails PD ON CN.PaymentId = PD.PaymentID INNER JOIN tblInsuree I ON IsHead = 1 @@ -343,23 +346,27 @@ WHERE CN.ValidityTo IS NULL AND I.ValidityTo IS NULL AND CN.ControlNumber = @ControlNumber;"; - SqlParameter[] parameters = - { - new SqlParameter("@ControlNumber", policy.ControlNumber), - new SqlParameter("@PolicyId", policyId), - }; + SqlParameter[] parameters = + { + new SqlParameter("@ControlNumber", policy.ControlNumber), + new SqlParameter("@PolicyId", policyId), + }; - try - { - var dh = new DB.SqlServer.DataHelper.DataHelper(_configuration); - dh.Execute(sSQL, parameters, CommandType.Text); - } - catch (Exception) - { + try + { + var dh = new DB.SqlServer.DataHelper.DataHelper(_configuration); + dh.Execute(sSQL, parameters, CommandType.Text); + } + catch (Exception) + { + return 1001; + } - return 1001; } - + } + else + { + _logger.LogWarning("Family policy null in UpdateControlNumber, family HOFCHFID: " + family.HOFCHFID); } } return 0; @@ -377,7 +384,7 @@ public void CreatePremium(EnrolFamilyModel model) foreach (var policy in family.Policies) { int paymentId = payment.GetPaymentId(policy.ControlNumber); - _ = paymentLogic.CreatePremium(paymentId); + _ = paymentLogic.CreatePremium(paymentId, "GePG", model.SourceVersion); } } } diff --git a/OpenImis.ModulesV3/InsureeModule/Repositories/InsureeRepository.cs b/OpenImis.ModulesV3/InsureeModule/Repositories/InsureeRepository.cs index 7f47085e..9b3bb315 100644 --- a/OpenImis.ModulesV3/InsureeModule/Repositories/InsureeRepository.cs +++ b/OpenImis.ModulesV3/InsureeModule/Repositories/InsureeRepository.cs @@ -33,16 +33,13 @@ public GetEnquireModel GetEnquire(string chfid) var sql = "exec uspAPIGetCoverage @CHFID"; - DbConnection connection = imisContext.Database.GetDbConnection(); - - using (DbCommand cmd = connection.CreateCommand()) + using (DbCommand cmd = imisContext.CreateCommand()) { - cmd.CommandText = sql; cmd.Parameters.AddRange(new[] { chfidParameter }); - if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + imisContext.CheckConnection(); using (var reader = cmd.ExecuteReader()) { @@ -57,9 +54,13 @@ public GetEnquireModel GetEnquire(string chfid) response.InsureeName = string.Join(' ', reader["OtherNames"].ToString()) + ' ' + reader["LastName"].ToString(); response.CHFID = reader["CHFID"].ToString(); - response.PhotoPath = reader["PhotoPath"].ToString(); + response.PhotoPath = System.IO.Path.Combine(reader["PhotoPath"].ToString() + .Split(new[] { "\\" }, StringSplitOptions.None)); response.DOB = reader["DOB"].ToString().ToNullableDatetime(); response.Gender = reader["Gender"].ToString(); + response.OtherNames = reader["OtherNames"].ToString(); + response.LastName = reader["LastName"].ToString(); + } details.Add(new DetailModel @@ -119,7 +120,7 @@ join G in imisContext.TblGender on I.Gender equals G.Code DOB = I.Dob, Gender = G.Gender, InsureeName = I.LastName + " " + I.OtherNames, - PhotoPath = P.PhotoFolder + P.PhotoFileName + PhotoPath = System.IO.Path.Combine(P.PhotoFolder, P.PhotoFileName) }).FirstOrDefault(); } diff --git a/OpenImis.ModulesV3/MasterDataModule/Models/OfficerModel.cs b/OpenImis.ModulesV3/MasterDataModule/Models/OfficerModel.cs index ccbe4e32..01df2531 100644 --- a/OpenImis.ModulesV3/MasterDataModule/Models/OfficerModel.cs +++ b/OpenImis.ModulesV3/MasterDataModule/Models/OfficerModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.MasterDataModule.Models { diff --git a/OpenImis.ModulesV3/MasterDataModule/Models/ProductModel.cs b/OpenImis.ModulesV3/MasterDataModule/Models/ProductModel.cs index 0adc4cc5..42c48cf0 100644 --- a/OpenImis.ModulesV3/MasterDataModule/Models/ProductModel.cs +++ b/OpenImis.ModulesV3/MasterDataModule/Models/ProductModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.MasterDataModule.Models { diff --git a/OpenImis.ModulesV3/OpenImis.ModulesV3.csproj b/OpenImis.ModulesV3/OpenImis.ModulesV3.csproj index 511b5dd0..b2c8a602 100644 --- a/OpenImis.ModulesV3/OpenImis.ModulesV3.csproj +++ b/OpenImis.ModulesV3/OpenImis.ModulesV3.csproj @@ -22,6 +22,10 @@ + + + + diff --git a/OpenImis.ModulesV3/PolicyModule/Models/GetPolicyRenewalModel.cs b/OpenImis.ModulesV3/PolicyModule/Models/GetPolicyRenewalModel.cs index 22a0d39f..37780cd8 100644 --- a/OpenImis.ModulesV3/PolicyModule/Models/GetPolicyRenewalModel.cs +++ b/OpenImis.ModulesV3/PolicyModule/Models/GetPolicyRenewalModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.PolicyModule.Models { diff --git a/OpenImis.ModulesV3/PolicyModule/Models/PolicyRenewalModel.cs b/OpenImis.ModulesV3/PolicyModule/Models/PolicyRenewalModel.cs index 45223109..b6ee2d7c 100644 --- a/OpenImis.ModulesV3/PolicyModule/Models/PolicyRenewalModel.cs +++ b/OpenImis.ModulesV3/PolicyModule/Models/PolicyRenewalModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.PolicyModule.Models { @@ -14,15 +12,12 @@ public class PolicyRenewalModel public string ReceiptNo { get; set; } public string ProductCode { get; set; } public float Amount { get; set; } - [JsonConverter(typeof(IsoDateSerializer))] public DateTime Date { get; set; } public bool Discontinue { get; set; } public int PayerId { get; set; } - public string ControlNumber { get; set; } - public Policy GetPolicy() { return new Policy() diff --git a/OpenImis.ModulesV3/PolicyModule/Repositories/PolicyRenewalRepository.cs b/OpenImis.ModulesV3/PolicyModule/Repositories/PolicyRenewalRepository.cs index cdf6f197..ae6e8b46 100644 --- a/OpenImis.ModulesV3/PolicyModule/Repositories/PolicyRenewalRepository.cs +++ b/OpenImis.ModulesV3/PolicyModule/Repositories/PolicyRenewalRepository.cs @@ -155,7 +155,7 @@ public int Post(PolicyRenewalModel policy) int tempRV = (int)returnParameter.Value; bool moveToRejected = false; - switch (tempRV) + switch (tempRV) { case 0: RV = (int)Errors.Renewal.Accepted; @@ -181,12 +181,17 @@ public int Post(PolicyRenewalModel policy) break; } - if(moveToRejected) + if (moveToRejected) { + // Check if the file already exists in the rejected folder + // If yes then delete it otherwise it will throw and exception + if (File.Exists(fromPhoneRenewalRejectedDir + fileName)) + File.Delete(fromPhoneRenewalRejectedDir + fileName); + + if (File.Exists(fromPhoneRenewalDir + fileName)) - { File.Move(fromPhoneRenewalDir + fileName, fromPhoneRenewalRejectedDir + fileName); - } + } } } @@ -326,7 +331,7 @@ public void CreatePremium(PolicyRenewalModel renewal) if (_configuration.GetValue("PaymentGateWay:CreatePremiumOnPaymentReceived")) { int paymentId = payment.GetPaymentId(renewal.ControlNumber); - _ = paymentLogic.CreatePremium(paymentId); + _ = paymentLogic.CreatePremium(paymentId, "GePG", "1"); } } @@ -335,7 +340,7 @@ public async Task SelfRenewal(SelfRenewal renewal) { var helper = new SelfRenewalHelper(_configuration, _hostingEnvironment, _loggerFactory); var response = await helper.CreateSelfRenewal(renewal); - + return response; } } diff --git a/OpenImis.ModulesV3/ReportModule/Models/IndicatorRequestModel.cs b/OpenImis.ModulesV3/ReportModule/Models/IndicatorRequestModel.cs index 0ec2be8b..5f77edae 100644 --- a/OpenImis.ModulesV3/ReportModule/Models/IndicatorRequestModel.cs +++ b/OpenImis.ModulesV3/ReportModule/Models/IndicatorRequestModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.ReportModule.Models { diff --git a/OpenImis.ModulesV3/ReportModule/Models/SnapshotRequestModel.cs b/OpenImis.ModulesV3/ReportModule/Models/SnapshotRequestModel.cs index cc2c70b6..2c382d5b 100644 --- a/OpenImis.ModulesV3/ReportModule/Models/SnapshotRequestModel.cs +++ b/OpenImis.ModulesV3/ReportModule/Models/SnapshotRequestModel.cs @@ -1,8 +1,6 @@ using Newtonsoft.Json; -using OpenImis.ModulesV3.Utils; +using OpenImis.ModulesV3.Helpers; using System; -using System.Collections.Generic; -using System.Text; namespace OpenImis.ModulesV3.ReportModule.Models { diff --git a/OpenImis.ModulesV3/ReportModule/Repositories/ReportRepository.cs b/OpenImis.ModulesV3/ReportModule/Repositories/ReportRepository.cs index 0a91f1f8..64a1426c 100644 --- a/OpenImis.ModulesV3/ReportModule/Repositories/ReportRepository.cs +++ b/OpenImis.ModulesV3/ReportModule/Repositories/ReportRepository.cs @@ -130,15 +130,13 @@ public SnapshotResponseModel GetSnapshotIndicators(SnapshotRequestModel snapshot var sql = "SELECT Active, Expired, Idle, Suspended FROM udfGetSnapshotIndicators(@SnapshotDate,@OfficerId)"; - DbConnection connection = imisContext.Database.GetDbConnection(); - - using (DbCommand cmd = connection.CreateCommand()) + using (DbCommand cmd = imisContext.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(new[] { snapshotDateParameter, officerIdParameter }); - if (connection.State.Equals(ConnectionState.Closed)) connection.Open(); + imisContext.CheckConnection(); using (var reader = cmd.ExecuteReader()) { diff --git a/OpenImis.ModulesV3/Utils/LinqExtensions.cs b/OpenImis.ModulesV3/Utils/LinqExtensions.cs index fdf63727..267f552c 100644 --- a/OpenImis.ModulesV3/Utils/LinqExtensions.cs +++ b/OpenImis.ModulesV3/Utils/LinqExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace OpenImis.ModulesV3.Utils { diff --git a/OpenImis.ModulesV3/Utils/PhotoUtils.cs b/OpenImis.ModulesV3/Utils/PhotoUtils.cs index d9fea960..a2d3a09f 100644 --- a/OpenImis.ModulesV3/Utils/PhotoUtils.cs +++ b/OpenImis.ModulesV3/Utils/PhotoUtils.cs @@ -1,24 +1,25 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Text; +using System.Linq; +using Microsoft.Extensions.Logging; namespace OpenImis.ModulesV3.Utils { public static class PhotoUtils { - public static string CreateBase64ImageFromFilepath(string photoPath,string imageName) + public static string CreateBase64ImageFromFilepath(string photoPath,string imageName, ILogger logger=null) { var base64 = ""; if (!string.IsNullOrEmpty(imageName)) { - var startIndex = imageName.LastIndexOf("\\") == -1 ? 0 : imageName.LastIndexOf("\\"); - var fileName = imageName.Substring(startIndex); - var fileFullPath = Path.Join(photoPath, fileName); - - if (File.Exists(fileFullPath)) + var fileName = imageName.Replace('\\', '/').Split('/').Last(); + if (!string.IsNullOrEmpty(fileName)) { - base64 = Convert.ToBase64String(File.ReadAllBytes(fileFullPath)); + var fileFullPath = Path.Join(photoPath, fileName); + if (File.Exists(fileFullPath)) + { + base64 = Convert.ToBase64String(File.ReadAllBytes(fileFullPath)); + } } } return base64; diff --git a/OpenImis.ModulesV3/Utils/Repository.cs b/OpenImis.ModulesV3/Utils/Repository.cs index 8fccc798..617902a7 100644 --- a/OpenImis.ModulesV3/Utils/Repository.cs +++ b/OpenImis.ModulesV3/Utils/Repository.cs @@ -1,9 +1,7 @@ using OpenImis.DB.SqlServer; using System; -using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; -using System.Text; namespace OpenImis.ModulesV3.Utils { diff --git a/OpenImis.ModulesV3/Utils/TypeCast.cs b/OpenImis.ModulesV3/Utils/TypeCast.cs index 8a5abc64..a9e34667 100644 --- a/OpenImis.ModulesV3/Utils/TypeCast.cs +++ b/OpenImis.ModulesV3/Utils/TypeCast.cs @@ -1,8 +1,5 @@ using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace OpenImis.ModulesV3.Utils { diff --git a/OpenImis.RestApi/Controllers/V3/ClaimController.cs b/OpenImis.RestApi/Controllers/V3/ClaimController.cs index 2e535240..efa3ba09 100644 --- a/OpenImis.RestApi/Controllers/V3/ClaimController.cs +++ b/OpenImis.RestApi/Controllers/V3/ClaimController.cs @@ -7,9 +7,9 @@ using OpenImis.ModulesV3; using OpenImis.ModulesV3.ClaimModule.Models.RegisterClaim; using Microsoft.Extensions.Logging; -using OpenImis.RestApi.Util.ErrorHandling; using System.Net; using System.Collections.Generic; +using OpenImis.ModulesV3.Helpers; namespace OpenImis.RestApi.Controllers.V3 { @@ -47,6 +47,7 @@ public IActionResult Create([FromBody] List claims) } catch (Exception e) { + _logger.LogError("Error while uploading claims", e); return BadRequest(new SubmitClaimResponse { ClaimCode = "", diff --git a/OpenImis.RestApi/Controllers/V3/FamilyController.cs b/OpenImis.RestApi/Controllers/V3/FamilyController.cs index 565e9526..24642cad 100644 --- a/OpenImis.RestApi/Controllers/V3/FamilyController.cs +++ b/OpenImis.RestApi/Controllers/V3/FamilyController.cs @@ -1,11 +1,14 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Diagnostics; +using System.IO; using System.Linq; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using Newtonsoft.Json; using OpenImis.ModulesV3; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.InsureeModule.Models; using OpenImis.ModulesV3.InsureeModule.Models.EnrollFamilyModels; using OpenImis.RestApi.Util.ErrorHandling; @@ -20,11 +23,13 @@ namespace OpenImis.RestApi.Controllers.V3 public class FamilyController : Controller { private readonly IImisModules _imisModules; + private readonly IConfiguration _configuration; private readonly ILogger _logger; - public FamilyController(IImisModules imisModules, ILoggerFactory loggerFactory) + public FamilyController(IImisModules imisModules, ILoggerFactory loggerFactory, IConfiguration configuration) { _imisModules = imisModules; + _configuration = configuration; _logger = loggerFactory.CreateLogger(); } @@ -58,6 +63,35 @@ public IActionResult GetByCHFID(string chfid) [HttpPost] public IActionResult Create([FromBody] EnrolFamilyModel model) { + + // Save the payload in to a folder before performing any other tasks + // This will help us later to debug in case of any queries + Guid userUUID; + int officerId; + + try + { + + var JSON = JsonConvert.SerializeObject(model); + var dateFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Day.ToString() + Path.DirectorySeparatorChar; + var JsonDebugFolder = _configuration["AppSettings:JsonDebugFolder"] + Path.DirectorySeparatorChar + dateFolder; + + var hof = model.Family.Select(x => x.HOFCHFID).FirstOrDefault(); + userUUID = Guid.Parse(HttpContext.User.Claims.Where(w => w.Type == "UserUUID").Select(x => x.Value).FirstOrDefault()); + officerId = _imisModules.GetInsureeModule().GetFamilyLogic().GetOfficerIdByUserUUID(userUUID); + + var JsonFileName = string.Format("{0}_{1}_{2}.json", hof, officerId.ToString(), DateTime.Now.ToString(DateTimeFormats.FileNameDateTimeFormat)); + + if (!Directory.Exists(JsonDebugFolder)) Directory.CreateDirectory(JsonDebugFolder); + + System.IO.File.WriteAllText(JsonDebugFolder + JsonFileName, JSON); + + } + catch (Exception e) + { + + throw new BusinessException(e.Message); + } NewFamilyResponse response; if (!ModelState.IsValid) @@ -68,10 +102,10 @@ public IActionResult Create([FromBody] EnrolFamilyModel model) try { - Guid userUUID = Guid.Parse(HttpContext.User.Claims.Where(w => w.Type == "UserUUID").Select(x => x.Value).FirstOrDefault()); + int userId = _imisModules.GetInsureeModule().GetFamilyLogic().GetUserIdByUUID(userUUID); - int officerId = _imisModules.GetInsureeModule().GetFamilyLogic().GetOfficerIdByUserUUID(userUUID); + response = _imisModules.GetInsureeModule().GetFamilyLogic().Create(model, userId, officerId); } @@ -84,4 +118,4 @@ public IActionResult Create([FromBody] EnrolFamilyModel model) return Ok(response); } } -} \ No newline at end of file +} diff --git a/OpenImis.RestApi/Controllers/V3/FeedbackController.cs b/OpenImis.RestApi/Controllers/V3/FeedbackController.cs index 287d216a..1f0c6cb9 100644 --- a/OpenImis.RestApi/Controllers/V3/FeedbackController.cs +++ b/OpenImis.RestApi/Controllers/V3/FeedbackController.cs @@ -7,8 +7,8 @@ using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; using OpenImis.ModulesV3.FeedbackModule.Models; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.Utils; -using OpenImis.RestApi.Util.ErrorHandling; using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 diff --git a/OpenImis.RestApi/Controllers/V3/InsureeController.cs b/OpenImis.RestApi/Controllers/V3/InsureeController.cs index 9febbb05..d6e00336 100644 --- a/OpenImis.RestApi/Controllers/V3/InsureeController.cs +++ b/OpenImis.RestApi/Controllers/V3/InsureeController.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.InsureeModule.Models; -using OpenImis.RestApi.Util.ErrorHandling; using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 diff --git a/OpenImis.RestApi/Controllers/V3/MasterDataController.cs b/OpenImis.RestApi/Controllers/V3/MasterDataController.cs index 0ce539d8..ea2d109a 100644 --- a/OpenImis.RestApi/Controllers/V3/MasterDataController.cs +++ b/OpenImis.RestApi/Controllers/V3/MasterDataController.cs @@ -1,12 +1,10 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; using OpenImis.ModulesV3.MasterDataModule.Models; -using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 { @@ -48,7 +46,6 @@ public MasterDataController(IConfiguration configuration, IImisModules imisModul public IActionResult GetMasterData() { MasterDataModel masterData = _imisModules.GetMasterDataModule().GetMasterDataLogic().GetMasterData(); - return Ok(masterData); } } diff --git a/OpenImis.RestApi/Controllers/V3/PolicyRenewalController.cs b/OpenImis.RestApi/Controllers/V3/PolicyRenewalController.cs index b86d17f8..e847956c 100644 --- a/OpenImis.RestApi/Controllers/V3/PolicyRenewalController.cs +++ b/OpenImis.RestApi/Controllers/V3/PolicyRenewalController.cs @@ -7,9 +7,9 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.PolicyModule.Models; using OpenImis.ModulesV3.Utils; -using OpenImis.RestApi.Util.ErrorHandling; using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 diff --git a/OpenImis.RestApi/Controllers/V3/PremiumController.cs b/OpenImis.RestApi/Controllers/V3/PremiumController.cs index fcc41004..d5f2858e 100644 --- a/OpenImis.RestApi/Controllers/V3/PremiumController.cs +++ b/OpenImis.RestApi/Controllers/V3/PremiumController.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.PremiumModule.Models; -using OpenImis.RestApi.Util.ErrorHandling; using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 diff --git a/OpenImis.RestApi/Controllers/V3/ReportController.cs b/OpenImis.RestApi/Controllers/V3/ReportController.cs index 9ad79fde..59d0983e 100644 --- a/OpenImis.RestApi/Controllers/V3/ReportController.cs +++ b/OpenImis.RestApi/Controllers/V3/ReportController.cs @@ -5,9 +5,9 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OpenImis.ModulesV3; +using OpenImis.ModulesV3.Helpers; using OpenImis.ModulesV3.ReportModule.Models; using OpenImis.ModulesV3.Utils; -using OpenImis.RestApi.Util.ErrorHandling; using OpenImis.Security.Security; namespace OpenImis.RestApi.Controllers.V3 diff --git a/OpenImis.RestApi/Controllers/V3/SystemController.cs b/OpenImis.RestApi/Controllers/V3/SystemController.cs index 8aa0ff37..4df6d28a 100644 --- a/OpenImis.RestApi/Controllers/V3/SystemController.cs +++ b/OpenImis.RestApi/Controllers/V3/SystemController.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OpenImis.ModulesV2; diff --git a/OpenImis.RestApi/Startup.cs b/OpenImis.RestApi/Startup.cs index 5e6c9419..494d49b2 100644 --- a/OpenImis.RestApi/Startup.cs +++ b/OpenImis.RestApi/Startup.cs @@ -21,6 +21,7 @@ using OpenImis.ePayment.Scheduler; using OpenImis.RestApi.Scheduler; using OpenImis.RestApi.Util.ErrorHandling; +using OpenImis.ePayment.QueueSystem; // using OpenImis.ePayment.Formaters; namespace OpenImis.RestApi @@ -131,6 +132,10 @@ public void ConfigureServices(IServiceCollection services) services.AddSingleton(new JobMetaData(Guid.NewGuid(), typeof(MatchPaymentJob), jobName , cronExpression)); services.AddHostedService(); + // Queue system + services.AddHostedService(); + services.AddSingleton(); + } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) diff --git a/OpenImis.RestApi/Util/ErrorHandling/ErrorHandlerMiddleware.cs b/OpenImis.RestApi/Util/ErrorHandling/ErrorHandlerMiddleware.cs index 865b6675..be7dc92b 100644 --- a/OpenImis.RestApi/Util/ErrorHandling/ErrorHandlerMiddleware.cs +++ b/OpenImis.RestApi/Util/ErrorHandling/ErrorHandlerMiddleware.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using OpenImis.ModulesV3.Helpers; using System; using System.Net; using System.Threading.Tasks; diff --git a/OpenImis.RestApi/config/appsettings.Development.json.dist b/OpenImis.RestApi/config/appsettings.Development.json.dist index 7b536b9b..4ac1db76 100644 --- a/OpenImis.RestApi/config/appsettings.Development.json.dist +++ b/OpenImis.RestApi/config/appsettings.Development.json.dist @@ -2,6 +2,9 @@ "ConnectionStrings": { "IMISDatabase": "Server=Server;Database=IMIS;User ID=User;Password=Password" }, + "ConnectionSettings": { + "CommandTimeout": 30 + }, "Logging": { "IncludeScopes": false, "LogLevel": { diff --git a/OpenImis.RestApi/config/appsettings.Production.json.dist b/OpenImis.RestApi/config/appsettings.Production.json.dist index d269e844..d7cb8bf1 100644 --- a/OpenImis.RestApi/config/appsettings.Production.json.dist +++ b/OpenImis.RestApi/config/appsettings.Production.json.dist @@ -2,7 +2,9 @@ "ConnectionStrings": { "IMISDatabase": "Server=Server;Database=IMIS;User ID=User;Password=Password" }, - + "ConnectionSettings": { + "CommandTimeout": 30 + }, "Log4NetCore": { "PropertyOverrides": [ { diff --git a/OpenImis.ePayment/Data/ImisBasePayment.cs b/OpenImis.ePayment/Data/ImisBasePayment.cs index 9d16a9f2..761cf5a7 100644 --- a/OpenImis.ePayment/Data/ImisBasePayment.cs +++ b/OpenImis.ePayment/Data/ImisBasePayment.cs @@ -1003,7 +1003,7 @@ public virtual async Task ControlNumbersToBeRequested(string productCode) } - public virtual int CreatePremium(int paymentId) + public virtual int CreatePremium(int paymentId, string source, string sourceVersion) { return 0; } diff --git a/OpenImis.ePayment/Escape/Payment/Controllers/PaymentController.cs b/OpenImis.ePayment/Escape/Payment/Controllers/PaymentController.cs index 0b791b3d..75e59886 100644 --- a/OpenImis.ePayment/Escape/Payment/Controllers/PaymentController.cs +++ b/OpenImis.ePayment/Escape/Payment/Controllers/PaymentController.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json; using OpenImis.ePayment.Responses; using Microsoft.Extensions.Logging; +using OpenImis.ePayment.QueueSystem; namespace OpenImis.ePayment.Controllers { @@ -30,12 +31,14 @@ public class PaymentController : PaymentBaseController { private ImisPayment imisPayment; private IHostingEnvironment env; + private readonly BackgroundWorkerQueue _backgroundWorkerQueue; private readonly GepgFileRequestLogger _gepgFileLogger; private readonly ILogger _logger; - public PaymentController(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory) : base(configuration, hostingEnvironment, loggerFactory) + public PaymentController(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory, BackgroundWorkerQueue backgroundWorkerQueue) : base(configuration, hostingEnvironment, loggerFactory) { env = hostingEnvironment; + _backgroundWorkerQueue = backgroundWorkerQueue; imisPayment = new ImisPayment(configuration, hostingEnvironment, loggerFactory); _gepgFileLogger = new GepgFileRequestLogger(hostingEnvironment, loggerFactory); _logger = loggerFactory.CreateLogger(); @@ -97,12 +100,12 @@ public override async Task CHFRequestControlNumberForSimplePolicy [Route("api/GetReqControlNumber")] public async Task GePGReceiveControlNumber([FromBody] gepgBillSubResp model) { + if (!ModelState.IsValid) + return BadRequest(imisPayment.ControlNumberResp(GepgCodeResponses.GepgResponseCodes["Invalid Request Data"])); + int billId; if (model.HasValidSignature) { - if (!ModelState.IsValid) - return BadRequest(imisPayment.ControlNumberResp(GepgCodeResponses.GepgResponseCodes["Invalid Request Data"])); - ControlNumberResp ControlNumberResponse; foreach (var bill in model.BillTrxInf) { @@ -281,8 +284,13 @@ public async Task GetPaymentChf([FromBody] gepgPmtSpInfo model) string reconc = JsonConvert.SerializeObject(_response); _gepgFileLogger.Log(billId, "Payment", reconc); - - _response = await base.GetPaymentData(pay); + + + _backgroundWorkerQueue.QueueBackgroundWorkerItem(async token => + { + await base.GetPaymentData(pay); + }); + // _response = await base.GetPaymentData(pay); } diff --git a/OpenImis.ePayment/Escape/Payment/Data/ImisPayment.cs b/OpenImis.ePayment/Escape/Payment/Data/ImisPayment.cs index 23848fb7..e01e9575 100644 --- a/OpenImis.ePayment/Escape/Payment/Data/ImisPayment.cs +++ b/OpenImis.ePayment/Escape/Payment/Data/ImisPayment.cs @@ -589,7 +589,7 @@ SELECT CASE WHEN Last3MonthsEnrollment > ControlNumbersLeft THEN Last3MonthsEnro return await Task.FromResult(needToRequest); } - public override int CreatePremium(int paymentId) + public override int CreatePremium(int paymentId, string source = "unknown", string sourceVersion = "1") { var sSQL = @"IF EXISTS(SELECT 1 FROM tblInsuree I @@ -601,11 +601,9 @@ AND P.ReceivedAmount > 0 AND I.ValidityTo IS NULL AND PD.ValidityTo IS NULL) BEGIN - DECLARE @tblPremiums TABLE(PremiumId INT, PolicyId INT, PayDate DATETIME) - - INSERT INTO tblPremium(PolicyID, PayerID, Amount, Receipt, PayDate, PayType, ValidityFrom, AuditUserID, isOffline, isPhotoFee) - OUTPUT inserted.PremiumID, inserted.PolicyID, inserted.PayDate INTO @tblPremiums(PremiumId, PolicyId, PayDate) - SELECT PL.PolicyID, NULL PayerId, P.ReceivedAmount Amount, P.ReceiptNo Receipt, P.PaymentDate PayDate, N'M' PayType, GETDATE() ValidityFrom, -1 AuditUserId, 0 IsOffline, 0 IsPhotoFee + + INSERT INTO tblPremium(PolicyID, PayerID, Amount, Receipt, PayDate, PayType, ValidityFrom, AuditUserID, isOffline, isPhotoFee, Source, SourceVersion) + SELECT PL.PolicyID, NULL PayerId, P.ReceivedAmount Amount, P.ReceiptNo Receipt, P.PaymentDate PayDate, N'M' PayType, GETDATE() ValidityFrom, -1 AuditUserId, 0 IsOffline, 0 IsPhotoFee, @Source, @SourceVersion FROM tblControlNumber CN INNER JOIN tblPayment P ON CN.PaymentID = P.PaymentID INNER JOIN tblPaymentDetails PD ON P.PaymentID = PD.PaymentID @@ -630,32 +628,33 @@ DECLARE @TotalPremium DECIMAL(18, 2), @PolicyValue DECIMAL(18, 2), @PremiumId INT = 0; - SELECT TOP 1 @PremiumId = PremiumID FROM @tblPremiums; + SELECT @PremiumId = SCOPE_IDENTITY(); SELECT @TotalPremium = SUM(PR.Amount) OVER(ORDER BY Pr.Amount), @PolicyValue = PL.PolicyValue FROM tblPremium PR - INNER JOIN @tblPremiums dt ON PR.PolicyID = dt.PolicyID INNER JOIN tblPolicy PL ON PR.PolicyID = PL.PolicyID WHERE PR.ValidityTo IS NULL AND PL.ValidityTo IS NULL + AND PR.PremiumId = @PremiumId; IF @TotalPremium >= @PolicyValue BEGIN - UPDATE PL SET PolicyStatus = 2, EffectiveDate = dt.PayDate + UPDATE PL SET PolicyStatus = 2, EffectiveDate = PR.PayDate FROM tblPolicy PL - INNER JOIN @tblPremiums dt ON PL.PolicyID = dt.PolicyId - WHERE PL.ValidityTo IS NULL; + INNER JOIN tblPremium PR ON PL.PolicyID = PR.PolicyId + WHERE PL.ValidityTo IS NULL + AND PR.PremiumId = @PremiumId; UPDATE InsPol SET EffectiveDate = PL.EffectiveDate FROM tblPolicy PL - INNER JOIN @tblPremiums dt ON PL.PolicyID = dt.PolicyId + INNER JOIN tblPremium PR ON PL.PolicyID = PR.PolicyId INNER JOIN tblInsuree I ON PL.FamilyID = I.FamilyID INNER JOIN tblInsureePolicy InsPol ON PL.PolicyId = InsPol.PolicyId AND I.InsureeId = InsPol.InsureeId WHERE PL.ValidityTo IS NULL AND I.ValidityTo IS NULL - AND InsPol.ValidityTo IS NULL; - + AND InsPol.ValidityTo IS NULL + AND PR.PremiumId = @PremiumId; UPDATE PD @@ -670,14 +669,16 @@ UPDATE tblPayment END - SELECT PremiumId FROM @tblPremiums + SELECT @PremiumId PremiumId; END"; var dh = new DataHelper(config); SqlParameter[] parameters = { - new SqlParameter("@PaymentId", paymentId) + new SqlParameter("@PaymentId", paymentId), + new SqlParameter("@Source", source){DbType = DbType.String, Size =50}, + new SqlParameter("@SourceVersion", sourceVersion){DbType = DbType.String, Size =15} }; var dt = dh.GetDataTable(sSQL, parameters, CommandType.Text); diff --git a/OpenImis.ePayment/Logic/PaymentLogic.cs b/OpenImis.ePayment/Logic/PaymentLogic.cs index 47fa9ac0..57facc73 100644 --- a/OpenImis.ePayment/Logic/PaymentLogic.cs +++ b/OpenImis.ePayment/Logic/PaymentLogic.cs @@ -163,7 +163,7 @@ public async Task SavePayment(PaymentData model) { if (_configuration.GetValue("PaymentGateWay:CreatePremiumOnPaymentReceived") & response.Code == 0) - CreatePremium(payment.PaymentId); + CreatePremium(payment.PaymentId, "GePG", "1"); SendPaymentConfirmationSms(model, payment); } @@ -603,10 +603,10 @@ public async Task ControlNumbersToBeRequested(string productCode) return await imisPayment.ControlNumbersToBeRequested(productCode); } - public int CreatePremium(int paymentId) + public int CreatePremium(int paymentId, string source, string sourceVersion) { var imisPayment = new ImisPayment(_configuration, _hostingEnvironment, _loggerFactory); - return imisPayment.CreatePremium(paymentId); + return imisPayment.CreatePremium(paymentId, source, sourceVersion); } public async Task HandleControlNumbersToBeRequested(string productCode) diff --git a/OpenImis.ePayment/QueueSystem/BackgroundWorkerQueue.cs b/OpenImis.ePayment/QueueSystem/BackgroundWorkerQueue.cs new file mode 100644 index 00000000..487f8401 --- /dev/null +++ b/OpenImis.ePayment/QueueSystem/BackgroundWorkerQueue.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenImis.ePayment.QueueSystem +{ + public class BackgroundWorkerQueue + { + private ConcurrentQueue> _workItems = new ConcurrentQueue>(); + private SemaphoreSlim _signal = new SemaphoreSlim(0); + + public async Task> DequeueAsync(CancellationToken cancellationToken) + { + await _signal.WaitAsync(cancellationToken); + _workItems.TryDequeue(out var workItem); + + return workItem; + } + + public void QueueBackgroundWorkerItem(Func workItem) + { + if (workItem == null) + { + throw new ArgumentNullException(nameof(workItem)); + } + + _workItems.Enqueue(workItem); + _signal.Release(); + } + } +} diff --git a/OpenImis.ePayment/QueueSystem/LongRunningServices.cs b/OpenImis.ePayment/QueueSystem/LongRunningServices.cs new file mode 100644 index 00000000..900c3c37 --- /dev/null +++ b/OpenImis.ePayment/QueueSystem/LongRunningServices.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Hosting; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenImis.ePayment.QueueSystem +{ + public class LongRunningServices : BackgroundService + { + private readonly BackgroundWorkerQueue _queue; + + public LongRunningServices(BackgroundWorkerQueue queue) + { + _queue = queue; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + var workItem = await _queue.DequeueAsync(stoppingToken); + await workItem(stoppingToken); + } + } + } +} diff --git a/README.md b/README.md index e5876982..d2f8f4b1 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ dotnet build ``` Before running the application, you need to change the connection string to connect to the -database in the [appsettings.Development.json](./OpenImis.RestApi/appsettings.Development.json) file within [OpenImis.RestApi](./OpenImis.RestApi) folder. +database in the [appsettings.Development.json.dist](./OpenImis.RestApi/config/appsettings.Development.json.dist) file within [OpenImis.RestApi.config](./OpenImis.RestApi/config) folder. File name should be changed to `appsettings.Development.json` (`.dist` extension removed). ``` "ConnectionStrings":{"IMISDatabase":"Server=Server;Database=IMIS;User ID=User;Password=Password"}