Files
mws.backend.dotnet/application/Documents/Commands/MoveDocument.cs
T

60 lines
2.2 KiB
C#
Raw Normal View History

using MediatR;
2026-09-20 16:21:15 +07:00
using mws.backend.dotnet.application.Audit;
2026-08-19 23:25:08 +07:00
using mws.backend.dotnet.application.Common;
using mws.backend.dotnet.application.Permissions;
using mws.backend.dotnet.domain.Documents;
2026-08-19 23:25:08 +07:00
namespace mws.backend.dotnet.application.Documents;
2026-09-20 16:21:15 +07:00
public record MoveDocumentCommand(Guid UserId, Guid DocumentId, Guid? NewParentId) : IRequest, IAuditableRequest
{
public string Action => "Document.Move";
public string EntityType => "Document";
public Guid? EntityId => DocumentId;
}
2026-09-20 16:21:15 +07:00
public class MoveDocumentHandler(IUnitOfWork uow, IAuditContext auditContext) : IRequestHandler<MoveDocumentCommand>
{
public async Task Handle(MoveDocumentCommand command, CancellationToken ct)
{
var doc = await DocumentAccess.GetDocumentForUserAsync(uow, command.UserId, command.DocumentId, ct);
await DocumentAccess.EnsureDocumentPermissionAsync(uow, command.UserId, doc.ProjectId, PermissionAction.Edit, ct);
if (command.NewParentId == command.DocumentId)
{
throw new BadRequestException("A document cannot be moved into itself");
}
if (command.NewParentId is { } parentId)
{
var parent = await uow.Documents.GetByIdAsync(parentId, ct)
?? throw new NotFoundException("Parent folder not found");
if (parent.ProjectId != doc.ProjectId)
{
throw new BadRequestException("Parent must belong to the same project");
}
if (parent.Type != DocumentType.Folder)
{
throw new BadRequestException("Parent must be a folder");
}
var cursor = parent.ParentId;
while (cursor is not null)
{
if (cursor == command.DocumentId)
{
throw new BadRequestException("A folder cannot be moved into its own descendant");
}
cursor = await uow.Documents.GetParentIdAsync(cursor.Value, ct);
}
}
doc.ParentId = command.NewParentId;
doc.UpdatedAt = DateTime.UtcNow;
doc.UpdatedBy = command.UserId;
await uow.SaveChangesAsync(ct);
2026-09-20 16:21:15 +07:00
auditContext.EntityName = doc.Title;
}
}