Commit 1bd0daac authored by Krishna Reddy Tamatam's avatar Krishna Reddy Tamatam

For release v3,0

parent b428c842
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading.Tasks;
using FluentFTP;
using FTP_Services.Core.Models;
using FTP_Services.Services;
using iTextSharp.text.pdf;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using FluentFtpClient = FluentFTP.FtpClient;
namespace FTP_Services.Services.Controllers
{
......@@ -60,14 +65,28 @@ namespace FTP_Services.Services.Controllers
}
[HttpGet("GetSearchedHistoryPatients")]
public IActionResult GetSearchedHistoryPatients(string SearchText, int ProviderId, int LocationId, int DateType, string StartDate, string EndDate)
public IActionResult GetSearchedHistoryPatients(
string SearchText,
int ProviderId,
int LocationId,
int DateType,
string StartDate,
string EndDate
)
{
log.Debug("GetSearchedPatients ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// List<SearchPatients>? RequestsList = adapter.SearchedPatientsData(SearchText);
List<object>? RequestsList = adapter.SearchedPatientsHistoryData(SearchText, ProviderId, LocationId, DateType, StartDate, EndDate);
List<object>? RequestsList = adapter.SearchedPatientsHistoryData(
SearchText,
ProviderId,
LocationId,
DateType,
StartDate,
EndDate
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -78,14 +97,30 @@ namespace FTP_Services.Services.Controllers
}
[HttpGet("GetSearchedPatients")]
public IActionResult GetSearchedPatients(string SearchText, int ProviderId, int LocationId, int DateType, string StartDate, string EndDate, int DischType)
public IActionResult GetSearchedPatients(
string SearchText,
int ProviderId,
int LocationId,
int DateType,
string StartDate,
string EndDate,
int DischType
)
{
log.Debug("GetSearchedPatients ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// List<SearchPatients>? RequestsList = adapter.SearchedPatientsData(SearchText);
List<object>? RequestsList = adapter.SearchedPatientsData(SearchText, ProviderId, LocationId, DateType, StartDate, EndDate, DischType);
List<object>? RequestsList = adapter.SearchedPatientsData(
SearchText,
ProviderId,
LocationId,
DateType,
StartDate,
EndDate,
DischType
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -96,13 +131,29 @@ namespace FTP_Services.Services.Controllers
}
[HttpGet("GetAdmissionDataHistory")]
public IActionResult GetAdmissionDataHistory(int PatientID, int LocationID, int ProviderID, int DateType, string StartDate, string EndDate, int RecType)
public IActionResult GetAdmissionDataHistory(
int PatientID,
int LocationID,
int ProviderID,
int DateType,
string StartDate,
string EndDate,
int RecType
)
{
log.Debug("GetAdmissionDataHistory ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetAdmissionDataHistory(PatientID, LocationID, ProviderID, DateType, StartDate, EndDate, RecType);
List<object>? RequestsList = adapter.GetAdmissionDataHistory(
PatientID,
LocationID,
ProviderID,
DateType,
StartDate,
EndDate,
RecType
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -113,13 +164,29 @@ namespace FTP_Services.Services.Controllers
}
[HttpGet("GetAdmissionData")]
public IActionResult GetAdmissionData(int PatientID, int LocationID, int ProviderID, int DateType, string StartDate, string EndDate, int DischType)
public IActionResult GetAdmissionData(
int PatientID,
int LocationID,
int ProviderID,
int DateType,
string StartDate,
string EndDate,
int DischType
)
{
log.Debug("GetAdmissionData ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetAdmissionData(PatientID, LocationID, ProviderID, DateType, StartDate, EndDate, DischType);
List<object>? RequestsList = adapter.GetAdmissionData(
PatientID,
LocationID,
ProviderID,
DateType,
StartDate,
EndDate,
DischType
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -162,14 +229,15 @@ namespace FTP_Services.Services.Controllers
return NotFound("No results");
}
}
[HttpGet("GetLocations")]
public IActionResult GetLocations(Boolean IsLoadAll, int RecType) //int LocationId,
public IActionResult GetLocations(Boolean IsLoadAll, int RecType) //int LocationId,
{
log.Debug("GetLocations ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.LoadLocations(IsLoadAll, RecType);//LocationId,
List<object>? RequestsList = adapter.LoadLocations(IsLoadAll, RecType); //LocationId,
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -277,15 +345,14 @@ namespace FTP_Services.Services.Controllers
}
}
[HttpGet("LoadDocumentTypes")]
public IActionResult LoadDocumentTypes()
public IActionResult LoadDocumentTypes(int Type)
{
log.Debug("LoadDocumentTypes ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.LoadDocumentTypes();
List<object>? RequestsList = adapter.LoadDocumentTypes(Type);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -298,10 +365,10 @@ namespace FTP_Services.Services.Controllers
[HttpGet("GetConfigValues")]
public IActionResult GetConfigValues(int CompanyId)
{
string DatabaseName = _appSettings.ConnectionString;
log.Debug("GetConfigValues ==> ");
try
{
string DatabaseName = _appSettings.ConnectionString;
_appSettings.ConnectionString = _appSettings.AdminConnectionString;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.ConfigValues(CompanyId, DatabaseName);
......@@ -310,6 +377,7 @@ namespace FTP_Services.Services.Controllers
}
catch (Exception ex)
{
_appSettings.ConnectionString = DatabaseName;
log.Error("Fail to get data for GetConfigValues - Error:" + ex.Message);
return NotFound("No results");
}
......@@ -333,13 +401,31 @@ namespace FTP_Services.Services.Controllers
}
[HttpGet("GetPatientDocuments")]
public IActionResult GetPatientDocuments(int SPatientID, int SLocationID, int SAppointmentID, int SAdmissionID, int SDocID, int RecType, string SDueFrom, string SDueTO)
public IActionResult GetPatientDocuments(
int SPatientID,
int SLocationID,
int SAppointmentID,
int SAdmissionID,
int SDocID,
int RecType,
string SDueFrom,
string SDueTO
)
{
log.Debug("GetPatientDocuments ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.PatientDocuments(SPatientID, SLocationID, SAppointmentID, SAdmissionID, SDocID,RecType, SDueFrom, SDueTO);
List<object>? RequestsList = adapter.PatientDocuments(
SPatientID,
SLocationID,
SAppointmentID,
SAdmissionID,
SDocID,
RecType,
SDueFrom,
SDueTO
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -348,6 +434,7 @@ namespace FTP_Services.Services.Controllers
return NotFound("No results");
}
}
[HttpGet("GetDocumentYears")]
public IActionResult GetDocumentYears(int Parm_DType)
{
......@@ -389,7 +476,10 @@ namespace FTP_Services.Services.Controllers
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.AdmissionDischargeData(SndAdmissionID, SndRecType);
List<object>? RequestsList = adapter.AdmissionDischargeData(
SndAdmissionID,
SndRecType
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -399,20 +489,26 @@ namespace FTP_Services.Services.Controllers
}
}
[HttpPost("UpdateImageCategory")]
public int UpdateImageCategory(int sndPatDocId, int sndDocTypeId, int sndUserID)
{
int savedCount = 0;
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
savedCount = adapter.UpdateImageCategory(sndPatDocId, sndDocTypeId, sndUserID);
_appSettings.ConnectionString = DatabaseName;
}
catch (Exception ex)
{
log.Error("UpdateImageCategory -> Failed to save documents - Error: " + ex.Message);
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
return savedCount;
}
......@@ -420,8 +516,10 @@ namespace FTP_Services.Services.Controllers
public int UpdateImageSortNo([FromBody] PatientImgDocSort PatImgDoc)
{
int savedCount = 0;
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
savedCount = adapter.UpdateImageSortNo(PatImgDoc);
}
......@@ -429,36 +527,81 @@ namespace FTP_Services.Services.Controllers
{
log.Error("UpdateImageSortNo -> Failed to save documents - Error: " + ex.Message);
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
return savedCount;
}
[HttpPost("SavePatientDocument")]
public int SavePatientDocumentData([FromBody] List<PatientDocumentDetailsModel> models)
public IActionResult SavePatientDocument([FromBody] PatientDocumentRequest models)
{
log.Debug("SaveMultiplePatientDocuments ==> Received " + models.Count + " records.");
int savedCount = 0;
string DatabaseName = _appSettings.ConnectionString;
try
{
if (models == null || models.Count == 0)
{
log.Warn("SaveMultiplePatientDocuments => No data received.");
return 0;
}
string Parm_PatDoc = JsonConvert.SerializeObject(models);
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
savedCount = adapter.SavePatientDocumentData(models);
int savedCount = adapter.SavePatientDocumentData(Parm_PatDoc);
log.Info(
$"SavePatientDocument => Successfully saved {savedCount} records."
);
_appSettings.ConnectionString = DatabaseName;
return Ok(savedCount);
}
catch (Exception ex)
{
log.Error("SaveMultiplePatientDocuments -> Failed to save documents - Error: " + ex.Message);
log.Error("SavePatientDocument -> Failed to save data - " + ex.Message);
return StatusCode(500, "Internal server error");
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
return savedCount;
}
// [HttpPost("SavePatientDocument1")]
// public int SavePatientDocumentData([FromBody] List<PatientDocumentDetailsModel> models)
// {
// log.Debug("SaveMultiplePatientDocuments ==> Received " + models.Count + " records.");
// int savedCount = 0;
// string DatabaseName = _appSettings.ConnectionString;
// try
// {
// _appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
// if (models == null || models.Count == 0)
// {
// log.Warn("SaveMultiplePatientDocuments => No data received.");
// return 0;
// }
// FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// savedCount = adapter.SavePatientDocumentData(models);
// _appSettings.ConnectionString = DatabaseName;
// }
// catch (Exception ex)
// {
// log.Error(
// "SaveMultiplePatientDocuments -> Failed to save documents - Error: "
// + ex.Message
// );
// }
// finally
// {
// _appSettings.ConnectionString = DatabaseName;
// }
// return savedCount;
// }
[HttpPost("SaveAdmissionDischargeData")]
public IActionResult SaveAdmissionDischargeData([FromBody] List<AdmissionDischargeModel> models)
public IActionResult SaveAdmissionDischargeData(
[FromBody] List<AdmissionDischargeModel> models
)
{
string DatabaseName = _appSettings.ConnectionString;
if (models == null || models.Count == 0)
{
log.Warn("SaveAdmissionDischargeData => No data received.");
......@@ -469,10 +612,11 @@ namespace FTP_Services.Services.Controllers
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
int savedCount = adapter.SaveAdmissionDischargeData(models);
log.Info($"SaveAdmissionDischargeData => Successfully saved {savedCount} records.");
_appSettings.ConnectionString = DatabaseName;
return Ok(savedCount);
}
catch (Exception ex)
......@@ -480,8 +624,10 @@ namespace FTP_Services.Services.Controllers
log.Error("SaveAdmissionDischargeData -> Failed to save data - " + ex.Message);
return StatusCode(500, "Internal server error");
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
}
[HttpGet("GetUserLocations")]
......@@ -489,7 +635,7 @@ namespace FTP_Services.Services.Controllers
{
log.Debug("GetLocations ==> ");
try
{
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetUserLocations(sndUserName);
return Ok(RequestsList);
......@@ -517,6 +663,7 @@ namespace FTP_Services.Services.Controllers
return NotFound("No results");
}
}
[HttpGet("GetWards")]
public IActionResult GetWards(int sndLocationId)
{
......@@ -585,21 +732,37 @@ namespace FTP_Services.Services.Controllers
}
}
[HttpPost("DeletePatientDocument")]
public string DeletePatientDocument(int AdmissionId, int DocumentID, int UserID, int SndRecType)
public string DeletePatientDocument(
int AdmissionId,
int DocumentID,
int UserID,
int SndRecType
)
{
log.Debug("DeletePatientDocument ==> ");
string DeletePT = "";
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
DeletePT = adapter.DeletePatientDocumentData(AdmissionId, DocumentID, UserID, SndRecType);
DeletePT = adapter.DeletePatientDocumentData(
AdmissionId,
DocumentID,
UserID,
SndRecType
);
_appSettings.ConnectionString = DatabaseName;
}
catch (Exception ex)
{
log.Error("Fail to get data for delete patient documents - Error:" + ex.Message);
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
return DeletePT;
}
......@@ -632,7 +795,10 @@ namespace FTP_Services.Services.Controllers
byte[] buffer = new byte[1048576]; // 1 MB buffer
byte[] fileData = null;
string FTPURL = _appSettings.FTPConfiguration.FtpURL.ToString() + '/' + _appSettings.FTPConfiguration.DestinationPathFtp.ToString();
string FTPURL =
_appSettings.FTPConfiguration.FtpURL.ToString()
+ '/'
+ _appSettings.FTPConfiguration.DestinationPathFtp.ToString();
string FTPUserName = _appSettings.FTPConfiguration.Username.ToString();
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
......@@ -686,7 +852,9 @@ namespace FTP_Services.Services.Controllers
[HttpPost("DownloadBase64DataAsync_New")]
public IActionResult DownloadBase64DataAsync_New(string fileNameWithPath)
{
string strDestinationPath = _appSettings.FTPConfiguration.DestinationPathFile.ToString().Trim();
string strDestinationPath = _appSettings
.FTPConfiguration.DestinationPathFile.ToString()
.Trim();
string strMfN = fileNameWithPath.Replace("/", "\\").TrimStart('\\');
string strFullPath = Path.Combine(strDestinationPath, strMfN);
......@@ -697,7 +865,12 @@ namespace FTP_Services.Services.Controllers
try
{
var fileStream = new FileStream(strFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var fileStream = new FileStream(
strFullPath,
FileMode.Open,
FileAccess.Read,
FileShare.Read
);
var base64Stream = new Base64EncodingStream(fileStream);
return new FileStreamResult(base64Stream, "application/octet-stream")
{
......@@ -1386,13 +1559,12 @@ namespace FTP_Services.Services.Controllers
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
string strSourceFullPath = "";
string strBasePath = _appSettings
.FTPConfiguration.DestinationPathFtp.ToString()
.Trim();
.FTPConfiguration.DestinationPathFtp.ToString()
.Trim();
sourceFilePath = sourceFilePath.Replace("/", "\\").TrimStart('\\');
strSourceFullPath = Path.Combine(strBasePath, sourceFilePath);
FtpWebRequest ftp = (FtpWebRequest)
WebRequest.Create(FTPURL + strSourceFullPath);
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(FTPURL + strSourceFullPath);
ftp.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
......@@ -1509,7 +1681,6 @@ namespace FTP_Services.Services.Controllers
}
}
[HttpPost("MoveFileAsync")]
public async Task<string> MoveFileAsync(string sourceFilePath, string destinationFilePath)
{
......@@ -1595,13 +1766,29 @@ namespace FTP_Services.Services.Controllers
//----------------------------------------history function ----------------------------------------------------------
[HttpGet("CheckPatAdmExist")]
public IActionResult GetHist_CheckPatAdmExist(int Parm_PatientId, string Parm_OldUMRNo, string Parm_NewUMRNo, int Parm_AdmId, string Parm_OldIPNo, string Parm_NewIPNo, Boolean Parm_IsEdit)
public IActionResult GetHist_CheckPatAdmExist(
int Parm_PatientId,
string Parm_OldUMRNo,
string Parm_NewUMRNo,
int Parm_AdmId,
string Parm_OldIPNo,
string Parm_NewIPNo,
Boolean Parm_IsEdit
)
{
log.Debug("CheckPatAdmExist ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetHist_CheckPatAdmExist(Parm_PatientId, Parm_OldUMRNo, Parm_NewUMRNo, Parm_AdmId, Parm_OldIPNo, Parm_NewIPNo, Parm_IsEdit);
List<object>? RequestsList = adapter.GetHist_CheckPatAdmExist(
Parm_PatientId,
Parm_OldUMRNo,
Parm_NewUMRNo,
Parm_AdmId,
Parm_OldIPNo,
Parm_NewIPNo,
Parm_IsEdit
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -1615,8 +1802,10 @@ namespace FTP_Services.Services.Controllers
public IActionResult GetHistPatientData(int Parm_PatientId)
{
log.Debug("GetHistPatientData ==> ");
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetHist_PatientData(Parm_PatientId);
return Ok(RequestsList);
......@@ -1626,14 +1815,20 @@ namespace FTP_Services.Services.Controllers
log.Error("Fail to get data for GetHistPatientData - Error:" + ex.Message);
return NotFound("No results");
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
}
[HttpGet("GetHistAdmissionData")]
public IActionResult GetAdmissionHistoryData(int Parm_HistAdmId)
{
log.Debug("GetHistAdmissionData ==> ");
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetHist_AdmissIonData(Parm_HistAdmId);
return Ok(RequestsList);
......@@ -1643,16 +1838,28 @@ namespace FTP_Services.Services.Controllers
log.Error("Fail to get data for GetHistAdmissionData - Error:" + ex.Message);
return NotFound("No results");
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
}
[HttpGet("LoadLookupValues")]
public IActionResult LoadLookupValues(string Parm_LookupName, string Parm_WhereCond, Boolean Parm_ShowBlankRow)
public IActionResult LoadLookupValues(
string Parm_LookupName,
string Parm_WhereCond,
Boolean Parm_ShowBlankRow
)
{
log.Debug("LoadLookupValues ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.LoadLookupValues(Parm_LookupName, Parm_WhereCond, Parm_ShowBlankRow);
List<object>? RequestsList = adapter.LoadLookupValues(
Parm_LookupName,
Parm_WhereCond,
Parm_ShowBlankRow
);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -1662,16 +1869,20 @@ namespace FTP_Services.Services.Controllers
}
}
[HttpPost("SaveHistAdmissionDischargeData")]
public IActionResult SaveHistAdmissionDischargeData([FromBody] string Parm_AdmData)
{
string DatabaseName = _appSettings.ConnectionString;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
int savedCount = adapter.SaveHistoryOfAdmissionDischargeData(Parm_AdmData);
log.Info($"SaveHistAdmissionDischargeData => Successfully saved {savedCount} records.");
log.Info(
$"SaveHistAdmissionDischargeData => Successfully saved {savedCount} records."
);
_appSettings.ConnectionString = DatabaseName;
return Ok(savedCount);
}
catch (Exception ex)
......@@ -1679,46 +1890,1002 @@ namespace FTP_Services.Services.Controllers
log.Error("SaveHistAdmissionDischargeData -> Failed to save data - " + ex.Message);
return StatusCode(500, "Internal server error");
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
}
[HttpPost("ExecuteNonQuery")]
public string ExecuteNonQuery([FromBody] string jsonSql)
{
if (string.IsNullOrWhiteSpace(jsonSql))
string DatabaseName = _appSettings.ConnectionString;
try
{
log.Error("Request string is null or empty.");
return "Request string is null or empty.";
}
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
if (string.IsNullOrWhiteSpace(jsonSql))
{
log.Error("Request string is null or empty.");
return "Request string is null or empty.";
}
return new FTPDataAdapter(_appSettings).ExecuteNonQuery(jsonSql);
return new FTPDataAdapter(_appSettings).ExecuteNonQuery(jsonSql);
}
catch (Exception ex)
{
log.Error("SaveHistAdmissionDischargeData -> Failed to save data - " + ex.Message);
return "";
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
}
[HttpPost("SaveHistoryPatient")]
public int SaveHistoryPatient([FromBody] string Parm_PatientData)//string Parm_PatientData
public int SaveHistoryPatient([FromBody] string Parm_PatientData) //string Parm_PatientData
{
string DatabaseName = _appSettings.ConnectionString;
int savedCount = 0;
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
savedCount = adapter.SaveHistoryOfPatient(Parm_PatientData);
_appSettings.ConnectionString = DatabaseName;
}
catch (Exception ex)
{
log.Error("SaveHistoryPatient -> Failed to save documents - Error: " + ex.Message);
}
finally
{
_appSettings.ConnectionString = DatabaseName;
}
return savedCount;
}
//-------------------------------------------------------------------------Send Mail ----------------------------------------------------------------------------
private async Task<string> EmailBodyBuilding(string sourceFilePath)
{
try
{
return "";
}
catch (WebException ex)
{
return "Error deleting file: " + ex.Message.ToString();
}
}
[HttpPost("SendEmail")]
public async Task<ActionResult> SendEmail([FromBody] EmailModel model)
{
try
{
string smtpServer = "smtp.gmail.com";
int smtpPort = 587;
string senderEmail = "himsithelpdesk@gmail.com";
string senderPassword = "twevdeadvwpzjakv";
// Pick name based on who is sending
string senderDisplayName = model.StatusCode == "R"
? $"{model.UserName} (Rejected by MRD)"
: $"{model.ApprovedBy ?? model.UserName} (MRD Department)";
using (var smtp = new SmtpClient(smtpServer, smtpPort))
{
smtp.Credentials = new NetworkCredential(senderEmail, senderPassword);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
using (var message = new MailMessage())
{
message.From = new MailAddress(senderEmail, senderDisplayName);
message.Subject = string.IsNullOrEmpty(model.Subject)
? (model.StatusCode == "A" ? "MRD Request Approved" : "MRD Request Rejected")
: model.Subject;
message.Body = model.Body;
message.IsBodyHtml = true;
// Add multiple recipients
if (!string.IsNullOrEmpty(model.Email))
{
foreach (var email in model.Email.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
message.To.Add(email.Trim());
}
}
// Optional tracking emails
// message.CC.Add("mrdteam@hospitaldomain.com");
// message.Bcc.Add("auditlogs@hospitaldomain.com");
await smtp.SendMailAsync(message);
}
}
return Ok("Email sent successfully!");
}
catch (Exception ex)
{
return BadRequest($"Error sending email: {ex.Message}");
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------------
// [HttpGet("AcknowldgeMRDRequest_v1")]
// public IActionResult AcknowldgeMRDRequest_v1(int Parm_ACKType, int Parm_AccessId, string Parm_ApprovedBy, String Parm_RequestType) //,DateTime Parm_ApprovedFromDate,DateTime Parm_ApprovedToDate
// {
// string databaseName = _appSettings.ConnectionString;
// int savedCount = 0;
// string html = "";
// try
// {
// string strBody = "";
// string strSubject = "";
// string strStatusCode = Parm_ACKType == 1 ? "A" : "D";
// _appSettings.ConnectionString = _appSettings.ConnectionString_106;
// FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// savedCount = adapter.AcknowldgeMRDRequest(Parm_ACKType, Parm_AccessId, Parm_ApprovedBy); //Parm_ApprovedFromDate,Parm_ApprovedToDate,
// if (savedCount > 0)
// {
// if (Parm_ACKType == 1)
// {
// html = HtmlTemplates.GetApprovedHtml("Request approved successfully.");//GetApprovedHtml("Request approved successfully.");//HtmlTemplates.GetApprovedHtml("Request approved successfully.");//GetApprovedHtml("Request approved successfully.");//
// //SendEmail ()
// }
// else if (Parm_ACKType == 2)
// {
// html = HtmlTemplates.GetRejectedHtml("Request rejected successfully.");//GetRejectedHtml("Request rejected successfully.");
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("Unknown request type.");//GetFailedHtml("Unknown request type.");
// }
// }
// else if (savedCount == -1)
// {
// html = HtmlTemplates.GetinformationHtml("MRDRequest Acknowldgement already done....."); //GetFailedHtml("Unknown request type.");
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("MRDRequest Acknowldgement failed. No record updated."); //GetFailedHtml("Unknown request type.");
// }
// }
// catch (Exception ex)
// {
// log.Error("AcknowldgeMRDRequest -> Error: " + ex);
// html = HtmlTemplates.GetFailedHtml("Error occurred: " + System.Net.WebUtility.HtmlEncode(ex.Message));
// }
// finally
// {
// _appSettings.ConnectionString = databaseName;
// }
// return Content(html, "text/html");
// }
// [HttpGet("AcknowldgeMRDRequest")]
// public async Task<IActionResult> AcknowldgeMRDRequest(int MrdAccessId, string UniqueId, int AckType, string AcknowledgedBy)
// {
// string databaseName = _appSettings.ConnectionString;
// int savedCount = 0;
// string html = "";
// try
// {
// _appSettings.ConnectionString = _appSettings.ConnectionString_158;
// FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// // Step 1: Update acknowledgement using existing logic
// savedCount = adapter.AcknowldgeMRDRequest(
// MrdAccessId,
// UniqueId,
// AckType,
// AcknowledgedBy //DecodeBase64UrlToUtf8
// );
// // Step 2: If update successful → fetch stored email body from DB
// if (savedCount > 0)
// {
// var ackInfo = adapter.AcknowldgeReqInfo(
// MrdAccessId,
// UniqueId,
// AckType,
// AcknowledgedBy//DecodeBase64UrlToUtf8()
// );
// if (ackInfo == null)
// {
// html = HtmlTemplates.GetFailedHtml("No acknowledgement info found for this UniqueId.");
// return Content(html, "text/html");
// }
// string decodedBody = "";
// string subject = "";
// // Step 3: Approve or Reject Logic
// if (AckType == 1)
// {
// html = HtmlTemplates.GetApprovedHtml("Request approved successfully.");
// decodedBody = ackInfo.ApprovedEmailBody; //DecodeBase64UrlToUtf8();
// subject = "Your MRD Request has been Approved";
// // Step 4: Build model for SendEmail
// var emailModel = new EmailModel
// {
// Email = ackInfo.RequestedEmail,
// Subject = subject,
// Body = decodedBody,
// UserName = AcknowledgedBy, //DecodeBase64UrlToUtf8()
// StatusCode = "A",
// ApprovedBy = AcknowledgedBy //DecodeBase64UrlToUtf8()
// };
// // Step 5: Reuse existing SendEmail method
// await SendEmail(emailModel);
// }
// else if (AckType == 2)
// {
// html = HtmlTemplates.GetRejectedHtml("Request rejected successfully.");
// decodedBody = ackInfo.RejectedEmailBody; //DecodeBase64UrlToUtf8();
// subject = "Your MRD Request has been Rejected";
// var emailModel = new EmailModel
// {
// Email = ackInfo.RequestedEmail,
// Subject = subject,
// Body = decodedBody,
// UserName = AcknowledgedBy,
// StatusCode = "D",
// ApprovedBy = AcknowledgedBy
// };
// await SendEmail(emailModel);
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("Unknown request type.");
// }
// }
// else if (savedCount == -1)
// {
// html = HtmlTemplates.GetinformationHtml("MRD Request Acknowledgement already done.");
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("MRD Request Acknowledgement failed. No record updated.");
// }
// }
// catch (Exception ex)
// {
// log.Error("AcknowldgeMRDRequest -> Error: " + ex.Message);
// html = HtmlTemplates.GetFailedHtml("Error occurred: " + System.Net.WebUtility.HtmlEncode(ex.Message));
// }
// finally
// {
// _appSettings.ConnectionString = databaseName;
// }
// return Content(html, "text/html");
// }
private static string DecodeBase64UrlToUtf8(string base64Url)
{
if (string.IsNullOrEmpty(base64Url)) return "";
string s = base64Url.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2: s += "=="; break;
case 3: s += "="; break;
}
var bytes = Convert.FromBase64String(s);
return System.Text.Encoding.UTF8.GetString(bytes);
}
// [HttpGet("AcknowldgeMRDRequest")]
// public async Task<IActionResult> AcknowldgeMRDRequest(
// int MrdAccessId, string UniqueId, int AckType, string AcknowledgedBy)
// {
// string databaseName = _appSettings.ConnectionString;
// int savedCount = 0;
// string html = "";
// try
// {
// _appSettings.ConnectionString = _appSettings.ConnectionString_Staging;
// FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// AcknowledgedBy = SafeDecodeBase64(AcknowledgedBy).Trim('"').Trim();
// // STEP 1: Update acknowledgement record (approve/reject)
// savedCount = adapter.AcknowldgeMRDRequest(
// MrdAccessId,
// UniqueId,
// AckType,
// AcknowledgedBy
// );
// // STEP 2: If update successful → get stored email body from DB
// if (savedCount > 0)
// {
// var ackInfo = adapter.AcknowldgeReqInfo(
// MrdAccessId,
// UniqueId,
// AckType,
// AcknowledgedBy
// );
// if (ackInfo == null)
// {
// html = HtmlTemplates.GetFailedHtml("No acknowledgement info found for this UniqueId.");
// return Content(html, "text/html");
// }
// string decodedBody = "";
// string subject = "";
// // STEP 3: Build email content dynamically
// if (AckType == 1) // APPROVE
// {
// html = HtmlTemplates.GetApprovedHtml("Request approved successfully.");
// decodedBody = SafeDecodeBase64(ackInfo.ApprovedEmailBody)
// .Replace("\\n", "")
// .Replace("\n", "")
// .Trim('"').Trim();
// subject = "Access to MRD Report for All Patients";
// var emailModel = new EmailModel
// {
// Email = ackInfo.RequestedEmail,
// Subject = subject,
// Body = decodedBody,//.Replace("$@AcknowledgedBy@$",),
// UserName = AcknowledgedBy,
// StatusCode = "A",
// ApprovedBy = AcknowledgedBy
// };
// await SendEmail(emailModel);
// }
// else if (AckType == 2) // REJECT
// {
// html = HtmlTemplates.GetRejectedHtml("Request rejected successfully.");
// decodedBody = SafeDecodeBase64(ackInfo.RejectedEmailBody)
// .Replace("\\n", "")
// .Replace("\n", "")
// .Trim();
// subject = "MRD Request Rejected for All Patients";
// var emailModel = new EmailModel
// {
// Email = ackInfo.RequestedEmail,
// Subject = subject,
// Body = decodedBody,
// UserName = AcknowledgedBy,
// StatusCode = "D",
// ApprovedBy = AcknowledgedBy
// };
// await SendEmail(emailModel);
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("Unknown request type.");
// }
// }
// else if (savedCount == -1)
// {
// html = HtmlTemplates.GetinformationHtml("MRD Request Acknowledgement already done.");
// }
// else
// {
// html = HtmlTemplates.GetFailedHtml("MRD Request Acknowledgement failed. No record updated.");
// }
// }
// catch (Exception ex)
// {
// log.Error("AcknowldgeMRDRequest -> Error: " + ex.Message);
// html = HtmlTemplates.GetFailedHtml("Error occurred: " + System.Net.WebUtility.HtmlEncode(ex.Message));
// }
// finally
// {
// _appSettings.ConnectionString = databaseName;
// }
// return Content(html, "text/html");
// }
// // Safe decode method — decodes only if Base64
// private static string SafeDecodeBase64(string value)
// {
// if (string.IsNullOrWhiteSpace(value))
// return "";
// // Check if the string looks like Base64
// if (!System.Text.RegularExpressions.Regex.IsMatch(value, @"^[A-Za-z0-9\-_+/=]+$"))
// return value; // Already plain HTML → return directly
// try
// {
// string s = value.Replace('-', '+').Replace('_', '/');
// switch (s.Length % 4)
// {
// case 2: s += "=="; break;
// case 3: s += "="; break;
// }
// var bytes = Convert.FromBase64String(s);
// return System.Text.Encoding.UTF8.GetString(bytes);
// }
// catch
// {
// return value; // fallback if not valid Base64
// }
// }
[HttpGet("GetFileCountByAdmId")]
public async Task<IActionResult> GetFileCountByAdmId(int PatientId, int AdmissionId, int DocumentTypeId, int RecTypeId, int AppointmentId)
{
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
//List<object>? FileCountlist = adapter.GetFileCountByAdmId(PatientId,AdmissionId,DocumentTypeId,RecTypeId,AppointmentId);
int FileCount = adapter.GetFileCountByAdmId(PatientId,AdmissionId,DocumentTypeId,RecTypeId,AppointmentId);
return Ok(FileCount);
}
catch (Exception ex)
{
log.Error("Fail to get data for LoadLookupValues - Error:" + ex.Message);
return NotFound("No results");
}
finally
{
}
}
[HttpGet("AcknowldgeMRDRequest")]
public async Task<IActionResult> AcknowldgeMRDRequest(
int MrdAccessId, string UniqueId, int AckType, string AcknowledgedBy)
{
string databaseName = _appSettings.ConnectionString;
int savedCount = 0;
string html = "";
try
{
_appSettings.ConnectionString = _appSettings.ConnectionString;
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
AcknowledgedBy = SafeDecodeBase64(AcknowledgedBy).Trim('"').Trim();
// STEP 1: Update acknowledgement record (approve/reject)
savedCount = adapter.AcknowldgeMRDRequest(
MrdAccessId,
UniqueId,
AckType,
AcknowledgedBy
);
// STEP 2: If update successful → get stored email body from DB
if (savedCount > 0)
{
var ackInfo = adapter.AcknowldgeReqInfo(
MrdAccessId,
UniqueId,
AckType,
AcknowledgedBy
);
if (ackInfo == null)
{
html = HtmlTemplates.GetFailedHtml("No acknowledgement info found for this UniqueId.");
return Content(html, "text/html");
}
string decodedBody = "";
string subject = "";
// STEP 3: Build email content dynamically
if (AckType == 1) // APPROVE
{
html = HtmlTemplates.GetApprovedHtml("Request approved successfully.");
decodedBody = CleanDecodedHtml(SafeDecodeBase64(ackInfo.ApprovedEmailBody));
decodedBody = decodedBody.Replace("$@AcknowledgedUserName@$", ackInfo.AcknowledgedUserName);
subject = "MRD Request Approved";
var emailModel = new EmailModel
{
Email = ackInfo.RequestedEmail,
Subject = subject,
Body = decodedBody,
UserName = AcknowledgedBy,
StatusCode = "A",
ApprovedBy = AcknowledgedBy
};
await SendEmail(emailModel);
}
else if (AckType == 2) // REJECT
{
html = HtmlTemplates.GetRejectedHtml("Request rejected successfully.");
decodedBody = CleanDecodedHtml(SafeDecodeBase64(ackInfo.RejectedEmailBody));
decodedBody = decodedBody.Replace("$@AcknowledgedUserName@$", ackInfo.AcknowledgedUserName);
subject = "MRD Request Rejected";
var emailModel = new EmailModel
{
Email = ackInfo.RequestedEmail,
Subject = subject,
Body = decodedBody,
UserName = AcknowledgedBy,
StatusCode = "D",
ApprovedBy = AcknowledgedBy
};
await SendEmail(emailModel);
}
else
{
html = HtmlTemplates.GetFailedHtml("Unknown request type.");
}
}
else if (savedCount == -1)
{
html = HtmlTemplates.GetinformationHtml("MRD Request Acknowledgement already done.");
}
else
{
html = HtmlTemplates.GetFailedHtml("MRD Request Acknowledgement failed. No record updated.");
}
}
catch (Exception ex)
{
log.Error("AcknowldgeMRDRequest -> Error: " + ex.Message);
html = HtmlTemplates.GetFailedHtml("Error occurred: " + System.Net.WebUtility.HtmlEncode(ex.Message));
}
finally
{
_appSettings.ConnectionString = databaseName;
}
return Content(html, "text/html");
}
// Decode safely — if already plain HTML, return as is
private static string SafeDecodeBase64(string value)
{
if (string.IsNullOrWhiteSpace(value))
return "";
try
{
// Detect if it's base64 or plain HTML
if (!System.Text.RegularExpressions.Regex.IsMatch(value, @"^[A-Za-z0-9+/=_-]+$"))
return value; // return raw HTML (already clean)
string s = value.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2: s += "=="; break;
case 3: s += "="; break;
}
var bytes = Convert.FromBase64String(s);
return Encoding.UTF8.GetString(bytes);
}
catch
{
return value;
}
}
// Remove slashes, quotes, and JSON artifacts
private static string CleanDecodedHtml(string html)
{
if (string.IsNullOrEmpty(html)) return html;
return html
.Replace("\\\"", "\"")
.Replace("\\/", "/")
.Replace("\\n", "")
.Replace("\\t", "")
.Replace("\\r", "")
.Trim('"')
.Trim();
}
private static string BuildHtml(string title, string color, string emoji, string message)
{
return $@"
<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
<style>
body {{
background: linear-gradient(135deg, {color}15, #fff);
font-family: 'Segoe UI', Tahoma, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}}
.card {{
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
text-align: center;
padding: 40px;
width: 420px;
animation: fadeIn 0.6s ease-in-out;
}}
h1 {{
color: {color};
font-size: 28px;
margin-bottom: 10px;
}}
p {{
color: #333;
font-size: 16px;
}}
button {{
margin-top: 20px;
background-color: {color};
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
transition: background 0.3s;
}}
button:hover {{
filter: brightness(90%);
}}
#fallback {{
display: none;
margin-top: 15px;
font-size: 13px;
color: #777;
}}
@keyframes fadeIn {{
from {{ opacity: 0; transform: translateY(10px); }}
to {{ opacity: 1; transform: translateY(0); }}
}}
</style>
</head>
<body>
<div class='card'>
<h1>{emoji} {title}</h1>
<p>{System.Net.WebUtility.HtmlEncode(message)}</p>
<button onclick='tryCloseOrRedirect()'>Close</button>
<div id='fallback'>If this window doesn't close automatically, please close it manually.</div>
</div>
<script>
function tryCloseOrRedirect() {{
debugger;
try {{
alert('kr')
window.open('', '_self'); window.close(); }} catch(e){{}}
setTimeout(function() {{
var fallback = document.getElementById('fallback');
if (fallback) fallback.style.display = 'block';
}}, 1000);
}}
// Attempt auto-close after 3 seconds
window.onload = function() {{
setTimeout(tryCloseOrRedirect, 3000);
}};
</script>
</body>
</html>";
}
public static string GetApprovedHtml(string message) =>
BuildHtml("Approved Successfully", "#16a34a", "✔", message);
public static string GetRejectedHtml(string message) =>
BuildHtml("Rejected", "#dc2626", "✖", message);
public static string GetFailedHtml(string message) =>
BuildHtml("Operation Failed", "#f97316", "⚠", message);
public static class HtmlTemplates
{
public static string GetApprovedHtml(string message) => $@"
<!DOCTYPE html>
<html>
<head>
<title>Approved</title>
<style>
body {{
background: linear-gradient(135deg, #e6ffed, #d2ffe0);
font-family: 'Segoe UI', Tahoma, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}}
.card {{
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
text-align: center;
padding: 40px;
width: 420px;
}}
h1 {{
color: #16a34a;
font-size: 28px;
margin-bottom: 10px;
}}
h2 {{
color: #16a34a;
font-size: 16px;
margin-bottom: 10px;
}}
p {{
color: #333;
font-size: 16px;
}}
button {{
margin-top: 20px;
background-color: #16a34a;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
}}
button:hover {{
background-color: #138a3f;
}}
</style>
</head>
<body>
<div class='card'>
<h1>Approved</h1>
<h2>{System.Net.WebUtility.HtmlEncode(message)}</h2>
<button onclick='window.close()'>Close</button>
</div>
<script>
function tryCloseOrRedirect() {{
debugger;
try {{
window.open('', '_self'); window.close(); }} catch(e){{}}
setTimeout(function() {{
var fallback = document.getElementById('fallback');
if (fallback) fallback.style.display = 'block';
}}, 1000);
}}
// Attempt auto-close after 3 seconds
window.onload = function() {{
setTimeout(tryCloseOrRedirect, 3000);
}};
</script>
</body>
</html>";
public static string GetRejectedHtml(string message) => $@"
<!DOCTYPE html>
<html>
<head>
<title>Rejected</title>
<style>
body {{
background: linear-gradient(135deg, #ffeaea, #ffdede);
font-family: 'Segoe UI', Tahoma, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}}
.card {{
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
text-align: center;
padding: 40px;
width: 420px;
}}
h1 {{
color: #dc2626;
font-size: 28px;
margin-bottom: 10px;
}}
h2 {{
color: #dc2626;
font-size: 16px;
margin-bottom: 10px;
}}
p {{
color: #333;
font-size: 16px;
}}
button {{
margin-top: 20px;
background-color: #dc2626;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
}}
button:hover {{
background-color: #b91c1c;
}}
</style>
</head>
<body>
<div class='card'>
<h1>Rejected</h1>
<h2>{System.Net.WebUtility.HtmlEncode(message)}</h2>
<button onclick='window.close()'>Close</button>
</div>
</body>
</html>";
public static string GetFailedHtml(string message) => $@"
<!DOCTYPE html>
<html>
<head>
<title>Operation Failed</title>
<style>
body {{
background: linear-gradient(135deg, #fff6e6, #ffedd5);
font-family: 'Segoe UI', Tahoma, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}}
.card {{
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
text-align: center;
padding: 40px;
width: 420px;
}}
h1 {{
color: #f97316;
font-size: 28px;
margin-bottom: 10px;
}}
h2 {{
color: #f97316;
font-size: 16px;
margin-bottom: 10px;
}}
p {{
color: #333;
font-size: 16px;
}}
button {{
margin-top: 20px;
background-color: #f97316;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
}}
button:hover {{
background-color: #ea580c;
}}
</style>
</head>
<body>
<div class='card'>
<h1>Failed</h1>
<h2>{System.Net.WebUtility.HtmlEncode(message)}</h2>
<button onclick='window.close()'>Close</button>
</div>
</body>
</html>";
public static string GetinformationHtml(string message) => $@"
<!DOCTYPE html>
<html>
<head>
<title>Information</title>
<style>
body {{
background: linear-gradient(135deg, #fff6e6, #ffedd5);
font-family: 'Segoe UI', Tahoma, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}}
.card {{
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
text-align: center;
padding: 40px;
width: 420px;
}}
h1 {{
color: #157e8bff;
font-size: 28px;
margin-bottom: 10px;
}}
h2 {{
color: #157e8bff;
font-size: 16px;
margin-bottom: 10px;
}}
p {{
color: #333;
font-size: 16px;
}}
button {{
margin-top: 20px;
background-color: #157e8bff;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
cursor: pointer;
}}
button:hover {{
background-color: #157e8bff;
}}
</style>
</head>
<body>
<div class='card'>
<h1>Info</h1>
<h2>{System.Net.WebUtility.HtmlEncode(message)}</h2>
<button onclick='window.close()'>Close</button>
</div>
</body>
</html>";
}
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
[HttpGet("GetDocumentCountList")]
public IActionResult GetDocumentCountList(string Parm_Year,int Parm_DType)
public IActionResult GetDocumentCountList(string Parm_Year, int Parm_DType)
{
log.Debug("GetDocumentCountList ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<object>? RequestsList = adapter.GetDocumentCountList(Parm_Year,Parm_DType);
List<object>? RequestsList = adapter.GetDocumentCountList(Parm_Year, Parm_DType);
return Ok(RequestsList);
}
catch (Exception ex)
......@@ -1728,7 +2895,6 @@ namespace FTP_Services.Services.Controllers
}
}
//-------------------------------------------------------------------Patient docs Merge Api -----------------------
[HttpGet("GetPatientMergeDocuments")]
public async Task<bool> GetPatientMergeDocuments(int PatientID)
......@@ -1758,7 +2924,6 @@ namespace FTP_Services.Services.Controllers
if (doc == null || string.IsNullOrWhiteSpace(doc.DocumentPath))
continue;
string FileFullPath = Path.GetFullPath(doc.DocumentPath);
await ProcessPatientDocFile(FileFullPath, pdfByteArrays);
}
......@@ -1775,17 +2940,21 @@ namespace FTP_Services.Services.Controllers
if (!string.IsNullOrEmpty(SavedPathFile))
{
string strFileFullPath = Path.GetFullPath(SavedPathFile)
.Replace(primaryFolderPath, "")
.Replace(secondaryFolderPath, "");
.Replace(primaryFolderPath, "")
.Replace(secondaryFolderPath, "");
string[] parts = strFileFullPath.Split('\\');
string resultpath = ""; string outputFileName = "";
string resultpath = "";
string outputFileName = "";
if (parts.Length >= 3)
{
string patientId = parts[1];
string guid = parts[2];
outputFileName = Path.Combine($"{patientId}\\{guid}\\{"ALL Info"}", $"{PatientID}_AllInfoPatDocuments.pdf");
outputFileName = Path.Combine(
$"{patientId}\\{guid}\\{"ALL Info"}",
$"{PatientID}_AllInfoPatDocuments.pdf"
);
}
string outputFilePath = Path.Combine(primaryFolderPath, outputFileName);
var directoryPath = Path.GetDirectoryName(outputFilePath);
......@@ -1840,6 +3009,7 @@ namespace FTP_Services.Services.Controllers
Console.WriteLine($"Error processing file: {filePath}, {ex.Message}");
}
}
public string NormalizePathForCurrentOS(string path)
{
if (string.IsNullOrEmpty(path))
......@@ -1995,7 +3165,13 @@ namespace FTP_Services.Services.Controllers
aes.IV = keyBytes.Take(16).ToArray();
using (ICryptoTransform decryptor = aes.CreateDecryptor())
using (CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
using (
CryptoStream cryptoStream = new CryptoStream(
encryptedStream,
decryptor,
CryptoStreamMode.Read
)
)
{
cryptoStream.CopyTo(decryptedStream);
}
......@@ -2008,8 +3184,8 @@ namespace FTP_Services.Services.Controllers
[HttpPost("GetMRDCompressedIcons")]
public async Task<IActionResult> GetMRDCompressedIcons(
[FromBody] DocumentResponseModel model
)
[FromBody] DocumentResponseModel model
)
{
if (model == null || string.IsNullOrWhiteSpace(model.FolderPath))
return BadRequest("Folder path is required.");
......@@ -2091,46 +3267,191 @@ namespace FTP_Services.Services.Controllers
return bmp;
}
// [HttpPost("GetMRDFTPCompressedFolderIcons")]
// public async Task<IActionResult> GetMRDFTPCompressedFolderIcons(
// [FromBody] FTPDocumentResponseModel model
// )
// {
// if (model == null || string.IsNullOrWhiteSpace(model.FolderPath))
// return BadRequest("FolderPath is required.");
// if (model.FilePaths == null || !model.FilePaths.Any())
// return BadRequest("FilePaths list is empty.");
// // Resolve IWebHostEnvironment inside the method
// var env = HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
// string localTempDir = Path.Combine(env.ContentRootPath, "TempFTPDownloads");
// var ftpService = new FluentFtpService(); // or resolve via DI too
// var results = await ftpService.DownloadAndGetBase64FilesAsync(
// model,
// localTempDir,
// int.Parse(_appSettings.ResolutionSettings.Height),
// int.Parse(_appSettings.ResolutionSettings.Width)
// );
// return Ok(
// results.Select(r => new
// {
// FileName = r.FileName,
// Base64 = r.Base64,
// Error = r.Error
// })
// );
// }
[HttpPost("GetMRDFTPCompressedFolderIcons")]
public async Task<IActionResult> GetMRDFTPCompressedFolderIcons(
[FromBody] FTPDocumentResponseModel model
)
{
if (model == null || string.IsNullOrWhiteSpace(model.FolderPath))
return BadRequest("FolderPath is required.");
if (model.FilePaths == null || !model.FilePaths.Any())
return BadRequest("FilePaths list is empty.");
var env = HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
string localTempDir = Path.Combine(env.ContentRootPath, "TempFTPDownloads");
WriteLog(
$"================ API START [{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ================"
);
var stopwatch = Stopwatch.StartNew();
var ftpService = new FluentFtpService(WriteLog); // or resolve via DI too
var results = await ftpService.DownloadAndGetBase64FilesAsync(
model,
localTempDir,
int.Parse(_appSettings.ResolutionSettings.Height),
int.Parse(_appSettings.ResolutionSettings.Width)
);
stopwatch.Stop();
WriteLog(
$"================ API END [{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ================"
);
WriteLog(
$"Total API Execution Time: {stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m {stopwatch.Elapsed.Seconds}s\n"
);
return Ok(
results.Select(r => new
{
FileName = r.FileName,
Base64 = r.Base64,
Error = r.Error
})
);
}
[HttpPost("GetMRDFTPSelectedFilesAsIcons")]
public async Task<IActionResult> GetMRDFTPSelectedFilesAsIcons(
[FromBody] FTPDocumentResponseModel model
)
{
if (model == null || string.IsNullOrWhiteSpace(model.FolderPath))
return BadRequest("FolderPath is required.");
if (model.FilePaths == null || !model.FilePaths.Any())
return BadRequest("FilePaths list is empty.");
var env = HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
string localTempDir = Path.Combine(env.ContentRootPath, "TempFTPDownloads");
WriteLog(
$"================ API START [{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ================"
);
var stopwatch = Stopwatch.StartNew();
var ftpService = new FluentFtpService(WriteLog);
var results = await ftpService.DownloadSelectedFilesAndConvertToBase64Async(
model,
localTempDir,
int.Parse(_appSettings.ResolutionSettings.Height),
int.Parse(_appSettings.ResolutionSettings.Width)
);
stopwatch.Stop();
WriteLog(
$"================ API END [{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ================"
);
WriteLog(
$"Total API Execution Time: {stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m {stopwatch.Elapsed.Seconds}s\n"
);
return Ok(
results.Select(r => new
{
FileName = r.FileName,
Base64 = r.Base64,
Error = r.Error
})
);
}
public void WriteLog(string SndException)
{
string strfname = Convert.ToString(DateTime.Today.ToString("yyyy-MM-dd"));
string strDirectory =
System
.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
)
.Replace("file:\\", "") + "\\LOGDetails";
string strFile =
System
.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
)
.Replace("file:\\", "")
+ "\\LOGDetails\\"
+ strfname
+ ".txt";
if (!System.IO.Directory.Exists(strDirectory))
string strfname = DateTime.Today.ToString("yyyy-MM-dd");
string? assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
string? baseDirectory = System.IO.Path.GetDirectoryName(assemblyLocation);
if (string.IsNullOrEmpty(baseDirectory))
{
System.IO.Directory.CreateDirectory(strDirectory);
throw new InvalidOperationException("Unable to determine the assembly directory.");
}
StreamWriter objStreamWriter = default(StreamWriter);
if (!System.IO.File.Exists(strFile))
string logDirectory = System.IO.Path.Combine(baseDirectory, "LOGDetails");
string logFile = System.IO.Path.Combine(logDirectory, $"{strfname}.txt");
if (!System.IO.Directory.Exists(logDirectory))
{
FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
objStreamWriter = new StreamWriter(fs);
objStreamWriter.BaseStream.Seek(0, SeekOrigin.End);
System.IO.Directory.CreateDirectory(logDirectory);
}
else
using (StreamWriter writer = new StreamWriter(logFile, append: true))
{
objStreamWriter = System.IO.File.AppendText(strFile);
writer.WriteLine(SndException);
}
objStreamWriter.WriteLine(SndException);
objStreamWriter.Close();
}
// public void WriteLog(string SndException)
// {
// string strfname = Convert.ToString(DateTime.Today.ToString("yyyy-MM-dd"));
// string strDirectory =
// System
// .IO.Path.GetDirectoryName(
// System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
// )
// .Replace("file:\\", "") + "\\LOGDetails";
// string strFile =
// System
// .IO.Path.GetDirectoryName(
// System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
// )
// .Replace("file:\\", "")
// + "\\LOGDetails\\"
// + strfname
// + ".txt";
// if (!System.IO.Directory.Exists(strDirectory))
// {
// System.IO.Directory.CreateDirectory(strDirectory);
// }
// StreamWriter objStreamWriter = default(StreamWriter);
// if (!System.IO.File.Exists(strFile))
// {
// FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
// objStreamWriter = new StreamWriter(fs);
// objStreamWriter.BaseStream.Seek(0, SeekOrigin.End);
// }
// else
// {
// objStreamWriter = System.IO.File.AppendText(strFile);
// }
// objStreamWriter.WriteLine(SndException);
// objStreamWriter.Close();
// }
}
}
......@@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="ExcelDataReader" Version="3.6.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
<PackageReference Include="FluentFTP" Version="53.0.1" />
<PackageReference Include="iTextSharp" Version="5.5.13.4" />
<PackageReference Include="log4net" Version="2.0.14" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="4.1.0" />
......
......@@ -4,6 +4,7 @@ namespace FTP_Services.Core.Models
{
public string ConnectionString { get; set; }
public string AdminConnectionString { get; set; }
public string ConnectionString_MRD { get; set; }
public string Secret { get; set; }
public AppSettings()
......@@ -11,6 +12,7 @@ namespace FTP_Services.Core.Models
Secret = "";
ConnectionString = "";
AdminConnectionString = "";
ConnectionString_MRD = "";
}
public FTPConfiguration FTPConfiguration { get; set; }
......
namespace FTP_Services.Core.Models
{
public class PatientDocumentDetailsModel
public class PatientDocumentRequest
{
public int UserId { get; set; }
public int PatientId { get; set; }
public int RecType { get; set; }
public int AdmissionID { get; set; }
public int DocumentType { get; set; }
public int PatDocId { get; set; }
public List<PatientImgDoc> PatientImgDoc { get; set; }
}
public class PatientImgDoc
{
public DateTime UploadedDate { get; set; }
public string Description { get; set; }
public string DocumentName { get; set; }
public long Size { get; set; }
public string DocumentUrl { get; set; }
public int SlNo { get; set; }
}
public class PatientDocumentDetailsModel1
{
public int DocumentType { get; set; }
public string Description { get; set; }
......@@ -18,7 +38,7 @@ namespace FTP_Services.Core.Models
public int SortNo { get; set; }
public int RecType { get; set; }
public PatientDocumentDetailsModel()
public PatientDocumentDetailsModel1()
{
DocumentType = 0;
Description = "";
......@@ -38,7 +58,6 @@ namespace FTP_Services.Core.Models
}
}
public class FileResponseModel
{
public string Base64String { get; set; }
......@@ -132,6 +151,7 @@ namespace FTP_Services.Core.Models
Name = "";
}
}
public class ConfigValues
{
public int ID { get; set; }
......@@ -152,7 +172,6 @@ namespace FTP_Services.Core.Models
public string RemotePort { get; set; }
public string ToolVersion { get; set; }
public ConfigValues()
{
ID = -1;
......@@ -200,7 +219,6 @@ namespace FTP_Services.Core.Models
public string AdmissionDate { get; set; }
public PatientDocuments()
{
PatientId = -1;
......@@ -227,6 +245,7 @@ namespace FTP_Services.Core.Models
AdmissionDate = "";
}
}
public class Admissions
{
public int ID { get; set; }
......@@ -248,20 +267,22 @@ namespace FTP_Services.Core.Models
RecordCount = -1;
}
}
public class AdmissionDischargeHistData
{
public string Parm_AdmData { get; set; }
}
public class PatientHistData
{
public string Parm_PatientData { get; set; }
}
public class SQLRequest
{
public string sql { get; set; }
}
public class AdmissionDischargeModel
{
public int MRDId { get; set; }
......@@ -274,6 +295,7 @@ namespace FTP_Services.Core.Models
public DateTime? AdmissionDate { get; set; }
public int AdmissionTypeId { get; set; }
public DateTime? DischargeDate { get; set; }
//public int DischargeTypeId { get; set; }
public string DischargeType { get; set; }
public string Cause { get; set; }
......@@ -306,20 +328,20 @@ namespace FTP_Services.Core.Models
public class ProcedureModel
{
public string ProcName { get; set; }
}
public class PatientImgDocSort
{
public int UserId { get; set; }
public List<PatientImgDocModel> PatientImgDoc { get; set; }
}
public class PatientImgDocModel
{
public int PatDocId { get; set; }
public int SortNo { get; set; }
}
public class PatientDocumentsPathsData
{
public int PatientId { get; set; }
......@@ -334,4 +356,15 @@ namespace FTP_Services.Core.Models
public string? FolderPath { get; set; }
public List<string>? FilePaths { get; set; }
}
public class FTPDocumentResponseModel
{
public string? FolderPath { get; set; }
public List<string>? FilePaths { get; set; }
public string? RemoteHost { get; set; }
public string? RemoteUser { get; set; }
public string? RemotePassword { get; set; }
public int RemotePort { get; set; }
public string? WebRemotePath { get; set; }
}
}
......@@ -138,9 +138,10 @@ if (app.Environment.IsDevelopment())
}
else
{
//app.Run(); //For Test Site
app.Run("http://*:4708"); // For Production
app.Run(); //For Test Site
//app.Run("http://*:4708"); // For Production
//app.Run("http://*:4709"); // For Admin
}
......@@ -17,6 +17,7 @@ namespace FTP_Services.Services
{
#region Variables
protected PetaPoco.Database _repository;
protected PetaPoco.Database _adminRepository;
//protected IConfiguration _configuration;
protected AppSettings _appSettings;
protected readonly log4net.ILog log = log4net.LogManager.GetLogger("BaseDataAdapter");
......@@ -26,16 +27,19 @@ namespace FTP_Services.Services
public BaseDataAdapter(AppSettings appSettings)
{
log.Debug("BaseDataAdapter() called");
//this._configuration=configuration;
//string constr = _configuration.GetSection("MySettings").GetSection("ConnectionString").Value;
this._appSettings=appSettings;
this._appSettings = appSettings;
string constr = _appSettings.ConnectionString;
log.Debug("Connection String -" + constr);
// this._repository = new PetaPoco.Database(new Npgsql.NpgsqlConnection(constr));
_auth_user_id=0;
_user_id=0;
// this._repository = new PetaPoco.Database(constr,"Microsoft.Data.SqlClient");
_repository = new PetaPoco.Database(constr, "npgsql");
string Adminconstr = _appSettings.AdminConnectionString;
log.Debug("Connection String -" + constr);
_auth_user_id=0;
_user_id=0;
_repository = new PetaPoco.Database(Adminconstr, "npgsql");
}
public void Dispose()
......
......@@ -18,6 +18,7 @@ using Newtonsoft.Json;
using Npgsql;
using PetaPoco;
using Newtonsoft.Json.Linq;
using Microsoft.VisualBasic;
namespace FTP_Services.Services
{
......@@ -229,7 +230,7 @@ namespace FTP_Services.Services
return null;
}
}
public List<object>? LoadDocumentTypes()
public List<object>? LoadDocumentTypes(int Type)
{
List<object>? DocumentTypesData = null;
try
......@@ -237,9 +238,16 @@ namespace FTP_Services.Services
using (var tx = _repository.GetTransaction())
{
//string sqlQuery = $"SELECT * FROM \"SPScanTool_LoadPhysicians\"(@Parm_Type)";
string sqlQuery = $"SELECT * FROM \"SPScanTool_LoadDocumentTypes\"(@Parm_Type)";
DocumentTypesData = _repository.Fetch<object>(
"SELECT * FROM \"SPScanTool_LoadDocumentTypes\"();"
sqlQuery,
new { Parm_Type = Type }
);
// DocumentTypesData = _repository.Fetch<object>(
// "SELECT * FROM \"LoadDocumentTypes\"();"
// );
GC.Collect();
tx.Complete();
}
......@@ -594,7 +602,7 @@ namespace FTP_Services.Services
}
}
public List<object>? PatientDocuments(int SPatientID, int SLocationID, int SAppointmentID, int SAdmissionID, int SDocID,int RecType, string? SDueFrom, string? SDueTO)
public List<object>? PatientDocuments(int SPatientID, int SLocationID, int SAppointmentID, int SAdmissionID, int SDocID, int RecType, string? SDueFrom, string? SDueTO)
{
List<object>? PatientDocumentsData = null;
try
......@@ -679,14 +687,18 @@ namespace FTP_Services.Services
return null;
}
}
public int SaveAdmissionDischargeData(List<AdmissionDischargeModel> models)
{
int savedCount = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string SQLStr = "SELECT public.\"SPScanTool_SaveAdmissionDischargeData\"(@MRDId, @PatientId, @AdmissionId, @ProviderId, " +
//SPScanTool_SaveAdmissionDischargeData
string SQLStr = "SELECT public.\"MRD_SaveAdmissionDischargeData\"(@MRDId, @PatientId, @AdmissionId, @ProviderId, " +
"@LocationId, @DepartmentId, @AdmissionAge, @AdmissionDate, @AdmissionTypeId, @DischargeDate, " +
"@DischargeType, @Cause, @UserId, @IsWardChanged, @IsICDChanged, @IsProcChanged, " +
"@Wards::jsonb, @ICDCodes::jsonb, @Procedures::jsonb, @MRD_Diagnosis,@MRD_OtherProcedures,@Parm_RecType)"; // Explicitly cast JSON to jsonb @MRD_Diagnosis::jsonb
......@@ -734,64 +746,105 @@ namespace FTP_Services.Services
{
log.Error($"SaveAdmissionDischargeData -> Failed to execute query - Error: {ex.Message}", ex);
}
finally
{
}
return savedCount;
}
public int SavePatientDocumentData(List<PatientDocumentDetailsModel> patientDocs)
//Json Model
public int SavePatientDocumentData(string patientDocs)
{
int savedCount = 0;
int result = 0;
try
{
using (var tx = _repository.GetTransaction())
{
foreach (var doc in patientDocs)
{
string SQLStr = "SELECT * FROM \"SPScanTool_SavePatientDocument\"(@PatDocId, @UploadedDate, @PatientId, @UploadedBy, " +
"@DocumentName, @DocumentType, @ContentType, @Size, @Description, @DocumentUrl, @ThumbnailUrl,@SortNo, @SplID, @AdmissionID,@Parm_RecType)";
string escaped = patientDocs;
var parameters = new
{
PatDocId = doc.PatDocId,
UploadedDate = doc.UploadedDate, // Ensure valid date format if needed
PatientId = doc.PatientId,
UploadedBy = doc.UploadedBy,
DocumentName = doc.DocumentName,
DocumentType = doc.DocumentType,
ContentType = doc.ContentType,
Size = doc.Size, // Ensure string is handled correctly
Description = doc.Description,
DocumentUrl = doc.DocumentUrl,
ThumbnailUrl = doc.ThumbnailUrl,
SortNo = doc.SortNo,
SplID = doc.SplID,
AdmissionID = doc.AdmissionID,
Parm_RecType = doc.RecType
};
var obj = JsonConvert.DeserializeObject<object>(escaped);
string cleanJson = JsonConvert.SerializeObject(obj);
//string SQLStr = "SELECT * FROM \"SPScanTool_Hist_SaveAdmissionDischargeData\"(@Parm_AdmData::jsonb)"; //::json
string SQLStr = "SELECT * FROM \"MRD_SavePatientDocument\"(@Parm_PatDocData::jsonb)"; //::json
var parameters = new { Parm_PatDocData = cleanJson };
result = _repository.Single<int>(SQLStr, parameters);
_repository.Single<int>(SQLStr, parameters);
savedCount++;
}
tx.Complete();
}
}
catch (Exception ex)
{
log.Error("SaveMultiplePatientDocuments -> Failed to save records - Error: " + ex.Message);
log.Error("SavePatientDocumentData -> Failed to save PatientDocumentData - Error: " + ex.Message);
}
return savedCount;
finally
{
}
return result;
}
// //Json Model
// public int SavePatientDocumentData1(List<PatientDocumentDetailsModel> patientDocs)
// {
// int savedCount = 0;
// try
// {
// using (var tx = _repository.GetTransaction())
// {
// foreach (var doc in patientDocs)
// {
// //SPScanTool_SavePatientDocument
// string SQLStr = "SELECT * FROM \"MRD_SavePatientDocument\"(@PatDocId, @UploadedDate, @PatientId, @UploadedBy, " +
// "@DocumentName, @DocumentType, @ContentType, @Size, @Description, @DocumentUrl, @ThumbnailUrl,@SortNo, @SplID, @AdmissionID,@Parm_RecType)";
// var parameters = new
// {
// PatDocId = doc.PatDocId,
// UploadedDate = doc.UploadedDate, // Ensure valid date format if needed
// PatientId = doc.PatientId,
// UploadedBy = doc.UploadedBy,
// DocumentName = doc.DocumentName,
// DocumentType = doc.DocumentType,
// ContentType = doc.ContentType,
// Size = doc.Size, // Ensure string is handled correctly
// Description = doc.Description,
// DocumentUrl = doc.DocumentUrl,
// ThumbnailUrl = doc.ThumbnailUrl,
// SortNo = doc.SortNo,
// SplID = doc.SplID,
// AdmissionID = doc.AdmissionID,
// Parm_RecType = doc.RecType
// };
// _repository.Single<int>(SQLStr, parameters);
// savedCount++;
// }
// tx.Complete();
// }
// }
// catch (Exception ex)
// {
// log.Error("SaveMultiplePatientDocuments -> Failed to save records - Error: " + ex.Message);
// }
// finally
// {
// }
// return savedCount;
// }
public int UpdateImageCategory(int sndPatDocId, int sndDocTypeId, int sndUserID)
{
int savedCount = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string SQLStr = "SELECT * FROM \"SPScanTool_UpdateImageCategory\"(@PatDocId, @DocTypeId, @UserID)";
//string SQLStr = "SELECT * FROM \"SPScanTool_UpdateImageCategory\"(@PatDocId, @DocTypeId, @UserID)";
string SQLStr = "SELECT * FROM \"MRD_UpdateImageCategory\"(@PatDocId, @DocTypeId, @UserID)";
var parameters = new
{
......@@ -800,6 +853,8 @@ namespace FTP_Services.Services
UserID = sndUserID
};
//repository.ConnectionString = _appSettings.ConnectionString;
_repository.Single<int>(SQLStr, parameters);
savedCount++;
tx.Complete();
......@@ -809,6 +864,9 @@ namespace FTP_Services.Services
{
log.Error("UpdateImageCategory -> Failed to save records - Error: " + ex.Message);
}
finally
{
}
return savedCount;
}
public int UpdateImageSortNo(PatientImgDocSort model)
......@@ -816,9 +874,12 @@ namespace FTP_Services.Services
int savedCount = 0;
try
{
string DatabaseName = _appSettings.ConnectionString;
_appSettings.ConnectionString = _appSettings.ConnectionString_MRD;
using (var tx = _repository.GetTransaction())
{
string SQLStr = "SELECT * FROM public.\"SPScanTool_UpdateImageSortNo\"(@Parm_SortData::jsonb)";
//string SQLStr = "SELECT * FROM public.\"SPScanTool_UpdateImageSortNo\"(@Parm_SortData::jsonb)";
string SQLStr = "SELECT * FROM public.\"MRD_UpdateImageSortNo\"(@Parm_SortData::jsonb)";
var parameters = new
{
......@@ -830,6 +891,7 @@ namespace FTP_Services.Services
_repository.Single<int>(SQLStr, parameters);
savedCount++;
tx.Complete();
_appSettings.ConnectionString = DatabaseName;
}
}
catch (Exception ex)
......@@ -918,13 +980,12 @@ namespace FTP_Services.Services
using (var tx = _repository.GetTransaction())
{
string SQLStr =
"SELECT * FROM \"SPScanTool_DeletePatientDocument\"("
// "SELECT * FROM \"SPScanTool_DeletePatientDocument\"("
"SELECT * FROM \"MRD_DeletePatientDocument\"("
+ SndAdmissionId + ',' + SndPatDocRecID + ',' + SndUserID + ',' + SndRecType
+ ");";
result = _repository.Single<string>(SQLStr);
GC.Collect();
tx.Complete();
}
......@@ -934,6 +995,9 @@ namespace FTP_Services.Services
log.Error("DeletePatientDocumentData->Failed to get info from db - " + ex.Message);
result = "Error: " + ex.Message;
}
finally
{
}
return result;
}
......@@ -1007,11 +1071,14 @@ namespace FTP_Services.Services
List<object>? PatientHistoryData = null;
try
{
using (var tx = _repository.GetTransaction())
{
// string sqlQuery =
// $"SELECT * FROM \"SPScanTool_Hist_GetPatientData\"(@Parm_PatientId)";
string sqlQuery =
$"SELECT * FROM \"SPScanTool_Hist_GetPatientData\"(@Parm_PatientId)";
$"SELECT * FROM \"MRD_Hist_GetPatientData\"(@Parm_PatientId)";
PatientHistoryData = _repository.Fetch<object>(
sqlQuery,
new
......@@ -1029,6 +1096,9 @@ namespace FTP_Services.Services
log.Error("PatientHistoryData->Failed to get info from db - " + ex.Message);
return null;
}
finally
{
}
}
public List<object>? LoadLookupValues(string sndLookupName, string sndWhereCond, Boolean sndShowBlankRow) //string Parm_LookupName,string Parm_WhereCond,Boolean Parm_ShowBlankRow
{
......@@ -1069,9 +1139,8 @@ namespace FTP_Services.Services
{
using (var tx = _repository.GetTransaction())
{
string sqlQuery =
$"SELECT * FROM \"SPScanTool_Hist_GetAdmissIonData\"(@Parm_HistAdmId)";
string sqlQuery = $"SELECT * FROM \"MRD_Hist_GetAdmissIonData\"(@Parm_HistAdmId)";
// $"SELECT * FROM \"SPScanTool_Hist_GetAdmissIonData\"(@Parm_HistAdmId)";
PatientAdmissionHistoryData = _repository.Fetch<object>(
sqlQuery,
new
......@@ -1084,11 +1153,15 @@ namespace FTP_Services.Services
}
return PatientAdmissionHistoryData;
}
catch (Exception ex)
{
log.Error("PatientAdmissionHistoryData->Failed to get info from db - " + ex.Message);
return null;
}
finally
{
}
}
public int SaveHistoryOfAdmissionDischargeData(string admissionDischargeJson)
......@@ -1096,6 +1169,7 @@ namespace FTP_Services.Services
int result = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string escaped = admissionDischargeJson;
......@@ -1103,7 +1177,8 @@ namespace FTP_Services.Services
var obj = JsonConvert.DeserializeObject<object>(escaped);
string cleanJson = JsonConvert.SerializeObject(obj);
string SQLStr = "SELECT * FROM \"SPScanTool_Hist_SaveAdmissionDischargeData\"(@Parm_AdmData::jsonb)"; //::json
//string SQLStr = "SELECT * FROM \"SPScanTool_Hist_SaveAdmissionDischargeData\"(@Parm_AdmData::jsonb)"; //::json
string SQLStr = "SELECT * FROM \"MRD_Hist_SaveAdmissionDischargeData\"(@Parm_AdmData::jsonb)"; //::json
var parameters = new { Parm_AdmData = cleanJson };
result = _repository.Single<int>(SQLStr, parameters);
......@@ -1115,6 +1190,9 @@ namespace FTP_Services.Services
{
log.Error("SaveHistoryOfAdmissionDischargeData -> Failed to save admission/discharge data - Error: " + ex.Message);
}
finally
{
}
return result;
}
......@@ -1132,11 +1210,11 @@ namespace FTP_Services.Services
string cleanJson = JsonConvert.SerializeObject(obj);
Console.WriteLine(cleanJson);
// No deserialization — use sndSQL directly
string SQLStr = "SELECT * FROM \"SPScanTool_ExecuteNonQuery\"(@Parm_SQL::jsonb)";
//string SQLStr = "SELECT * FROM \"SPScanTool_ExecuteNonQuery\"(@Parm_SQL::jsonb)";
string SQLStr = "SELECT * FROM \"MRD_ExecuteNonQuery\"(@Parm_SQL::jsonb)";
var parameters = new { Parm_SQL = cleanJson }; // Use the raw JSON string
result = _repository.Single<string>(SQLStr, parameters);
result = _repository.Single<string>(SQLStr, parameters);
tx.Complete();
}
......@@ -1145,6 +1223,9 @@ namespace FTP_Services.Services
{
log.Error("ExecuteNonQuery -> Failed to save ExecuteNonQuery - Error: " + ex.Message);
}
finally
{
}
return result;
}
......@@ -1154,6 +1235,7 @@ namespace FTP_Services.Services
int result = 0;
try
{
using (var tx = _repository.GetTransaction())
{
......@@ -1163,7 +1245,8 @@ namespace FTP_Services.Services
string cleanJson = JsonConvert.SerializeObject(obj);
//Console.WriteLine(cleanJson);
string SQLStr = "SELECT * FROM \"SPScanTool_SaveHistoryPatient\"(@Parm_PatientData::jsonb)";
// string SQLStr = "SELECT * FROM \"SPScanTool_SaveHistoryPatient\"(@Parm_PatientData::jsonb)";
string SQLStr = "SELECT * FROM \"MRD_SaveHistoryPatient\"(@Parm_PatientData::jsonb)";
var parameters = new { Parm_PatientData = cleanJson }; // No serialization here
result = _repository.Single<int>(SQLStr, parameters);
......@@ -1175,11 +1258,101 @@ namespace FTP_Services.Services
{
log.Error("SaveHistoryPatient -> Failed to save patient history data - Error: " + ex.Message);
}
finally
{
}
return result;
}
public int AcknowldgeMRDRequest(int mrdAccessId, string uniqueId, int AckType, string AcknowledgedBy)
{
int result = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string sql = "SELECT public.\"SPScanTool_AcknowldgeMRDRequest\"(@Parm_Request_Type, @Parm_MrdDocumentAccessId, @Parm_ApprovedByEmail, @Parm_UniqueId)";
var parameters = new
{
Parm_Request_Type = AckType,
Parm_MrdDocumentAccessId = mrdAccessId,
Parm_ApprovedByEmail = AcknowledgedBy,
Parm_UniqueId = uniqueId
};
// Since the function returns int, use SingleOrDefault<int>() to capture result
result = _repository.SingleOrDefault<int>(sql, parameters);
tx.Complete();
}
}
catch (Exception ex)
{
log.Error($"AcknowldgeMRDRequest -> Failed to update MRD Request. Error: {ex.Message}");
result = 0; // Failure
}
return result;
}
public MrdAcknowledgementModel AcknowldgeReqInfo(int mrdAccessId, string UniqueId, int ActionType, string AcknowledgedBy)
{
MrdAcknowledgementModel ackInfo = null;
try
{
using (var tx = _repository.GetTransaction())
{
string sql = "SELECT * FROM \"SPScanTool_GetAcknowldgementInfo\"(@Parm_UniqueId)";
var parameters = new { Parm_UniqueId = UniqueId };
// Since SP returns a TABLE, we expect one row (for that UniqueId)
ackInfo = _repository.SingleOrDefault<MrdAcknowledgementModel>(sql, parameters);
tx.Complete();
}
}
catch (Exception ex)
{
log.Error($"AcknowldgeReqInfo -> Failed to get acknowledgement info. Error: {ex.Message}");
ackInfo = null;
}
return ackInfo;
}
public int GetFileCountByAdmId(int PatientId, int AdmissionId, int DocumentTypeId, int RecTypeId, int AppointmentId)
{
int fileCount = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string sql = "SELECT \"SPScanTool_GetFileCountByAdmId\"(@Parm_PatientId,@Parm_AdmissionId,@Parm_DocumentTypeId,@Parm_RecTypeId,@Parm_AppointmentId)";
var parameters = new
{
Parm_PatientId = PatientId,
Parm_AdmissionId = AdmissionId,
Parm_DocumentTypeId = DocumentTypeId,
Parm_RecTypeId = RecTypeId,
Parm_AppointmentId = AppointmentId
};
fileCount = _repository.SingleOrDefault<int>(sql, parameters);
tx.Complete();
}
}
catch (Exception ex)
{
log.Error("Error: " + ex.Message);
}
return fileCount;
}
public List<object>? GetDocumentCountList(string sndParm_Year,int sndDType)
public List<object>? GetDocumentCountList(string sndParm_Year, int sndDType)
{
List<object>? documentCountList = null;
try
......@@ -1214,7 +1387,7 @@ namespace FTP_Services.Services
using (var tx = _repository.GetTransaction())
{
string sqlQuery = $"SELECT * FROM \"SPScanTool_GetDocumentYears\"(@Parm_DType)";
string sqlQuery = $"SELECT * FROM \"SPScanTool_GetDocumentYears\"(@Parm_DType)";
documentsYearsList = _repository.Fetch<object>(sqlQuery,
new { Parm_DType = sndDType }
);
......
{
"AppSettings": {
"Secret": "A78E-F7FA-B0FD-DAA45BB866CD-AA73D560-DACC-978C-4A9B-9924-5DE7E33F0040-GCD00",
"ConnectionString101": "SERVER=192.168.1.101;PORT=5432;UID=dbuser;PWD=dbuser123!;Database=FF_test_20250620;Timeout=1000",
"ConnectionString158": "SERVER=10.11.12.158;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=FF_TEST_16052025;Timeout=1000",
"ConnectionString": "SERVER=10.11.12.158;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=Fernandez_Test_20250718;Timeout=1000",
"AdminConnectionString": "SERVER=10.11.12.106;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;database=CareaxesAdmin;Timeout=1000",
"ConnectionString": "SERVER=10.11.12.106;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=fernandez_20241125;Timeout=1000",
"ConnectionString207": "SERVER=192.168.7.207;PORT=5432;UID=ff4dbuser;PWD=dbuser4ff123!;Database=fernandez_test_20250409_dev;Timeout=1000",
"ConnectionString_MRD": "SERVER=10.11.12.158;PORT=5432;UID=himsdbuser;PWD=dbuser@hims123!;Database=MRD_DEMO;Timeout=1000",
"FTPConfiguration": {
"Username": "admin",
"Password": "Fmh@xp@rt01",
......@@ -19,7 +17,7 @@
"SecondaryFolderPath": "D:\\GT\\Second_Folder"
},
"MappedDriveSettings": {
"BaseDirectory": "Z:\\FTPAPI"
"BaseDirectory": "E:\\MRD_IMAGES\\MRD_UAT"
},
"ResolutionSettings": {
"Height": "20",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment