Исправление в работе с данными

1. Изменил сущность уведомления. Добавил состояние уведомления
2. Удалил сущность для доставки уведомлений.
3. Изменение DTO уведомления.
4. Добавил миграцию.
5. Поправил DbContext.
This commit is contained in:
parent 88f391dadd
commit 985c0489d0
13 changed files with 257 additions and 390 deletions

View File

@ -1,9 +1,10 @@
using System;
using System.Text.Json.Serialization;
namespace AsbCloudApp.Data;
/// <summary>
/// DTO уведомлений
/// DTO уведомления
/// </summary>
public class NotificationDto : IId
{
@ -17,11 +18,6 @@ public class NotificationDto : IId
/// </summary>
public int IdUser { get; set; }
/// <summary>
/// Id способа отправки уведомления
/// </summary>
public int IdNotificationTransport { get; set; }
/// <summary>
/// Id категории уведомления
/// </summary>
@ -33,9 +29,9 @@ public class NotificationDto : IId
public string Title { get; set; } = null!;
/// <summary>
/// Текст уведомления
/// Сообщение уведомления
/// </summary>
public string Subject { get; set; } = null!;
public string Message { get; set; } = null!;
/// <summary>
/// Время жизни уведомления
@ -45,20 +41,52 @@ public class NotificationDto : IId
/// <summary>
/// Дата отправки уведомления
/// </summary>
public DateTime? SentDateAtUtc { get; set; }
public DateTime? SentDate { get; set; }
/// <summary>
/// Состояния уведомления
/// </summary>
public NotificationState NotificationState { get; set; }
/// <summary>
/// Способ доставки уведомления
/// </summary>
public NotificationTransport NotificationTransport { get; set; }
/// <summary>
/// Прочитано ли уведомление
/// </summary>
public bool? IsRead { get; set; }
/// <summary>
/// DTO способа доставки уведомления
/// </summary>
public NotificationTransportDto NotificationTransport { get; set; } = null!;
/// <summary>
/// DTO категории уведомления
/// </summary>
public NotificationCategoryDto NotificationCategory { get; set; } = null!;
}
/// <summary>
/// Состояние уведомления
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NotificationState
{
/// <summary>
/// Зарегистрировано
/// </summary>
Registered = 1,
/// <summary>
/// Отправлено
/// </summary>
Sent = 2,
/// <summary>
/// Прочитано
/// </summary>
Read = 3,
}
/// <summary>
/// Способ отправки уведомления
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NotificationTransport
{
/// <summary>
/// SignalR
/// </summary>
SignalR = 1
}

View File

@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
namespace AsbCloudApp.Repositories;
@ -12,28 +13,25 @@ namespace AsbCloudApp.Repositories;
public interface INotificationRepository : ICrudRepository<NotificationDto>
{
/// <summary>
/// Метод для получения не отправленных уведомлений
/// Получение не отправленных уведомлений
/// </summary>
/// <param name="idUser"></param>
/// <param name="idNotificationTransport"></param>
/// <param name="notificationTransport"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<NotificationDto>> GetUnsentNotificationsAsync(int idUser,
int idNotificationTransport,
NotificationTransport notificationTransport,
CancellationToken cancellationToken);
/// <summary>
/// Метод получения уведомлений по параметрам
/// Получение уведомлений по параметрам
/// </summary>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <param name="idUser"></param>
/// <param name="idNotificationTransport"></param>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<PaginationContainer<NotificationDto>> GetNotificationsAsync(int? skip,
int? take,
int idUser,
int idNotificationTransport,
Task<PaginationContainer<NotificationDto>> GetNotificationsAsync(int idUser,
NotificationRequest request,
CancellationToken cancellationToken);
}

View File

@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using AsbCloudApp.Data;
namespace AsbCloudApp.Requests;
/// <summary>
/// Параметры запроса для получения уведомлений
/// </summary>
public class NotificationRequest : RequestBase
{
/// <summary>
/// Способ отправки уведомления
/// </summary>
[Required]
public NotificationTransport NotificationTransport { get; set; }
}

