Files
mws.backend.dotnet/application/Projects/Commands/CreateProject.cs
T

54 lines
1.7 KiB
C#
Raw Normal View History

using AutoMapper;
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;
2026-09-12 19:40:59 +07:00
using mws.backend.dotnet.application.Permissions;
2026-08-19 23:25:08 +07:00
using mws.backend.dotnet.domain.Projects;
2026-08-19 23:25:08 +07:00
namespace mws.backend.dotnet.application.Projects;
2026-09-20 16:21:15 +07:00
public record CreateProjectCommand(Guid UserId, CreateProjectRequest Request) : IRequest<ProjectDto>, IAuditableRequest
{
public string Action => "Project.Create";
public string EntityType => "Project";
public string? EntityName => Request.Name;
}
2026-09-12 19:40:59 +07:00
public class CreateProjectHandler(IUnitOfWork uow, IMapper mapper, IPermissionService permissions) : IRequestHandler<CreateProjectCommand, ProjectDto>
{
public async Task<ProjectDto> Handle(CreateProjectCommand command, CancellationToken ct)
{
2026-09-12 19:40:59 +07:00
await permissions.EnsureAsync(command.UserId, "projects", PermissionAction.Create, ct);
var request = command.Request;
if (string.IsNullOrWhiteSpace(request.Name))
{
throw new BadRequestException("Project name is required");
}
var now = DateTime.UtcNow;
var project = new Project
{
Id = Guid.NewGuid(),
Name = request.Name.Trim(),
Description = request.Description,
Status = ProjectStatus.Active,
2026-08-19 23:25:08 +07:00
CreatedBy = command.UserId,
CreatedAt = now,
2026-08-19 23:25:08 +07:00
UpdatedBy = command.UserId,
UpdatedAt = now,
};
project.Members.Add(new ProjectMember
{
ProjectId = project.Id,
UserId = command.UserId,
Role = MemberRole.Owner,
});
uow.Projects.Add(project);
await uow.SaveChangesAsync(ct);
return mapper.Map<ProjectDto>(project);
}
}