Implemented basic endpoints
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Api;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Grants;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public class CreateBudgetEndpoint : IEndpoint
|
||||
{
|
||||
public record CreateBudgetRequest(long ProjectId, string Name, decimal Amount);
|
||||
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/grants/budgets", async (CreateBudgetRequest 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.");
|
||||
|
||||
if (request.Amount <= 0)
|
||||
return Results.BadRequest("Budget amount must be greater than zero.");
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Projects.AnyAsync(p => p.Id == request.ProjectId, cancellationToken))
|
||||
return Results.BadRequest($"Project with ID {request.ProjectId} does not exist.");
|
||||
|
||||
var budget = new Domain.Entities.Budget
|
||||
{
|
||||
ProjectId = request.ProjectId,
|
||||
Name = request.Name,
|
||||
Amount = request.Amount,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
context.Budgets.Add(budget);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Results.Created($"api/grants/budgets/{budget.Id}", budget)
|
||||
: Results.BadRequest("Failed to create budget");
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithDescription("Create a new budget line (M05)")
|
||||
.WithName(typeof(CreateBudgetEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Domain.Entities.Budget>(StatusCodes.Status201Created)
|
||||
.Produces(StatusCodes.Status400BadRequest)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Grants);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user