You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OptifitWebService/Server/Services/FormationServices.cs

79 lines
3.1 KiB

using Infrastructure;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
using Server.Mappers;
namespace Server.Services;
public class FormationServices(AlumniDbContext context) : IFormationsService
{
public Task<ResponseFormationDto?> GetFormationById(string id)
{
var result = context.Formations.FirstOrDefault(form => form.Id == id);
return Task.FromResult(result?.ToDto());
}
public Task<(long Count, IEnumerable<ResponseFormationDto> Formations)> GetFormations(string? name, int page, int size,
FormationOrderCriteria orderCriteria = FormationOrderCriteria.EndDate, bool ascending = true)
{
var query = context.Formations.Skip((page-1) * size).Take(size);
if (name != null)
{
query = context.Formations.Where(e => e.Name.Contains(name)).Skip((page-1) * size).Take(size);
}
switch (orderCriteria)
{
case FormationOrderCriteria.StartDate:
query = ascending ? query.OrderBy(e => e.StartDate) : query.OrderByDescending(e => e.StartDate);
break;
case FormationOrderCriteria.EndDate:
query = ascending ? query.OrderBy(e => e.EndDate) : query.OrderByDescending(e => e.EndDate);
break;
case FormationOrderCriteria.Name:
query = ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
break;
case FormationOrderCriteria.SchoolName:
query = ascending ? query.OrderBy(e => e.SchoolName) : query.OrderByDescending(e => e.SchoolName);
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDto())));
}
public Task<ResponseFormationDto?> CreateFormation(RequestFormationDto formation)
{
var result = context.Formations.AddAsync(formation.ToEntity());
var alica = context.Alumni.FirstOrDefault(a => a.Id == formation.AlumniId);
alica?.Formations.Add(result.Result.Entity);
context.SaveChangesAsync();
return Task.FromResult(result.Result.Entity.ToDto());
}
public Task<ResponseFormationDto?> UpdateFormation(string id, RequestFormationDto formation)
{
var result = context.Formations.FirstOrDefault(e => e.Id == id);
if (result == null)
{
return Task.FromResult<ResponseFormationDto?>(null);
}
result.SchoolName = formation.SchoolName;
result.Name = formation.Name;
result.StartDate = formation.StartingDate;
result.EndDate = formation.EndingDate;
result.IsCurrent = formation.CurrentFormation;
context.SaveChangesAsync();
return Task.FromResult(result.ToDto());
}
public Task<bool> DeleteFormation(string id)
{
var result = context.Formations.FirstOrDefault(form => form.Id == id);
if (result == null) return Task.FromResult(false);
context.Formations.Remove(result);
context.SaveChangesAsync();
return Task.FromResult(true);
}
}