using BMA.EHR.Application.Common.Interfaces; using BMA.EHR.Application.Messaging; using BMA.EHR.Application.Responses; using BMA.EHR.Application.Responses.Messages; using BMA.EHR.Domain.Models.HR; using BMA.EHR.Domain.Models.Notifications; using BMA.EHR.Domain.Shared; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System.Net.Http.Headers; using System.Text.RegularExpressions; namespace BMA.EHR.Application.Repositories.MessageQueue { public class NotificationRepository : GenericRepository { #region " Fields " private readonly IApplicationDBContext _dbContext; private readonly IHttpContextAccessor _httpContextAccessor; private readonly EmailSenderService _emailSenderService; private readonly IConfiguration _configuration; #endregion #region " Constructor and Destuctor " public NotificationRepository(IApplicationDBContext dbContext, EmailSenderService emailSenderService, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) : base(dbContext, httpContextAccessor) { _dbContext = dbContext; _httpContextAccessor = httpContextAccessor; _emailSenderService = emailSenderService; _configuration = configuration; } #endregion #region " Methods " public async Task GetMyNotificationAsync(int page = 1, int pageSize = 25) { try { // var profile = await _dbContext.Set() // .FirstOrDefaultAsync(p => p.KeycloakId == Guid.Parse(UserId!)); // if (profile == null) // { // return new List(); // // throw new Exception(GlobalMessages.DataNotFound); // } //var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId"; var profileId = ""; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return new List(); profileId = org.result.profileId == null ? "" : org.result.profileId; } if (profileId == null || profileId == "") return new List(); var data_search = await _dbContext.Set() .Where(x => x.ReceiverUserId == Guid.Parse(profileId)) .Where(x => x.DeleteDate == null) .OrderByDescending(x => x.ReceiveDate) .ToListAsync(); var totalNoti = data_search.Where(x => x.IsOpen == false).Count(); var data = data_search .Skip((page - 1) * pageSize) .Take(pageSize) .Select(x => new NotificationResponse { Id = x.Id, Body = x.Body, ReceiverUserId = x.ReceiverUserId, KeycloakUserId = x.KeycloakUserId, IsOpen = x.IsOpen, Type = x.Type, ReceiveDate = x.ReceiveDate, OpenDate = x.OpenDate, Payload = x.Payload }).ToList(); var data_opens = await _dbContext.Set() .Where(x => x.ReceiverUserId == Guid.Parse(profileId)) .Where(x => x.DeleteDate == null) .OrderByDescending(x => x.ReceiveDate) .Skip((page - 1) * pageSize) .Take(pageSize) // .Where(x => x.IsOpen == false) .ToListAsync(); foreach (var data_open in data_opens) { data_open.IsOpen = true; data_open.OpenDate = DateTime.Now; } await _dbContext.SaveChangesAsync(); var _data = new { data, total = data_search.Count(), totalNoti = totalNoti }; return _data; } catch { throw; } } public async Task GetMyNotificationAsyncNoread() { try { // var profile = await _dbContext.Set() // .FirstOrDefaultAsync(p => p.KeycloakId == Guid.Parse(UserId!)); // if (profile == null) // { // return 0; // } //var apiUrl = $"{_configuration["API"]}/org/profile/keycloak/position"; var apiUrl = $"{_configuration["API"]}/org/dotnet/get-profileId"; var profileId = ""; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); var org = JsonConvert.DeserializeObject(_result); if (org == null || org.result == null) return 0; profileId = org.result.profileId == null ? "" : org.result.profileId; } if (profileId == null || profileId == "") return 0; var data_search = await _dbContext.Set() .Where(x => x.ReceiverUserId == Guid.Parse(profileId)) .Where(x => x.DeleteDate == null) .Where(x => x.IsOpen == false) .OrderByDescending(x => x.ReceiveDate) .ToListAsync(); return data_search.Count(); } catch { throw; } } public async Task DeleteMyNotificationAsync(Guid id) { try { var notification = await _dbContext.Set() .FirstOrDefaultAsync(p => p.Id == id); if (notification != null) { notification.DeleteDate = DateTime.Now; // _dbContext.Set().Remove(notification); await _dbContext.SaveChangesAsync(); } } catch { throw; } } public async Task PushNotificationAsync(Guid ReceiverUserId, string Subject, string Body, string Payload = "", string NotiLink = "", bool IsSendInbox = false, bool IsSendMail = false) { try { // var profile = await _dbContext.Set().FirstOrDefaultAsync(x => x.Id == ReceiverUserId); //if (profile != null) //{ _dbContext.Set().Add(new Notification { Body = Body, ReceiverUserId = ReceiverUserId, Type = "", Payload = NotiLink, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); if (IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, ReceiverUserId = ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); } if (IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } await _dbContext.SaveChangesAsync(); //} } catch { throw; } } public async Task PushNotificationAsync2(Guid ReceiverUserId, string Subject, string Body, string Payload = "", string NotiLink = "", bool IsSendInbox = false, bool IsSendMail = false) { try { _dbContext.Set().Add(new Notification { Body = Body, ReceiverUserId = ReceiverUserId, Type = "", Payload = NotiLink, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); /* if (IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, ReceiverUserId = ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); }*/ if (IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } await _dbContext.SaveChangesAsync(); } catch { throw; } } public async Task PushEmailAsync(string Subject, string Body, string Email = "") { try { _emailSenderService.SendMail(Subject, Body, Email); } catch { throw; } } public async Task PushNotificationsAsync(Guid[] ReceiverUserIds, string Subject, string Body, string Payload = "", string NotiLink = "", bool IsSendInbox = false, bool IsSendMail = false) { try { foreach (var ReceiverUserId in ReceiverUserIds) { _dbContext.Set().Add(new Notification { Body = Body, ReceiverUserId = ReceiverUserId, Type = "", Payload = NotiLink, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); if (IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, ReceiverUserId = ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); } if (IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } } await _dbContext.SaveChangesAsync(); } catch { throw; } } public class NotisLinkRequest { public Guid ReceiverUserId { get; set; } public string NotiLink { get; set; } } public class ResultRequest { public string result { get; set; } } public async Task PushNotificationsLinkAsync(NotisLinkRequest[] ReceiverUserIds, string Subject, string Body, string Payload = "", bool IsSendInbox = false, bool IsSendMail = false) { try { foreach (var ReceiverUserId in ReceiverUserIds) { _dbContext.Set().Add(new Notification { Body = Body, ReceiverUserId = ReceiverUserId.ReceiverUserId, Type = "", Payload = ReceiverUserId.NotiLink, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); if (IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, ReceiverUserId = ReceiverUserId.ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); } if (IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{ReceiverUserId.ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } } await _dbContext.SaveChangesAsync(); } catch { throw; } } public class NotisLinkSendRequest { public Guid ReceiverUserId { get; set; } public string NotiLink { get; set; } public bool IsSendMail { get; set; } public bool IsSendInbox { get; set; } } public async Task PushNotificationsLinkSendAsync(NotisLinkSendRequest[] ReceiverUserIds, string Subject, string Body, string Payload = "") { try { foreach (var data in ReceiverUserIds) { _dbContext.Set().Add(new Notification { Body = Body, ReceiverUserId = data.ReceiverUserId, Type = "", Payload = data.NotiLink, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); if (data.IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, ReceiverUserId = data.ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); } if (data.IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{data.ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } } await _dbContext.SaveChangesAsync(); } catch { throw; } } public async Task PushNotificationAsyncV2(string? ReceiverUserId, string Subject, string Body, string Payload = "", bool IsSendInbox = false, bool IsSendMail = false) { try { if (ReceiverUserId != null) { _dbContext.Set().Add(new Notification { Body = Body, KeycloakUserId = ReceiverUserId, Type = "", Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); if (IsSendInbox == true) { _dbContext.Set().Add(new Inbox { Subject = Subject, Body = Body, KeycloakUserId = ReceiverUserId, Payload = Payload, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); } if (IsSendMail == true) { var apiUrl = $"{_configuration["API"]}/org/dotnet/email/{ReceiverUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", "")); client.DefaultRequestHeaders.Add("api-key", _configuration["API_KEY"]); var _req = new HttpRequestMessage(HttpMethod.Get, apiUrl); var _res = await client.SendAsync(_req); var _result = await _res.Content.ReadAsStringAsync(); if (_res.IsSuccessStatusCode) { var org = JsonConvert.DeserializeObject(_result); if (org != null && org.result != null && org.result != "") _emailSenderService.SendMail(Subject, Body, org.result); } } } await _dbContext.SaveChangesAsync(); } } catch { throw; } } #endregion } }