View File

@ -1,176 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Notifications : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "id_category",
table: "t_help_page",
type: "integer",
nullable: false,
comment: "Id категории файла",
oldClrType: typeof(int),
oldType: "integer",
oldComment: "id категории файла");
migrationBuilder.CreateTable(
name: "t_notification_category",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_t_notification_category", x => x.id);
},
comment: "Категории уведомлений");
migrationBuilder.CreateTable(
name: "t_notification_transport",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
name = table.Column<string>(type: "text", nullable: false, comment: "Название способа доставки уведомлений")
},
constraints: table =>
{
table.PrimaryKey("PK_t_notification_transport", x => x.id);
},
comment: "Способ доставки уведомлений");
migrationBuilder.CreateTable(
name: "t_notification",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user = table.Column<int>(type: "integer", nullable: false, comment: "Id получателя"),
id_notification_transport = table.Column<int>(type: "integer", nullable: false, comment: "Id способа доставки уведомления"),
id_notification_category = table.Column<int>(type: "integer", nullable: false, comment: "Id категории уведомления"),
title = table.Column<string>(type: "text", nullable: false, comment: "Заголовок уведомления"),
subject = table.Column<string>(type: "text", nullable: false, comment: "Текст уведомления"),
time_to_life = table.Column<TimeSpan>(type: "interval", nullable: false, comment: "Время жизни уведомления"),
sent_date_at_utc = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "Дата отправки уведомления"),
is_read = table.Column<bool>(type: "boolean", nullable: true, comment: "Прочитано ли уведомление")
},
constraints: table =>
{
table.PrimaryKey("PK_t_notification", x => x.id);
table.ForeignKey(
name: "FK_t_notification_t_notification_category_id_notification_cate~",
column: x => x.id_notification_category,
principalTable: "t_notification_category",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_notification_t_notification_transport_id_notification_tra~",
column: x => x.id_notification_transport,
principalTable: "t_notification_transport",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_notification_t_user_id_user",
column: x => x.id_user,
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Уведомлений");
migrationBuilder.InsertData(
table: "t_notification_category",
columns: new[] { "id", "name" },
values: new object[] { 1, "Системные уведомления" });
migrationBuilder.InsertData(
table: "t_notification_transport",
columns: new[] { "id", "name" },
values: new object[] { 1, "SignalR" });
migrationBuilder.InsertData(
table: "t_permission",
columns: new[] { "id", "description", "name" },
values: new object[,]
{
{ 519, "Разрешение просматривать список контактов", "WellContact.get" },
{ 520, "Разрешение редактировать список контактов", "WellContact.edit" }
});
migrationBuilder.InsertData(
table: "t_relation_user_role_permission",
columns: new[] { "id_permission", "id_user_role" },
values: new object[,]
{
{ 519, 1 },
{ 520, 1 }
});
migrationBuilder.CreateIndex(
name: "IX_t_notification_id_notification_category",
table: "t_notification",
column: "id_notification_category");
migrationBuilder.CreateIndex(
name: "IX_t_notification_id_notification_transport",
table: "t_notification",
column: "id_notification_transport");
migrationBuilder.CreateIndex(
name: "IX_t_notification_id_user",
table: "t_notification",
column: "id_user");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_notification");
migrationBuilder.DropTable(
name: "t_notification_category");
migrationBuilder.DropTable(
name: "t_notification_transport");
migrationBuilder.DeleteData(
table: "t_relation_user_role_permission",
keyColumns: new[] { "id_permission", "id_user_role" },
keyValues: new object[] { 519, 1 });
migrationBuilder.DeleteData(
table: "t_relation_user_role_permission",
keyColumns: new[] { "id_permission", "id_user_role" },
keyValues: new object[] { 520, 1 });
migrationBuilder.DeleteData(
table: "t_permission",
keyColumn: "id",
keyValue: 519);
migrationBuilder.DeleteData(
table: "t_permission",
keyColumn: "id",
keyValue: 520);
migrationBuilder.AlterColumn<int>(
name: "id_category",
table: "t_help_page",
type: "integer",
nullable: false,
comment: "id категории файла",
oldClrType: typeof(int),
oldType: "integer",
oldComment: "Id категории файла");
}
}
}

