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
🚀 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:
@@ -153,6 +153,10 @@ public class EndpointAuthorizationTests : IClassFixture<ApiWebApplicationFactory
|
|||||||
yield return E("sync/rooms POST [Admin]", "POST", "api/v1/sync/rooms", "Admin", forbidden: ["Student", "Teacher"]);
|
yield return E("sync/rooms POST [Admin]", "POST", "api/v1/sync/rooms", "Admin", forbidden: ["Student", "Teacher"]);
|
||||||
yield return E("sync/employees POST [Admin]", "POST", "api/v1/sync/employees?fullname=test","Admin",forbidden: ["Student", "Teacher"]);
|
yield return E("sync/employees POST [Admin]", "POST", "api/v1/sync/employees?fullname=test","Admin",forbidden: ["Student", "Teacher"]);
|
||||||
|
|
||||||
|
// ── Notifications — any auth ───────────────────────────────────────────
|
||||||
|
yield return E("notifications GET [AnyAuth]", "GET", "api/v1/notifications", "Student");
|
||||||
|
yield return E("notifications/read-all PATCH [AnyAuth]", "PATCH", "api/v1/notifications/read-all", "Student");
|
||||||
|
|
||||||
// ── Notifications — Admin only ─────────────────────────────────────────
|
// ── Notifications — Admin only ─────────────────────────────────────────
|
||||||
yield return E("notifications/send POST [Admin]", "POST", "api/v1/notifications/send", "Admin", forbidden: ["Student", "Teacher"],
|
yield return E("notifications/send POST [Admin]", "POST", "api/v1/notifications/send", "Admin", forbidden: ["Student", "Teacher"],
|
||||||
body: """{"channel":"email","recipient":"user@test.com","subject":"Test","body":"Hello"}""");
|
body: """{"channel":"email","recipient":"user@test.com","subject":"Test","body":"Hello"}""");
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
using UniVerse.Application.DTOs.Notifications;
|
||||||
|
using UniVerse.Application.Interfaces;
|
||||||
using UniVerse.Domain.Entities;
|
using UniVerse.Domain.Entities;
|
||||||
using UniVerse.Domain.Enums;
|
using UniVerse.Domain.Enums;
|
||||||
using UniVerse.Infrastructure.Data;
|
using UniVerse.Infrastructure.Data;
|
||||||
@@ -105,6 +108,17 @@ public class GamificationServiceTests
|
|||||||
|
|
||||||
private static GamificationService CreateService(AppDbContext db)
|
private static GamificationService CreateService(AppDbContext db)
|
||||||
{
|
{
|
||||||
|
var notifications = Substitute.For<INotificationService>();
|
||||||
|
notifications.CreateUserNotificationAsync(
|
||||||
|
Arg.Any<int>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<CancellationToken>())
|
||||||
|
.Returns(callInfo => new UserNotificationDto(1, callInfo.ArgAt<string>(1), callInfo.ArgAt<string>(2), callInfo.ArgAt<string>(3), false, DateTime.UtcNow));
|
||||||
|
notifications.SendAsync(Arg.Any<NotificationMessage>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var configuration = new ConfigurationBuilder()
|
var configuration = new ConfigurationBuilder()
|
||||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
@@ -114,7 +128,7 @@ public class GamificationServiceTests
|
|||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
return new GamificationService(db, configuration, NullLogger<GamificationService>.Instance);
|
return new GamificationService(db, configuration, notifications, NullLogger<GamificationService>.Instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Achievement Achievement(int id, string name, string condition, int coinReward) => new()
|
private static Achievement Achievement(int id, string name, string condition, int coinReward) => new()
|
||||||
|
|||||||
@@ -134,6 +134,17 @@ public class ApiWebApplicationFactory : WebApplicationFactory<Program>
|
|||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
stub.ScheduleAsync(Arg.Any<ScheduleNotificationRequest>(), Arg.Any<CancellationToken>())
|
stub.ScheduleAsync(Arg.Any<ScheduleNotificationRequest>(), Arg.Any<CancellationToken>())
|
||||||
.Returns(new ScheduledNotificationResponse("test-job", DateTimeOffset.UtcNow.AddMinutes(5)));
|
.Returns(new ScheduledNotificationResponse("test-job", DateTimeOffset.UtcNow.AddMinutes(5)));
|
||||||
|
stub.GetUserNotificationsAsync(Arg.Any<int>(), Arg.Any<PaginationRequest>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(PagedResult<UserNotificationDto>.Create([], 0, 1, 20));
|
||||||
|
stub.MarkAllReadAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
stub.CreateUserNotificationAsync(
|
||||||
|
Arg.Any<int>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<CancellationToken>())
|
||||||
|
.Returns(new UserNotificationDto(1, "achievement", "Title", "Body", false, DateTime.UtcNow));
|
||||||
return stub;
|
return stub;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using UniVerse.Application.DTOs.Common;
|
||||||
using UniVerse.Application.DTOs.Notifications;
|
using UniVerse.Application.DTOs.Notifications;
|
||||||
using UniVerse.Application.Interfaces;
|
using UniVerse.Application.Interfaces;
|
||||||
|
|
||||||
@@ -8,7 +10,7 @@ namespace UniVerse.Api.Controllers;
|
|||||||
/// <summary>Отправка и планирование уведомлений через доступные каналы.</summary>
|
/// <summary>Отправка и планирование уведомлений через доступные каналы.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/notifications")]
|
[Route("api/v1/notifications")]
|
||||||
[Authorize(Roles = "Admin")]
|
[Authorize]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public class NotificationsController : ControllerBase
|
public class NotificationsController : ControllerBase
|
||||||
{
|
{
|
||||||
@@ -19,6 +21,34 @@ public class NotificationsController : ControllerBase
|
|||||||
_notifications = notifications;
|
_notifications = notifications;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int CurrentUserId => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub") ?? "0");
|
||||||
|
|
||||||
|
/// <summary>Получить уведомления текущего пользователя.</summary>
|
||||||
|
/// <param name="pagination">Параметры пагинации.</param>
|
||||||
|
/// <param name="cancellationToken">Токен отмены запроса.</param>
|
||||||
|
/// <response code="200">Список уведомлений.</response>
|
||||||
|
/// <response code="401">Требуется аутентификация.</response>
|
||||||
|
[HttpGet]
|
||||||
|
[ProducesResponseType(typeof(PagedResult<UserNotificationDto>), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
public async Task<ActionResult<PagedResult<UserNotificationDto>>> GetMine(
|
||||||
|
[FromQuery] PaginationRequest pagination,
|
||||||
|
CancellationToken cancellationToken) =>
|
||||||
|
Ok(await _notifications.GetUserNotificationsAsync(CurrentUserId, pagination, cancellationToken));
|
||||||
|
|
||||||
|
/// <summary>Отметить все уведомления текущего пользователя как прочитанные.</summary>
|
||||||
|
/// <param name="cancellationToken">Токен отмены запроса.</param>
|
||||||
|
/// <response code="204">Уведомления отмечены прочитанными.</response>
|
||||||
|
/// <response code="401">Требуется аутентификация.</response>
|
||||||
|
[HttpPatch("read-all")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
public async Task<IActionResult> MarkAllRead(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await _notifications.MarkAllReadAsync(CurrentUserId, cancellationToken);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Отправить уведомление немедленно.</summary>
|
/// <summary>Отправить уведомление немедленно.</summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// Канал задаётся строкой, например `email`. Новые провайдеры добавляются через `INotificationProvider`.
|
/// Канал задаётся строкой, например `email`. Новые провайдеры добавляются через `INotificationProvider`.
|
||||||
@@ -27,6 +57,7 @@ public class NotificationsController : ControllerBase
|
|||||||
/// <response code="202">Уведомление принято к отправке.</response>
|
/// <response code="202">Уведомление принято к отправке.</response>
|
||||||
/// <response code="401">Требуется аутентификация.</response>
|
/// <response code="401">Требуется аутентификация.</response>
|
||||||
/// <response code="403">Требуется роль Admin.</response>
|
/// <response code="403">Требуется роль Admin.</response>
|
||||||
|
[Authorize(Roles = "Admin")]
|
||||||
[HttpPost("send")]
|
[HttpPost("send")]
|
||||||
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
||||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
@@ -50,6 +81,7 @@ public class NotificationsController : ControllerBase
|
|||||||
/// <response code="202">Уведомление поставлено в очередь Quartz.NET.</response>
|
/// <response code="202">Уведомление поставлено в очередь Quartz.NET.</response>
|
||||||
/// <response code="401">Требуется аутентификация.</response>
|
/// <response code="401">Требуется аутентификация.</response>
|
||||||
/// <response code="403">Требуется роль Admin.</response>
|
/// <response code="403">Требуется роль Admin.</response>
|
||||||
|
[Authorize(Roles = "Admin")]
|
||||||
[HttpPost("schedule")]
|
[HttpPost("schedule")]
|
||||||
[ProducesResponseType(typeof(ScheduledNotificationResponse), StatusCodes.Status202Accepted)]
|
[ProducesResponseType(typeof(ScheduledNotificationResponse), StatusCodes.Status202Accepted)]
|
||||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
|||||||
@@ -31,3 +31,12 @@ public record ScheduleNotificationRequest(
|
|||||||
IReadOnlyDictionary<string, string>? Metadata = null);
|
IReadOnlyDictionary<string, string>? Metadata = null);
|
||||||
|
|
||||||
public record ScheduledNotificationResponse(string JobId, DateTimeOffset SendAt);
|
public record ScheduledNotificationResponse(string JobId, DateTimeOffset SendAt);
|
||||||
|
|
||||||
|
public record UserNotificationDto(
|
||||||
|
int Id,
|
||||||
|
string Type,
|
||||||
|
string Title,
|
||||||
|
string Body,
|
||||||
|
bool IsRead,
|
||||||
|
DateTime CreatedAt
|
||||||
|
);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using UniVerse.Application.DTOs.Notifications;
|
using UniVerse.Application.DTOs.Notifications;
|
||||||
|
using UniVerse.Application.DTOs.Common;
|
||||||
|
|
||||||
namespace UniVerse.Application.Interfaces;
|
namespace UniVerse.Application.Interfaces;
|
||||||
|
|
||||||
@@ -6,4 +7,7 @@ public interface INotificationService
|
|||||||
{
|
{
|
||||||
Task SendAsync(NotificationMessage message, CancellationToken cancellationToken = default);
|
Task SendAsync(NotificationMessage message, CancellationToken cancellationToken = default);
|
||||||
Task<ScheduledNotificationResponse> ScheduleAsync(ScheduleNotificationRequest request, CancellationToken cancellationToken = default);
|
Task<ScheduledNotificationResponse> ScheduleAsync(ScheduleNotificationRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task<UserNotificationDto> CreateUserNotificationAsync(int userId, string type, string title, string body, CancellationToken cancellationToken = default);
|
||||||
|
Task<PagedResult<UserNotificationDto>> GetUserNotificationsAsync(int userId, PaginationRequest pagination, CancellationToken cancellationToken = default);
|
||||||
|
Task MarkAllReadAsync(int userId, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,5 +23,6 @@ public class User
|
|||||||
public ICollection<Review> Reviews { get; set; } = new List<Review>();
|
public ICollection<Review> Reviews { get; set; } = new List<Review>();
|
||||||
public ICollection<UserAchievement> UserAchievements { get; set; } = new List<UserAchievement>();
|
public ICollection<UserAchievement> UserAchievements { get; set; } = new List<UserAchievement>();
|
||||||
public ICollection<CoinTransaction> CoinTransactions { get; set; } = new List<CoinTransaction>();
|
public ICollection<CoinTransaction> CoinTransactions { get; set; } = new List<CoinTransaction>();
|
||||||
|
public ICollection<UserNotification> Notifications { get; set; } = new List<UserNotification>();
|
||||||
public ICollection<RefreshToken> RefreshTokens { get; set; } = new List<RefreshToken>();
|
public ICollection<RefreshToken> RefreshTokens { get; set; } = new List<RefreshToken>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace UniVerse.Domain.Entities;
|
||||||
|
|
||||||
|
public class UserNotification
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int UserId { get; set; }
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
public string Body { get; set; } = string.Empty;
|
||||||
|
public bool IsRead { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
|
||||||
|
public User User { get; set; } = null!;
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ public class AppDbContext : DbContext
|
|||||||
public DbSet<Achievement> Achievements { get; set; } = null!;
|
public DbSet<Achievement> Achievements { get; set; } = null!;
|
||||||
public DbSet<UserAchievement> UserAchievements { get; set; } = null!;
|
public DbSet<UserAchievement> UserAchievements { get; set; } = null!;
|
||||||
public DbSet<CoinTransaction> CoinTransactions { get; set; } = null!;
|
public DbSet<CoinTransaction> CoinTransactions { get; set; } = null!;
|
||||||
|
public DbSet<UserNotification> UserNotifications { get; set; } = null!;
|
||||||
public DbSet<RefreshToken> RefreshTokens { get; set; } = null!;
|
public DbSet<RefreshToken> RefreshTokens { get; set; } = null!;
|
||||||
|
|
||||||
static AppDbContext()
|
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);
|
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 =>
|
modelBuilder.Entity("UniVerse.Domain.Entities.UserRoleAssignment", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("UserId")
|
b.Property<int>("UserId")
|
||||||
@@ -905,6 +955,17 @@ namespace UniVerse.Infrastructure.Migrations
|
|||||||
b.Navigation("User");
|
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 =>
|
modelBuilder.Entity("UniVerse.Domain.Entities.UserRoleAssignment", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("UniVerse.Domain.Entities.User", "User")
|
b.HasOne("UniVerse.Domain.Entities.User", "User")
|
||||||
@@ -958,6 +1019,8 @@ namespace UniVerse.Infrastructure.Migrations
|
|||||||
|
|
||||||
b.Navigation("Enrollments");
|
b.Navigation("Enrollments");
|
||||||
|
|
||||||
|
b.Navigation("Notifications");
|
||||||
|
|
||||||
b.Navigation("RefreshTokens");
|
b.Navigation("RefreshTokens");
|
||||||
|
|
||||||
b.Navigation("Reviews");
|
b.Navigation("Reviews");
|
||||||
|
|||||||
@@ -1,20 +1,27 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using UniVerse.Application.DTOs.Common;
|
||||||
using UniVerse.Application.DTOs.Notifications;
|
using UniVerse.Application.DTOs.Notifications;
|
||||||
using UniVerse.Application.Interfaces;
|
using UniVerse.Application.Interfaces;
|
||||||
|
using UniVerse.Domain.Entities;
|
||||||
|
using UniVerse.Infrastructure.Data;
|
||||||
|
|
||||||
namespace UniVerse.Infrastructure.Notifications;
|
namespace UniVerse.Infrastructure.Notifications;
|
||||||
|
|
||||||
public class NotificationService : INotificationService
|
public class NotificationService : INotificationService
|
||||||
{
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
private readonly IEnumerable<INotificationProvider> _providers;
|
private readonly IEnumerable<INotificationProvider> _providers;
|
||||||
private readonly INotificationScheduler _scheduler;
|
private readonly INotificationScheduler _scheduler;
|
||||||
private readonly ILogger<NotificationService> _logger;
|
private readonly ILogger<NotificationService> _logger;
|
||||||
|
|
||||||
public NotificationService(
|
public NotificationService(
|
||||||
|
AppDbContext db,
|
||||||
IEnumerable<INotificationProvider> providers,
|
IEnumerable<INotificationProvider> providers,
|
||||||
INotificationScheduler scheduler,
|
INotificationScheduler scheduler,
|
||||||
ILogger<NotificationService> logger)
|
ILogger<NotificationService> logger)
|
||||||
{
|
{
|
||||||
|
_db = db;
|
||||||
_providers = providers;
|
_providers = providers;
|
||||||
_scheduler = scheduler;
|
_scheduler = scheduler;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
@@ -46,4 +53,68 @@ public class NotificationService : INotificationService
|
|||||||
|
|
||||||
return _scheduler.ScheduleAsync(message, request.SendAt, cancellationToken);
|
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.Achievements;
|
||||||
using UniVerse.Application.DTOs.Common;
|
using UniVerse.Application.DTOs.Common;
|
||||||
using UniVerse.Application.DTOs.Gamification;
|
using UniVerse.Application.DTOs.Gamification;
|
||||||
|
using UniVerse.Application.DTOs.Notifications;
|
||||||
using UniVerse.Application.Interfaces;
|
using UniVerse.Application.Interfaces;
|
||||||
using UniVerse.Application.Mappings;
|
using UniVerse.Application.Mappings;
|
||||||
using UniVerse.Domain.Entities;
|
using UniVerse.Domain.Entities;
|
||||||
@@ -17,11 +18,16 @@ public class GamificationService : IGamificationService
|
|||||||
{
|
{
|
||||||
private readonly AppDbContext _db;
|
private readonly AppDbContext _db;
|
||||||
private readonly IConfiguration _config;
|
private readonly IConfiguration _config;
|
||||||
|
private readonly INotificationService _notifications;
|
||||||
private readonly ILogger<GamificationService> _logger;
|
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,
|
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}");
|
achievementId: achievement.Id, description: $"Achievement: {achievement.Name}");
|
||||||
earnedCoins += achievement.CoinReward;
|
earnedCoins += achievement.CoinReward;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await TryNotifyAchievementAsync(user, achievement);
|
||||||
}
|
}
|
||||||
await _db.SaveChangesAsync();
|
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)
|
private static bool TryParseCondition(string? condition, out string type, out int value)
|
||||||
{
|
{
|
||||||
type = string.Empty;
|
type = string.Empty;
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import type {
|
|||||||
UserAchievementDto,
|
UserAchievementDto,
|
||||||
UserDto,
|
UserDto,
|
||||||
UserQuery,
|
UserQuery,
|
||||||
|
UserNotificationDto,
|
||||||
UserStatsDto,
|
UserStatsDto,
|
||||||
} from './types'
|
} from './types'
|
||||||
|
|
||||||
@@ -85,6 +86,14 @@ export const achievementsApi = {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const notificationsApi = {
|
||||||
|
async list() {
|
||||||
|
const payload = await apiRequest<PagedResult<UserNotificationDto> | UserNotificationDto[]>('/notifications')
|
||||||
|
return extractItems(payload)
|
||||||
|
},
|
||||||
|
markAllRead: () => apiRequest<void>('/notifications/read-all', { method: 'PATCH' }),
|
||||||
|
}
|
||||||
|
|
||||||
export const reviewsApi = {
|
export const reviewsApi = {
|
||||||
create: (lectureId: string | number, rating: 'Like' | 'Neutral' | 'Dislike', text: string) =>
|
create: (lectureId: string | number, rating: 'Like' | 'Neutral' | 'Dislike', text: string) =>
|
||||||
apiRequest<ReviewDto>('/reviews', {
|
apiRequest<ReviewDto>('/reviews', {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Achievement, CoinTransaction, Lecture, Review, User, UserRole } from '@/types'
|
import type { Achievement, CoinTransaction, Lecture, Notification, Review, User, UserRole } from '@/types'
|
||||||
import type {
|
import type {
|
||||||
AchievementDto,
|
AchievementDto,
|
||||||
CoinTransactionDto,
|
CoinTransactionDto,
|
||||||
@@ -8,6 +8,7 @@ import type {
|
|||||||
UserDto,
|
UserDto,
|
||||||
UserStatsDto,
|
UserStatsDto,
|
||||||
UserAchievementDto,
|
UserAchievementDto,
|
||||||
|
UserNotificationDto,
|
||||||
} from './types'
|
} from './types'
|
||||||
|
|
||||||
export function mapApiRole(role: string | undefined): UserRole {
|
export function mapApiRole(role: string | undefined): UserRole {
|
||||||
@@ -127,3 +128,14 @@ export function mapApiCoinTransaction(transaction: CoinTransactionDto): CoinTran
|
|||||||
type: transaction.amount >= 0 ? 'earned' : 'spent',
|
type: transaction.amount >= 0 ? 'earned' : 'spent',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function mapApiNotification(notification: UserNotificationDto): Notification {
|
||||||
|
return {
|
||||||
|
id: String(notification.id),
|
||||||
|
type: notification.type,
|
||||||
|
title: notification.title,
|
||||||
|
body: notification.body,
|
||||||
|
read: notification.isRead,
|
||||||
|
createdAt: notification.createdAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -185,6 +185,15 @@ export interface CoinTransactionDto {
|
|||||||
createdAt: string
|
createdAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UserNotificationDto {
|
||||||
|
id: number
|
||||||
|
type: 'reminder' | 'schedule-change' | 'achievement' | 'coins' | 'recommendation'
|
||||||
|
title: string
|
||||||
|
body: string
|
||||||
|
isRead: boolean
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface LectureQuery {
|
export interface LectureQuery {
|
||||||
DateFrom?: string
|
DateFrom?: string
|
||||||
DateTo?: string
|
DateTo?: string
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { achievementsApi, usersApi } from '@/api'
|
import { achievementsApi, notificationsApi, usersApi } from '@/api'
|
||||||
import { mapApiAchievement, mapApiCoinTransaction } from '@/api/mappers'
|
import { mapApiAchievement, mapApiCoinTransaction, mapApiNotification } from '@/api/mappers'
|
||||||
import type { Achievement, CoinTransaction, Notification } from '@/types'
|
import type { Achievement, CoinTransaction, Notification } from '@/types'
|
||||||
import { useAuthStore } from './auth'
|
import { useAuthStore } from './auth'
|
||||||
|
|
||||||
@@ -25,7 +25,10 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
usersApi.achievements(id),
|
usersApi.achievements(id),
|
||||||
usersApi.transactions(id),
|
usersApi.transactions(id),
|
||||||
])
|
])
|
||||||
const achievementCatalog = await achievementsApi.list()
|
const [achievementCatalog, notificationPayload] = await Promise.all([
|
||||||
|
achievementsApi.list(),
|
||||||
|
notificationsApi.list(),
|
||||||
|
])
|
||||||
|
|
||||||
if (auth.user) {
|
if (auth.user) {
|
||||||
auth.setUser({
|
auth.setUser({
|
||||||
@@ -55,6 +58,7 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
(a, b) => Number(a.id) - Number(b.id),
|
(a, b) => Number(a.id) - Number(b.id),
|
||||||
)
|
)
|
||||||
coinHistory.value = transactions.map(mapApiCoinTransaction)
|
coinHistory.value = transactions.map(mapApiCoinTransaction)
|
||||||
|
notifications.value = notificationPayload.map(mapApiNotification)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value = err instanceof Error ? err.message : 'Не удалось загрузить данные профиля.'
|
error.value = err instanceof Error ? err.message : 'Не удалось загрузить данные профиля.'
|
||||||
} finally {
|
} finally {
|
||||||
@@ -62,7 +66,13 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function markAllRead() {
|
async function fetchNotifications() {
|
||||||
|
const payload = await notificationsApi.list()
|
||||||
|
notifications.value = payload.map(mapApiNotification)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function markAllRead() {
|
||||||
|
await notificationsApi.markAllRead()
|
||||||
notifications.value.forEach(n => (n.read = true))
|
notifications.value.forEach(n => (n.read = true))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +85,7 @@ export const useUserStore = defineStore('user', () => {
|
|||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
fetchStudentData,
|
fetchStudentData,
|
||||||
|
fetchNotifications,
|
||||||
markAllRead,
|
markAllRead,
|
||||||
unreadCount,
|
unreadCount,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue'
|
import { computed, onMounted } from 'vue'
|
||||||
import { useUserStore } from '@/stores/user'
|
import { useUserStore } from '@/stores/user'
|
||||||
import GlassCard from '@/components/ui/GlassCard.vue'
|
import GlassCard from '@/components/ui/GlassCard.vue'
|
||||||
import AppIcon from '@/components/ui/AppIcon.vue'
|
import AppIcon from '@/components/ui/AppIcon.vue'
|
||||||
@@ -7,6 +7,10 @@ import EmptyState from '@/components/ui/EmptyState.vue'
|
|||||||
|
|
||||||
const userStore = useUserStore()
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void userStore.fetchNotifications()
|
||||||
|
})
|
||||||
|
|
||||||
const grouped = computed(() => {
|
const grouped = computed(() => {
|
||||||
const map: Record<string, typeof userStore.notifications> = {}
|
const map: Record<string, typeof userStore.notifications> = {}
|
||||||
userStore.notifications.forEach(n => {
|
userStore.notifications.forEach(n => {
|
||||||
|
|||||||
Reference in New Issue
Block a user