hrms-api-backend/BMA.EHR.Application/Repositories/MessageQueue/InboxRepository.cs
2023-09-11 14:22:21 +07:00

115 lines
3.7 KiB
C#

using BMA.EHR.Application.Common.Interfaces;
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 Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace BMA.EHR.Application.Repositories.MessageQueue
{
public class InboxRepository : GenericRepository<Guid, Inbox>
{
#region " Fields "
private readonly IApplicationDBContext _dbContext;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destuctor "
public InboxRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
{
_dbContext = dbContext;
_httpContextAccessor = httpContextAccessor;
}
#endregion
#region " Methods "
public async Task<List<InboxResponse>> GetMyInboxAsync()
{
try
{
var profile = await _dbContext.Set<Profile>()
.FirstOrDefaultAsync(p => p.KeycloakId == Guid.Parse(UserId!));
if (profile == null)
{
throw new Exception(GlobalMessages.DataNotFound);
}
var data = await _dbContext.Set<Inbox>()
.Where(x => x.ReceiverUserId == profile.Id)
.Where(x => x.IsOpen == false)
.OrderByDescending(x => x.ReceiveDate)
.Select(x => new InboxResponse
{
Subject = x.Subject,
Body = x.Body,
ReceiverUserId = x.ReceiverUserId,
IsOpen = x.IsOpen,
ReceiveDate = x.ReceiveDate,
OpenDate = x.OpenDate,
Payload = x.Payload == "" ? null : JsonConvert.DeserializeObject<CommandPayload>(Regex.Unescape(x.Payload))
})
.Take(20)
.ToListAsync();
return data;
}
catch
{
throw;
}
}
public async Task DeleteMyInboxAsync(Guid id)
{
try
{
var inbox = await _dbContext.Set<Inbox>()
.FirstOrDefaultAsync(p => p.Id == id);
if (inbox != null)
{
inbox.IsOpen = true;
// _dbContext.Set<Inbox>().Remove(inbox);
await _dbContext.SaveChangesAsync();
}
}
catch
{
throw;
}
}
public async Task GetByIdMyInboxAsync(Guid id)
{
try
{
var inbox = await _dbContext.Set<Inbox>()
.FirstOrDefaultAsync(p => p.Id == id);
if (inbox != null)
{
inbox.OpenDate = DateTime.Now;
// _dbContext.Set<Inbox>().Remove(inbox);
await _dbContext.SaveChangesAsync();
}
}
catch
{
throw;
}
}
#endregion
}
}