View File

@ -13,8 +13,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace AsbCloudDb.Migrations
{
[DbContext(typeof(AsbCloudDbContext))]
[Migration("20230710113646_Add_Notifications")]
partial class Add_Notifications
[Migration("20230711130624_Add_Notification")]
partial class Add_Notification
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
@ -991,7 +991,7 @@ namespace AsbCloudDb.Migrations
b.Property<int>("IdCategory")
.HasColumnType("integer")
.HasColumnName("id_category")
.HasComment("Id категории файла");
.HasComment("id категории файла");
b.Property<string>("Name")
.IsRequired()
@ -1168,31 +1168,33 @@ namespace AsbCloudDb.Migrations
.HasColumnName("id_notification_category")
.HasComment("Id категории уведомления");
b.Property<int>("IdNotificationTransport")
.HasColumnType("integer")
.HasColumnName("id_notification_transport")
.HasComment("Id способа доставки уведомления");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("Id получателя");
b.Property<bool?>("IsRead")
.HasColumnType("boolean")
.HasColumnName("is_read")
.HasComment("Прочитано ли уведомление");
b.Property<DateTime?>("SentDateAtUtc")
.HasColumnType("timestamp with time zone")
.HasColumnName("sent_date_at_utc")
.HasComment("Дата отправки уведомления");
b.Property<string>("Subject")
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text")
.HasColumnName("subject")
.HasComment("Текст уведомления");
.HasColumnName("message")
.HasComment("Сообщение уведомления");
b.Property<string>("NotificationState")
.IsRequired()
.HasColumnType("text")
.HasColumnName("notification_state")
.HasComment("Состояние уведомления");
b.Property<string>("NotificationTransport")
.IsRequired()
.HasColumnType("text")
.HasColumnName("notification_transport")
.HasComment("Метод доставки уведомления");
b.Property<DateTime?>("SentDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("sent_date")
.HasComment("Дата отправки уведомления");
b.Property<TimeSpan>("TimeToLife")
.HasColumnType("interval")
@ -1209,13 +1211,11 @@ namespace AsbCloudDb.Migrations
b.HasIndex("IdNotificationCategory");
b.HasIndex("IdNotificationTransport");
b.HasIndex("IdUser");
b.ToTable("t_notification");
b.HasComment("Уведомлений");
b.HasComment("Уведомления");
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationCategory", b =>
@ -1246,35 +1246,6 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationTransport", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text")
.HasColumnName("name")
.HasComment("Название способа доставки уведомлений");
b.HasKey("Id");
b.ToTable("t_notification_transport");
b.HasComment("Способ доставки уведомлений");
b.HasData(
new
{
Id = 1,
Name = "SignalR"
});
});
modelBuilder.Entity("AsbCloudDb.Model.OperationValue", b =>
{
b.Property<int>("Id")
@ -7690,12 +7661,6 @@ namespace AsbCloudDb.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.NotificationTransport", "NotificationTransport")
.WithMany("Notifications")
.HasForeignKey("IdNotificationTransport")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
@ -7704,8 +7669,6 @@ namespace AsbCloudDb.Migrations
b.Navigation("NotificationCategory");
b.Navigation("NotificationTransport");
b.Navigation("User");
});
@ -8306,11 +8269,6 @@ namespace AsbCloudDb.Migrations
b.Navigation("Notifications");
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationTransport", b =>
{
b.Navigation("Notifications");
});
modelBuilder.Entity("AsbCloudDb.Model.Permission", b =>
{
b.Navigation("RelationUserRolePermissions");

View File

@ -0,0 +1,85 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Notification : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "t_notification_category",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_t_notification_category", x => x.id);
},
comment: "Категории уведомлений");
migrationBuilder.CreateTable(
name: "t_notification",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user = table.Column<int>(type: "integer", nullable: false, comment: "Id получателя"),
id_notification_category = table.Column<int>(type: "integer", nullable: false, comment: "Id категории уведомления"),
title = table.Column<string>(type: "text", nullable: false, comment: "Заголовок уведомления"),
message = table.Column<string>(type: "text", nullable: false, comment: "Сообщение уведомления"),
time_to_life = table.Column<TimeSpan>(type: "interval", nullable: false, comment: "Время жизни уведомления"),
sent_date = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "Дата отправки уведомления"),
notification_state = table.Column<string>(type: "text", nullable: false, comment: "Состояние уведомления"),
notification_transport = table.Column<string>(type: "text", nullable: false, comment: "Метод доставки уведомления")
},
constraints: table =>
{
table.PrimaryKey("PK_t_notification", x => x.id);
table.ForeignKey(
name: "FK_t_notification_t_notification_category_id_notification_cate~",
column: x => x.id_notification_category,
principalTable: "t_notification_category",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_notification_t_user_id_user",
column: x => x.id_user,
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Уведомления");
migrationBuilder.InsertData(
table: "t_notification_category",
columns: new[] { "id", "name" },
values: new object[] { 1, "Системные уведомления" });
migrationBuilder.CreateIndex(
name: "IX_t_notification_id_notification_category",
table: "t_notification",
column: "id_notification_category");
migrationBuilder.CreateIndex(
name: "IX_t_notification_id_user",
table: "t_notification",
column: "id_user");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_notification");
migrationBuilder.DropTable(
name: "t_notification_category");
}
}
}

