53 lines
2.0 KiB
C#
53 lines
2.0 KiB
C#
using MediatR;
|
|||
|
|
using MemeVault.Application.Common;
|
||
|
|
using MemeVault.Domain.Enums;
|
||
|
|
using MemeVault.Domain.Exceptions;
|
||
|
|
using MemeVault.Domain.Repositories;
|
||
|
|
|
||
|
|
namespace MemeVault.Application.Commands.AcceptCollectionInvite;
|
||
|
|
|
||
|
|
public sealed class AcceptCollectionInviteCommandHandler
|
||
|
|
: IRequestHandler<AcceptCollectionInviteCommand, Guid?>
|
||
|
|
{
|
||
|
|
private readonly ICollectionInviteRepository _invites;
|
||
|
|
private readonly ICollectionRepository _collections;
|
||
|
|
private readonly IUnitOfWork _uow;
|
||
|
|
|
||
|
|
public AcceptCollectionInviteCommandHandler(
|
||
|
|
ICollectionInviteRepository invites,
|
||
|
|
ICollectionRepository collections,
|
||
|
|
IUnitOfWork uow)
|
||
|
|
{
|
||
|
|
_invites = invites;
|
||
|
|
_collections = collections;
|
||
|
|
_uow = uow;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<Guid?> Handle(
|
||
|
|
AcceptCollectionInviteCommand request, CancellationToken cancellationToken)
|
||
|
|
{
|
||
|
|
var invite = await _invites.GetByTokenAsync(request.Token, cancellationToken);
|
||
|
|
if (invite is null || invite.IsRevoked)
|
||
|
|
return null;
|
||
|
|
|
||
|
|
var collection = await _collections.GetByIdAsync(invite.CollectionId, cancellationToken)
|
||
|
|
?? throw new DomainException("Collection no longer exists.");
|
||
|
|
|
||
|
|
// Владелец не может принять инвайт в собственную коллекцию
|
||
|
|
if (collection.OwnerTelegramId == request.AcceptingTelegramId)
|
||
|
|
return collection.Id;
|
||
|
|
|
||
|
|
// Если уже участник — просто возвращаем коллекцию (идемпотентность)
|
||
|
|
if (collection.GetRole(request.AcceptingTelegramId) is not null)
|
||
|
|
return collection.Id;
|
||
|
|
|
||
|
|
// Owner создаёт инвайт с правами requestingTelegramId, добавляем участника
|
||
|
|
collection.AddMember(request.AcceptingTelegramId, invite.Role, collection.OwnerTelegramId);
|
||
|
|
|
||
|
|
await _collections.UpdateAsync(collection, cancellationToken);
|
||
|
|
await _uow.SaveChangesAsync(cancellationToken);
|
||
|
|
|
||
|
|
return collection.Id;
|
||
|
|
}
|
||
|
|
}
|