DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/NotificationRepository.cs

87 lines
2.1 KiB
C#

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudDb;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
namespace AsbCloudInfrastructure.Repository;
public class NotificationRepository : CrudRepositoryBase<NotificationDto, Notification>, INotificationRepository
{
private static IQueryable<Notification> MakeQueryNotification(DbSet<Notification> dbSet)
=> dbSet.Include(n => n.NotificationCategory)
.Include(n => n.User)
.AsNoTracking();
public NotificationRepository(IAsbCloudDbContext context)
: base(context, MakeQueryNotification)
{
}
public async Task<PaginationContainer<NotificationDto>> GetNotificationsAsync(int idUser,
NotificationRequest request,
CancellationToken cancellationToken)
{
var skip = request.Skip ?? 0;
var take = request.Take ?? 10;
var query = BuildQuery(idUser, request);
var result = new PaginationContainer<NotificationDto>
{
Skip = skip,
Take = take,
Count = await query.CountAsync(cancellationToken),
};
if (result.Count < skip)
return result;
result.Items = await query
.SortBy(request.SortFields)
.Skip(skip)
.Take(take)
.AsNoTracking()
.Select(x => x.Adapt<NotificationDto>())
.ToArrayAsync(cancellationToken);
return result;
}
public async Task<int> GetUnreadCountAsync(int idUser, CancellationToken cancellationToken)
{
var count = await dbContext.Notifications
.Where(n => n.ReadDate == null)
.Where(n => n.IdUser == idUser)
.CountAsync(cancellationToken);
return count;
}
private IQueryable<Notification> BuildQuery(int idUser,
NotificationRequest request)
{
var query = dbContext.Notifications
.Include(x => x.NotificationCategory)
.Where(n => n.IdUser == idUser);
if (request.IsSent.HasValue)
{
query = request.IsSent.Value ?
query.Where(n => n.SentDate != null)
: query.Where(n => n.SentDate == null);
}
if (request.IdTransportType.HasValue)
query = query.Where(n => n.IdTransportType == request.IdTransportType);
return query;
}
}