View File

@ -1166,31 +1166,33 @@ namespace AsbCloudDb.Migrations
.HasColumnName("id_notification_category")
.HasComment("Id категории уведомления");
b.Property<int>("IdNotificationTransport")
.HasColumnType("integer")
.HasColumnName("id_notification_transport")
.HasComment("Id способа доставки уведомления");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("Id получателя");
b.Property<bool?>("IsRead")
.HasColumnType("boolean")
.HasColumnName("is_read")
.HasComment("Прочитано ли уведомление");
b.Property<DateTime?>("SentDateAtUtc")
.HasColumnType("timestamp with time zone")
.HasColumnName("sent_date_at_utc")
.HasComment("Дата отправки уведомления");
b.Property<string>("Subject")
b.Property<string>("Message")
.IsRequired()
.HasColumnType("text")
.HasColumnName("subject")
.HasComment("Текст уведомления");
.HasColumnName("message")
.HasComment("Сообщение уведомления");
b.Property<string>("NotificationState")
.IsRequired()
.HasColumnType("text")
.HasColumnName("notification_state")
.HasComment("Состояние уведомления");
b.Property<string>("NotificationTransport")
.IsRequired()
.HasColumnType("text")
.HasColumnName("notification_transport")
.HasComment("Метод доставки уведомления");
b.Property<DateTime?>("SentDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("sent_date")
.HasComment("Дата отправки уведомления");
b.Property<TimeSpan>("TimeToLife")
.HasColumnType("interval")
@ -1207,13 +1209,11 @@ namespace AsbCloudDb.Migrations
b.HasIndex("IdNotificationCategory");
b.HasIndex("IdNotificationTransport");
b.HasIndex("IdUser");
b.ToTable("t_notification");
b.HasComment("Уведомлений");
b.HasComment("Уведомления");
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationCategory", b =>
@ -1244,35 +1244,6 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationTransport", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text")
.HasColumnName("name")
.HasComment("Название способа доставки уведомлений");
b.HasKey("Id");
b.ToTable("t_notification_transport");
b.HasComment("Способ доставки уведомлений");
b.HasData(
new
{
Id = 1,
Name = "SignalR"
});
});
modelBuilder.Entity("AsbCloudDb.Model.OperationValue", b =>
{
b.Property<int>("Id")
@ -7688,12 +7659,6 @@ namespace AsbCloudDb.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.NotificationTransport", "NotificationTransport")
.WithMany("Notifications")
.HasForeignKey("IdNotificationTransport")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
@ -7702,8 +7667,6 @@ namespace AsbCloudDb.Migrations
b.Navigation("NotificationCategory");
b.Navigation("NotificationTransport");
b.Navigation("User");
});
@ -8304,11 +8267,6 @@ namespace AsbCloudDb.Migrations
b.Navigation("Notifications");
});
modelBuilder.Entity("AsbCloudDb.Model.NotificationTransport", b =>
{
b.Navigation("Notifications");
});
modelBuilder.Entity("AsbCloudDb.Model.Permission", b =>
{
b.Navigation("RelationUserRolePermissions");

View File

@ -77,7 +77,6 @@ namespace AsbCloudDb.Model
public DbSet<HelpPage> HelpPages => Set<HelpPage>();
public DbSet<Notification> Notifications => Set<Notification>();
public DbSet<NotificationCategory> NotificationCategories => Set<NotificationCategory>();
public DbSet<NotificationTransport> NotificationTransports => Set<NotificationTransport>();
public AsbCloudDbContext() : base()
{

View File

@ -26,7 +26,6 @@ namespace AsbCloudDb.Model.DefaultData
{ typeof(CompanyType), new EntityFillerCompanyType()},
{ typeof(Subsystems.Subsystem), new EntityFillerSubsystem() },
{ typeof(NotificationCategory), new EntityNotificationCategory()},
{ typeof(NotificationTransport), new EntityNotificationTransport() }
};
return fillers;
}

View File

@ -1,9 +0,0 @@
namespace AsbCloudDb.Model.DefaultData;
public class EntityNotificationTransport : EntityFiller<NotificationTransport>
{
public override NotificationTransport[] GetData() => new NotificationTransport[]
{
new() { Id = 1, Name = "SignalR" }
};
}

View File

@ -70,8 +70,6 @@ namespace AsbCloudDb.Model
DbSet<HelpPage> HelpPages { get; }
DbSet<Notification> Notifications { get; }
DbSet<NotificationCategory> NotificationCategories { get; }
DbSet<NotificationTransport> NotificationTransports { get; }
DatabaseFacade Database { get; }
Task<int> RefreshMaterializedViewAsync(string mwName, CancellationToken token);

View File

@ -5,7 +5,7 @@ using Microsoft.EntityFrameworkCore;
namespace AsbCloudDb.Model;
[Table("t_notification"), Comment("Уведомлений")]
[Table("t_notification"), Comment("Уведомления")]
public class Notification : IId
{
[Key]
@ -14,31 +14,28 @@ public class Notification : IId
[Column("id_user"), Comment("Id получателя")]
public int IdUser { get; set; }
[Column("id_notification_transport"), Comment("Id способа доставки уведомления")]
public int IdNotificationTransport { get; set; }
[Column("id_notification_category"), Comment("Id категории уведомления")]
public int IdNotificationCategory { get; set; }
[Column("title"), Comment("Заголовок уведомления")]
public string Title { get; set; } = null!;
[Column("subject"), Comment("Текст уведомления")]
public string Subject { get; set; } = null!;
[Column("message"), Comment("Сообщение уведомления")]
public string Message { get; set; } = null!;
[Column("time_to_life"), Comment("Время жизни уведомления")]
public TimeSpan TimeToLife { get; set; }
[Column("sent_date_at_utc"), Comment("Дата отправки уведомления")]
public DateTime? SentDateAtUtc { get; set; }
[Column("is_read"), Comment("Прочитано ли уведомление")]
public bool? IsRead { get; set; }
[Column("sent_date"), Comment("Дата отправки уведомления")]
public DateTime? SentDate { get; set; }
[Column("notification_state"), Comment("Состояние уведомления")]
public string NotificationState { get; set; } = null!;
[Column("notification_transport"), Comment("Метод доставки уведомления")]
public string NotificationTransport { get; set; } = null!;
[ForeignKey(nameof(IdNotificationTransport))]
public virtual NotificationTransport NotificationTransport { get; set; } = null!;
[ForeignKey(nameof(IdNotificationCategory))]
public virtual NotificationCategory NotificationCategory { get; set; } = null!;

View File

@ -5,57 +5,54 @@ 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;
using Microsoft.Extensions.Caching.Memory;
namespace AsbCloudInfrastructure.Repository;
public class NotificationRepository : CrudRepositoryBase<NotificationDto, Notification>, INotificationRepository
public class NotificationRepository : CrudCacheRepositoryBase<NotificationDto, Notification>, INotificationRepository
{
public NotificationRepository(IAsbCloudDbContext context) : base(context)
{
}
private static IQueryable<Notification> MakeQueryNotification(DbSet<Notification> dbSet)
=> dbSet.AsNoTracking()
.Include(n => n.NotificationCategory);
public NotificationRepository(IAsbCloudDbContext context,
Func<DbSet<Notification>, IQueryable<Notification>> makeQuery) : base(context, makeQuery)
public NotificationRepository(IAsbCloudDbContext dbContext, IMemoryCache memoryCache)
: base(dbContext, memoryCache, MakeQueryNotification)
{
}
public async Task<IEnumerable<NotificationDto>> GetUnsentNotificationsAsync(int idUser,
int idNotificationTransport,
NotificationTransport notificationTransport,
CancellationToken cancellationToken)
{
var notifications = await dbContext.Notifications
var notifications = (await GetCacheAsync(cancellationToken))
.Where(x => x.IdUser == idUser &&
x.IdNotificationTransport == idNotificationTransport &&
x.SentDateAtUtc == null)
.Include(x => x.NotificationTransport)
.Include(x => x.NotificationCategory)
.ToListAsync(cancellationToken);
x.NotificationTransport == notificationTransport.ToString() &&
x.SentDate == null);
return notifications.Select(x => x.Adapt<NotificationDto>());
return notifications.Select(Convert);
}
public async Task<PaginationContainer<NotificationDto>> GetNotificationsAsync(int? skip,
int? take,
int idUser,
int idNotificationTransport,
public async Task<PaginationContainer<NotificationDto>> GetNotificationsAsync(int idUser,
NotificationRequest request,
CancellationToken cancellationToken)
{
skip ??= 0;
take ??= 10;
request.Skip ??= 0;
request.Take ??= 10;
var query = dbContext.Notifications
.Where(x => x.IdNotificationTransport == idNotificationTransport &&
.Where(x => x.NotificationTransport == request.NotificationTransport.ToString() &&
x.IdUser == idUser &&
x.SentDateAtUtc != null);
x.SentDate != null);
var result = new PaginationContainer<NotificationDto>()
{
Skip = skip.Value,
Take = take.Value,
Skip = request.Skip.Value,
Take = request.Take.Value,
Count = await query.CountAsync(cancellationToken),
};
@ -63,13 +60,32 @@ public class NotificationRepository : CrudRepositoryBase<NotificationDto, Notifi
return result;
result.Items = await query
.OrderBy(x => x.SentDateAtUtc)
.SkipTake(skip, take)
.SortBy(request.SortFields)
.SkipTake(request.Skip, request.Take)
.Include(x => x.NotificationCategory)
.Include(x => x.NotificationTransport)
.Select(x => x.Adapt<NotificationDto>())
.ToListAsync(cancellationToken);
return result;
}
protected override Notification Convert(NotificationDto src)
{
var entity = src.Adapt<Notification>();
entity.NotificationState = src.NotificationState.ToString();
entity.NotificationTransport = src.NotificationTransport.ToString();
return entity;
}
protected override NotificationDto Convert(Notification src)
{
var dto = src.Adapt<NotificationDto>();
dto.NotificationState = (NotificationState)Enum.Parse(typeof(NotificationState), src.NotificationState);
dto.NotificationTransport = (NotificationTransport)Enum.Parse(typeof(NotificationTransport), src.NotificationTransport);
return dto;
}
}