From 274e60a4339dcbc6cb855496d26ba895f9e5cc8e Mon Sep 17 00:00:00 2001 From: Sergey Gut Date: Wed, 7 Oct 2026 02:45:37 +0400 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BC=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=BF=D0=BB=D0=B0=D0=BD=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D0=BE=D0=B3=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - клонирование коллекции - добавление паблик-коллекций - регенерация паблик-ссылок --- .../Controllers/CollectionsController.cs | 41 +++ .../CloneCollection/CloneCollectionCommand.cs | 11 + .../CloneCollectionCommandHandler.cs | 54 +++ .../CopyMediaToCollectionCommandHandler.cs | 6 +- .../CreateCollectionCommandHandler.cs | 7 +- .../DeleteCollectionCommandHandler.cs | 8 +- .../DeleteMedia/DeleteMediaCommandHandler.cs | 29 +- .../EnsureUser/EnsureUserCommandHandler.cs | 1 + .../JoinPublicCollectionCommand.cs | 11 + .../JoinPublicCollectionCommandHandler.cs | 28 ++ .../RegenerateShareLinkCommand.cs | 10 + .../RegenerateShareLinkCommandHandler.cs | 26 ++ .../SaveMedia/SaveMediaCommandHandler.cs | 10 +- .../SetCollectionInboxCommandHandler.cs | 15 +- .../UpdateCollectionCommandHandler.cs | 6 + .../UpdateMedia/UpdateMediaCommandHandler.cs | 5 +- .../GetUserCollectionsQueryHandler.cs | 31 +- .../Aggregates/BotUser/BotUser.cs | 8 + .../Aggregates/Collection/Collection.cs | 50 +-- .../Repositories/ICollectionRepository.cs | 3 - ...06223631_DropCollectionIsInbox.Designer.cs | 316 ++++++++++++++++++ .../20261006223631_DropCollectionIsInbox.cs | 61 ++++ .../Migrations/AppDbContextModelSnapshot.cs | 18 +- .../Configurations/BotUserConfiguration.cs | 10 + .../Configurations/CollectionConfiguration.cs | 4 - .../Repositories/CollectionRepository.cs | 14 +- .../Domain/CollectionTests.cs | 12 +- .../DeleteCollectionCommandHandlerTests.cs | 18 +- .../Handlers/EnsureUserCommandHandlerTests.cs | 2 +- .../Handlers/SaveMediaCommandHandlerTests.cs | 16 +- 30 files changed, 719 insertions(+), 112 deletions(-) create mode 100644 src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommand.cs create mode 100644 src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommandHandler.cs create mode 100644 src/MemeVault.Application/Commands/JoinPublicCollection/JoinPublicCollectionCommand.cs create mode 100644 src/MemeVault.Application/Commands/JoinPublicCollection/JoinPublicCollectionCommandHandler.cs create mode 100644 src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommand.cs create mode 100644 src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommandHandler.cs create mode 100644 src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.Designer.cs create mode 100644 src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.cs diff --git a/src/MemeVault.Api/Controllers/CollectionsController.cs b/src/MemeVault.Api/Controllers/CollectionsController.cs index 5b84618..09a43b4 100644 --- a/src/MemeVault.Api/Controllers/CollectionsController.cs +++ b/src/MemeVault.Api/Controllers/CollectionsController.cs @@ -4,6 +4,9 @@ using MemeVault.Application.Commands.CreateCollection; using MemeVault.Application.Commands.CreateCollectionInvite; using MemeVault.Application.Commands.DeleteCollection; 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.SetCollectionNsfw; using MemeVault.Application.Commands.ShareCollection; @@ -111,6 +114,32 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren return ok ? NoContent() : NotFound(); } + // POST /api/collections/{id}/clone + [HttpPost("{id:guid}/clone")] + [ProducesResponseType(typeof(object), StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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 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 [HttpPut("{id:guid}/inbox")] public async Task SetInbox(Guid id, CancellationToken ct) @@ -133,6 +162,18 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren 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 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 [HttpPut("{id:guid}/visibility")] public async Task SetVisibility( diff --git a/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommand.cs b/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommand.cs new file mode 100644 index 0000000..e37e89f --- /dev/null +++ b/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommand.cs @@ -0,0 +1,11 @@ +using MediatR; + +namespace MemeVault.Application.Commands.CloneCollection; + +/// ID коллекции-источника. +/// Telegram ID пользователя, создающего клон. +/// ID новой коллекции, null если источник не найден или нет доступа. +public sealed record CloneCollectionCommand( + Guid SourceCollectionId, + long RequestingTelegramId +) : IRequest; diff --git a/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommandHandler.cs new file mode 100644 index 0000000..022bbb7 --- /dev/null +++ b/src/MemeVault.Application/Commands/CloneCollection/CloneCollectionCommandHandler.cs @@ -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 +{ + private const int CollectionOwnerLimit = 5; + + public async Task 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; + } +} diff --git a/src/MemeVault.Application/Commands/CopyMediaToCollection/CopyMediaToCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/CopyMediaToCollection/CopyMediaToCollectionCommandHandler.cs index 6b8845a..963ad39 100644 --- a/src/MemeVault.Application/Commands/CopyMediaToCollection/CopyMediaToCollectionCommandHandler.cs +++ b/src/MemeVault.Application/Commands/CopyMediaToCollection/CopyMediaToCollectionCommandHandler.cs @@ -15,7 +15,11 @@ public sealed class CopyMediaToCollectionCommandHandler( public async Task Handle(CopyMediaToCollectionCommand request, CancellationToken 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; var target = await collections.GetByIdAsync(request.TargetCollectionId, ct); diff --git a/src/MemeVault.Application/Commands/CreateCollection/CreateCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/CreateCollection/CreateCollectionCommandHandler.cs index 368aac5..25e97e5 100644 --- a/src/MemeVault.Application/Commands/CreateCollection/CreateCollectionCommandHandler.cs +++ b/src/MemeVault.Application/Commands/CreateCollection/CreateCollectionCommandHandler.cs @@ -9,11 +9,13 @@ namespace MemeVault.Application.Commands.CreateCollection; public sealed class CreateCollectionCommandHandler : IRequestHandler { private readonly ICollectionRepository _collections; + private readonly IBotUserRepository _users; private readonly IUnitOfWork _uow; - public CreateCollectionCommandHandler(ICollectionRepository collections, IUnitOfWork uow) + public CreateCollectionCommandHandler(ICollectionRepository collections, IBotUserRepository users, IUnitOfWork uow) { _collections = collections; + _users = users; _uow = uow; } @@ -21,8 +23,9 @@ public sealed class CreateCollectionCommandHandler : IRequestHandler !c.IsInbox) >= CollectionOwnerLimit) + if (owned.Count(c => c.Id != user?.InboxCollectionId) >= CollectionOwnerLimit) throw new CollectionQuotaExceededException(CollectionOwnerLimit); var collection = Collection.Create(request.OwnerTelegramId, request.Name, request.Description); diff --git a/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs index 2936e68..c168421 100644 --- a/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs +++ b/src/MemeVault.Application/Commands/DeleteCollection/DeleteCollectionCommandHandler.cs @@ -1,12 +1,14 @@ using MediatR; using MemeVault.Application.Common; using MemeVault.Domain.Enums; +using MemeVault.Domain.Exceptions; using MemeVault.Domain.Repositories; namespace MemeVault.Application.Commands.DeleteCollection; public sealed class DeleteCollectionCommandHandler( ICollectionRepository collections, + IBotUserRepository users, IUnitOfWork unitOfWork) : IRequestHandler { @@ -16,7 +18,11 @@ public sealed class DeleteCollectionCommandHandler( if (collection is null || collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner) 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 unitOfWork.SaveChangesAsync(ct); return true; diff --git a/src/MemeVault.Application/Commands/DeleteMedia/DeleteMediaCommandHandler.cs b/src/MemeVault.Application/Commands/DeleteMedia/DeleteMediaCommandHandler.cs index 95e85fb..ce9febe 100644 --- a/src/MemeVault.Application/Commands/DeleteMedia/DeleteMediaCommandHandler.cs +++ b/src/MemeVault.Application/Commands/DeleteMedia/DeleteMediaCommandHandler.cs @@ -5,26 +5,23 @@ using MemeVault.Domain.Repositories; namespace MemeVault.Application.Commands.DeleteMedia; -public sealed class DeleteMediaCommandHandler : IRequestHandler +public sealed class DeleteMediaCommandHandler( + IMediaItemRepository mediaItems, + ICollectionRepository collections, + IUnitOfWork uow) + : IRequestHandler { - 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) { - var item = await _mediaItems.GetByIdAsync(request.MediaItemId, cancellationToken) - ?? throw new DomainException($"MediaItem {request.MediaItemId} not found."); + var item = await mediaItems.GetByIdAsync(request.MediaItemId, cancellationToken); + if (item is null) + return; - if (item.OwnerTelegramId != request.RequestingTelegramId) - throw new DomainException("You are not the owner of this item."); + var collection = await collections.GetByIdAsync(item.CollectionId, cancellationToken); + 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 _uow.SaveChangesAsync(cancellationToken); + await mediaItems.RemoveAsync(item, cancellationToken); + await uow.SaveChangesAsync(cancellationToken); } } diff --git a/src/MemeVault.Application/Commands/EnsureUser/EnsureUserCommandHandler.cs b/src/MemeVault.Application/Commands/EnsureUser/EnsureUserCommandHandler.cs index 8b9617c..5642e38 100644 --- a/src/MemeVault.Application/Commands/EnsureUser/EnsureUserCommandHandler.cs +++ b/src/MemeVault.Application/Commands/EnsureUser/EnsureUserCommandHandler.cs @@ -34,6 +34,7 @@ public sealed class EnsureUserCommandHandler : IRequestHandlerID публичной коллекции. +/// Telegram ID вступающего пользователя. +/// true — вступил или уже был участником; false — коллекция не найдена. +public sealed record JoinPublicCollectionCommand( + Guid CollectionId, + long RequestingTelegramId +) : IRequest; diff --git a/src/MemeVault.Application/Commands/JoinPublicCollection/JoinPublicCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/JoinPublicCollection/JoinPublicCollectionCommandHandler.cs new file mode 100644 index 0000000..d9e3840 --- /dev/null +++ b/src/MemeVault.Application/Commands/JoinPublicCollection/JoinPublicCollectionCommandHandler.cs @@ -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 +{ + public async Task 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; + } +} diff --git a/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommand.cs b/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommand.cs new file mode 100644 index 0000000..32ad4ae --- /dev/null +++ b/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommand.cs @@ -0,0 +1,10 @@ +using MediatR; + +namespace MemeVault.Application.Commands.RegenerateShareLink; + +/// Перегенерировать share-токен коллекции. Требует роль Manager или Owner. +/// Новый токен, null если коллекция не найдена. +public sealed record RegenerateShareLinkCommand( + Guid CollectionId, + long RequestingTelegramId +) : IRequest; diff --git a/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommandHandler.cs b/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommandHandler.cs new file mode 100644 index 0000000..000aa0e --- /dev/null +++ b/src/MemeVault.Application/Commands/RegenerateShareLink/RegenerateShareLinkCommandHandler.cs @@ -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 +{ + public async Task 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; + } +} diff --git a/src/MemeVault.Application/Commands/SaveMedia/SaveMediaCommandHandler.cs b/src/MemeVault.Application/Commands/SaveMedia/SaveMediaCommandHandler.cs index cd37a8d..269754e 100644 --- a/src/MemeVault.Application/Commands/SaveMedia/SaveMediaCommandHandler.cs +++ b/src/MemeVault.Application/Commands/SaveMedia/SaveMediaCommandHandler.cs @@ -11,15 +11,18 @@ public sealed class SaveMediaCommandHandler : IRequestHandler { @@ -17,16 +18,14 @@ public sealed class SetCollectionInboxCommandHandler( if (target is null || target.GetRole(request.RequestingTelegramId) != CollectionRole.Owner) 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."); - // Снимаем флаг с текущего Inbox - var currentInbox = await collections.GetInboxAsync(request.RequestingTelegramId, ct); - currentInbox?.DemoteFromInbox(); - - // Промоция целевой коллекции - target.PromoteToInbox(request.RequestingTelegramId); - + user.SetInboxCollection(target.Id); + await users.UpdateAsync(user, ct); await unitOfWork.SaveChangesAsync(ct); return true; } diff --git a/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs b/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs index f4afb97..b4768b5 100644 --- a/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs +++ b/src/MemeVault.Application/Commands/UpdateCollection/UpdateCollectionCommandHandler.cs @@ -1,11 +1,13 @@ using MediatR; using MemeVault.Application.Common; +using MemeVault.Domain.Exceptions; using MemeVault.Domain.Repositories; namespace MemeVault.Application.Commands.UpdateCollection; public sealed class UpdateCollectionCommandHandler( ICollectionRepository collections, + IBotUserRepository users, IUnitOfWork unitOfWork) : IRequestHandler { @@ -17,6 +19,10 @@ public sealed class UpdateCollectionCommandHandler( if (collection is null || collection.GetRole(request.RequestingTelegramId) is null) 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); await unitOfWork.SaveChangesAsync(ct); return true; diff --git a/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs index 4fde65f..69c260d 100644 --- a/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs +++ b/src/MemeVault.Application/Commands/UpdateMedia/UpdateMediaCommandHandler.cs @@ -15,8 +15,11 @@ public sealed class UpdateMediaCommandHandler( public async Task Handle(UpdateMediaCommand request, CancellationToken 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; item.UpdateCaption(request.Caption); diff --git a/src/MemeVault.Application/Queries/GetUserCollections/GetUserCollectionsQueryHandler.cs b/src/MemeVault.Application/Queries/GetUserCollections/GetUserCollectionsQueryHandler.cs index d7bb150..898f7f1 100644 --- a/src/MemeVault.Application/Queries/GetUserCollections/GetUserCollectionsQueryHandler.cs +++ b/src/MemeVault.Application/Queries/GetUserCollections/GetUserCollectionsQueryHandler.cs @@ -5,7 +5,8 @@ namespace MemeVault.Application.Queries.GetUserCollections; public sealed class GetUserCollectionsQueryHandler( ICollectionRepository collections, - IMediaItemRepository mediaItems) + IMediaItemRepository mediaItems, + IBotUserRepository users) : IRequestHandler> { public async Task> Handle( @@ -15,20 +16,26 @@ public sealed class GetUserCollectionsQueryHandler( // Все коллекции, в которых пользователь — участник (любая роль), включая шаренные var cols = await collections.GetByMemberAsync(request.OwnerTelegramId, ct); + var user = await users.GetByTelegramIdAsync(request.OwnerTelegramId, ct); + var inboxId = user?.InboxCollectionId; + // Подсчёт элементов по всем коллекциям за один GROUP BY запрос var collectionIds = cols.Select(c => c.Id).ToList(); var countByCollection = await mediaItems.GetCountsByCollectionIdsAsync(collectionIds, ct); - return cols.Select(c => new CollectionDto( - c.Id, - c.Name, - c.Description, - c.IsInbox, - c.Visibility, - c.IsNsfw, - c.ShareToken, - countByCollection.GetValueOrDefault(c.Id, 0), - c.CreatedAt - )).ToList(); + return cols + .OrderBy(c => c.Id == inboxId ? 0 : 1) + .ThenBy(c => c.Name) + .Select(c => new CollectionDto( + c.Id, + c.Name, + c.Description, + c.Id == inboxId, + c.Visibility, + c.IsNsfw, + c.ShareToken, + countByCollection.GetValueOrDefault(c.Id, 0), + c.CreatedAt + )).ToList(); } } diff --git a/src/MemeVault.Domain/Aggregates/BotUser/BotUser.cs b/src/MemeVault.Domain/Aggregates/BotUser/BotUser.cs index 018a2db..5325da6 100644 --- a/src/MemeVault.Domain/Aggregates/BotUser/BotUser.cs +++ b/src/MemeVault.Domain/Aggregates/BotUser/BotUser.cs @@ -16,6 +16,9 @@ public sealed class BotUser public DateTimeOffset CreatedAt { get; private set; } public DateTimeOffset LastSeenAt { get; private set; } + /// FK на коллекцию, в которую по умолчанию сохраняется новый контент. + public Guid? InboxCollectionId { get; private set; } + public IReadOnlyList DomainEvents => _domainEvents.AsReadOnly(); // EF Core constructor @@ -38,6 +41,11 @@ public sealed class BotUser return user; } + public void SetInboxCollection(Guid collectionId) + { + InboxCollectionId = collectionId; + } + public void RecordActivity() { LastSeenAt = DateTimeOffset.UtcNow; diff --git a/src/MemeVault.Domain/Aggregates/Collection/Collection.cs b/src/MemeVault.Domain/Aggregates/Collection/Collection.cs index fd144ec..fa31578 100644 --- a/src/MemeVault.Domain/Aggregates/Collection/Collection.cs +++ b/src/MemeVault.Domain/Aggregates/Collection/Collection.cs @@ -6,7 +6,6 @@ namespace MemeVault.Domain.Aggregates.Collection; /// /// Aggregate Root: коллекция медиа-элементов с ACL-моделью доступа. -/// Каждый пользователь имеет ровно одну системную коллекцию Inbox (IsInbox = true). /// public sealed class Collection { @@ -23,9 +22,6 @@ public sealed class Collection public string? Description { get; private set; } public CollectionVisibility Visibility { get; private set; } - /// Системная коллекция входящих. Нельзя удалить или переименовать. - public bool IsInbox { get; private set; } - /// Коллекция содержит контент 18+. Скрывается в inline-режиме. public bool IsNsfw { get; private set; } @@ -41,12 +37,11 @@ public sealed class Collection // EF Core constructor 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; Name = name; Description = description; - IsInbox = isInbox; Visibility = CollectionVisibility.Private; CreatedAt = DateTimeOffset.UtcNow; @@ -62,12 +57,12 @@ public sealed class Collection if (name.Length > 100) 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); } /// Создаёт системную коллекцию входящих для нового пользователя. 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) { - if (IsInbox) - throw new DomainException("Cannot rename the Inbox collection."); - EnsureRole(requestingTelegramId, CollectionRole.Manager); if (string.IsNullOrWhiteSpace(newName)) @@ -152,29 +144,39 @@ public sealed class Collection public void Delete(long requestingTelegramId) { EnsureRole(requestingTelegramId, CollectionRole.Owner); - if (IsInbox) - throw new DomainException("Cannot delete the Inbox collection."); } - // ── Inbox ───────────────────────────────────────────────────────────────── + // ── Share-ссылка ────────────────────────────────────────────────────────── /// - /// Делает коллекцию основной (Inbox). Вызывать только после снятия флага с текущего Inbox. + /// Перегенерирует токен share-ссылки. Доступно Manager и Owner. + /// Бросает , если коллекция Private (ссылки нет). /// - public void PromoteToInbox(long requestingTelegramId) + public string RegenerateShareLink(long requestingTelegramId) { - EnsureRole(requestingTelegramId, CollectionRole.Owner); - if (IsInbox) - throw new DomainException("Collection is already the Inbox."); - IsInbox = true; + EnsureRole(requestingTelegramId, CollectionRole.Manager); + + if (Visibility == CollectionVisibility.Private) + throw new DomainException("Cannot regenerate share link for a private collection."); + + ShareToken = GenerateToken(); UpdatedAt = DateTimeOffset.UtcNow; + return ShareToken; } - /// Снимает флаг Inbox. Вызывать перед промоцией другой коллекции. - public void DemoteFromInbox() + // ── Публичное вступление ───────────────────────────────────────────────── + + /// + /// Добавляет пользователя как Viewer в публичную коллекцию без инвайта. + /// Бросает , если коллекция не публичная. + /// Идемпотентно: уже являющийся участником — без изменений (возвращает false). + /// + public bool TryJoinPublic(long telegramId) { - IsInbox = false; - UpdatedAt = DateTimeOffset.UtcNow; + if (Visibility != CollectionVisibility.Public) + throw new DomainException("Collection is not public."); + + return TryAcceptInvite(telegramId, CollectionRole.Viewer); } // ── Инвайты ─────────────────────────────────────────────────────────────── diff --git a/src/MemeVault.Domain/Repositories/ICollectionRepository.cs b/src/MemeVault.Domain/Repositories/ICollectionRepository.cs index e233c21..fb24474 100644 --- a/src/MemeVault.Domain/Repositories/ICollectionRepository.cs +++ b/src/MemeVault.Domain/Repositories/ICollectionRepository.cs @@ -11,9 +11,6 @@ public interface ICollectionRepository /// Все коллекции, в которых пользователь является участником (любая роль). Task> GetByMemberAsync(long telegramId, CancellationToken ct = default); - /// Возвращает системную коллекцию Inbox пользователя. - Task GetInboxAsync(long ownerTelegramId, CancellationToken ct = default); - Task AddAsync(Collection collection, CancellationToken ct = default); Task UpdateAsync(Collection collection, CancellationToken ct = default); Task RemoveAsync(Collection collection, CancellationToken ct = default); diff --git a/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.Designer.cs b/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.Designer.cs new file mode 100644 index 0000000..03903c1 --- /dev/null +++ b/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.Designer.cs @@ -0,0 +1,316 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("FirstName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("first_name"); + + b.Property("InboxCollectionId") + .HasColumnType("uuid") + .HasColumnName("inbox_collection_id"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_seen_at"); + + b.Property("TelegramId") + .HasColumnType("bigint") + .HasColumnName("telegram_id"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("IsNsfw") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_nsfw"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("name"); + + b.Property("ShareToken") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("share_token"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CollectionId") + .HasColumnType("uuid") + .HasColumnName("collection_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("CreatedByTelegramId") + .HasColumnType("bigint") + .HasColumnName("created_by_telegram_id"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("IsRevoked") + .HasColumnType("boolean") + .HasColumnName("is_revoked"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text") + .HasColumnName("role"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Caption") + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("caption"); + + b.Property("CollectionId") + .HasColumnType("uuid") + .HasColumnName("collection_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("MediaGroupId") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("media_group_id"); + + b.Property("OwnerTelegramId") + .HasColumnType("bigint") + .HasColumnName("owner_telegram_id"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text") + .HasColumnName("type"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("_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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b1.Property("AddedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("added_at"); + + b1.Property("CollectionId") + .HasColumnType("uuid") + .HasColumnName("collection_id"); + + b1.Property("Role") + .IsRequired() + .HasColumnType("text") + .HasColumnName("role"); + + b1.Property("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("MediaItemId") + .HasColumnType("uuid"); + + b1.Property("Origin") + .HasColumnType("text") + .HasColumnName("source_origin"); + + b1.Property("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 + } + } +} diff --git a/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.cs b/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.cs new file mode 100644 index 0000000..3d5ccc0 --- /dev/null +++ b/src/MemeVault.Infrastructure/Migrations/20261006223631_DropCollectionIsInbox.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MemeVault.Infrastructure.Migrations +{ + /// + public partial class DropCollectionIsInbox : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "is_inbox", + table: "collections"); + + migrationBuilder.AddColumn( + 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); + } + + /// + 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( + name: "is_inbox", + table: "collections", + type: "boolean", + nullable: false, + defaultValue: false); + } + } +} diff --git a/src/MemeVault.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/MemeVault.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 370f877..e336bf0 100644 --- a/src/MemeVault.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/MemeVault.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -38,6 +38,10 @@ namespace MemeVault.Infrastructure.Migrations .HasColumnType("character varying(64)") .HasColumnName("first_name"); + b.Property("InboxCollectionId") + .HasColumnType("uuid") + .HasColumnName("inbox_collection_id"); + b.Property("LastSeenAt") .HasColumnType("timestamp with time zone") .HasColumnName("last_seen_at"); @@ -54,6 +58,8 @@ namespace MemeVault.Infrastructure.Migrations b.HasKey("Id"); + b.HasIndex("InboxCollectionId"); + b.HasIndex("TelegramId") .IsUnique() .HasDatabaseName("ix_bot_users_telegram_id"); @@ -77,10 +83,6 @@ namespace MemeVault.Infrastructure.Migrations .HasColumnType("character varying(500)") .HasColumnName("description"); - b.Property("IsInbox") - .HasColumnType("boolean") - .HasColumnName("is_inbox"); - b.Property("IsNsfw") .ValueGeneratedOnAdd() .HasColumnType("boolean") @@ -230,6 +232,14 @@ namespace MemeVault.Infrastructure.Migrations 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 => diff --git a/src/MemeVault.Infrastructure/Persistence/Configurations/BotUserConfiguration.cs b/src/MemeVault.Infrastructure/Persistence/Configurations/BotUserConfiguration.cs index 98e26dc..d080e6f 100644 --- a/src/MemeVault.Infrastructure/Persistence/Configurations/BotUserConfiguration.cs +++ b/src/MemeVault.Infrastructure/Persistence/Configurations/BotUserConfiguration.cs @@ -32,5 +32,15 @@ public sealed class BotUserConfiguration : IEntityTypeConfiguration builder.Property(x => x.CreatedAt).HasColumnName("created_at"); builder.Property(x => x.LastSeenAt).HasColumnName("last_seen_at"); + + builder.Property(x => x.InboxCollectionId) + .HasColumnName("inbox_collection_id"); + + // FK → collections.id; без навигационного свойства на агрегате + builder.HasOne() + .WithMany() + .HasForeignKey(u => u.InboxCollectionId) + .IsRequired(false) + .OnDelete(DeleteBehavior.SetNull); } } diff --git a/src/MemeVault.Infrastructure/Persistence/Configurations/CollectionConfiguration.cs b/src/MemeVault.Infrastructure/Persistence/Configurations/CollectionConfiguration.cs index 081768a..9db57db 100644 --- a/src/MemeVault.Infrastructure/Persistence/Configurations/CollectionConfiguration.cs +++ b/src/MemeVault.Infrastructure/Persistence/Configurations/CollectionConfiguration.cs @@ -25,10 +25,6 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration x.IsInbox) - .HasColumnName("is_inbox") - .IsRequired(); - builder.Property(x => x.IsNsfw) .HasColumnName("is_nsfw") .IsRequired() diff --git a/src/MemeVault.Infrastructure/Persistence/Repositories/CollectionRepository.cs b/src/MemeVault.Infrastructure/Persistence/Repositories/CollectionRepository.cs index ab60ccf..8845af8 100644 --- a/src/MemeVault.Infrastructure/Persistence/Repositories/CollectionRepository.cs +++ b/src/MemeVault.Infrastructure/Persistence/Repositories/CollectionRepository.cs @@ -27,8 +27,7 @@ public sealed class CollectionRepository : ICollectionRepository .Include(c => c.Members) .Where(c => c.Members.Any(m => m.TelegramId == ownerTelegramId && m.Role == CollectionRole.Owner)) - .OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым - .ThenBy(x => x.Name) + .OrderBy(x => x.Name) .ToListAsync(ct); } @@ -37,19 +36,10 @@ public sealed class CollectionRepository : ICollectionRepository return await _db.Collections .Include(c => c.Members) .Where(c => c.Members.Any(m => m.TelegramId == telegramId)) - .OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым - .ThenBy(x => x.Name) + .OrderBy(x => x.Name) .ToListAsync(ct); } - public Task 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) => await _db.Collections.AddAsync(collection, ct); diff --git a/src/MemeVault.Tests.Unit/Domain/CollectionTests.cs b/src/MemeVault.Tests.Unit/Domain/CollectionTests.cs index 227c5c8..bfd2589 100644 --- a/src/MemeVault.Tests.Unit/Domain/CollectionTests.cs +++ b/src/MemeVault.Tests.Unit/Domain/CollectionTests.cs @@ -20,7 +20,6 @@ public sealed class CollectionTests Assert.Equal(Owner, c.OwnerTelegramId); Assert.Equal("My Memes", c.Name); Assert.Equal("some desc", c.Description); - Assert.False(c.IsInbox); Assert.Equal(CollectionVisibility.Private, c.Visibility); Assert.NotEqual(Guid.Empty, c.Id); } @@ -53,11 +52,10 @@ public sealed class CollectionTests // ── CreateInbox ─────────────────────────────────────────────────────────── [Fact] - public void CreateInbox_SetsIsInboxTrue() + public void CreateInbox_SetsNameToInbox() { var inbox = Collection.CreateInbox(Owner); - Assert.True(inbox.IsInbox); Assert.Equal("Inbox", inbox.Name); Assert.Equal(Owner, inbox.OwnerTelegramId); } @@ -85,14 +83,6 @@ public sealed class CollectionTests Assert.Equal("New", c.Name); } - [Fact] - public void Rename_OnInbox_ThrowsDomainException() - { - var inbox = Collection.CreateInbox(Owner); - - Assert.Throws(() => inbox.Rename("Renamed", Owner)); - } - [Fact] public void Rename_ByViewer_ThrowsDomainException() { diff --git a/src/MemeVault.Tests.Unit/Handlers/DeleteCollectionCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/DeleteCollectionCommandHandlerTests.cs index 2199344..8428ccb 100644 --- a/src/MemeVault.Tests.Unit/Handlers/DeleteCollectionCommandHandlerTests.cs +++ b/src/MemeVault.Tests.Unit/Handlers/DeleteCollectionCommandHandlerTests.cs @@ -1,5 +1,6 @@ using MemeVault.Application.Commands.DeleteCollection; using MemeVault.Application.Common; +using MemeVault.Domain.Aggregates.BotUser; using MemeVault.Domain.Aggregates.Collection; using MemeVault.Domain.Exceptions; using MemeVault.Domain.Repositories; @@ -11,6 +12,7 @@ namespace MemeVault.Tests.Unit.Handlers; public sealed class DeleteCollectionCommandHandlerTests { private readonly ICollectionRepository _collections = Substitute.For(); + private readonly IBotUserRepository _users = Substitute.For(); private readonly IUnitOfWork _uow = Substitute.For(); private readonly DeleteCollectionCommandHandler _handler; @@ -18,7 +20,7 @@ public sealed class DeleteCollectionCommandHandlerTests public DeleteCollectionCommandHandlerTests() { - _handler = new DeleteCollectionCommandHandler(_collections, _uow); + _handler = new DeleteCollectionCommandHandler(_collections, _users, _uow); } [Fact] @@ -49,11 +51,15 @@ public sealed class DeleteCollectionCommandHandlerTests [Fact] public async Task Handle_InboxCollection_ThrowsDomainException() { - var inbox = Collection.CreateInbox(UserId); - _collections.GetByIdAsync(inbox.Id, Arg.Any()).Returns(inbox); + var col = Collection.Create(UserId, "Inbox"); + _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + + var user = BotUser.Create(UserId, "testuser", null); + user.SetInboxCollection(col.Id); + _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); await Assert.ThrowsAsync(() => - _handler.Handle(new DeleteCollectionCommand(inbox.Id, UserId), default)); + _handler.Handle(new DeleteCollectionCommand(col.Id, UserId), default)); } [Fact] @@ -62,6 +68,10 @@ public sealed class DeleteCollectionCommandHandlerTests var col = Collection.Create(UserId, "Memes"); _collections.GetByIdAsync(col.Id, Arg.Any()).Returns(col); + var user = BotUser.Create(UserId, "testuser", null); + user.SetInboxCollection(Guid.NewGuid()); // different inbox collection + _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); + var result = await _handler.Handle( new DeleteCollectionCommand(col.Id, UserId), default); diff --git a/src/MemeVault.Tests.Unit/Handlers/EnsureUserCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/EnsureUserCommandHandlerTests.cs index 45ef6b1..cb29c29 100644 --- a/src/MemeVault.Tests.Unit/Handlers/EnsureUserCommandHandlerTests.cs +++ b/src/MemeVault.Tests.Unit/Handlers/EnsureUserCommandHandlerTests.cs @@ -33,7 +33,7 @@ public sealed class EnsureUserCommandHandlerTests Arg.Any()); await _collections.Received(1).AddAsync( - Arg.Is(c => c.IsInbox && c.OwnerTelegramId == 123L), + Arg.Is(c => c.Name == "Inbox" && c.OwnerTelegramId == 123L), Arg.Any()); await _uow.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/src/MemeVault.Tests.Unit/Handlers/SaveMediaCommandHandlerTests.cs b/src/MemeVault.Tests.Unit/Handlers/SaveMediaCommandHandlerTests.cs index 4e076eb..a7c7c48 100644 --- a/src/MemeVault.Tests.Unit/Handlers/SaveMediaCommandHandlerTests.cs +++ b/src/MemeVault.Tests.Unit/Handlers/SaveMediaCommandHandlerTests.cs @@ -1,5 +1,6 @@ using MemeVault.Application.Commands.SaveMedia; using MemeVault.Application.Common; +using MemeVault.Domain.Aggregates.BotUser; using MemeVault.Domain.Aggregates.Collection; using MemeVault.Domain.Aggregates.MediaItem; using MemeVault.Domain.Enums; @@ -15,6 +16,7 @@ public sealed class SaveMediaCommandHandlerTests { private readonly IMediaItemRepository _mediaItems = Substitute.For(); private readonly ICollectionRepository _collections = Substitute.For(); + private readonly IBotUserRepository _users = Substitute.For(); private readonly IUnitOfWork _uow = Substitute.For(); private readonly SaveMediaCommandHandler _handler; @@ -22,7 +24,7 @@ public sealed class SaveMediaCommandHandlerTests public SaveMediaCommandHandlerTests() { - _handler = new SaveMediaCommandHandler(_mediaItems, _collections, _uow); + _handler = new SaveMediaCommandHandler(_mediaItems, _collections, _users, _uow); } private static SaveMediaCommand PhotoCommand(Guid? collectionId = null) => @@ -33,7 +35,9 @@ public sealed class SaveMediaCommandHandlerTests public async Task Handle_NoCollectionId_SavesItemToInbox() { var inbox = Collection.CreateInbox(UserId); - _collections.GetInboxAsync(UserId, Arg.Any()).Returns(inbox); + var user = BotUser.Create(UserId, "testuser", null); + user.SetInboxCollection(inbox.Id); + _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); var id = await _handler.Handle(PhotoCommand(), default); @@ -61,8 +65,8 @@ public sealed class SaveMediaCommandHandlerTests [Fact] public async Task Handle_InboxNotFound_ThrowsDomainException() { - _collections.GetInboxAsync(UserId, Arg.Any()) - .Returns((Collection?)null); + _users.GetByTelegramIdAsync(UserId, Arg.Any()) + .Returns((BotUser?)null); await Assert.ThrowsAsync(() => _handler.Handle(PhotoCommand(), default)); @@ -94,7 +98,9 @@ public sealed class SaveMediaCommandHandlerTests public async Task Handle_TextMedia_WithCaption_Succeeds() { var inbox = Collection.CreateInbox(UserId); - _collections.GetInboxAsync(UserId, Arg.Any()).Returns(inbox); + var user = BotUser.Create(UserId, "testuser", null); + user.SetInboxCollection(inbox.Id); + _users.GetByTelegramIdAsync(UserId, Arg.Any()).Returns(user); var cmd = new SaveMediaCommand(UserId, Source: null, MediaType.Text, Caption: "interesting text", Tags: []);