57 lines
2.4 KiB
C#
57 lines
2.4 KiB
C#
using PostFundManagement.Domain;
|
|
using PostFundManagement.Domain.Abstractions;
|
|
using PostFundManagement.Domain.Api;
|
|
using PostFundManagement.Domain.Extensions;
|
|
using PostFundManagement.Infrastructure.Database;
|
|
|
|
namespace PostFundManagement.Api.Endpoints.Projects;
|
|
|
|
[ApiVersionTarget(1)]
|
|
public class CreateProjectEndpoint : IEndpoint
|
|
{
|
|
public record CreateProjectRequest(long ProgrammeId, string Name, string Description, IndustrySector Sector, ProjectType ProjectType);
|
|
|
|
public void Map(IEndpointRouteBuilder builder)
|
|
{
|
|
builder.MapPost("api/projects", async (CreateProjectRequest request, ClaimsPrincipal principal,
|
|
IDbContextFactory<ApplicationDbContext> contextFactory, CancellationToken cancellationToken = default) =>
|
|
{
|
|
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
|
|
|
|
if (!Guid.TryParse(sidClaim, out var userId))
|
|
return Results.BadRequest("Missing or invalid 'sid' claim.");
|
|
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
if (!await context.Programmes.AnyAsync(p => p.Id == request.ProgrammeId, cancellationToken))
|
|
return Results.BadRequest($"Programme with ID {request.ProgrammeId} does not exist.");
|
|
|
|
var project = new Domain.Entities.Project
|
|
{
|
|
ProgrammeId = request.ProgrammeId,
|
|
Name = request.Name,
|
|
Description = request.Description,
|
|
Sector = request.Sector,
|
|
ProjectType = request.ProjectType,
|
|
Status = ApprovalStatus.Pending,
|
|
CreatedBy = userId,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
|
|
context.Projects.Add(project);
|
|
|
|
return await context.SaveChangesAsync(cancellationToken) > 0
|
|
? Results.Created($"api/projects/{project.Id}", project)
|
|
: Results.BadRequest("Failed to create prject");
|
|
})
|
|
.RequireAuthorization()
|
|
.WithDescription("Create a new project (M04)")
|
|
.WithName(typeof(CreateProjectEndpoint).ToEndpointName())
|
|
.MapToApiVersion(new ApiVersion(1))
|
|
.Produces<Domain.Entities.Project>(StatusCodes.Status201Created)
|
|
.Produces(StatusCodes.Status400BadRequest)
|
|
.Produces(StatusCodes.Status401Unauthorized)
|
|
.WithTags(EndpointTags.Projects);
|
|
}
|
|
}
|