Files
mws.backend.dotnet/mws.application/Documents/Commands/CreateDocument.cs
T
namdhandClaude Sonnet 5 c3384d76d9 Convert Documents module to MediatR commands/queries
Replaces IDocumentService/DocumentService. The permission-check and
descendant-deletion logic moves to a shared DocumentAccess static
helper used by all seven handlers.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 21:03:16 +07:00

58 lines
2.0 KiB
C#

using AutoMapper;
using MediatR;
using Mws.Application.Common;
using Mws.Application.Permissions;
using Mws.Domain.Documents;
namespace Mws.Application.Documents;
public record CreateDocumentCommand(Guid UserId, Guid ProjectId, CreateDocumentRequest Request) : IRequest<DocumentDto>;
public class CreateDocumentHandler(IUnitOfWork uow, IMapper mapper) : IRequestHandler<CreateDocumentCommand, DocumentDto>
{
public async Task<DocumentDto> Handle(CreateDocumentCommand command, CancellationToken ct)
{
await DocumentAccess.EnsureDocumentPermissionAsync(uow, command.UserId, command.ProjectId, PermissionAction.Create, ct);
var request = command.Request;
if (string.IsNullOrWhiteSpace(request.Title))
{
throw new BadRequestException("Title is required");
}
if (request.ParentId is { } parentId)
{
var parent = await uow.Documents.GetInProjectAsync(parentId, command.ProjectId, ct)
?? throw new BadRequestException("Parent document not found");
if (parent.Type != DocumentType.Folder)
{
throw new BadRequestException("Parent must be a folder");
}
}
if (request.Type == DocumentType.Folder && !string.IsNullOrWhiteSpace(request.Content))
{
throw new BadRequestException("Folders cannot have content");
}
var now = DateTime.UtcNow;
var doc = new Document
{
Id = Guid.NewGuid(),
ProjectId = command.ProjectId,
ParentId = request.ParentId,
Title = request.Title.Trim(),
Type = request.Type,
Content = request.Type == DocumentType.Document ? request.Content : null,
CreatedBy = command.UserId,
CreatedAt = now,
UpdatedBy = command.UserId,
UpdatedAt = now,
};
uow.Documents.Add(doc);
await uow.SaveChangesAsync(ct);
return mapper.Map<DocumentDto>(doc);
}
}