feat: добавил личные уведомления для пользователей
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 9s
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 26s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Successful in 19s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 8s

Реализовал хранение, получение и отметку прочитанными пользовательских уведомлений. Обновил фронтенд для отображения и управления уведомлениями в профиле студента.
This commit is contained in:
2026-05-12 23:54:55 +03:00
parent feff77b232
commit b0a4a6d259
19 changed files with 401 additions and 10 deletions
@@ -23,6 +23,7 @@ public class AppDbContext : DbContext
public DbSet<Achievement> Achievements { get; set; } = null!;
public DbSet<UserAchievement> UserAchievements { get; set; } = null!;
public DbSet<CoinTransaction> CoinTransactions { get; set; } = null!;
public DbSet<UserNotification> UserNotifications { get; set; } = null!;
public DbSet<RefreshToken> RefreshTokens { get; set; } = null!;
static AppDbContext()
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using UniVerse.Domain.Entities;
namespace UniVerse.Infrastructure.Data.Configurations;
public class UserNotificationConfiguration : IEntityTypeConfiguration<UserNotification>
{
public void Configure(EntityTypeBuilder<UserNotification> builder)
{
builder.ToTable("user_notifications");
builder.HasKey(n => n.Id);
builder.Property(n => n.Id).HasColumnName("id");
builder.Property(n => n.UserId).HasColumnName("user_id");
builder.Property(n => n.Type).HasColumnName("type").HasMaxLength(50).IsRequired();
builder.Property(n => n.Title).HasColumnName("title").HasMaxLength(255).IsRequired();
builder.Property(n => n.Body).HasColumnName("body").HasMaxLength(1000).IsRequired();
builder.Property(n => n.IsRead).HasColumnName("is_read").HasDefaultValue(false);
builder.Property(n => n.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
builder.HasOne(n => n.User)
.WithMany(u => u.Notifications)
.HasForeignKey(n => n.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(n => new { n.UserId, n.CreatedAt });
}
}
@@ -0,0 +1,54 @@
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using UniVerse.Infrastructure.Data;
#nullable disable
namespace UniVerse.Infrastructure.Migrations
{
/// <inheritdoc />
[DbContext(typeof(AppDbContext))]
[Migration("20260512123000_UserNotifications")]
public partial class UserNotifications : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "user_notifications",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
user_id = table.Column<int>(type: "integer", nullable: false),
type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
title = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
body = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: false),
is_read = table.Column<bool>(type: "boolean", nullable: false, defaultValue: false),
created_at = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
},
constraints: table =>
{
table.PrimaryKey("PK_user_notifications", x => x.id);
table.ForeignKey(
name: "FK_user_notifications_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_user_notifications_user_id_created_at",
table: "user_notifications",
columns: new[] { "user_id", "created_at" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "user_notifications");
}
}
}
@@ -721,6 +721,56 @@ namespace UniVerse.Infrastructure.Migrations
b.ToTable("user_achievements", (string)null);
});
modelBuilder.Entity("UniVerse.Domain.Entities.UserNotification", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Body")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)")
.HasColumnName("body");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<bool>("IsRead")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasColumnName("is_read");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("title");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("type");
b.Property<int>("UserId")
.HasColumnType("integer")
.HasColumnName("user_id");
b.HasKey("Id");
b.HasIndex("UserId", "CreatedAt");
b.ToTable("user_notifications", (string)null);
});
modelBuilder.Entity("UniVerse.Domain.Entities.UserRoleAssignment", b =>
{
b.Property<int>("UserId")
@@ -905,6 +955,17 @@ namespace UniVerse.Infrastructure.Migrations
b.Navigation("User");
});
modelBuilder.Entity("UniVerse.Domain.Entities.UserNotification", b =>
{
b.HasOne("UniVerse.Domain.Entities.User", "User")
.WithMany("Notifications")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("UniVerse.Domain.Entities.UserRoleAssignment", b =>
{
b.HasOne("UniVerse.Domain.Entities.User", "User")
@@ -958,6 +1019,8 @@ namespace UniVerse.Infrastructure.Migrations
b.Navigation("Enrollments");
b.Navigation("Notifications");
b.Navigation("RefreshTokens");
b.Navigation("Reviews");
@@ -1,20 +1,27 @@
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using UniVerse.Application.DTOs.Common;
using UniVerse.Application.DTOs.Notifications;
using UniVerse.Application.Interfaces;
using UniVerse.Domain.Entities;
using UniVerse.Infrastructure.Data;
namespace UniVerse.Infrastructure.Notifications;
public class NotificationService : INotificationService
{
private readonly AppDbContext _db;
private readonly IEnumerable<INotificationProvider> _providers;
private readonly INotificationScheduler _scheduler;
private readonly ILogger<NotificationService> _logger;
public NotificationService(
AppDbContext db,
IEnumerable<INotificationProvider> providers,
INotificationScheduler scheduler,
ILogger<NotificationService> logger)
{
_db = db;
_providers = providers;
_scheduler = scheduler;
_logger = logger;
@@ -46,4 +53,68 @@ public class NotificationService : INotificationService
return _scheduler.ScheduleAsync(message, request.SendAt, cancellationToken);
}
public async Task<UserNotificationDto> CreateUserNotificationAsync(
int userId,
string type,
string title,
string body,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(type);
ArgumentException.ThrowIfNullOrWhiteSpace(title);
ArgumentException.ThrowIfNullOrWhiteSpace(body);
var notification = new UserNotification
{
UserId = userId,
Type = type,
Title = title,
Body = body
};
_db.UserNotifications.Add(notification);
await _db.SaveChangesAsync(cancellationToken);
return ToDto(notification);
}
public async Task<PagedResult<UserNotificationDto>> GetUserNotificationsAsync(
int userId,
PaginationRequest pagination,
CancellationToken cancellationToken = default)
{
var query = _db.UserNotifications.Where(n => n.UserId == userId);
var total = await query.CountAsync(cancellationToken);
var items = await query
.OrderByDescending(n => n.CreatedAt)
.Skip((pagination.Page - 1) * pagination.PageSize)
.Take(pagination.PageSize)
.Select(n => new UserNotificationDto(
n.Id,
n.Type,
n.Title,
n.Body,
n.IsRead,
n.CreatedAt))
.ToListAsync(cancellationToken);
return PagedResult<UserNotificationDto>.Create(items, total, pagination.Page, pagination.PageSize);
}
public async Task MarkAllReadAsync(int userId, CancellationToken cancellationToken = default)
{
await _db.UserNotifications
.Where(n => n.UserId == userId && !n.IsRead)
.ExecuteUpdateAsync(setters => setters.SetProperty(n => n.IsRead, true), cancellationToken);
}
private static UserNotificationDto ToDto(UserNotification notification) => new(
notification.Id,
notification.Type,
notification.Title,
notification.Body,
notification.IsRead,
notification.CreatedAt
);
}
@@ -5,6 +5,7 @@ using System.Globalization;
using UniVerse.Application.DTOs.Achievements;
using UniVerse.Application.DTOs.Common;
using UniVerse.Application.DTOs.Gamification;
using UniVerse.Application.DTOs.Notifications;
using UniVerse.Application.Interfaces;
using UniVerse.Application.Mappings;
using UniVerse.Domain.Entities;
@@ -17,11 +18,16 @@ public class GamificationService : IGamificationService
{
private readonly AppDbContext _db;
private readonly IConfiguration _config;
private readonly INotificationService _notifications;
private readonly ILogger<GamificationService> _logger;
public GamificationService(AppDbContext db, IConfiguration config, ILogger<GamificationService> logger)
public GamificationService(
AppDbContext db,
IConfiguration config,
INotificationService notifications,
ILogger<GamificationService> logger)
{
_db = db; _config = config; _logger = logger;
_db = db; _config = config; _notifications = notifications; _logger = logger;
}
public async Task AwardCoinsAsync(int userId, int amount, CoinTransactionType type,
@@ -91,10 +97,43 @@ public class GamificationService : IGamificationService
achievementId: achievement.Id, description: $"Achievement: {achievement.Name}");
earnedCoins += achievement.CoinReward;
}
await TryNotifyAchievementAsync(user, achievement);
}
await _db.SaveChangesAsync();
}
private async Task TryNotifyAchievementAsync(User user, Achievement achievement)
{
try
{
var title = $"Новое достижение: {achievement.Name}";
var rewardText = achievement.CoinReward > 0
? $" Награда: {achievement.CoinReward} монет."
: string.Empty;
var body = $"{achievement.Description ?? "Вы выполнили условие достижения."}{rewardText}";
await _notifications.CreateUserNotificationAsync(user.Id, "achievement", title, body);
await _notifications.SendAsync(new NotificationMessage(
NotificationChannels.Email,
user.Email,
title,
$"Здравствуйте, {user.DisplayName ?? user.Email}!\n\nПоздравляем: вы получили достижение «{achievement.Name}» в UniVerse.\n\n{body}",
user.DisplayName,
new Dictionary<string, string>
{
["event"] = "achievement_earned",
["achievement_id"] = achievement.Id.ToString(),
["achievement_name"] = achievement.Name
}));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to send achievement notification {AchievementId} to user {UserId}", achievement.Id, user.Id);
}
}
private static bool TryParseCondition(string? condition, out string type, out int value)
{
type = string.Empty;