feat: много запланированного

- клонирование коллекции
- добавление паблик-коллекций
- регенерация паблик-ссылок
This commit is contained in:
2026-10-07 02:45:37 +04:00
parent c1b052e2c7
commit 274e60a433
30 changed files with 719 additions and 112 deletions
@@ -4,6 +4,9 @@ using MemeVault.Application.Commands.CreateCollection;
using MemeVault.Application.Commands.CreateCollectionInvite; using MemeVault.Application.Commands.CreateCollectionInvite;
using MemeVault.Application.Commands.DeleteCollection; using MemeVault.Application.Commands.DeleteCollection;
using MemeVault.Application.Commands.RevokeCollectionInvite; using MemeVault.Application.Commands.RevokeCollectionInvite;
using MemeVault.Application.Commands.CloneCollection;
using MemeVault.Application.Commands.RegenerateShareLink;
using MemeVault.Application.Commands.JoinPublicCollection;
using MemeVault.Application.Commands.SetCollectionInbox; using MemeVault.Application.Commands.SetCollectionInbox;
using MemeVault.Application.Commands.SetCollectionNsfw; using MemeVault.Application.Commands.SetCollectionNsfw;
using MemeVault.Application.Commands.ShareCollection; using MemeVault.Application.Commands.ShareCollection;
@@ -111,6 +114,32 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
return ok ? NoContent() : NotFound(); return ok ? NoContent() : NotFound();
} }
// POST /api/collections/{id}/clone
[HttpPost("{id:guid}/clone")]
[ProducesResponseType(typeof(object), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Clone(Guid id, CancellationToken ct)
{
var newId = await mediator.Send(
new CloneCollectionCommand(id, currentUser.TelegramId), ct);
return newId is null
? NotFound()
: CreatedAtAction(nameof(GetAll), new { id = newId }, new { id = newId });
}
// POST /api/collections/{id}/join
[HttpPost("{id:guid}/join")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Join(Guid id, CancellationToken ct)
{
var ok = await mediator.Send(
new JoinPublicCollectionCommand(id, currentUser.TelegramId), ct);
return ok ? NoContent() : NotFound();
}
// PUT /api/collections/{id}/inbox // PUT /api/collections/{id}/inbox
[HttpPut("{id:guid}/inbox")] [HttpPut("{id:guid}/inbox")]
public async Task<IActionResult> SetInbox(Guid id, CancellationToken ct) public async Task<IActionResult> SetInbox(Guid id, CancellationToken ct)
@@ -133,6 +162,18 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
return ok ? NoContent() : NotFound(); return ok ? NoContent() : NotFound();
} }
// POST /api/collections/{id}/share-link/regenerate
[HttpPost("{id:guid}/share-link/regenerate")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> RegenerateShareLink(Guid id, CancellationToken ct)
{
var token = await mediator.Send(
new RegenerateShareLinkCommand(id, currentUser.TelegramId), ct);
return token is null ? NotFound() : Ok(new { shareToken = token });
}
// PUT /api/collections/{id}/visibility // PUT /api/collections/{id}/visibility
[HttpPut("{id:guid}/visibility")] [HttpPut("{id:guid}/visibility")]
public async Task<IActionResult> SetVisibility( public async Task<IActionResult> SetVisibility(
@@ -0,0 +1,11 @@
using MediatR;
namespace MemeVault.Application.Commands.CloneCollection;
/// <param name="SourceCollectionId">ID коллекции-источника.</param>
/// <param name="RequestingTelegramId">Telegram ID пользователя, создающего клон.</param>
/// <returns>ID новой коллекции, null если источник не найден или нет доступа.</returns>
public sealed record CloneCollectionCommand(
Guid SourceCollectionId,
long RequestingTelegramId
) : IRequest<Guid?>;
@@ -0,0 +1,54 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.CloneCollection;
public sealed class CloneCollectionCommandHandler(
ICollectionRepository collections,
IMediaItemRepository mediaItems,
IBotUserRepository users,
IUnitOfWork unitOfWork)
: IRequestHandler<CloneCollectionCommand, Guid?>
{
private const int CollectionOwnerLimit = 5;
public async Task<Guid?> Handle(CloneCollectionCommand request, CancellationToken ct)
{
var source = await collections.GetByIdAsync(request.SourceCollectionId, ct);
if (source is null || !source.CanView(request.RequestingTelegramId))
return null;
// Проверяем квоту коллекций у клонирующего пользователя
var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
var owned = await collections.GetByOwnerAsync(request.RequestingTelegramId, ct);
if (owned.Count(c => c.Id != user?.InboxCollectionId) >= CollectionOwnerLimit)
throw new CollectionQuotaExceededException(CollectionOwnerLimit);
// Создаём новую коллекцию с теми же именем и описанием
var clone = Collection.Create(request.RequestingTelegramId, source.Name, source.Description);
await collections.AddAsync(clone, ct);
// Копируем все медиа-элементы
var items = await mediaItems.GetByCollectionAsync(request.SourceCollectionId, ct);
foreach (var item in items)
{
var copy = MediaItem.Create(
request.RequestingTelegramId,
clone.Id,
item.Source,
item.Type,
item.Caption,
mediaGroupId: null, // клон не связан с оригинальным альбомом
item.Tags);
await mediaItems.AddAsync(copy, ct);
}
await unitOfWork.SaveChangesAsync(ct);
return clone.Id;
}
}
@@ -15,7 +15,11 @@ public sealed class CopyMediaToCollectionCommandHandler(
public async Task<Guid?> Handle(CopyMediaToCollectionCommand request, CancellationToken ct) public async Task<Guid?> Handle(CopyMediaToCollectionCommand request, CancellationToken ct)
{ {
var source = await mediaItems.GetByIdAsync(request.SourceMediaItemId, ct); var source = await mediaItems.GetByIdAsync(request.SourceMediaItemId, ct);
if (source is null || source.OwnerTelegramId != request.RequestingTelegramId) if (source is null)
return null;
var sourceCollection = await collections.GetByIdAsync(source.CollectionId, ct);
if (sourceCollection is null || !sourceCollection.CanView(request.RequestingTelegramId))
return null; return null;
var target = await collections.GetByIdAsync(request.TargetCollectionId, ct); var target = await collections.GetByIdAsync(request.TargetCollectionId, ct);
@@ -9,11 +9,13 @@ namespace MemeVault.Application.Commands.CreateCollection;
public sealed class CreateCollectionCommandHandler : IRequestHandler<CreateCollectionCommand, Guid> public sealed class CreateCollectionCommandHandler : IRequestHandler<CreateCollectionCommand, Guid>
{ {
private readonly ICollectionRepository _collections; private readonly ICollectionRepository _collections;
private readonly IBotUserRepository _users;
private readonly IUnitOfWork _uow; private readonly IUnitOfWork _uow;
public CreateCollectionCommandHandler(ICollectionRepository collections, IUnitOfWork uow) public CreateCollectionCommandHandler(ICollectionRepository collections, IBotUserRepository users, IUnitOfWork uow)
{ {
_collections = collections; _collections = collections;
_users = users;
_uow = uow; _uow = uow;
} }
@@ -21,8 +23,9 @@ public sealed class CreateCollectionCommandHandler : IRequestHandler<CreateColle
{ {
const int CollectionOwnerLimit = 5; const int CollectionOwnerLimit = 5;
var owned = await _collections.GetByOwnerAsync(request.OwnerTelegramId, cancellationToken); var owned = await _collections.GetByOwnerAsync(request.OwnerTelegramId, cancellationToken);
var user = await _users.GetByTelegramIdAsync(request.OwnerTelegramId, cancellationToken);
// Inbox не считается — пользовательские коллекции только // Inbox не считается — пользовательские коллекции только
if (owned.Count(c => !c.IsInbox) >= CollectionOwnerLimit) if (owned.Count(c => c.Id != user?.InboxCollectionId) >= CollectionOwnerLimit)
throw new CollectionQuotaExceededException(CollectionOwnerLimit); throw new CollectionQuotaExceededException(CollectionOwnerLimit);
var collection = Collection.Create(request.OwnerTelegramId, request.Name, request.Description); var collection = Collection.Create(request.OwnerTelegramId, request.Name, request.Description);
@@ -1,12 +1,14 @@
using MediatR; using MediatR;
using MemeVault.Application.Common; using MemeVault.Application.Common;
using MemeVault.Domain.Enums; using MemeVault.Domain.Enums;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories; using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.DeleteCollection; namespace MemeVault.Application.Commands.DeleteCollection;
public sealed class DeleteCollectionCommandHandler( public sealed class DeleteCollectionCommandHandler(
ICollectionRepository collections, ICollectionRepository collections,
IBotUserRepository users,
IUnitOfWork unitOfWork) IUnitOfWork unitOfWork)
: IRequestHandler<DeleteCollectionCommand, bool> : IRequestHandler<DeleteCollectionCommand, bool>
{ {
@@ -16,7 +18,11 @@ public sealed class DeleteCollectionCommandHandler(
if (collection is null || collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner) if (collection is null || collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return false; return false;
collection.Delete(request.RequestingTelegramId); // бросает DomainException если IsInbox var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user?.InboxCollectionId == collection.Id)
throw new DomainException("Cannot delete the Inbox collection.");
collection.Delete(request.RequestingTelegramId);
await collections.RemoveAsync(collection, ct); await collections.RemoveAsync(collection, ct);
await unitOfWork.SaveChangesAsync(ct); await unitOfWork.SaveChangesAsync(ct);
return true; return true;
@@ -5,26 +5,23 @@ using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.DeleteMedia; namespace MemeVault.Application.Commands.DeleteMedia;
public sealed class DeleteMediaCommandHandler : IRequestHandler<DeleteMediaCommand> public sealed class DeleteMediaCommandHandler(
IMediaItemRepository mediaItems,
ICollectionRepository collections,
IUnitOfWork uow)
: IRequestHandler<DeleteMediaCommand>
{ {
private readonly IMediaItemRepository _mediaItems;
private readonly IUnitOfWork _uow;
public DeleteMediaCommandHandler(IMediaItemRepository mediaItems, IUnitOfWork uow)
{
_mediaItems = mediaItems;
_uow = uow;
}
public async Task Handle(DeleteMediaCommand request, CancellationToken cancellationToken) public async Task Handle(DeleteMediaCommand request, CancellationToken cancellationToken)
{ {
var item = await _mediaItems.GetByIdAsync(request.MediaItemId, cancellationToken) var item = await mediaItems.GetByIdAsync(request.MediaItemId, cancellationToken);
?? throw new DomainException($"MediaItem {request.MediaItemId} not found."); if (item is null)
return;
if (item.OwnerTelegramId != request.RequestingTelegramId) var collection = await collections.GetByIdAsync(item.CollectionId, cancellationToken);
throw new DomainException("You are not the owner of this item."); if (collection is null || !collection.CanWrite(request.RequestingTelegramId))
throw new DomainException("You don't have permission to delete this item.");
await _mediaItems.RemoveAsync(item, cancellationToken); await mediaItems.RemoveAsync(item, cancellationToken);
await _uow.SaveChangesAsync(cancellationToken); await uow.SaveChangesAsync(cancellationToken);
} }
} }
@@ -34,6 +34,7 @@ public sealed class EnsureUserCommandHandler : IRequestHandler<EnsureUserCommand
// Каждый новый пользователь получает системную коллекцию Inbox // Каждый новый пользователь получает системную коллекцию Inbox
var inbox = Collection.CreateInbox(request.TelegramId); var inbox = Collection.CreateInbox(request.TelegramId);
await _collections.AddAsync(inbox, cancellationToken); await _collections.AddAsync(inbox, cancellationToken);
user.SetInboxCollection(inbox.Id);
} }
else else
{ {
@@ -0,0 +1,11 @@
using MediatR;
namespace MemeVault.Application.Commands.JoinPublicCollection;
/// <param name="CollectionId">ID публичной коллекции.</param>
/// <param name="RequestingTelegramId">Telegram ID вступающего пользователя.</param>
/// <returns>true — вступил или уже был участником; false — коллекция не найдена.</returns>
public sealed record JoinPublicCollectionCommand(
Guid CollectionId,
long RequestingTelegramId
) : IRequest<bool>;
@@ -0,0 +1,28 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.JoinPublicCollection;
public sealed class JoinPublicCollectionCommandHandler(
ICollectionRepository collections,
IUnitOfWork unitOfWork)
: IRequestHandler<JoinPublicCollectionCommand, bool>
{
public async Task<bool> Handle(JoinPublicCollectionCommand request, CancellationToken ct)
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
if (collection is null)
return false;
// TryJoinPublic бросит DomainException, если Visibility != Public
var added = collection.TryJoinPublic(request.RequestingTelegramId);
if (added)
{
await collections.UpdateAsync(collection, ct);
await unitOfWork.SaveChangesAsync(ct);
}
return true;
}
}
@@ -0,0 +1,10 @@
using MediatR;
namespace MemeVault.Application.Commands.RegenerateShareLink;
/// <summary>Перегенерировать share-токен коллекции. Требует роль Manager или Owner.</summary>
/// <returns>Новый токен, null если коллекция не найдена.</returns>
public sealed record RegenerateShareLinkCommand(
Guid CollectionId,
long RequestingTelegramId
) : IRequest<string?>;
@@ -0,0 +1,26 @@
using MediatR;
using MemeVault.Application.Common;
using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.RegenerateShareLink;
public sealed class RegenerateShareLinkCommandHandler(
ICollectionRepository collections,
IUnitOfWork unitOfWork)
: IRequestHandler<RegenerateShareLinkCommand, string?>
{
public async Task<string?> Handle(RegenerateShareLinkCommand request, CancellationToken ct)
{
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
if (collection is null)
return null;
// RegenerateShareLink бросит DomainException при Private или недостаточной роли
var token = collection.RegenerateShareLink(request.RequestingTelegramId);
await collections.UpdateAsync(collection, ct);
await unitOfWork.SaveChangesAsync(ct);
return token;
}
}
@@ -11,15 +11,18 @@ public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand,
{ {
private readonly IMediaItemRepository _mediaItems; private readonly IMediaItemRepository _mediaItems;
private readonly ICollectionRepository _collections; private readonly ICollectionRepository _collections;
private readonly IBotUserRepository _users;
private readonly IUnitOfWork _uow; private readonly IUnitOfWork _uow;
public SaveMediaCommandHandler( public SaveMediaCommandHandler(
IMediaItemRepository mediaItems, IMediaItemRepository mediaItems,
ICollectionRepository collections, ICollectionRepository collections,
IBotUserRepository users,
IUnitOfWork uow) IUnitOfWork uow)
{ {
_mediaItems = mediaItems; _mediaItems = mediaItems;
_collections = collections; _collections = collections;
_users = users;
_uow = uow; _uow = uow;
} }
@@ -38,9 +41,10 @@ public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand,
} }
else else
{ {
var inbox = await _collections.GetInboxAsync(request.OwnerTelegramId, cancellationToken) var user = await _users.GetByTelegramIdAsync(request.OwnerTelegramId, cancellationToken);
?? throw new DomainException("User inbox not found."); if (user?.InboxCollectionId is null)
collectionId = inbox.Id; throw new DomainException("User inbox not found.");
collectionId = user.InboxCollectionId.Value;
} }
const int CollectionMediaLimit = 120; const int CollectionMediaLimit = 120;
@@ -8,6 +8,7 @@ namespace MemeVault.Application.Commands.SetCollectionInbox;
public sealed class SetCollectionInboxCommandHandler( public sealed class SetCollectionInboxCommandHandler(
ICollectionRepository collections, ICollectionRepository collections,
IBotUserRepository users,
IUnitOfWork unitOfWork) IUnitOfWork unitOfWork)
: IRequestHandler<SetCollectionInboxCommand, bool> : IRequestHandler<SetCollectionInboxCommand, bool>
{ {
@@ -17,16 +18,14 @@ public sealed class SetCollectionInboxCommandHandler(
if (target is null || target.GetRole(request.RequestingTelegramId) != CollectionRole.Owner) if (target is null || target.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
return false; return false;
if (target.IsInbox) var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user is null) return false;
if (user.InboxCollectionId == target.Id)
throw new DomainException("Collection is already the Inbox."); throw new DomainException("Collection is already the Inbox.");
// Снимаем флаг с текущего Inbox user.SetInboxCollection(target.Id);
var currentInbox = await collections.GetInboxAsync(request.RequestingTelegramId, ct); await users.UpdateAsync(user, ct);
currentInbox?.DemoteFromInbox();
// Промоция целевой коллекции
target.PromoteToInbox(request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct); await unitOfWork.SaveChangesAsync(ct);
return true; return true;
} }
@@ -1,11 +1,13 @@
using MediatR; using MediatR;
using MemeVault.Application.Common; using MemeVault.Application.Common;
using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories; using MemeVault.Domain.Repositories;
namespace MemeVault.Application.Commands.UpdateCollection; namespace MemeVault.Application.Commands.UpdateCollection;
public sealed class UpdateCollectionCommandHandler( public sealed class UpdateCollectionCommandHandler(
ICollectionRepository collections, ICollectionRepository collections,
IBotUserRepository users,
IUnitOfWork unitOfWork) IUnitOfWork unitOfWork)
: IRequestHandler<UpdateCollectionCommand, bool> : IRequestHandler<UpdateCollectionCommand, bool>
{ {
@@ -17,6 +19,10 @@ public sealed class UpdateCollectionCommandHandler(
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null) if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
return false; return false;
var user = await users.GetByTelegramIdAsync(request.RequestingTelegramId, ct);
if (user?.InboxCollectionId == collection.Id)
throw new DomainException("Cannot rename the Inbox collection.");
collection.Rename(request.Name, request.RequestingTelegramId); collection.Rename(request.Name, request.RequestingTelegramId);
await unitOfWork.SaveChangesAsync(ct); await unitOfWork.SaveChangesAsync(ct);
return true; return true;
@@ -15,8 +15,11 @@ public sealed class UpdateMediaCommandHandler(
public async Task<bool> Handle(UpdateMediaCommand request, CancellationToken ct) public async Task<bool> Handle(UpdateMediaCommand request, CancellationToken ct)
{ {
var item = await mediaItems.GetByIdAsync(request.MediaItemId, ct); var item = await mediaItems.GetByIdAsync(request.MediaItemId, ct);
if (item is null)
return false;
if (item is null || item.OwnerTelegramId != request.RequestingTelegramId) var sourceCollection = await collections.GetByIdAsync(item.CollectionId, ct);
if (sourceCollection is null || !sourceCollection.CanWrite(request.RequestingTelegramId))
return false; return false;
item.UpdateCaption(request.Caption); item.UpdateCaption(request.Caption);
@@ -5,7 +5,8 @@ namespace MemeVault.Application.Queries.GetUserCollections;
public sealed class GetUserCollectionsQueryHandler( public sealed class GetUserCollectionsQueryHandler(
ICollectionRepository collections, ICollectionRepository collections,
IMediaItemRepository mediaItems) IMediaItemRepository mediaItems,
IBotUserRepository users)
: IRequestHandler<GetUserCollectionsQuery, IReadOnlyList<CollectionDto>> : IRequestHandler<GetUserCollectionsQuery, IReadOnlyList<CollectionDto>>
{ {
public async Task<IReadOnlyList<CollectionDto>> Handle( public async Task<IReadOnlyList<CollectionDto>> Handle(
@@ -15,15 +16,21 @@ public sealed class GetUserCollectionsQueryHandler(
// Все коллекции, в которых пользователь — участник (любая роль), включая шаренные // Все коллекции, в которых пользователь — участник (любая роль), включая шаренные
var cols = await collections.GetByMemberAsync(request.OwnerTelegramId, ct); var cols = await collections.GetByMemberAsync(request.OwnerTelegramId, ct);
var user = await users.GetByTelegramIdAsync(request.OwnerTelegramId, ct);
var inboxId = user?.InboxCollectionId;
// Подсчёт элементов по всем коллекциям за один GROUP BY запрос // Подсчёт элементов по всем коллекциям за один GROUP BY запрос
var collectionIds = cols.Select(c => c.Id).ToList(); var collectionIds = cols.Select(c => c.Id).ToList();
var countByCollection = await mediaItems.GetCountsByCollectionIdsAsync(collectionIds, ct); var countByCollection = await mediaItems.GetCountsByCollectionIdsAsync(collectionIds, ct);
return cols.Select(c => new CollectionDto( return cols
.OrderBy(c => c.Id == inboxId ? 0 : 1)
.ThenBy(c => c.Name)
.Select(c => new CollectionDto(
c.Id, c.Id,
c.Name, c.Name,
c.Description, c.Description,
c.IsInbox, c.Id == inboxId,
c.Visibility, c.Visibility,
c.IsNsfw, c.IsNsfw,
c.ShareToken, c.ShareToken,
@@ -16,6 +16,9 @@ public sealed class BotUser
public DateTimeOffset CreatedAt { get; private set; } public DateTimeOffset CreatedAt { get; private set; }
public DateTimeOffset LastSeenAt { get; private set; } public DateTimeOffset LastSeenAt { get; private set; }
/// <summary>FK на коллекцию, в которую по умолчанию сохраняется новый контент.</summary>
public Guid? InboxCollectionId { get; private set; }
public IReadOnlyList<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly(); public IReadOnlyList<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
// EF Core constructor // EF Core constructor
@@ -38,6 +41,11 @@ public sealed class BotUser
return user; return user;
} }
public void SetInboxCollection(Guid collectionId)
{
InboxCollectionId = collectionId;
}
public void RecordActivity() public void RecordActivity()
{ {
LastSeenAt = DateTimeOffset.UtcNow; LastSeenAt = DateTimeOffset.UtcNow;
@@ -6,7 +6,6 @@ namespace MemeVault.Domain.Aggregates.Collection;
/// <summary> /// <summary>
/// Aggregate Root: коллекция медиа-элементов с ACL-моделью доступа. /// Aggregate Root: коллекция медиа-элементов с ACL-моделью доступа.
/// Каждый пользователь имеет ровно одну системную коллекцию Inbox (IsInbox = true).
/// </summary> /// </summary>
public sealed class Collection public sealed class Collection
{ {
@@ -23,9 +22,6 @@ public sealed class Collection
public string? Description { get; private set; } public string? Description { get; private set; }
public CollectionVisibility Visibility { get; private set; } public CollectionVisibility Visibility { get; private set; }
/// <summary>Системная коллекция входящих. Нельзя удалить или переименовать.</summary>
public bool IsInbox { get; private set; }
/// <summary>Коллекция содержит контент 18+. Скрывается в inline-режиме.</summary> /// <summary>Коллекция содержит контент 18+. Скрывается в inline-режиме.</summary>
public bool IsNsfw { get; private set; } public bool IsNsfw { get; private set; }
@@ -41,12 +37,11 @@ public sealed class Collection
// EF Core constructor // EF Core constructor
private Collection() { } private Collection() { }
private Collection(Guid id, long ownerTelegramId, string name, string? description, bool isInbox) private Collection(Guid id, long ownerTelegramId, string name, string? description)
{ {
Id = id; Id = id;
Name = name; Name = name;
Description = description; Description = description;
IsInbox = isInbox;
Visibility = CollectionVisibility.Private; Visibility = CollectionVisibility.Private;
CreatedAt = DateTimeOffset.UtcNow; CreatedAt = DateTimeOffset.UtcNow;
@@ -62,12 +57,12 @@ public sealed class Collection
if (name.Length > 100) if (name.Length > 100)
throw new DomainException("Collection name must be 100 characters or less."); throw new DomainException("Collection name must be 100 characters or less.");
return new Collection(Guid.NewGuid(), ownerTelegramId, name, description, isInbox: false); return new Collection(Guid.NewGuid(), ownerTelegramId, name, description);
} }
/// <summary>Создаёт системную коллекцию входящих для нового пользователя.</summary> /// <summary>Создаёт системную коллекцию входящих для нового пользователя.</summary>
public static Collection CreateInbox(long ownerTelegramId) => public static Collection CreateInbox(long ownerTelegramId) =>
new(Guid.NewGuid(), ownerTelegramId, "Inbox", description: null, isInbox: true); new(Guid.NewGuid(), ownerTelegramId, "Inbox", description: null);
// ── Управление участниками ───────────────────────────────────────────────── // ── Управление участниками ─────────────────────────────────────────────────
@@ -131,9 +126,6 @@ public sealed class Collection
public void Rename(string newName, long requestingTelegramId) public void Rename(string newName, long requestingTelegramId)
{ {
if (IsInbox)
throw new DomainException("Cannot rename the Inbox collection.");
EnsureRole(requestingTelegramId, CollectionRole.Manager); EnsureRole(requestingTelegramId, CollectionRole.Manager);
if (string.IsNullOrWhiteSpace(newName)) if (string.IsNullOrWhiteSpace(newName))
@@ -152,29 +144,39 @@ public sealed class Collection
public void Delete(long requestingTelegramId) public void Delete(long requestingTelegramId)
{ {
EnsureRole(requestingTelegramId, CollectionRole.Owner); EnsureRole(requestingTelegramId, CollectionRole.Owner);
if (IsInbox)
throw new DomainException("Cannot delete the Inbox collection.");
} }
// ── Inbox ───────────────────────────────────────────────────────────────── // ── Share-ссылка ──────────────────────────────────────────────────────────
/// <summary> /// <summary>
/// Делает коллекцию основной (Inbox). Вызывать только после снятия флага с текущего Inbox. /// Перегенерирует токен share-ссылки. Доступно Manager и Owner.
/// Бросает <see cref="DomainException"/>, если коллекция Private (ссылки нет).
/// </summary> /// </summary>
public void PromoteToInbox(long requestingTelegramId) public string RegenerateShareLink(long requestingTelegramId)
{ {
EnsureRole(requestingTelegramId, CollectionRole.Owner); EnsureRole(requestingTelegramId, CollectionRole.Manager);
if (IsInbox)
throw new DomainException("Collection is already the Inbox."); if (Visibility == CollectionVisibility.Private)
IsInbox = true; throw new DomainException("Cannot regenerate share link for a private collection.");
ShareToken = GenerateToken();
UpdatedAt = DateTimeOffset.UtcNow; UpdatedAt = DateTimeOffset.UtcNow;
return ShareToken;
} }
/// <summary>Снимает флаг Inbox. Вызывать перед промоцией другой коллекции.</summary> // ── Публичное вступление ─────────────────────────────────────────────────
public void DemoteFromInbox()
/// <summary>
/// Добавляет пользователя как Viewer в публичную коллекцию без инвайта.
/// Бросает <see cref="DomainException"/>, если коллекция не публичная.
/// Идемпотентно: уже являющийся участником — без изменений (возвращает false).
/// </summary>
public bool TryJoinPublic(long telegramId)
{ {
IsInbox = false; if (Visibility != CollectionVisibility.Public)
UpdatedAt = DateTimeOffset.UtcNow; throw new DomainException("Collection is not public.");
return TryAcceptInvite(telegramId, CollectionRole.Viewer);
} }
// ── Инвайты ─────────────────────────────────────────────────────────────── // ── Инвайты ───────────────────────────────────────────────────────────────
@@ -11,9 +11,6 @@ public interface ICollectionRepository
/// <summary>Все коллекции, в которых пользователь является участником (любая роль).</summary> /// <summary>Все коллекции, в которых пользователь является участником (любая роль).</summary>
Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct = default); Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct = default);
/// <summary>Возвращает системную коллекцию Inbox пользователя.</summary>
Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct = default);
Task AddAsync(Collection collection, CancellationToken ct = default); Task AddAsync(Collection collection, CancellationToken ct = default);
Task UpdateAsync(Collection collection, CancellationToken ct = default); Task UpdateAsync(Collection collection, CancellationToken ct = default);
Task RemoveAsync(Collection collection, CancellationToken ct = default); Task RemoveAsync(Collection collection, CancellationToken ct = default);
@@ -0,0 +1,316 @@
// <auto-generated />
using System;
using MemeVault.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20261006223631_DropCollectionIsInbox")]
partial class DropCollectionIsInbox
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("FirstName")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("first_name");
b.Property<Guid?>("InboxCollectionId")
.HasColumnType("uuid")
.HasColumnName("inbox_collection_id");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("last_seen_at");
b.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("username");
b.HasKey("Id");
b.HasIndex("InboxCollectionId");
b.HasIndex("TelegramId")
.IsUnique()
.HasDatabaseName("ix_bot_users_telegram_id");
b.ToTable("bot_users", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("description");
b.Property<bool>("IsNsfw")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasColumnName("is_nsfw");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("name");
b.Property<string>("ShareToken")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("share_token");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string>("Visibility")
.IsRequired()
.HasColumnType("text")
.HasColumnName("visibility");
b.HasKey("Id");
b.HasIndex("ShareToken")
.IsUnique()
.HasDatabaseName("ix_collections_share_token")
.HasFilter("share_token IS NOT NULL");
b.ToTable("collections", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<long>("CreatedByTelegramId")
.HasColumnType("bigint")
.HasColumnName("created_by_telegram_id");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("expires_at");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean")
.HasColumnName("is_revoked");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("revoked_at");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("character varying(32)")
.HasColumnName("token");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_collection_invites_collection_id");
b.HasIndex("Token")
.IsUnique()
.HasDatabaseName("ix_collection_invites_token");
b.ToTable("collection_invites", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b.Property<string>("Caption")
.HasMaxLength(4096)
.HasColumnType("character varying(4096)")
.HasColumnName("caption");
b.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at");
b.Property<string>("MediaGroupId")
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasColumnName("media_group_id");
b.Property<long>("OwnerTelegramId")
.HasColumnType("bigint")
.HasColumnName("owner_telegram_id");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text")
.HasColumnName("type");
b.Property<DateTimeOffset?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("updated_at");
b.Property<string[]>("_tags")
.IsRequired()
.HasColumnType("text[]")
.HasColumnName("tags");
b.HasKey("Id");
b.HasIndex("CollectionId")
.HasDatabaseName("ix_media_items_collection");
b.HasIndex("OwnerTelegramId")
.HasDatabaseName("ix_media_items_owner");
b.HasIndex("_tags")
.HasDatabaseName("ix_media_items_tags");
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
b.ToTable("media_items", (string)null);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
{
b.HasOne("MemeVault.Domain.Aggregates.Collection.Collection", null)
.WithMany()
.HasForeignKey("InboxCollectionId")
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
{
b1.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id");
b1.Property<DateTimeOffset>("AddedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("added_at");
b1.Property<Guid>("CollectionId")
.HasColumnType("uuid")
.HasColumnName("collection_id");
b1.Property<string>("Role")
.IsRequired()
.HasColumnType("text")
.HasColumnName("role");
b1.Property<long>("TelegramId")
.HasColumnType("bigint")
.HasColumnName("telegram_id");
b1.HasKey("Id");
b1.HasIndex("CollectionId", "TelegramId")
.IsUnique()
.HasDatabaseName("ix_collection_members_unique");
b1.ToTable("collection_members", (string)null);
b1.WithOwner()
.HasForeignKey("CollectionId");
});
b.Navigation("Members");
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
{
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
{
b1.Property<Guid>("MediaItemId")
.HasColumnType("uuid");
b1.Property<string>("Origin")
.HasColumnType("text")
.HasColumnName("source_origin");
b1.Property<string>("Reference")
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.HasColumnName("source_reference");
b1.HasKey("MediaItemId");
b1.ToTable("media_items");
b1.WithOwner()
.HasForeignKey("MediaItemId");
});
b.Navigation("Source");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,61 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MemeVault.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class DropCollectionIsInbox : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "is_inbox",
table: "collections");
migrationBuilder.AddColumn<Guid>(
name: "inbox_collection_id",
table: "bot_users",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_bot_users_inbox_collection_id",
table: "bot_users",
column: "inbox_collection_id");
migrationBuilder.AddForeignKey(
name: "FK_bot_users_collections_inbox_collection_id",
table: "bot_users",
column: "inbox_collection_id",
principalTable: "collections",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_bot_users_collections_inbox_collection_id",
table: "bot_users");
migrationBuilder.DropIndex(
name: "IX_bot_users_inbox_collection_id",
table: "bot_users");
migrationBuilder.DropColumn(
name: "inbox_collection_id",
table: "bot_users");
migrationBuilder.AddColumn<bool>(
name: "is_inbox",
table: "collections",
type: "boolean",
nullable: false,
defaultValue: false);
}
}
}
@@ -38,6 +38,10 @@ namespace MemeVault.Infrastructure.Migrations
.HasColumnType("character varying(64)") .HasColumnType("character varying(64)")
.HasColumnName("first_name"); .HasColumnName("first_name");
b.Property<Guid?>("InboxCollectionId")
.HasColumnType("uuid")
.HasColumnName("inbox_collection_id");
b.Property<DateTimeOffset>("LastSeenAt") b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone") .HasColumnType("timestamp with time zone")
.HasColumnName("last_seen_at"); .HasColumnName("last_seen_at");
@@ -54,6 +58,8 @@ namespace MemeVault.Infrastructure.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("InboxCollectionId");
b.HasIndex("TelegramId") b.HasIndex("TelegramId")
.IsUnique() .IsUnique()
.HasDatabaseName("ix_bot_users_telegram_id"); .HasDatabaseName("ix_bot_users_telegram_id");
@@ -77,10 +83,6 @@ namespace MemeVault.Infrastructure.Migrations
.HasColumnType("character varying(500)") .HasColumnType("character varying(500)")
.HasColumnName("description"); .HasColumnName("description");
b.Property<bool>("IsInbox")
.HasColumnType("boolean")
.HasColumnName("is_inbox");
b.Property<bool>("IsNsfw") b.Property<bool>("IsNsfw")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("boolean") .HasColumnType("boolean")
@@ -230,6 +232,14 @@ namespace MemeVault.Infrastructure.Migrations
b.ToTable("media_items", (string)null); b.ToTable("media_items", (string)null);
}); });
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
{
b.HasOne("MemeVault.Domain.Aggregates.Collection.Collection", null)
.WithMany()
.HasForeignKey("InboxCollectionId")
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b => modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
{ {
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 => b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
@@ -32,5 +32,15 @@ public sealed class BotUserConfiguration : IEntityTypeConfiguration<BotUser>
builder.Property(x => x.CreatedAt).HasColumnName("created_at"); builder.Property(x => x.CreatedAt).HasColumnName("created_at");
builder.Property(x => x.LastSeenAt).HasColumnName("last_seen_at"); builder.Property(x => x.LastSeenAt).HasColumnName("last_seen_at");
builder.Property(x => x.InboxCollectionId)
.HasColumnName("inbox_collection_id");
// FK → collections.id; без навигационного свойства на агрегате
builder.HasOne<Domain.Aggregates.Collection.Collection>()
.WithMany()
.HasForeignKey(u => u.InboxCollectionId)
.IsRequired(false)
.OnDelete(DeleteBehavior.SetNull);
} }
} }
@@ -25,10 +25,6 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
.HasColumnName("description") .HasColumnName("description")
.HasMaxLength(500); .HasMaxLength(500);
builder.Property(x => x.IsInbox)
.HasColumnName("is_inbox")
.IsRequired();
builder.Property(x => x.IsNsfw) builder.Property(x => x.IsNsfw)
.HasColumnName("is_nsfw") .HasColumnName("is_nsfw")
.IsRequired() .IsRequired()
@@ -27,8 +27,7 @@ public sealed class CollectionRepository : ICollectionRepository
.Include(c => c.Members) .Include(c => c.Members)
.Where(c => c.Members.Any(m => .Where(c => c.Members.Any(m =>
m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner)) m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner))
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым .OrderBy(x => x.Name)
.ThenBy(x => x.Name)
.ToListAsync(ct); .ToListAsync(ct);
} }
@@ -37,19 +36,10 @@ public sealed class CollectionRepository : ICollectionRepository
return await _db.Collections return await _db.Collections
.Include(c => c.Members) .Include(c => c.Members)
.Where(c => c.Members.Any(m => m.TelegramId == telegramId)) .Where(c => c.Members.Any(m => m.TelegramId == telegramId))
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым .OrderBy(x => x.Name)
.ThenBy(x => x.Name)
.ToListAsync(ct); .ToListAsync(ct);
} }
public Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct) =>
_db.Collections
.Include(c => c.Members)
.FirstOrDefaultAsync(c =>
c.IsInbox &&
c.Members.Any(m => m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner),
ct);
public async Task AddAsync(Collection collection, CancellationToken ct) => public async Task AddAsync(Collection collection, CancellationToken ct) =>
await _db.Collections.AddAsync(collection, ct); await _db.Collections.AddAsync(collection, ct);
@@ -20,7 +20,6 @@ public sealed class CollectionTests
Assert.Equal(Owner, c.OwnerTelegramId); Assert.Equal(Owner, c.OwnerTelegramId);
Assert.Equal("My Memes", c.Name); Assert.Equal("My Memes", c.Name);
Assert.Equal("some desc", c.Description); Assert.Equal("some desc", c.Description);
Assert.False(c.IsInbox);
Assert.Equal(CollectionVisibility.Private, c.Visibility); Assert.Equal(CollectionVisibility.Private, c.Visibility);
Assert.NotEqual(Guid.Empty, c.Id); Assert.NotEqual(Guid.Empty, c.Id);
} }
@@ -53,11 +52,10 @@ public sealed class CollectionTests
// ── CreateInbox ─────────────────────────────────────────────────────────── // ── CreateInbox ───────────────────────────────────────────────────────────
[Fact] [Fact]
public void CreateInbox_SetsIsInboxTrue() public void CreateInbox_SetsNameToInbox()
{ {
var inbox = Collection.CreateInbox(Owner); var inbox = Collection.CreateInbox(Owner);
Assert.True(inbox.IsInbox);
Assert.Equal("Inbox", inbox.Name); Assert.Equal("Inbox", inbox.Name);
Assert.Equal(Owner, inbox.OwnerTelegramId); Assert.Equal(Owner, inbox.OwnerTelegramId);
} }
@@ -85,14 +83,6 @@ public sealed class CollectionTests
Assert.Equal("New", c.Name); Assert.Equal("New", c.Name);
} }
[Fact]
public void Rename_OnInbox_ThrowsDomainException()
{
var inbox = Collection.CreateInbox(Owner);
Assert.Throws<DomainException>(() => inbox.Rename("Renamed", Owner));
}
[Fact] [Fact]
public void Rename_ByViewer_ThrowsDomainException() public void Rename_ByViewer_ThrowsDomainException()
{ {
@@ -1,5 +1,6 @@
using MemeVault.Application.Commands.DeleteCollection; using MemeVault.Application.Commands.DeleteCollection;
using MemeVault.Application.Common; using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.BotUser;
using MemeVault.Domain.Aggregates.Collection; using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Exceptions; using MemeVault.Domain.Exceptions;
using MemeVault.Domain.Repositories; using MemeVault.Domain.Repositories;
@@ -11,6 +12,7 @@ namespace MemeVault.Tests.Unit.Handlers;
public sealed class DeleteCollectionCommandHandlerTests public sealed class DeleteCollectionCommandHandlerTests
{ {
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>(); private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IBotUserRepository _users = Substitute.For<IBotUserRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>(); private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly DeleteCollectionCommandHandler _handler; private readonly DeleteCollectionCommandHandler _handler;
@@ -18,7 +20,7 @@ public sealed class DeleteCollectionCommandHandlerTests
public DeleteCollectionCommandHandlerTests() public DeleteCollectionCommandHandlerTests()
{ {
_handler = new DeleteCollectionCommandHandler(_collections, _uow); _handler = new DeleteCollectionCommandHandler(_collections, _users, _uow);
} }
[Fact] [Fact]
@@ -49,11 +51,15 @@ public sealed class DeleteCollectionCommandHandlerTests
[Fact] [Fact]
public async Task Handle_InboxCollection_ThrowsDomainException() public async Task Handle_InboxCollection_ThrowsDomainException()
{ {
var inbox = Collection.CreateInbox(UserId); var col = Collection.Create(UserId, "Inbox");
_collections.GetByIdAsync(inbox.Id, Arg.Any<CancellationToken>()).Returns(inbox); _collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(col.Id);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
await Assert.ThrowsAsync<DomainException>(() => await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(new DeleteCollectionCommand(inbox.Id, UserId), default)); _handler.Handle(new DeleteCollectionCommand(col.Id, UserId), default));
} }
[Fact] [Fact]
@@ -62,6 +68,10 @@ public sealed class DeleteCollectionCommandHandlerTests
var col = Collection.Create(UserId, "Memes"); var col = Collection.Create(UserId, "Memes");
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col); _collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(Guid.NewGuid()); // different inbox collection
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
var result = await _handler.Handle( var result = await _handler.Handle(
new DeleteCollectionCommand(col.Id, UserId), default); new DeleteCollectionCommand(col.Id, UserId), default);
@@ -33,7 +33,7 @@ public sealed class EnsureUserCommandHandlerTests
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _collections.Received(1).AddAsync( await _collections.Received(1).AddAsync(
Arg.Is<Collection>(c => c.IsInbox && c.OwnerTelegramId == 123L), Arg.Is<Collection>(c => c.Name == "Inbox" && c.OwnerTelegramId == 123L),
Arg.Any<CancellationToken>()); Arg.Any<CancellationToken>());
await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -1,5 +1,6 @@
using MemeVault.Application.Commands.SaveMedia; using MemeVault.Application.Commands.SaveMedia;
using MemeVault.Application.Common; using MemeVault.Application.Common;
using MemeVault.Domain.Aggregates.BotUser;
using MemeVault.Domain.Aggregates.Collection; using MemeVault.Domain.Aggregates.Collection;
using MemeVault.Domain.Aggregates.MediaItem; using MemeVault.Domain.Aggregates.MediaItem;
using MemeVault.Domain.Enums; using MemeVault.Domain.Enums;
@@ -15,6 +16,7 @@ public sealed class SaveMediaCommandHandlerTests
{ {
private readonly IMediaItemRepository _mediaItems = Substitute.For<IMediaItemRepository>(); private readonly IMediaItemRepository _mediaItems = Substitute.For<IMediaItemRepository>();
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>(); private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
private readonly IBotUserRepository _users = Substitute.For<IBotUserRepository>();
private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>(); private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
private readonly SaveMediaCommandHandler _handler; private readonly SaveMediaCommandHandler _handler;
@@ -22,7 +24,7 @@ public sealed class SaveMediaCommandHandlerTests
public SaveMediaCommandHandlerTests() public SaveMediaCommandHandlerTests()
{ {
_handler = new SaveMediaCommandHandler(_mediaItems, _collections, _uow); _handler = new SaveMediaCommandHandler(_mediaItems, _collections, _users, _uow);
} }
private static SaveMediaCommand PhotoCommand(Guid? collectionId = null) => private static SaveMediaCommand PhotoCommand(Guid? collectionId = null) =>
@@ -33,7 +35,9 @@ public sealed class SaveMediaCommandHandlerTests
public async Task Handle_NoCollectionId_SavesItemToInbox() public async Task Handle_NoCollectionId_SavesItemToInbox()
{ {
var inbox = Collection.CreateInbox(UserId); var inbox = Collection.CreateInbox(UserId);
_collections.GetInboxAsync(UserId, Arg.Any<CancellationToken>()).Returns(inbox); var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(inbox.Id);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
var id = await _handler.Handle(PhotoCommand(), default); var id = await _handler.Handle(PhotoCommand(), default);
@@ -61,8 +65,8 @@ public sealed class SaveMediaCommandHandlerTests
[Fact] [Fact]
public async Task Handle_InboxNotFound_ThrowsDomainException() public async Task Handle_InboxNotFound_ThrowsDomainException()
{ {
_collections.GetInboxAsync(UserId, Arg.Any<CancellationToken>()) _users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>())
.Returns((Collection?)null); .Returns((BotUser?)null);
await Assert.ThrowsAsync<DomainException>(() => await Assert.ThrowsAsync<DomainException>(() =>
_handler.Handle(PhotoCommand(), default)); _handler.Handle(PhotoCommand(), default));
@@ -94,7 +98,9 @@ public sealed class SaveMediaCommandHandlerTests
public async Task Handle_TextMedia_WithCaption_Succeeds() public async Task Handle_TextMedia_WithCaption_Succeeds()
{ {
var inbox = Collection.CreateInbox(UserId); var inbox = Collection.CreateInbox(UserId);
_collections.GetInboxAsync(UserId, Arg.Any<CancellationToken>()).Returns(inbox); var user = BotUser.Create(UserId, "testuser", null);
user.SetInboxCollection(inbox.Id);
_users.GetByTelegramIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);
var cmd = new SaveMediaCommand(UserId, Source: null, MediaType.Text, var cmd = new SaveMediaCommand(UserId, Source: null, MediaType.Text,
Caption: "interesting text", Tags: []); Caption: "interesting text", Tags: []);