using BMA.EHR.Application.Repositories; using BMA.EHR.Application.Repositories.MessageQueue; using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Models.Probation; using BMA.EHR.Domain.Shared; using BMA.EHR.Infrastructure.Persistence; using BMA.EHR.Placement.Service.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using RabbitMQ.Client.Events; using RabbitMQ.Client; using Swashbuckle.AspNetCore.Annotations; using System.Net.Http.Headers; using System.Security.Claims; using System.Text; namespace BMA.EHR.Placement.Service.Controllers { [Route("api/v{version:apiVersion}/placement/noti")] [ApiVersion("1.0")] [ApiController] [Produces("application/json")] [Authorize] [SwaggerTag("ระบบบรรจุ")] public class NotifyController : BaseController { private readonly PlacementRepository _repository; private readonly ApplicationDBContext _context; private readonly MinIOService _documentService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly NotificationRepository _repositoryNoti; private readonly IConfiguration _configuration; public NotifyController(PlacementRepository repository, ApplicationDBContext context, MinIOService documentService, NotificationRepository repositoryNoti, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) { _repository = repository; _repositoryNoti = repositoryNoti; _context = context; _documentService = documentService; _httpContextAccessor = httpContextAccessor; _configuration = configuration; } #region " Properties " private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value; private string? token => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"]; #endregion /// /// ทดสอบ (Rabbit MQ) /// /// [HttpPost("test-queue")] public async Task> TestRabbitMQ([FromBody] NotiRequest req) { var host = "localhost"; var userName = "guest"; var password = "guest"; var factory = new ConnectionFactory() { HostName = host, UserName = userName, Password = password }; Console.WriteLine("Send to Consume!"); using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "test_dotnet", durable: false, exclusive: false, autoDelete: false, arguments: null); var jsonString = JsonConvert.SerializeObject(req); var body = Encoding.UTF8.GetBytes(jsonString); channel.BasicPublish(exchange: "", routingKey: "test_dotnet", basicProperties: null, body: body); var consumer = new EventingBasicConsumer(channel); var receivedTaskCompletionSource = new TaskCompletionSource(); consumer.Received += async (model, x) => { await _repositoryNoti.PushNotificationAsync2( Guid.Parse(req.ReceiverUserId), req.Subject, req.Body, req.Payload, "", req.IsSendInbox, req.IsSendMail ); receivedTaskCompletionSource.SetResult(true); }; channel.BasicConsume("test_dotnet", autoAck: true, consumer); Console.WriteLine("Consume Worked!"); return Success(); } } [HttpPost()] public async Task> UpdatePropertyByUser([FromBody] NotiRequest req) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(req.ReceiverUserId), req.Subject, req.Body, req.Payload, "", req.IsSendInbox, req.IsSendMail ); return Success(); } [HttpPost("keycloak")] public async Task> UpdatePropertyByUserKeycloak([FromBody] NotiRequest req) { var apiUrl = $"{_configuration["API"]}/org/profile/keycloakid/position/" + req.ReceiverUserId; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.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) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(org.result.id), req.Subject, req.Body, req.Payload, "", req.IsSendInbox, req.IsSendMail ); } return Success(); } } [HttpPost("profile")] public async Task> UpdatePropertyByUserProfile([FromBody] NotiRequest req) { if (req.ReceiverUserId != null) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(req.ReceiverUserId), req.Subject, req.Body, req.Payload, "", req.IsSendInbox, req.IsSendMail ); } return Success(); } [HttpPost("email")] public async Task> SendEmail([FromBody] SendEmailRequest req) { await _repositoryNoti.PushEmailAsync( req.Subject, req.Body, req.Email ); return Success(); } [HttpPost("profiles")] public async Task> UpdatePropertyByUserProfiles([FromBody] NotisRequest req) { await _repositoryNoti.PushNotificationsLinkAsync( req.ReceiverUserIds, req.Subject, req.Body, req.Payload, req.IsSendInbox, req.IsSendMail ); return Success(); } [HttpPost("profiles-send")] public async Task> UpdatePropertyByUserProfiles_send([FromBody] NotisSendRequest req) { await _repositoryNoti.PushNotificationsLinkSendAsync( req.ReceiverUserIds, req.Subject, req.Body, req.Payload ); return Success(); } [HttpPut("{id:length(36)}")] public async Task> ReplyPropertyByUser([FromBody] NotiReplyRequest req, Guid id) { var inbox = await _context.Inboxes.FirstOrDefaultAsync(x => x.Id == id); if (inbox == null) return Error(GlobalMessages.DataNotFound); if (inbox.CreatedUserId == null || inbox.CreatedUserId == "") return Error("ข้อความนี้เป็นการแจ้งเตือนจากระบบไม่สามารถตอบกลับได้"); var apiUrl = $"{_configuration["API"]}/org/profile/keycloakid/position/{inbox.CreatedUserId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.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) { await _repositoryNoti.PushNotificationAsync( Guid.Parse(org.result.id), req.Subject, req.Body, req.Payload, "", req.IsSendInbox, req.IsSendMail ); } return Success(); } } [HttpPost("send-mail")] public async Task> sendEmailOnly([FromBody] NotiEmailRequest req) { await _repositoryNoti.PushEmailAsync( req.Subject, req.Body, req.Email ); return Success(); } [HttpPost("cronjob")] public async Task> CornjobProbation([FromBody] NotiCronjobProbationRequest req) { // var profile = await _context.Profiles.FirstOrDefaultAsync(x => x.Id == req.ReceiverUserId); // if (profile == null) // return Error(GlobalMessages.DataNotFound); _context.CronjobNotiProbations.Add(new CronjobNotiProbation { IsSendNoti = false, Subject = req.Subject, Body = req.Body, ReceiverUserId = req.ReceiverUserId, Payload = req.Payload, IsSendMail = req.IsSendMail, IsSendInbox = req.IsSendInbox, ReceiveDate = req.ReceiveDate, CreatedFullName = FullName ?? "System Administrator", CreatedUserId = UserId ?? "", CreatedAt = DateTime.Now, LastUpdateFullName = FullName ?? "System Administrator", LastUpdateUserId = UserId ?? "", LastUpdatedAt = DateTime.Now, }); await _context.SaveChangesAsync(); return Success(); } } }