Initial commit

This commit is contained in:
2026-05-05 10:39:43 +02:00
commit b590ecdc35
87 changed files with 3934 additions and 0 deletions
@@ -0,0 +1,40 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class CreateCourseEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<CreateCourseDto, GetCourseDto>
{
public override void Configure()
{
Post("api/courses");
AllowAnonymous();
Summary(s => s.Summary = "Crée un nouveau cours (statut Brouillon par défaut)");
}
public override async Task HandleAsync(CreateCourseDto req, CancellationToken ct)
{
var creatorExists = await db.Users.AnyAsync(u => u.Id == req.CreatorId, ct);
if (!creatorExists)
{
AddError(r => r.CreatorId, "L'utilisateur créateur n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
var course = mapper.Map<Course>(req);
db.Courses.Add(course);
await db.SaveChangesAsync(ct);
var created = await db.Courses
.Include(c => c.Creator)
.Include(c => c.Topics)
.FirstAsync(c => c.Id == course.Id, ct);
await SendAsync(mapper.Map<GetCourseDto>(created), 201, ct);
}
}
@@ -0,0 +1,44 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class DeleteCourseRequest
{
public Guid Id { get; set; }
}
public class DeleteCourseEndpoint(AppDbContext db) : Endpoint<DeleteCourseRequest>
{
public override void Configure()
{
Delete("api/courses/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Supprime un cours (uniquement si brouillon sans inscriptions)");
}
public override async Task HandleAsync(DeleteCourseRequest req, CancellationToken ct)
{
var course = await db.Courses
.Include(c => c.UserCourses)
.FirstOrDefaultAsync(c => c.Id == req.Id, ct);
if (course is null)
{
await SendNotFoundAsync(ct);
return;
}
if (course.UserCourses.Any())
{
AddError("Impossible de supprimer un cours auquel des utilisateurs sont inscrits.");
await SendErrorsAsync(409, ct);
return;
}
db.Courses.Remove(course);
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,41 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class GetCourseRequest
{
public Guid Id { get; set; }
}
public class GetCourseEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetCourseRequest, GetCourseDetailsDto>
{
public override void Configure()
{
Get("api/courses/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Récupère le détail d'un cours avec ses sujets et ressources");
}
public override async Task HandleAsync(GetCourseRequest req, CancellationToken ct)
{
var course = await db.Courses
.AsNoTracking()
.Include(c => c.Creator)
.Include(c => c.Topics.OrderBy(t => t.Position))
.ThenInclude(t => t.TopicResources.OrderBy(tr => tr.Position))
.ThenInclude(tr => tr.Resource)
.FirstOrDefaultAsync(c => c.Id == req.Id, ct);
if (course is null)
{
await SendNotFoundAsync(ct);
return;
}
await SendOkAsync(mapper.Map<GetCourseDetailsDto>(course), ct);
}
}
@@ -0,0 +1,47 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class GetCoursesRequest
{
public string? Search { get; set; }
}
public class GetCoursesEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetCoursesRequest, List<GetCourseDto>>
{
public override void Configure()
{
Get("api/courses");
AllowAnonymous();
Summary(s =>
{
s.Summary = "Liste les cours publiés";
s.Description = "Retourne tous les cours avec le statut Publié, avec recherche optionnelle.";
});
}
public override async Task HandleAsync(GetCoursesRequest req, CancellationToken ct)
{
var query = db.Courses
.AsNoTracking()
.Include(c => c.Creator)
.Include(c => c.Topics)
.Where(c => c.Status == Entities.CourseStatus.Published);
if (!string.IsNullOrWhiteSpace(req.Search))
{
var search = req.Search.ToLower();
query = query.Where(c =>
c.Title.ToLower().Contains(search) ||
c.Description.ToLower().Contains(search) ||
c.Creator.Name.ToLower().Contains(search));
}
var courses = await query.OrderByDescending(c => c.CreatedAt).ToListAsync(ct);
await SendOkAsync(mapper.Map<List<GetCourseDto>>(courses), ct);
}
}
@@ -0,0 +1,35 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class GetUserCoursesRequest
{
public Guid UserId { get; set; }
}
public class GetUserCoursesEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetUserCoursesRequest, List<GetCourseDto>>
{
public override void Configure()
{
Get("api/users/{userId}/courses");
AllowAnonymous();
Summary(s => s.Summary = "Liste les cours créés par un utilisateur");
}
public override async Task HandleAsync(GetUserCoursesRequest req, CancellationToken ct)
{
var courses = await db.Courses
.AsNoTracking()
.Include(c => c.Creator)
.Include(c => c.Topics)
.Where(c => c.CreatorId == req.UserId)
.OrderByDescending(c => c.UpdatedAt)
.ToListAsync(ct);
await SendOkAsync(mapper.Map<List<GetCourseDto>>(courses), ct);
}
}
@@ -0,0 +1,60 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class PublishCourseRequest
{
public Guid Id { get; set; }
}
public class PublishCourseEndpoint(AppDbContext db) : Endpoint<PublishCourseRequest, GetCourseDto>
{
public override void Configure()
{
Patch("api/courses/{id}/publish");
AllowAnonymous();
Summary(s => s.Summary = "Publie un cours (le rend visible dans le catalogue)");
}
public override async Task HandleAsync(PublishCourseRequest req, CancellationToken ct)
{
var course = await db.Courses
.Include(c => c.Creator)
.Include(c => c.Topics)
.FirstOrDefaultAsync(c => c.Id == req.Id, ct);
if (course is null)
{
await SendNotFoundAsync(ct);
return;
}
if (!course.Topics.Any())
{
AddError("Un cours doit avoir au moins un sujet pour être publié.");
await SendErrorsAsync(422, ct);
return;
}
course.Status = CourseStatus.Published;
course.UpdatedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
await SendOkAsync(new GetCourseDto
{
Id = course.Id,
Title = course.Title,
Description = course.Description,
Status = course.Status.ToString(),
CreatorId = course.CreatorId,
CreatorName = course.Creator.Name,
TopicCount = course.Topics.Count,
CreatedAt = course.CreatedAt,
UpdatedAt = course.UpdatedAt
}, ct);
}
}
@@ -0,0 +1,37 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Courses;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Courses;
public class UpdateCourseEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<UpdateCourseDto, GetCourseDto>
{
public override void Configure()
{
Put("api/courses/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Met à jour le titre et la description d'un cours");
}
public override async Task HandleAsync(UpdateCourseDto req, CancellationToken ct)
{
var course = await db.Courses
.Include(c => c.Creator)
.Include(c => c.Topics)
.FirstOrDefaultAsync(c => c.Id == req.Id, ct);
if (course is null)
{
await SendNotFoundAsync(ct);
return;
}
mapper.Map(req, course);
course.UpdatedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
await SendOkAsync(mapper.Map<GetCourseDto>(course), ct);
}
}
@@ -0,0 +1,66 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Progress;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Progress;
public class GetCourseProgressRequest
{
public Guid CourseId { get; set; }
public Guid UserId { get; set; }
}
public class GetCourseProgressEndpoint(AppDbContext db) : Endpoint<GetCourseProgressRequest, CourseProgressDto>
{
public override void Configure()
{
Get("api/courses/{courseId}/progress");
AllowAnonymous();
Summary(s => s.Summary = "Retourne la progression d'un utilisateur dans un cours");
}
public override async Task HandleAsync(GetCourseProgressRequest req, CancellationToken ct)
{
var course = await db.Courses
.AsNoTracking()
.Include(c => c.Topics)
.ThenInclude(t => t.TopicResources)
.FirstOrDefaultAsync(c => c.Id == req.CourseId, ct);
if (course is null)
{
await SendNotFoundAsync(ct);
return;
}
var topicIds = course.Topics.Select(t => t.Id).ToList();
var resourceIds = course.Topics
.SelectMany(t => t.TopicResources.Select(tr => tr.ResourceId))
.Distinct()
.ToList();
var completedTopics = await db.UserTopicProgresses
.CountAsync(p => p.UserId == req.UserId && topicIds.Contains(p.TopicId) && p.Completed, ct);
var completedResources = await db.UserResourceProgresses
.CountAsync(p => p.UserId == req.UserId && resourceIds.Contains(p.ResourceId) && p.Completed, ct);
var totalTopics = topicIds.Count;
var totalResources = resourceIds.Count;
var percentage = totalTopics == 0 ? 0 :
Math.Round((completedTopics + completedResources) / (double)(totalTopics + totalResources) * 100, 1);
await SendOkAsync(new CourseProgressDto
{
CourseId = req.CourseId,
UserId = req.UserId,
TotalTopics = totalTopics,
CompletedTopics = completedTopics,
TotalResources = totalResources,
CompletedResources = completedResources,
ProgressPercentage = percentage
}, ct);
}
}
@@ -0,0 +1,42 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Progress;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Progress;
public class MarkResourceProgressEndpoint(AppDbContext db) : Endpoint<MarkResourceProgressDto>
{
public override void Configure()
{
Post("api/resources/{resourceId}/progress");
AllowAnonymous();
Summary(s => s.Summary = "Marque une ressource comme terminée ou non terminée pour un utilisateur");
}
public override async Task HandleAsync(MarkResourceProgressDto req, CancellationToken ct)
{
var progress = await db.UserResourceProgresses
.FirstOrDefaultAsync(p => p.UserId == req.UserId && p.ResourceId == req.ResourceId, ct);
if (progress is null)
{
db.UserResourceProgresses.Add(new UserResourceProgress
{
UserId = req.UserId,
ResourceId = req.ResourceId,
Completed = req.Completed,
CompletedAt = req.Completed ? DateTime.UtcNow : null
});
}
else
{
progress.Completed = req.Completed;
progress.CompletedAt = req.Completed ? DateTime.UtcNow : null;
}
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,42 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Progress;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Progress;
public class MarkTopicProgressEndpoint(AppDbContext db) : Endpoint<MarkTopicProgressDto>
{
public override void Configure()
{
Post("api/topics/{topicId}/progress");
AllowAnonymous();
Summary(s => s.Summary = "Marque un sujet comme terminé ou non terminé pour un utilisateur");
}
public override async Task HandleAsync(MarkTopicProgressDto req, CancellationToken ct)
{
var progress = await db.UserTopicProgresses
.FirstOrDefaultAsync(p => p.UserId == req.UserId && p.TopicId == req.TopicId, ct);
if (progress is null)
{
db.UserTopicProgresses.Add(new UserTopicProgress
{
UserId = req.UserId,
TopicId = req.TopicId,
Completed = req.Completed,
CompletedAt = req.Completed ? DateTime.UtcNow : null
});
}
else
{
progress.Completed = req.Completed;
progress.CompletedAt = req.Completed ? DateTime.UtcNow : null;
}
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,25 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Resources;
using MetaCourse.Api.Entities;
namespace MetaCourse.Api.Endpoints.Resources;
public class CreateResourceEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<CreateResourceDto, GetResourceDto>
{
public override void Configure()
{
Post("api/resources");
AllowAnonymous();
Summary(s => s.Summary = "Crée une nouvelle ressource dans le catalogue");
}
public override async Task HandleAsync(CreateResourceDto req, CancellationToken ct)
{
var resource = mapper.Map<Resource>(req);
db.Resources.Add(resource);
await db.SaveChangesAsync(ct);
await SendAsync(mapper.Map<GetResourceDto>(resource), 201, ct);
}
}
@@ -0,0 +1,34 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Resources;
public class DeleteResourceRequest
{
public Guid Id { get; set; }
}
public class DeleteResourceEndpoint(AppDbContext db) : Endpoint<DeleteResourceRequest>
{
public override void Configure()
{
Delete("api/resources/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Supprime une ressource (et ses associations aux sujets)");
}
public override async Task HandleAsync(DeleteResourceRequest req, CancellationToken ct)
{
var resource = await db.Resources.FirstOrDefaultAsync(r => r.Id == req.Id, ct);
if (resource is null)
{
await SendNotFoundAsync(ct);
return;
}
db.Resources.Remove(resource);
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,33 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Resources;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Resources;
public class GetResourceRequest
{
public Guid Id { get; set; }
}
public class GetResourceEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetResourceRequest, GetResourceDto>
{
public override void Configure()
{
Get("api/resources/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Récupère une ressource par son identifiant");
}
public override async Task HandleAsync(GetResourceRequest req, CancellationToken ct)
{
var resource = await db.Resources.AsNoTracking().FirstOrDefaultAsync(r => r.Id == req.Id, ct);
if (resource is null)
{
await SendNotFoundAsync(ct);
return;
}
await SendOkAsync(mapper.Map<GetResourceDto>(resource), ct);
}
}
@@ -0,0 +1,27 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Resources;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Resources;
public class GetResourcesEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : EndpointWithoutRequest<List<GetResourceDto>>
{
public override void Configure()
{
Get("api/resources");
AllowAnonymous();
Summary(s => s.Summary = "Liste toutes les ressources du catalogue");
}
public override async Task HandleAsync(CancellationToken ct)
{
var resources = await db.Resources
.AsNoTracking()
.OrderByDescending(r => r.CreatedAt)
.ToListAsync(ct);
await SendOkAsync(mapper.Map<List<GetResourceDto>>(resources), ct);
}
}
@@ -0,0 +1,31 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Resources;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Resources;
public class UpdateResourceEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<UpdateResourceDto, GetResourceDto>
{
public override void Configure()
{
Put("api/resources/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Met à jour une ressource");
}
public override async Task HandleAsync(UpdateResourceDto req, CancellationToken ct)
{
var resource = await db.Resources.FirstOrDefaultAsync(r => r.Id == req.Id, ct);
if (resource is null)
{
await SendNotFoundAsync(ct);
return;
}
mapper.Map(req, resource);
await db.SaveChangesAsync(ct);
await SendOkAsync(mapper.Map<GetResourceDto>(resource), ct);
}
}
@@ -0,0 +1,35 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Topics;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class CreateTopicEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<CreateTopicDto, GetTopicDto>
{
public override void Configure()
{
Post("api/topics");
AllowAnonymous();
Summary(s => s.Summary = "Ajoute un sujet à un cours");
}
public override async Task HandleAsync(CreateTopicDto req, CancellationToken ct)
{
var courseExists = await db.Courses.AnyAsync(c => c.Id == req.CourseId, ct);
if (!courseExists)
{
AddError(r => r.CourseId, "Le cours n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
var topic = mapper.Map<Topic>(req);
db.Topics.Add(topic);
await db.SaveChangesAsync(ct);
await SendAsync(mapper.Map<GetTopicDto>(topic), 201, ct);
}
}
@@ -0,0 +1,34 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class DeleteTopicRequest
{
public Guid Id { get; set; }
}
public class DeleteTopicEndpoint(AppDbContext db) : Endpoint<DeleteTopicRequest>
{
public override void Configure()
{
Delete("api/topics/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Supprime un sujet et ses associations de ressources");
}
public override async Task HandleAsync(DeleteTopicRequest req, CancellationToken ct)
{
var topic = await db.Topics.FirstOrDefaultAsync(t => t.Id == req.Id, ct);
if (topic is null)
{
await SendNotFoundAsync(ct);
return;
}
db.Topics.Remove(topic);
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,39 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Topics;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class GetTopicRequest
{
public Guid Id { get; set; }
}
public class GetTopicEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetTopicRequest, GetTopicDto>
{
public override void Configure()
{
Get("api/topics/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Récupère un sujet avec ses ressources");
}
public override async Task HandleAsync(GetTopicRequest req, CancellationToken ct)
{
var topic = await db.Topics
.AsNoTracking()
.Include(t => t.TopicResources.OrderBy(tr => tr.Position))
.ThenInclude(tr => tr.Resource)
.FirstOrDefaultAsync(t => t.Id == req.Id, ct);
if (topic is null)
{
await SendNotFoundAsync(ct);
return;
}
await SendOkAsync(mapper.Map<GetTopicDto>(topic), ct);
}
}
@@ -0,0 +1,61 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class LinkResourceRequest
{
public Guid TopicId { get; set; }
public Guid ResourceId { get; set; }
public int Position { get; set; } = 1;
}
public class LinkResourceToTopicEndpoint(AppDbContext db) : Endpoint<LinkResourceRequest>
{
public override void Configure()
{
Post("api/topics/{topicId}/resources/{resourceId}");
AllowAnonymous();
Summary(s => s.Summary = "Associe une ressource à un sujet");
}
public override async Task HandleAsync(LinkResourceRequest req, CancellationToken ct)
{
var topicExists = await db.Topics.AnyAsync(t => t.Id == req.TopicId, ct);
if (!topicExists)
{
AddError("Le sujet n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
var resourceExists = await db.Resources.AnyAsync(r => r.Id == req.ResourceId, ct);
if (!resourceExists)
{
AddError("La ressource n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
var alreadyLinked = await db.TopicResources
.AnyAsync(tr => tr.TopicId == req.TopicId && tr.ResourceId == req.ResourceId, ct);
if (alreadyLinked)
{
AddError("Cette ressource est déjà associée à ce sujet.");
await SendErrorsAsync(409, ct);
return;
}
db.TopicResources.Add(new TopicResource
{
TopicId = req.TopicId,
ResourceId = req.ResourceId,
Position = req.Position
});
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,37 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class UnlinkResourceRequest
{
public Guid TopicId { get; set; }
public Guid ResourceId { get; set; }
}
public class UnlinkResourceFromTopicEndpoint(AppDbContext db) : Endpoint<UnlinkResourceRequest>
{
public override void Configure()
{
Delete("api/topics/{topicId}/resources/{resourceId}");
AllowAnonymous();
Summary(s => s.Summary = "Dissocie une ressource d'un sujet");
}
public override async Task HandleAsync(UnlinkResourceRequest req, CancellationToken ct)
{
var link = await db.TopicResources
.FirstOrDefaultAsync(tr => tr.TopicId == req.TopicId && tr.ResourceId == req.ResourceId, ct);
if (link is null)
{
await SendNotFoundAsync(ct);
return;
}
db.TopicResources.Remove(link);
await db.SaveChangesAsync(ct);
await SendNoContentAsync(ct);
}
}
@@ -0,0 +1,36 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Topics;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Topics;
public class UpdateTopicEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<UpdateTopicDto, GetTopicDto>
{
public override void Configure()
{
Put("api/topics/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Met à jour un sujet");
}
public override async Task HandleAsync(UpdateTopicDto req, CancellationToken ct)
{
var topic = await db.Topics
.Include(t => t.TopicResources)
.ThenInclude(tr => tr.Resource)
.FirstOrDefaultAsync(t => t.Id == req.Id, ct);
if (topic is null)
{
await SendNotFoundAsync(ct);
return;
}
mapper.Map(req, topic);
await db.SaveChangesAsync(ct);
await SendOkAsync(mapper.Map<GetTopicDto>(topic), ct);
}
}
@@ -0,0 +1,68 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.UserCourses;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.UserCourses;
public class EnrollEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<EnrollDto, GetEnrollmentDto>
{
public override void Configure()
{
Post("api/courses/{courseId}/enroll");
AllowAnonymous();
Summary(s => s.Summary = "Inscrit un utilisateur à un cours publié");
}
public override async Task HandleAsync(EnrollDto req, CancellationToken ct)
{
var course = await db.Courses.FirstOrDefaultAsync(c => c.Id == req.CourseId, ct);
if (course is null)
{
AddError("Le cours n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
if (course.Status != CourseStatus.Published)
{
AddError("Impossible de s'inscrire à un cours non publié.");
await SendErrorsAsync(422, ct);
return;
}
var userExists = await db.Users.AnyAsync(u => u.Id == req.UserId, ct);
if (!userExists)
{
AddError("L'utilisateur n'existe pas.");
await SendErrorsAsync(404, ct);
return;
}
var alreadyEnrolled = await db.UserCourses
.AnyAsync(uc => uc.UserId == req.UserId && uc.CourseId == req.CourseId, ct);
if (alreadyEnrolled)
{
AddError("L'utilisateur est déjà inscrit à ce cours.");
await SendErrorsAsync(409, ct);
return;
}
var enrollment = new UserCourse
{
UserId = req.UserId,
CourseId = req.CourseId
};
db.UserCourses.Add(enrollment);
await db.SaveChangesAsync(ct);
var result = await db.UserCourses
.Include(uc => uc.Course)
.FirstAsync(uc => uc.UserId == req.UserId && uc.CourseId == req.CourseId, ct);
await SendAsync(mapper.Map<GetEnrollmentDto>(result), 201, ct);
}
}
@@ -0,0 +1,35 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.UserCourses;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.UserCourses;
public class GetUserEnrollmentsRequest
{
public Guid UserId { get; set; }
}
public class GetUserEnrollmentsEndpoint(AppDbContext db, AutoMapper.IMapper mapper)
: Endpoint<GetUserEnrollmentsRequest, List<GetEnrollmentDto>>
{
public override void Configure()
{
Get("api/users/{userId}/enrollments");
AllowAnonymous();
Summary(s => s.Summary = "Liste les cours auxquels un utilisateur est inscrit");
}
public override async Task HandleAsync(GetUserEnrollmentsRequest req, CancellationToken ct)
{
var enrollments = await db.UserCourses
.AsNoTracking()
.Include(uc => uc.Course)
.Where(uc => uc.UserId == req.UserId)
.OrderByDescending(uc => uc.EnrolledAt)
.ToListAsync(ct);
await SendOkAsync(mapper.Map<List<GetEnrollmentDto>>(enrollments), ct);
}
}
@@ -0,0 +1,33 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Users;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Users;
public class GetUserRequest
{
public Guid Id { get; set; }
}
public class GetUserEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetUserRequest, GetUserDto>
{
public override void Configure()
{
Get("api/users/{id}");
AllowAnonymous();
Summary(s => s.Summary = "Récupère le profil d'un utilisateur");
}
public override async Task HandleAsync(GetUserRequest req, CancellationToken ct)
{
var user = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == req.Id, ct);
if (user is null)
{
await SendNotFoundAsync(ct);
return;
}
await SendOkAsync(mapper.Map<GetUserDto>(user), ct);
}
}
@@ -0,0 +1,39 @@
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Users;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Users;
public class LoginEndpoint(AppDbContext db) : Endpoint<LoginUserDto, LoginResponseDto>
{
public override void Configure()
{
Post("api/users/login");
AllowAnonymous();
Summary(s =>
{
s.Summary = "Connexion d'un utilisateur";
s.Description = "Authentifie l'utilisateur avec email et mot de passe.";
});
}
public override async Task HandleAsync(LoginUserDto req, CancellationToken ct)
{
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == req.Email, ct);
if (user is null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
{
AddError("Email ou mot de passe incorrect.");
await SendErrorsAsync(401, ct);
return;
}
await SendOkAsync(new LoginResponseDto
{
UserId = user.Id,
Name = user.Name,
Email = user.Email
}, ct);
}
}
@@ -0,0 +1,41 @@
using AutoMapper;
using FastEndpoints;
using MetaCourse.Api.Data;
using MetaCourse.Api.DTOs.Users;
using MetaCourse.Api.Entities;
using Microsoft.EntityFrameworkCore;
namespace MetaCourse.Api.Endpoints.Users;
public class RegisterEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint<RegisterUserDto, GetUserDto>
{
public override void Configure()
{
Post("api/users/register");
AllowAnonymous();
Summary(s =>
{
s.Summary = "Inscription d'un nouvel utilisateur";
s.Description = "Crée un compte utilisateur avec email unique et mot de passe haché.";
});
}
public override async Task HandleAsync(RegisterUserDto req, CancellationToken ct)
{
var emailExists = await db.Users.AnyAsync(u => u.Email == req.Email, ct);
if (emailExists)
{
AddError(r => r.Email, "Cet email est déjà utilisé.");
await SendErrorsAsync(409, ct);
return;
}
var user = mapper.Map<User>(req);
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(req.Password);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
await SendAsync(mapper.Map<GetUserDto>(user), 201, ct);
}
}