Yanaël GRETTE 4 years ago
commit ea59807f4c
  1. 340
      EPAServeur.Tests/Controllers/EngagementsApiTests.cs
  2. 526
      EPAServeur.Tests/Controllers/FormationApiTests.cs
  3. 5
      EPAServeur.Tests/EPAServeur.Tests.csproj
  4. 7
      EPAServeur.Tests/Properties/launchSettings.json
  5. 637
      EPAServeur.Tests/Services/EngagementServiceTests.cs
  6. 922
      EPAServeur.Tests/Services/FormationServiceTests.cs
  7. 19
      EPAServeur/Attributes/CannotBeEmptyAttribute.cs
  8. 791
      EPAServeur/Context/DataSeeder.cs
  9. 1
      EPAServeur/Context/EpContext.cs
  10. 208
      EPAServeur/Controllers/EngagementsApi.cs
  11. 591
      EPAServeur/Controllers/FormationsApi.cs
  12. 16
      EPAServeur/DTO/FormationDetailsDTO.cs
  13. 2
      EPAServeur/EPAServeur.csproj
  14. 2
      EPAServeur/Enum/StatutEp.cs
  15. 8
      EPAServeur/Exceptions/EngagementIncompatibleIdException.cs
  16. 8
      EPAServeur/Exceptions/EngagementInvalidException.cs
  17. 2
      EPAServeur/Exceptions/EngagementNotFoundException.cs
  18. 2
      EPAServeur/Exceptions/FormationIncompatibleIdException.cs
  19. 8
      EPAServeur/Exceptions/FormationInvalidException.cs
  20. 2
      EPAServeur/Exceptions/FormationNotFoundException.cs
  21. 2
      EPAServeur/Exceptions/ModeFormationNotFoundException.cs
  22. 2
      EPAServeur/Exceptions/OrigineFormationNotFoundException.cs
  23. 2
      EPAServeur/Exceptions/StatutFormationNotFoundException.cs
  24. 2
      EPAServeur/Exceptions/TypeFormationNotFoundException.cs
  25. 15
      EPAServeur/IServices/IEngagementService.cs
  26. 24
      EPAServeur/IServices/IFormationService.cs
  27. 5
      EPAServeur/Models/Formation/Formation.cs
  28. 512
      EPAServeur/Services/EngagementService.cs
  29. 990
      EPAServeur/Services/FormationService.cs
  30. 3
      EPAServeur/Startup.cs

@ -0,0 +1,340 @@
using EPAServeur.Context;
using EPAServeur.Exceptions;
using EPAServeur.Models.Formation;
using EPAServeur.Services;
using IO.Swagger.Controllers;
using IO.Swagger.DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using EPAServeur.IServices;
using Moq;
using IO.Swagger.ApiCollaborateur;
using IO.Swagger.Enum;
namespace EPAServeur.Tests.Controllers
{
[TestFixture]
public class EngagementsApiTests
{
#region Variables
private IEngagementService engagementService;
private Mock<IWebHostEnvironment> mockEnvironment;
private EpContext epContext;
#endregion
#region Setup
[SetUp]
public void Setup()
{
// Création d'une collection de services pour l'injection de dépendance
var services = new ServiceCollection();
// Utilisation d'une base de données en mémoire
var optionBuider = new DbContextOptionsBuilder<EpContext>()
.UseInMemoryDatabase("server_ep_test")
.Options;
services.AddDbContext<EpContext>(b => b.UseInMemoryDatabase("server_ep_test"));
epContext = new EpContext(optionBuider);
epContext.Database.EnsureDeleted();
epContext.Database.EnsureCreated();
epContext.SaveChanges();
// Ajout du jeu de données pour les tests
DataSeeder.AddEngagements(epContext);
// Détache les entités du context car la base de données InMemory créé des conflits
// entre les clés primaires lors d'un Update ou d'un Insert
foreach (var entity in epContext.ChangeTracker.Entries())
{
entity.State = EntityState.Detached;
}
services.AddScoped<ICollaborateurApi, CollaborateurApi>();
services.AddScoped<ICollaborateurService, CollaborateurService>();
services.AddScoped<IEngagementService, EngagementService>();
// Récupère le service qui sera utilsé pour tester le contrôleur
var serviceProvider = services.BuildServiceProvider();
engagementService = serviceProvider.GetService<IEngagementService>();
// Simule l'interface IWebHostEnvironment avec Moq
mockEnvironment = new Mock<IWebHostEnvironment>();
mockEnvironment
.Setup(m => m.EnvironmentName)
.Returns("Development");
}
#endregion
#region Tests GetEngagements
[Test]
public void GetEngagements_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult()
{
// Arrange
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
List<long> idBUs = new List<long> { 1, 2 };
// Act
var okResult = engagementsApiController.GetEngagements(idBUs, null, true, 1, 5, null, null);
// Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
[Test]
public void GetEngagements_PasseDesParamsPresentsDansLaBDD_RetourneLesCinqPremiersEngagements()
{
// Arrange
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
List<long> idBUs = new List<long> { 1, 2 };
int nbEngagement = 5;
int idFirstEngagement = 2;
int idLastEngagement = 10;
// Act
var okResult = engagementsApiController.GetEngagements(idBUs, null, true, 1, 5, null, null).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<EngagementDTO>>(okResult.Value);
Assert.AreEqual(nbEngagement, (okResult.Value as IEnumerable<EngagementDTO>).Count());
Assert.AreEqual(idFirstEngagement, (okResult.Value as IEnumerable<EngagementDTO>).First().Id);
Assert.AreEqual(idLastEngagement, (okResult.Value as IEnumerable<EngagementDTO>).Last().Id);
}
#endregion
#region Tests GetEngagementsCount
[Test]
public void GetEngagementsCount_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult()
{
// Arrange
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
List<long> idBUs = new List<long> { 1, 2 };
// Act
var okResult = engagementsApiController.GetEngagementsCount(idBUs, null, true, 1, 5, null, null);
// Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
[Test]
public void GetEngagementsCount_PasseDesParamsPresentsDansLaBDD_RetourneLeBonNombreDEngagement()
{
// Arrange
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
List<long> idBUs = new List<long> { 1, 2 };
int nbEngagement = 5;
// Act
var okResult = engagementsApiController.GetEngagementsCount(idBUs, null, true, 1, 5, null, null).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<long>(okResult.Value);
Assert.AreEqual(nbEngagement, (long)okResult.Value);
}
#endregion
#region Tests UpdateEngagement
[Test]
public void UpdateEngagement_ModifieUnEngagementAvecUnEPInvalide_RetourneUnObjetObjectResultDansCatchEngagementInvalidException()
{
// Arrange
long idEngagement = 1;
EtatEngagement reponse = EtatEngagement.Respecte;
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
EpInformationDTO epInformationDTO = null;
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = reponse,
Ep = epInformationDTO
};
// Act
var objectResult = engagementsApiController.UpdateEngagement(engagementDTO, idEngagement);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public void UpdateEngagement_ModifieUnEngagementAvecUnIdEngagementInvalide_RetourneUnObjetObjectResultDansCatchEngagementIncompatibleIdException()
{
// Arrange
long idEngagement = 1;
long idEngagementIncorrecte = 2;
long idEp = 9;
EtatEngagement reponse = EtatEngagement.Respecte;
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagementIncorrecte,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = reponse,
Ep = epInformationDTO
};
// Act
var objectResult = engagementsApiController.UpdateEngagement(engagementDTO, idEngagement);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public void UpdateEngagement_ModifieUnEngagementInexistant_RetourneUnObjetObjectResultDansCatchEngagementNotFoundExceptionn()
{
// Arrange
long idEngagementInexistant = 999;
long idEp = 9;
EtatEngagement reponse = EtatEngagement.Respecte;
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagementInexistant,
Action = "Toto.",
Dispositif = "Tata.",
Modalite = "Titi",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = reponse,
Ep = epInformationDTO
};
// Act
var objectResult = engagementsApiController.UpdateEngagement(engagementDTO, idEngagementInexistant);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public void UpdateEngagement_ModifieUnEngagementValide_RetourneUnObjetOkObjectResult()
{
// Arrange
long idEngagement = 1;
long idEp = 9;
EtatEngagement reponse = EtatEngagement.Respecte;
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = reponse,
Ep = epInformationDTO
};
// Act
var okObjectResult = engagementsApiController.UpdateEngagement(engagementDTO, idEngagement);
// Assert
Assert.IsInstanceOf<OkObjectResult>(okObjectResult.Result);
}
[Test]
public void UpdateEngagement_ModifieUnEngagementValide_RetourneLEngagementModifie()
{
// Arrange
long idEngagement = 1;
long idEp = 9;
EtatEngagement reponse = EtatEngagement.Respecte;
EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger<EngagementsApiController>(), mockEnvironment.Object);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = reponse,
Ep = epInformationDTO
};
// Act
var okObjectResult = engagementsApiController.UpdateEngagement(engagementDTO, idEngagement).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<EngagementDTO>(okObjectResult.Value);
Assert.AreEqual(reponse, (okObjectResult.Value as EngagementDTO).EtatEngagement);
}
#endregion
}
}

@ -13,6 +13,12 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using EPAServeur.IServices;
using Moq;
using IO.Swagger.ApiCollaborateur;
namespace EPAServeur.Tests.Controllers namespace EPAServeur.Tests.Controllers
{ {
@ -21,9 +27,9 @@ namespace EPAServeur.Tests.Controllers
{ {
#region Variables #region Variables
private FormationService formationService; private IFormationService formationService;
private readonly ILogger<FormationsApiController> logger; private Mock<IWebHostEnvironment> mockEnvironment;
private EpContext epContext;
#endregion #endregion
#region Setup #region Setup
@ -31,12 +37,17 @@ namespace EPAServeur.Tests.Controllers
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
// Création d'une collection de services pour l'injection de dépendance
var services = new ServiceCollection();
// Utilisation d'une base de données en mémoire // Utilisation d'une base de données en mémoire
var optionBuider = new DbContextOptionsBuilder<EpContext>() var optionBuider = new DbContextOptionsBuilder<EpContext>()
.UseInMemoryDatabase("server_ep_test") .UseInMemoryDatabase("server_ep_test")
.Options; .Options;
EpContext epContext = new EpContext(optionBuider); services.AddDbContext<EpContext>(b => b.UseInMemoryDatabase("server_ep_test"));
epContext = new EpContext(optionBuider);
epContext.Database.EnsureDeleted(); epContext.Database.EnsureDeleted();
epContext.Database.EnsureCreated(); epContext.Database.EnsureCreated();
@ -52,8 +63,21 @@ namespace EPAServeur.Tests.Controllers
entity.State = EntityState.Detached; entity.State = EntityState.Detached;
} }
// Instanciation du service qui sera utilisé dans le controleur services.AddScoped<ICollaborateurApi, CollaborateurApi>();
formationService = new FormationService(epContext); services.AddScoped<ICollaborateurService, CollaborateurService>();
services.AddScoped<IFormationService, FormationService>();
// Récupère le service qui sera utilsé pour tester le contrôleur
var serviceProvider = services.BuildServiceProvider();
formationService = serviceProvider.GetService<IFormationService>();
// Simule l'interface IWebHostEnvironment avec Moq
mockEnvironment = new Mock<IWebHostEnvironment>();
mockEnvironment
.Setup(m => m.EnvironmentName)
.Returns("Development");
} }
#endregion #endregion
@ -61,127 +85,521 @@ namespace EPAServeur.Tests.Controllers
#region Tests GetFormationById #region Tests GetFormationById
[Test] [Test]
public void GetFormationById_PasseEnParamUnIdPresentDansLaBDD_RetourneUnObjetOkResult() public void GetById_PasseEnParamUnIdInconnu_RetourneUnObjetNotFoundResult()
{ {
//// Arrange // Arrange
//FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>()); FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// // Act // Act
// var okResult = formationsApiController.GetFormationById(1); var notFoundResult = formationsApiController.GetFormationById(99999);
//// Assert // Assert
//Assert.IsInstanceOf<OkObjectResult>(okResult.Result); Assert.IsInstanceOf<NotFoundObjectResult>(notFoundResult.Result);
} }
[Test]
public void GetFormationById_PasseEnParamUnIdConnu_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
#endregion // Act
var okResult = formationsApiController.GetFormationById(1);
#region Tests GetFormations // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
// Arrange
// Act [Test]
public void GetFormationById_PasseEnParamUnIdConnu_RetourneLaBonneFormation()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
long idFormation = 1;
// Assert // Act
var okResult = formationsApiController.GetFormationById(idFormation).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<FormationDTO>(okResult.Value);
Assert.AreEqual(idFormation, (okResult.Value as FormationDTO).Id);
}
#endregion #endregion
#region Tests GetFormationAnnulees #region Tests GetFormations
// Arrange
// Act [Test]
public void GetFormations_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
List<int?> idStatuts = new List<int?> { 1, 2, 3 };
// Assert // Act
var okResult = formationsApiController.GetFormations(1, idStatuts, true, 1, 5, "formation", null, null, null);
#endregion // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
#region Tests GetFormationRealisee [Test]
public void GetFormations_PasseDesParamsPresentsDansLaBDD_RetourneLesCinqPremieresFormations()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
List<int?> idStatuts = new List<int?> { 1, 2, 3 };
int nbFormation = 5;
int idFirstFormation = 5;
int idLastFormation = 1;
// Act
var okResult = formationsApiController.GetFormations(1, idStatuts, true, 1, 5, "formation", null, null, null).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<FormationDetailsDTO>>(okResult.Value);
Assert.AreEqual(nbFormation, (okResult.Value as IEnumerable<FormationDetailsDTO>).Count());
Assert.AreEqual(idFirstFormation, (okResult.Value as IEnumerable<FormationDetailsDTO>).First().Id);
Assert.AreEqual(idLastFormation, (okResult.Value as IEnumerable<FormationDetailsDTO>).Last().Id);
}
// Arrange #endregion
// Act #region Tests GetFormationsCount
// Assert [Test]
public void GetFormationsCount_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
List<int?> idStatuts = new List<int?> { 1, 2, 3 };
#endregion // Act
var okResult = formationsApiController.GetFormationsCount(1, idStatuts, 1, 5, "formation", null, null);
#region Tests GetProchainesFormation // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
// Arrange [Test]
public void GetFormationsCount_PasseDesParamsPresentsDansLaBDD_RetourneLeBonNombreDeFormation()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
List<int?> idStatuts = new List<int?> { 1, 2, 3 };
int nbFormation = 5;
// Act // Act
var okResult = formationsApiController.GetFormationsCount(1, idStatuts, 1, 5, "formation", null, null).Result as OkObjectResult;
// Assert // Assert
Assert.IsInstanceOf<long>(okResult.Value);
Assert.AreEqual(nbFormation, (long)okResult.Value);
}
#endregion #endregion
#region Tests GetModesFormation #region Tests GetModesFormation
// Arrange
// Act [Test]
public void GetModesFormation_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// Act
var okResult = formationsApiController.GetModesFormation();
// Assert // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
[Test]
public void GetModesFormation_RetourneTousLesModes()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int nbModeFormation = 4;
// Act
var okResult = formationsApiController.GetModesFormation().Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<ModeFormationDTO>>(okResult.Value);
Assert.AreEqual(nbModeFormation, (okResult.Value as IEnumerable<ModeFormationDTO>).Count());
}
#endregion #endregion
#region Tests GetOriginesFormation #region Tests GetOriginesFormation
// Arrange [Test]
public void GetOriginesFormation_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// Act // Act
var okResult = formationsApiController.GetOriginesFormation();
// Assert // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
[Test]
public void GetOriginesFormation_RetourneToutesLesOrigines()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int nbOrigineFormation = 4;
// Act
var okResult = formationsApiController.GetOriginesFormation().Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<OrigineFormationDTO>>(okResult.Value);
Assert.AreEqual(nbOrigineFormation, (okResult.Value as IEnumerable<OrigineFormationDTO>).Count());
}
#endregion #endregion
#region Tests GetStatutsFormation #region Tests GetStatutsFormation
// Arrange [Test]
public void GetStatusFormation_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// Act
var okResult = formationsApiController.GetStatutsFormation();
// Act // Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
// Assert [Test]
public void GetStatutsFormation_RetourneTousLesStatuts()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int nbStatutFormation = 4;
// Act
var okResult = formationsApiController.GetStatutsFormation().Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<StatutFormationDTO>>(okResult.Value);
Assert.AreEqual(nbStatutFormation, (okResult.Value as IEnumerable<StatutFormationDTO>).Count());
}
#endregion #endregion
#region Tests GetTypesFormation #region Tests GetTypesFormation
// Arrange [Test]
public void GetTypesFormation_RetourneUnObjetOkResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// Act // Act
var okResult = formationsApiController.GetTypesFormation();
// Assert
Assert.IsInstanceOf<OkObjectResult>(okResult.Result);
}
// Assert [Test]
public void GetTypesFormation_RetourneTousLesTypes()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int nbTypeFormation = 4;
// Act
var okResult = formationsApiController.GetTypesFormation().Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<IEnumerable<TypeFormationDTO>>(okResult.Value);
Assert.AreEqual(nbTypeFormation, (okResult.Value as IEnumerable<TypeFormationDTO>).Count());
}
#endregion #endregion
#region Tests AddFormation #region Tests AddFormation
// Arrange [Test]
public void AddFormation_AjouteUneFormationAvecDesObjetsEnfantsInvalides_RetourneUnObjetObjectResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
ModeFormationDTO modeExterne = new ModeFormationDTO { Id = 0, Libelle = "Externe" };
StatutFormationDTO statutPlanifie = new StatutFormationDTO { Id = 1, Libelle = "Planifiée" };
TypeFormationDTO typeELearning = new TypeFormationDTO { Id = 3, Libelle = "E-learning" };
OrigineFormationDTO origineFormationCollaborateur = new OrigineFormationDTO { Id = 1, Libelle = "Demande collaborateur" };
FormationDTO formation = new FormationDTO
{
Intitule = "Test Formation",
IdAgence = 1,
DateDebut = new DateTime(2020, 10, 31),
DateFin = new DateTime(2020, 11, 02),
Heure = 2,
Jour = 1,
Mode = modeExterne,
Type = typeELearning,
Organisme = "Apside",
Origine = origineFormationCollaborateur,
Statut = statutPlanifie,
EstCertifiee = false
};
// Act
var objectResult = formationsApiController.AddFormation(formation);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public void AddFormation_AjouteUneFormationValide_RetourneUnObjetCreatedResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
ModeFormationDTO modeExterne = new ModeFormationDTO { Id = 1, Libelle = "Externe" };
StatutFormationDTO statutPlanifie = new StatutFormationDTO { Id = 1, Libelle = "Planifiée" };
TypeFormationDTO typeELearning = new TypeFormationDTO { Id = 3, Libelle = "E-learning" };
OrigineFormationDTO origineFormationCollaborateur = new OrigineFormationDTO { Id = 1, Libelle = "Demande collaborateur" };
FormationDTO formation = new FormationDTO
{
Intitule = "Test Formation",
IdAgence = 1,
DateDebut = new DateTime(2020, 10, 31),
DateFin = new DateTime(2020, 11, 02),
Heure = 2,
Jour = 1,
Mode = modeExterne,
Type = typeELearning,
Organisme = "Apside",
Origine = origineFormationCollaborateur,
Statut = statutPlanifie,
EstCertifiee = false
};
// Act
var createdResult = formationsApiController.AddFormation(formation);
// Assert
Assert.IsInstanceOf<CreatedResult>(createdResult.Result);
}
// Act [Test]
public void AddFormation_AjouteUneFormationValide_RetourneLaFormationCreee()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
// Assert ModeFormationDTO modeExterne = new ModeFormationDTO { Id = 1, Libelle = "Externe" };
StatutFormationDTO statutPlanifie = new StatutFormationDTO { Id = 1, Libelle = "Planifiée" };
TypeFormationDTO typeELearning = new TypeFormationDTO { Id = 3, Libelle = "E-learning" };
OrigineFormationDTO origineFormationCollaborateur = new OrigineFormationDTO { Id = 1, Libelle = "Demande collaborateur" };
FormationDTO formation = new FormationDTO
{
Intitule = "Test Formation",
IdAgence = 1,
DateDebut = new DateTime(2020, 10, 31),
DateFin = new DateTime(2020, 11, 02),
Heure = 2,
Jour = 1,
Mode = modeExterne,
Type = typeELearning,
Organisme = "Apside",
Origine = origineFormationCollaborateur,
Statut = statutPlanifie,
EstCertifiee = false
};
// Act
var createdResult = formationsApiController.AddFormation(formation).Result as CreatedResult;
// Assert
Assert.IsInstanceOf<FormationDTO>(createdResult.Value);
Assert.AreEqual("Test Formation", (createdResult.Value as FormationDTO).Intitule);
}
#endregion #endregion
#region Tests UpdateFormation #region Tests UpdateFormation
// Arrange [Test]
public async Task UpdateFormation_ModifieUneFormationAvecDesObjetsEnfantsInvalides_RetourneUnObjetObjectResultDansCatchFormationInvalidException()
{
// Arrange
long idFormation = 1;
string nouvelleIntitule = "Formation modifiée";
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation);
formation.Intitule = nouvelleIntitule;
formation.Mode.Id = 0;
formation.Statut.Id = 0;
// Act // Act
var objectResult = formationsApiController.UpdateFormation(formation, idFormation);
// Assert // Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public async Task UpdateFormation_ModifieUneFormationAvecDesObjetsEnfantsInvalides_RetourneUnObjetObjectResultDansCatchFormationIncompatibleIdException()
{
// Arrange
long idFormation = 1;
string nouvelleIntitule = "Formation modifiée";
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation);
idFormation = 2;
formation.Intitule = nouvelleIntitule;
// Act
var objectResult = formationsApiController.UpdateFormation(formation, idFormation);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public async Task UpdateFormation_ModifieUneFormatioInexistante_RetourneUnObjetObjectResultDansCatchFormationNotFoundExceptionn()
{
// Arrange
long idFormationExistant = 1;
long idFormationInexistant = 999;
string nouvelleIntitule = "Formation modifiée";
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
FormationDTO formation = await formationService.GetFormationByIdAsync(idFormationExistant);
formation.Id = idFormationInexistant;
formation.Intitule = nouvelleIntitule;
// Act
var objectResult = formationsApiController.UpdateFormation(formation, idFormationInexistant);
// Assert
Assert.IsInstanceOf<ObjectResult>(objectResult.Result);
}
[Test]
public async Task UpdateFormation_ModifieUneFormationValide_RetourneUnObjetOkObjectResult()
{
// Arrange
long idFormation = 1;
string nouvelleIntitule = "Formation modifiée";
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object); ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == 2)
.Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault();
StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == 2)
.Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault();
TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == 1)
.Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault();
OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == 1)
.Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault();
FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation);
formation.Intitule = nouvelleIntitule;
formation.Mode = modeExterne;
formation.Type = typeELearning;
formation.Origine = origineFormationCollaborateur;
formation.Statut = statutPlanifie;
// Act
var okObjectResult = formationsApiController.UpdateFormation(formation, idFormation);
// Assert
Assert.IsInstanceOf<OkObjectResult>(okObjectResult.Result);
}
[Test]
public async Task UpdateFormation_ModifieUneFormationValide_RetourneLaFormationModifiee()
{
// Arrange
long idFormation = 1;
string nouvelleIntitule = "Formation modifiée";
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == 2)
.Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault();
StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == 2)
.Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault();
TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == 1)
.Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault();
OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == 1)
.Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault();
FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation);
formation.Intitule = nouvelleIntitule;
formation.Mode = modeExterne;
formation.Type = typeELearning;
formation.Origine = origineFormationCollaborateur;
formation.Statut = statutPlanifie;
// Act
var okObjectResult = formationsApiController.UpdateFormation(formation, idFormation).Result as OkObjectResult;
// Assert
Assert.IsInstanceOf<FormationDTO>(okObjectResult.Value);
Assert.AreEqual(nouvelleIntitule, (okObjectResult.Value as FormationDTO).Intitule);
}
#endregion #endregion
#region Tests DeleteFormationById #region Tests DeleteFormationById
// Arrange [Test]
public void DeleteFormation_PasseEnParamUnIdFormationInexistant_RetourneUnObjetNotFoundObjectResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int idFormation = 999;
// Act
var notFoundObjectResult = formationsApiController.DeleteFormation(idFormation);
// Assert
Assert.IsInstanceOf<NotFoundObjectResult>(notFoundObjectResult.Result);
}
[Test]
public void DeleteFormation_PasseEnParamUnIdFormationExistant_RetourneUnObjetNoContentResult()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int idFormation = 1;
// Act // Act
var noContentResult = formationsApiController.DeleteFormation(idFormation);
// Assert
Assert.IsInstanceOf<NoContentResult>(noContentResult.Result);
}
[Test]
public async Task DeleteFormation_PasseEnParamUnIdFormationExistant_SupprimeBienUneFormation()
{
// Arrange
FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger<FormationsApiController>(), mockEnvironment.Object);
int idFormation = 1;
long nbFormationAvantSuppression = await formationService.GetFormationsCountAsync(null, null, null, null, null, null, null);
// Act
var noContentResult = formationsApiController.DeleteFormation(idFormation).Result as NoContentResult;
// Assert
long nbFormationApresSuppression = await formationService.GetFormationsCountAsync(null, null, null, null, null, null, null);
Assert.AreEqual(nbFormationAvantSuppression -1, nbFormationApresSuppression);
}
// Assert
#endregion #endregion
} }

@ -11,6 +11,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Moq" Version="4.15.2" />
<PackageReference Include="nunit" Version="3.12.0" /> <PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.15.1" /> <PackageReference Include="NUnit3TestAdapter" Version="3.15.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
@ -20,4 +21,8 @@
<ProjectReference Include="..\EPAServeur\EPAServeur.csproj" /> <ProjectReference Include="..\EPAServeur\EPAServeur.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="TestResults\" />
</ItemGroup>
</Project> </Project>

@ -0,0 +1,7 @@
{
"profiles": {
"EPAServeur.Tests": {
"commandName": "Project"
}
}
}

@ -0,0 +1,637 @@
using EPAServeur.Context;
using EPAServeur.Exceptions;
using EPAServeur.IServices;
using EPAServeur.Models.Formation;
using EPAServeur.Services;
using IO.Swagger.ApiCollaborateur;
using IO.Swagger.DTO;
using IO.Swagger.Enum;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Tests.Services
{
[TestFixture]
public class EngagementServiceTests
{
#region Variables
private EpContext epContext;
private ICollaborateurApi collaborateurApi;
private ICollaborateurService collaborateurService;
#endregion
#region Setup
[SetUp]
public void Setup()
{
// Utilisation d'une base de données en mémoire
var optionBuider = new DbContextOptionsBuilder<EpContext>()
.UseInMemoryDatabase("server_ep_test")
.Options;
epContext = new EpContext(optionBuider);
collaborateurApi = new CollaborateurApi();
collaborateurService = new CollaborateurService(collaborateurApi, epContext);
epContext.Database.EnsureDeleted();
epContext.Database.EnsureCreated();
epContext.SaveChanges();
// Ajout du jeu de données pour les tests
DataSeeder.AddEngagements(epContext);
// Détache les entités du context car la base de données InMemory créé des conflits
// entre les clés primaires lors d'un Update ou d'un Insert
foreach (var entity in epContext.ChangeTracker.Entries())
{
entity.State = EntityState.Detached;
}
}
#endregion
#region Tests GetEngagementsAsync
[TestCase(new long[] { 1, 2 })]
[TestCase(new long[] { 3 })]
public async Task GetEngagementsAsync_PasseDesParamsDesIdBUValides_RetourneDesEngagements(long[] arrIdBUs)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = arrIdBUs.Select(x => x).ToList();
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, null, null, null, null, null);
// Assert
Assert.Less(0, engagementDTOs.Count());
}
[TestCase(new EtatEngagement[] { EtatEngagement.EnAttente, EtatEngagement.Respecte })]
[TestCase(new EtatEngagement[] { EtatEngagement.DateLimitePassee })]
public async Task GetEngagementsAsync_PasseDesParamsDesEtatsDEngagementsValides_RetourneDesEngagements(EtatEngagement[] arrEtatsEngagement)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
List<EtatEngagement> etatEngagements = arrEtatsEngagement.Select(x => x).ToList();
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, etatEngagements, null, null, null, null, null);
// Assert
Assert.Less(0, engagementDTOs.Count());
}
[TestCase(1, 5)]
[TestCase(1, 10)]
public async Task GetEngagementsAsync_PasseEnParamNumPageEtParPage_RetourneLaPremierePageDesEngagements(int? numPage, int? parPage)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, null, numPage, parPage, null, null);
// Assert
Assert.AreEqual(parPage, engagementDTOs.Count());
}
[TestCase(2, 5)]
[TestCase(2, 6)]
[TestCase(2, 10)]
[TestCase(2, 15)]
public async Task GetEngagementsAsync_PasseEnParamNumPageEtParPage_RetourneLaDeuxiemePageDesFormations(int? numPage, int? parPage)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
int? nbEngagementDeuxiemePage;
switch (parPage)
{
case 5:
nbEngagementDeuxiemePage = 5;
break;
case 6:
nbEngagementDeuxiemePage = 6;
break;
case 10:
nbEngagementDeuxiemePage = 2;
break;
default:
nbEngagementDeuxiemePage = 0;
break;
}
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, null, numPage, parPage, null, null);
// Assert
Assert.AreEqual(nbEngagementDeuxiemePage, engagementDTOs.Count());
}
[TestCase(true, "action")]
[TestCase(true, null)]
[TestCase(true, "toto")]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParActionCroissant(bool? asc, string tri)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Je m'engage à attribuer 5 jours de congés supplémentaire.", engagementDTOs.First().Action);
Assert.AreEqual("Je m'engage à trouver une formation sur le Cobol.", engagementDTOs.Last().Action);
}
[TestCase(false, "action")]
[TestCase(false, null)]
[TestCase(false, "toto")]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParActionDecroissant(bool? asc, string tri)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Je m'engage à trouver une formation sur le Cobol.", engagementDTOs.First().Action);
Assert.AreEqual("Je m'engage à attribuer 5 jours de congés supplémentaire.", engagementDTOs.Last().Action);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParDispositifCroissant()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = true;
string tri = "dispositif";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Contacter le client pour planifier un rendez-vous.", engagementDTOs.First().Dispositif);
Assert.AreEqual("Planifier un point hebdomadaire sur Teams.", engagementDTOs.Last().Dispositif);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParDispositifDecroissant()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = false;
string tri = "dispositif";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Planifier un point hebdomadaire sur Teams.", engagementDTOs.First().Dispositif);
Assert.AreEqual("Contacter le client pour planifier un rendez-vous.", engagementDTOs.Last().Dispositif);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParModaliteCroissante()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = true;
string tri = "modalite";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Hors temps", engagementDTOs.First().Modalite);
Assert.AreEqual("Sur temps de travail", engagementDTOs.Last().Modalite);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParModaliteDecroissante()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = false;
string tri = "modalite";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual("Sur temps de travail", engagementDTOs.First().Modalite);
Assert.AreEqual("Hors temps", engagementDTOs.Last().Modalite);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParDateCroissante()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = true;
string tri = "date";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual(new DateTime(2020, 9, 1), engagementDTOs.First().DateLimite);
Assert.AreEqual(new DateTime(2021, 1, 31), engagementDTOs.Last().DateLimite);
}
[Test]
public async Task GetEngagementsAsync_PasseEnParamAscEtTri_RetourneDesEngagementsOrdonnancesParDateDecroissante()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>() { 1, 2, 3 };
bool? asc = false;
string tri = "date";
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, asc, null, null, null, tri);
// Assert
Assert.AreEqual(new DateTime(2021, 1, 31), engagementDTOs.First().DateLimite);
Assert.AreEqual(new DateTime(2020, 9, 1), engagementDTOs.Last().DateLimite);
}
[TestCase(new long[] { 0 }, null )]
[TestCase(new long[] { 4 }, null)]
[TestCase(new long[] { 1, 2 }, "azerty")]
public async Task GetEngagementsAsync_PasseDesParamsInvalides_RetourneZeroEngagement(long[] arrIdBUs, string texte)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs;
if (arrIdBUs != null)
idBUs = arrIdBUs.Select(x => x).ToList();
else
idBUs = new List<long>();
// Act
IEnumerable<EngagementDTO> engagementDTOs = await engagementService.GetEngagementsAsync(idBUs, null, null, null, null, texte, null);
// Assert
Assert.AreEqual(0, engagementDTOs.Count());
}
[Test]
public void GetEngagementsAsync_PasseDesParamsUneListeDIdsBUVide_LeveUneEngagementInvalidException()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = new List<long>();
// Act
AsyncTestDelegate throwException = () => engagementService.GetEngagementsAsync(idBUs, null, null, null, null, null, null);
// Assert
Assert.ThrowsAsync(typeof(EngagementInvalidException), throwException);
}
[Test]
public void GetEngagementsAsync_PasseDesParamsUneListeDIdsBUNull_LeveUneEngagementInvalidException()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs = null;
// Act
AsyncTestDelegate throwException = () => engagementService.GetEngagementsAsync(idBUs, null, null, null, null, null, null);
// Assert
Assert.ThrowsAsync(typeof(EngagementInvalidException), throwException);
}
#endregion
#region Tests GetEngagementsCountAsync
[TestCase(new long[] { 1, 2, 3 }, "formation")]
[TestCase(new long[] { 1 }, null)]
public async Task GetEngagementsCountAsync_PasseDesParamsValides_RetourneLeNombreTotalDEngagements(long[] arrIdBUs, string texte)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs;
if (arrIdBUs != null)
idBUs = arrIdBUs.Select(x => x).ToList();
else
idBUs = new List<long>();
// Act
long count = await engagementService.GetEngagementsCountAsync(idBUs, null, null, null, null, texte, null);
// Assert
Assert.Less(0, count);
}
[TestCase(new long[] { 0 }, null)]
[TestCase(new long[] { 4 }, null)]
[TestCase(new long[] { 1, 2 }, "azerty")]
public async Task GetEngagementsCountAsync_PasseDesParamsInvalides_RetourneZero(long[] arrIdBUs, string texte)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
List<long> idBUs;
if (arrIdBUs != null)
idBUs = arrIdBUs.Select(x => x).ToList();
else
idBUs = new List<long>();
// Act
long count = await engagementService.GetEngagementsCountAsync(idBUs, null, null, null, null, texte, null);
// Assert
Assert.AreEqual(0, count);
}
#endregion
#region Tests RepondreEngagementAsync
[TestCase(1, 9, EtatEngagement.Respecte, null)]
[TestCase(1, 9, EtatEngagement.EnAttente, null)]
[TestCase(2, 9, EtatEngagement.NonRealisable, "Impossible de respecter cet engagement car hors budget.")]
public async Task RepondreEngagementAsync_ModifieUnEngagementValide_EngagementModifieAvecSucces(long idEngagement, long idEp, EtatEngagement etatEngagement, string raisonNonRealisable)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO =new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = etatEngagement,
RaisonNonRealisable = raisonNonRealisable,
Ep = epInformationDTO
};
// Act
EngagementDTO engagementModifie = await engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.IsNotNull(engagementModifie);
Assert.AreEqual(idEngagement, engagementModifie.Id);
Assert.AreEqual(engagementDTO.Id, engagementModifie.Id);
Assert.AreEqual(engagementDTO.EtatEngagement, engagementModifie.EtatEngagement);
Assert.AreEqual(engagementDTO.RaisonNonRealisable, engagementModifie.RaisonNonRealisable);
}
[Test]
public async Task RepondreEngagementAsync_ModifieUnEngagementAvecUneDateLimitePasseeValide_EngagementModifieAvecSucces()
{
long idEngagement = 3;
long idEp = 9;
EtatEngagement etatEngagement = EtatEngagement.DateLimitePassee;
string raisonNonRealisableAvantUpdate = null;
string raisonNonRealisableApresUpdate = "La date limite pour respecter l'engagement est passée.";
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = etatEngagement,
RaisonNonRealisable = raisonNonRealisableAvantUpdate,
Ep = epInformationDTO
};
// Act
EngagementDTO engagementModifie = await engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.IsNotNull(engagementModifie);
Assert.AreEqual(idEngagement, engagementModifie.Id);
Assert.AreEqual(engagementDTO.Id, engagementModifie.Id);
Assert.AreEqual(engagementDTO.EtatEngagement, engagementModifie.EtatEngagement);
Assert.AreEqual(raisonNonRealisableApresUpdate, engagementModifie.RaisonNonRealisable);
}
[TestCase(1, 0, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "Demande de formation RH.", "Sur temps de travail", "2020-9-11", EtatEngagement.Respecte, null)]
[TestCase(1, 11, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "Demande de formation RH.", "Sur temps de travail", "2020-9-11", EtatEngagement.Respecte, null)]
[TestCase(1, 9, "", "Demande de formation RH.", "Sur temps de travail", "2020-9-11", EtatEngagement.Respecte, null)]
[TestCase(1, 9, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "", "Sur temps de travail", "2020-9-11", EtatEngagement.Respecte, null)]
[TestCase(1, 9, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "Demande de formation RH.", "", "2020-9-11", EtatEngagement.Respecte, null)]
[TestCase(1, 9, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "Demande de formation RH.", "Sur temps de travail", null, EtatEngagement.Respecte, null)]
[TestCase(1, 9, "Je m'engage à trouver une formation sur l'Asp.Net Core.", "Demande de formation RH.", "Sur temps de travail", "2020-9-11", EtatEngagement.NonRealisable, null)]
public void RepondreEngagementAsync_ModifieUnEngagementAvecDesProprietesInvalide_LeveUneEngagementInvalidException(long idEngagement, long idEp, string action, string dispositif, string modalite, DateTime? dateLimite, EtatEngagement etatEngagement, string raisonNonRealisable)
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = action,
Dispositif = dispositif,
Modalite = modalite,
DateLimite = dateLimite,
EtatEngagement = etatEngagement,
RaisonNonRealisable = raisonNonRealisable,
Ep = epInformationDTO
};
// Act
AsyncTestDelegate throwException = () => engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.ThrowsAsync(typeof(EngagementInvalidException), throwException);
}
[Test]
public void RepondreEngagementAsync_ModifieUnEngagementNull_LeveUneEngagementInvalidException()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EngagementDTO engagementDTO = null;
long idEngagement = 1;
// Act
AsyncTestDelegate throwException = () => engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.ThrowsAsync(typeof(EngagementInvalidException), throwException);
}
[Test]
public void RepondreEngagementAsync_ModifieUnEngagementAvecUnEPInexistantDansLaBDD_LeveUneEngagementInvalidException()
{
// Arrange
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
long idEngagement = 1;
EpInformationDTO epInformationDTO = new EpInformationDTO
{
Id = 999,
Type = TypeEp.EPA,
Statut = StatutEp.Signe,
DateDisponibilite = DateTime.Now,
DatePrevisionnelle = DateTime.Now,
Obligatoire = false
};
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = epInformationDTO
};
// Act
AsyncTestDelegate throwException = () => engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.ThrowsAsync(typeof(EngagementInvalidException), throwException);
}
[TestCase(1)]
[TestCase(null)]
public void RepondreEngagementAsync_ModifieUnEngagementAvecUnIdIncorrecte_LeveUneEngagementnIncompatibleIdException(long? idEngagement)
{
// Arrange
long idEngagementIncorrecte = 2;
long idEp = 9;
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = epInformationDTO
};
// Act
AsyncTestDelegate throwException = () => engagementService.RepondreEngagementAsync(engagementDTO, idEngagementIncorrecte);
// Assert
Assert.ThrowsAsync(typeof(EngagementIncompatibleIdException), throwException);
}
[Test]
public void RepondreEngagementAsync_ModifieUnEngagementAvecUnIdInexistant_LeveUneEngagementNotFoundException()
{
// Arrange
long idEngagement = 0;
long idEp = 9;
EngagementService engagementService = new EngagementService(epContext, collaborateurService);
EpInformationDTO epInformationDTO = epContext.Ep.Where(ep => ep.IdEP == idEp)
.Select(ep => new EpInformationDTO
{
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire
}).FirstOrDefault();
EngagementDTO engagementDTO = new EngagementDTO
{
Id = idEngagement,
Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = epInformationDTO
};
// Act
AsyncTestDelegate throwException = () => engagementService.RepondreEngagementAsync(engagementDTO, idEngagement);
// Assert
Assert.ThrowsAsync(typeof(EngagementNotFoundException), throwException);
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,19 @@
using System;
using System.Collections;
using System.ComponentModel.DataAnnotations;
namespace EPAServeur.Attributes
{
/// <summary>
/// Specifies that a collection of a specified type must have at least one element.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class CannotBeEmptyAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var list = value as IEnumerable;
return list != null && list.GetEnumerator().MoveNext();
}
}
}

@ -64,18 +64,18 @@ namespace EPAServeur.Context
TypeEntretien typeSite, typeClient, typeVisio, typeTelephone; TypeEntretien typeSite, typeClient, typeVisio, typeTelephone;
typeSite = new TypeEntretien { Libelle = "Sur site" }; typeSite = new TypeEntretien { Libelle = "Sur site" };
epContext.TypeEntretien.Add(typeSite); epContext.TypeEntretien.Add(typeSite);
typeClient = new TypeEntretien { Libelle = "Chez le client" }; typeClient = new TypeEntretien { Libelle = "Chez le client" };
epContext.TypeEntretien.Add(typeClient); epContext.TypeEntretien.Add(typeClient);
typeVisio = new TypeEntretien { Libelle = "Visioconférence" }; typeVisio = new TypeEntretien { Libelle = "Visioconférence" };
epContext.TypeEntretien.Add(typeVisio); epContext.TypeEntretien.Add(typeVisio);
typeTelephone = new TypeEntretien { Libelle = "Téléphonique" }; typeTelephone = new TypeEntretien { Libelle = "Téléphonique" };
epContext.TypeEntretien.Add(typeTelephone); epContext.TypeEntretien.Add(typeTelephone);
epContext.SaveChanges(); epContext.SaveChanges();
} }
/// <summary> /// <summary>
@ -256,63 +256,70 @@ namespace EPAServeur.Context
ep9 = new Ep ep9 = new Ep
{ {
IdCollaborateur = Guid.Parse("59a8becb-bc0a-4d3d-adb1-8a8bd13c48c9"), IdEP = 9,
IdReferent = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), IdCollaborateur = Guid.Parse("842650db-a548-4472-a3af-4c5fff3c1ab8"),
IdBu = 2, IdReferent = Guid.Parse("aa36f34c-9041-42f5-9db3-6536fe7f1696"),
Fonction = "Dev", IdBu = 1,
Fonction = "Ingénieur en Etudes et Développement",
TypeEP = TypeEp.EPA, TypeEP = TypeEp.EPA,
NumeroEp = 1, NumeroEp = 1,
DateCreation = new DateTime(2017, 7, 7), DateCreation = new DateTime(2020, 7, 7),
DatePrevisionnelle = new DateTime(2018, 7, 8), DatePrevisionnelle = new DateTime(2020, 7, 8),
Obligatoire = false, Obligatoire = false,
Statut = StatutEp.Signe, Statut = StatutEp.Signe,
CV = "CV.pdf", CV = "CV.pdf",
DateSaisie = new DateTime(2018, 6, 20) DateSaisie = new DateTime(2020, 7, 20)
}; };
epContext.Ep.Add(ep9); epContext.Ep.Add(ep9);
ep10 = new Ep ep10 = new Ep
{ {
IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), IdEP = 10,
IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), IdCollaborateur = Guid.Parse("301ba7f3-095e-4912-8998-a7c942dc5f23"),
IdBu = 2, IdReferent = Guid.Parse("ea027734-ff0f-4308-8879-133a09fb3c46"),
Fonction = "Dev", IdBu = 3,
TypeEP = TypeEp.EPA, Fonction = "Ingénieur en Etudes et Développement",
TypeEP = TypeEp.EPS,
NumeroEp = 1, NumeroEp = 1,
DateCreation = new DateTime(2017, 7, 7), DateCreation = new DateTime(2020, 6, 1),
DatePrevisionnelle = new DateTime(2018, 7, 8), DatePrevisionnelle = new DateTime(2020, 9, 25),
Obligatoire = false, Obligatoire = false,
Statut = StatutEp.Signe, Statut = StatutEp.Signe,
CV = "CV.pdf", CV = "CV.pdf",
DateSaisie = new DateTime(2018, 6, 20) DateSaisie = new DateTime(2020, 10, 5)
}; };
epContext.Ep.Add(ep10); epContext.Ep.Add(ep10);
ep11 = new Ep ep11 = new Ep
{ {
IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), IdEP = 11,
IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), IdCollaborateur = Guid.Parse("a0f40e2a-cc03-4032-a627-5389e1281c64"),
IdReferent = Guid.Parse("c199024f-5960-4c11-8e34-f9947d589284"),
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Ingénieur en Etudes et Développement",
TypeEP = TypeEp.EPA, TypeEP = TypeEp.EPA,
NumeroEp = 1, NumeroEp = 1,
DateCreation = new DateTime(2018, 1, 7), DateCreation = new DateTime(2020, 10, 15),
DatePrevisionnelle = new DateTime(2018, 1, 6), DatePrevisionnelle = new DateTime(2020, 12, 4),
Obligatoire = false, Obligatoire = false,
Statut = StatutEp.Signe, Statut = StatutEp.SignatureReferent,
CV = "CV.pdf", CV = "CV.pdf",
DateSaisie = new DateTime(2018, 6, 20) DateSaisie = new DateTime(2020, 12, 10)
}; };
epContext.Ep.Add(ep11); epContext.Ep.Add(ep11);
Engagement engagement1, engagement2, engagement3; Engagement engagement1, engagement2, engagement3; // EnAttente
Engagement engagement4, engagement5, engagement6; // Respecte
Engagement engagement7, engagement8, engagement9; // NonRealisable
Engagement engagement10, engagement11, engagement12; // DateLimitePassee
engagement1 = new Engagement engagement1 = new Engagement
{ {
Action = "Je m'engage à...", IdEngagement = 1,
Dispositif = "interne", Action = "Je m'engage à trouver une formation sur l'Asp.Net Core.",
Modalite = "Modalite", Dispositif = "Demande de formation RH.",
DateLimite = new DateTime(2017, 7, 7), Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.EnAttente, EtatEngagement = EtatEngagement.EnAttente,
RaisonNonRealisable = null, RaisonNonRealisable = null,
Ep = ep9 Ep = ep9
@ -321,28 +328,147 @@ namespace EPAServeur.Context
engagement2 = new Engagement engagement2 = new Engagement
{ {
Action = "Je m'engage à faire...", IdEngagement = 2,
Dispositif = "externe", Action = "Je m'engage à attribuer une progression salariale.",
Modalite = "Modalite 2", Dispositif = "Demande d'augmentation RH.",
DateLimite = new DateTime(2017, 7, 8), Modalite = "Hors temps",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.EnAttente, EtatEngagement = EtatEngagement.EnAttente,
RaisonNonRealisable = null, RaisonNonRealisable = null,
Ep = ep10 Ep = ep9
}; };
epContext.Engagement.Add(engagement2); epContext.Engagement.Add(engagement2);
engagement3 = new Engagement engagement3 = new Engagement
{ {
Action = "Je m'engage à faire...", IdEngagement = 3,
Dispositif = "externe", Action = "Je m'engage à réaliser des points hebdomadaires avec l'équipe pour renforcer le lien social.",
Modalite = "Modalite 3", Dispositif = "Planifier un point hebdomadaire sur Teams.",
DateLimite = new DateTime(2017, 7, 8), Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.EnAttente, EtatEngagement = EtatEngagement.EnAttente,
RaisonNonRealisable = "Aucune formation disponible", RaisonNonRealisable = null,
Ep = ep11 Ep = ep9
}; };
epContext.Engagement.Add(engagement3); epContext.Engagement.Add(engagement3);
engagement4 = new Engagement
{
IdEngagement = 4,
Action = "Je m'engage à fournir une connexion internet afin que le collaborateur puisse travailler dans de bonnes condition lorsque ce dernier est en télétravail.",
Dispositif = "Fournir un téléphone portable avec une connexion internet.",
Modalite = "Hors temps",
DateLimite = new DateTime(2020, 9, 1),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = ep9
};
epContext.Engagement.Add(engagement4);
engagement5 = new Engagement
{
IdEngagement = 5,
Action = "Je m'engage à trouver une formation sur la méthode SCRUM.",
Dispositif = "Demande de formation RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 12, 1),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = ep10
};
epContext.Engagement.Add(engagement5);
engagement6 = new Engagement
{
IdEngagement = 6,
Action = "Je m'engage à réaliser un point avec le client pour améliorer l'intégration du collaborateur dans l'équipe.",
Dispositif = "Contacter le client pour planifier un rendez-vous.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 10, 25),
EtatEngagement = EtatEngagement.Respecte,
RaisonNonRealisable = null,
Ep = ep10
};
epContext.Engagement.Add(engagement6);
engagement7 = new Engagement
{
IdEngagement = 7,
Action = "Je m'engage à attribuer 5 jours de télétravail pour le collbaorateur en dehors de la période Covid.",
Dispositif = "Demande RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 12, 1),
EtatEngagement = EtatEngagement.NonRealisable,
RaisonNonRealisable = "L'accord du télétravail ne permet pas d'avoir 5 jours de travail pour le Groupe 1.",
Ep = ep10
};
epContext.Engagement.Add(engagement7);
engagement8 = new Engagement
{
IdEngagement = 8,
Action = "Je m'engage à attribuer 5 jours de congés supplémentaire.",
Dispositif = "Demande RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2020, 12, 1),
EtatEngagement = EtatEngagement.NonRealisable,
RaisonNonRealisable = "On ne peut pas donner plus de jours de congés que le nombre de droits que le salarié a cotisé.",
Ep = ep10
};
epContext.Engagement.Add(engagement8);
engagement9 = new Engagement
{
IdEngagement = 9,
Action = "Je m'engage à augmenter le salaire mensuel du collaborateur de 1000 euros.",
Dispositif = "Demande RH.",
Modalite = "Hors temps",
DateLimite = new DateTime(2021, 1, 31),
EtatEngagement = EtatEngagement.NonRealisable,
RaisonNonRealisable = "La demande d'augmentation dépasse le crédit budgétaire.",
Ep = ep11
};
epContext.Engagement.Add(engagement9);
engagement10 = new Engagement
{
IdEngagement = 10,
Action = "Je m'engage à interdire le client de conctacter le collaborateur en dehors du temps de travail.",
Dispositif = "Contacter le client pour planifier un rendez-vous.",
Modalite = "Hors temps",
DateLimite = new DateTime(2021, 1, 31),
EtatEngagement = EtatEngagement.DateLimitePassee,
RaisonNonRealisable = "La date limite pour respecter l'engagement est passée.",
Ep = ep11
};
epContext.Engagement.Add(engagement10);
engagement11 = new Engagement
{
IdEngagement = 11,
Action = "Je m'engage à trouver une formation sur le Cobol.",
Dispositif = "Demande de formation auprès des RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2021, 1, 31),
EtatEngagement = EtatEngagement.DateLimitePassee,
RaisonNonRealisable = "La date limite pour respecter l'engagement est passée.",
Ep = ep11
};
epContext.Engagement.Add(engagement11);
engagement12 = new Engagement
{
IdEngagement = 12,
Action = "Je m'engage à fournir une disque dur externe au collaborateur.",
Dispositif = "Demande de matériel auprès des RH.",
Modalite = "Sur temps de travail",
DateLimite = new DateTime(2021, 1, 31),
EtatEngagement = EtatEngagement.DateLimitePassee,
RaisonNonRealisable = "La date limite pour respecter l'engagement est passée.",
Ep = ep11
};
epContext.Engagement.Add(engagement12);
epContext.SaveChanges(); epContext.SaveChanges();
} }
@ -358,7 +484,7 @@ namespace EPAServeur.Context
statutPlanifie = new StatutFormation { IdStatutFormation = 1, Libelle = "Planifiée" }; statutPlanifie = new StatutFormation { IdStatutFormation = 1, Libelle = "Planifiée" };
epContext.StatutFormation.Add(statutPlanifie); epContext.StatutFormation.Add(statutPlanifie);
statutReplanifie = new StatutFormation { IdStatutFormation = 2, Libelle = "Replanifié" }; statutReplanifie = new StatutFormation { IdStatutFormation = 2, Libelle = "Replanifiée" };
epContext.StatutFormation.Add(statutReplanifie); epContext.StatutFormation.Add(statutReplanifie);
statutRealise = new StatutFormation { IdStatutFormation = 3, Libelle = "Réalisée" }; statutRealise = new StatutFormation { IdStatutFormation = 3, Libelle = "Réalisée" };
@ -443,10 +569,11 @@ namespace EPAServeur.Context
f1 = new Formation f1 = new Formation
{ {
Intitule = "Formation1", IdFormation = 1,
Intitule = "Formation Mainframe Complète",
DateDebut = new DateTime(2020, 9, 16, 10, 0, 0), DateDebut = new DateTime(2020, 1, 25, 10, 0, 0),
DateFin = new DateTime(2020, 9, 16), DateFin = new DateTime(2020, 1, 27),
IdAgence = 1, IdAgence = 1,
Heure = 2, Heure = 2,
Jour = 1, Jour = 1,
@ -461,10 +588,11 @@ namespace EPAServeur.Context
f2 = new Formation f2 = new Formation
{ {
Intitule = "Formation2", IdFormation = 2,
Intitule = "Formation professionnelle React + Redux",
DateDebut = new DateTime(2020, 10, 5, 14, 0, 0), DateDebut = new DateTime(2020, 2, 25, 14, 0, 0),
DateFin = new DateTime(2020, 10, 9), DateFin = new DateTime(2020, 2, 27),
IdAgence = 1, IdAgence = 1,
Heure = 10, Heure = 10,
Jour = 5, Jour = 5,
@ -479,10 +607,11 @@ namespace EPAServeur.Context
f3 = new Formation f3 = new Formation
{ {
Intitule = "Formation3", IdFormation = 3,
Intitule = "Apprendre C# et le développement de logiciels avec WPF",
DateDebut = new DateTime(2020, 9, 21, 14, 0, 0), DateDebut = new DateTime(2020, 5, 25, 14, 0, 0),
DateFin = new DateTime(2020, 9, 21), DateFin = new DateTime(2020, 5, 27),
IdAgence = 1, IdAgence = 1,
Heure = 4, Heure = 4,
Jour = 2, Jour = 2,
@ -497,10 +626,11 @@ namespace EPAServeur.Context
f4 = new Formation f4 = new Formation
{ {
Intitule = "Formation4", IdFormation = 4,
Intitule = "Formation Visual Basic.Net - Initiation + Approfondissement",
DateDebut = new DateTime(2020, 05, 11, 14, 0, 0), DateDebut = new DateTime(2020, 7, 25, 14, 0, 0),
DateFin = new DateTime(2020, 05, 11), DateFin = new DateTime(2020, 7, 27),
IdAgence = 1, IdAgence = 1,
Heure = 3, Heure = 3,
Jour = 1, Jour = 1,
@ -515,10 +645,11 @@ namespace EPAServeur.Context
f5 = new Formation f5 = new Formation
{ {
Intitule = "Formation5", IdFormation = 5,
Intitule = "Formation Conception, langage SQL : Les fondamentaux",
DateDebut = new DateTime(2020, 08, 1, 13, 0, 0), DateDebut = new DateTime(2020, 8, 25, 14, 0, 0),
DateFin = new DateTime(2020, 08, 3), DateFin = new DateTime(2020, 8, 27),
IdAgence = 1, IdAgence = 1,
Heure = 6, Heure = 6,
Jour = 2, Jour = 2,
@ -533,10 +664,11 @@ namespace EPAServeur.Context
f6 = new Formation f6 = new Formation
{ {
Intitule = "Formation6", IdFormation = 6,
Intitule = "Formation Laravel 5.x, Développement WEB en PHP",
DateDebut = new DateTime(2020, 9, 30, 9, 0, 0), DateDebut = new DateTime(2020, 9, 25, 14, 0, 0),
DateFin = new DateTime(2020, 10, 1), DateFin = new DateTime(2020, 9, 27),
IdAgence = 1, IdAgence = 1,
Heure = 4, Heure = 4,
Jour = 2, Jour = 2,
@ -551,10 +683,11 @@ namespace EPAServeur.Context
f7 = new Formation f7 = new Formation
{ {
Intitule = "Formation7", IdFormation = 7,
Intitule = "Formation d’initiation aux Méthodes Agiles – Scrum",
DateDebut = new DateTime(2020, 10, 5, 10, 0, 0), DateDebut = new DateTime(2020, 11, 25, 14, 0, 0),
DateFin = new DateTime(2020, 10, 8), DateFin = new DateTime(2020, 11, 27),
IdAgence = 1, IdAgence = 1,
Heure = 6, Heure = 6,
Jour = 5, Jour = 5,
@ -569,9 +702,10 @@ namespace EPAServeur.Context
f8 = new Formation f8 = new Formation
{ {
Intitule = "Formation2", IdFormation = 8,
DateDebut = new DateTime(2020, 11, 18, 10, 0, 0), Intitule = "Formation Xamarin, Développer des applications mobiles en C# pour iOS et Android",
DateFin = new DateTime(2020, 11, 20), DateDebut = new DateTime(2020, 12, 25, 14, 0, 0),
DateFin = new DateTime(2020, 12, 27),
IdAgence = 1, IdAgence = 1,
Heure = 6, Heure = 6,
Jour = 3, Jour = 3,
@ -586,7 +720,8 @@ namespace EPAServeur.Context
f9 = new Formation f9 = new Formation
{ {
Intitule = "Formation9", IdFormation = 9,
Intitule = "Formation Développer des Web Services en Java",
DateDebut = new DateTime(2020, 11, 15, 9, 0, 0), DateDebut = new DateTime(2020, 11, 15, 9, 0, 0),
DateFin = new DateTime(2020, 11, 15), DateFin = new DateTime(2020, 11, 15),
IdAgence = 1, IdAgence = 1,
@ -603,7 +738,8 @@ namespace EPAServeur.Context
f10 = new Formation f10 = new Formation
{ {
Intitule = "Formation10", IdFormation = 10,
Intitule = "Architecture Microservices – Les fondamentaux",
DateDebut = new DateTime(2020, 8, 3, 14, 0, 0), DateDebut = new DateTime(2020, 8, 3, 14, 0, 0),
DateFin = new DateTime(2020, 8, 3), DateFin = new DateTime(2020, 8, 3),
IdAgence = 1, IdAgence = 1,
@ -612,7 +748,7 @@ namespace EPAServeur.Context
ModeFormation = modePresentiel, ModeFormation = modePresentiel,
TypeFormation = typeInterne, TypeFormation = typeInterne,
Organisme = "Organisme4", Organisme = "Organisme4",
Origine = origineFormationClient, Origine = origineFormationReglementaire,
Statut = statutAnnule, Statut = statutAnnule,
EstCertifiee = false EstCertifiee = false
}; };
@ -620,7 +756,8 @@ namespace EPAServeur.Context
f11 = new Formation f11 = new Formation
{ {
Intitule = "Formation11", IdFormation = 11,
Intitule = "Formation Clean Architecture .Net Core",
DateDebut = new DateTime(2020, 04, 6, 9, 0, 0), DateDebut = new DateTime(2020, 04, 6, 9, 0, 0),
DateFin = new DateTime(2020, 04, 11), DateFin = new DateTime(2020, 04, 11),
IdAgence = 1, IdAgence = 1,
@ -629,28 +766,514 @@ namespace EPAServeur.Context
ModeFormation = modePresentiel, ModeFormation = modePresentiel,
TypeFormation = typeInterne, TypeFormation = typeInterne,
Organisme = "Organisme1", Organisme = "Organisme1",
Origine = origineFormationClient, Origine = origineFormationReglementaire,
Statut = statutAnnule, Statut = statutAnnule,
EstCertifiee = false EstCertifiee = false
}; };
epContext.Formation.Add(f11); epContext.Formation.Add(f11);
/* /*
formations.Add(f1);
formations.Add(f2);
formations.Add(f3);
formations.Add(f4);
formations.Add(f5);
formations.Add(f6);
formations.Add(f7);
formations.Add(f8);
formations.Add(f9);
formations.Add(f10);
formations.Add(f11);
int[] npParticipants = { }; int[] npParticipants = { };
*/ */
// EP
Ep ep12, ep13, ep14, ep15;
Ep ep16, ep17, ep18, ep19;
Ep ep20;
ep12 = new Ep
{
IdEP = 12,
IdCollaborateur = Guid.Parse("842650db-a548-4472-a3af-4c5fff3c1ab8"),
IdReferent = Guid.Parse("aa36f34c-9041-42f5-9db3-6536fe7f1696"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPA,
NumeroEp = 1,
DateCreation = new DateTime(2020, 1, 21, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 1, 22, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 1, 23)
};
epContext.Ep.Add(ep12);
ep13 = new Ep
{
IdEP = 13,
IdCollaborateur = Guid.Parse("301ba7f3-095e-4912-8998-a7c942dc5f23"),
IdReferent = Guid.Parse("ea027734-ff0f-4308-8879-133a09fb3c46"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 3,
DateCreation = new DateTime(2020, 2, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 2, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 2, 23)
};
epContext.Ep.Add(ep13);
ep14 = new Ep
{
IdEP = 14,
IdCollaborateur = Guid.Parse("a0f40e2a-cc03-4032-a627-5389e1281c64"),
IdReferent = Guid.Parse("56e3d82d-4be4-4449-a1f7-b4004b6bd186"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 3, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 3, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 3, 23)
};
epContext.Ep.Add(ep14);
ep15 = new Ep
{
IdEP = 15,
IdCollaborateur = Guid.Parse("4f3fcd23-a1e4-4c9e-afa2-d06ca9216491"),
IdReferent = Guid.Parse("25d2b0ce-5c95-4ccc-98bb-63b06c4ee4ad"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 4, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 4, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 4, 23)
};
ep16 = new Ep
{
IdEP = 16,
IdCollaborateur = Guid.Parse("0968ccd3-1ef5-4041-83f3-1c76afb02bbf"),
IdReferent = Guid.Parse("01ee85ff-d7f3-494b-b1de-26ced8fbfa0d"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPA,
NumeroEp = 1,
DateCreation = new DateTime(2020, 5, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 5, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 5, 23)
};
epContext.Ep.Add(ep16);
ep17 = new Ep
{
IdEP = 17,
IdCollaborateur = Guid.Parse("e7820f92-eab1-42f5-ae96-5c16e71ff1e6"),
IdReferent = Guid.Parse("d4fc247b-015a-44d6-8f3e-a52f0902d2bf"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 6, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 6, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 6, 23)
};
epContext.Ep.Add(ep17);
ep18 = new Ep
{
IdEP = 18,
IdCollaborateur = Guid.Parse("1429be5b-9125-482c-80c4-c1d34afbd8d2"),
IdReferent = Guid.Parse("3f276ab8-727a-4e26-ad5d-4d296158688e"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 7, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 7, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 7, 23)
};
epContext.Ep.Add(ep18);
ep19 = new Ep
{
IdEP = 19,
IdCollaborateur = Guid.Parse("13fbe621-1bc9-4f04-afde-b54ca076e239"),
IdReferent = Guid.Parse("f1d14915-89f7-4c1a-a8e1-4148ed7d81d7"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPASIXANS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 8, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 8, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 8, 23)
};
epContext.Ep.Add(ep19);
ep20 = new Ep
{
IdEP = 20,
IdCollaborateur = Guid.Parse("b5254c6c-7caa-435f-a4bb-e0cf92559832"),
IdReferent = Guid.Parse("dfea9a3c-7896-444d-9aa0-61ae536091c1"),
IdBu = 2,
Fonction = "Dev",
TypeEP = TypeEp.EPS,
NumeroEp = 1,
DateCreation = new DateTime(2020, 9, 22, 9, 0, 0),
DatePrevisionnelle = new DateTime(2020, 9, 25, 9, 0, 0),
Obligatoire = false,
Statut = StatutEp.SignatureReferent,
CV = "CV.pdf",
DateSaisie = new DateTime(2020, 9, 23)
};
epContext.Ep.Add(ep20);
// Demande de formation
DemandeFormation d1, d2, d3, d4;//EnAttente
DemandeFormation d5, d6, d7, d8; // Validee
DemandeFormation d9, d10, d11, d12;//Rejetee
d1 = new DemandeFormation
{
IdDemandeFormation = 1,
Libelle = "Formation Cobol",
Description = "Demande de formation Cobol avec Mainframe",
DemandeRH = false,
DateDemande = new DateTime(2020, 1, 22, 9, 0, 0),
Etat = EtatDemande.EnAttente,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep12
};
epContext.DemandeFormation.Add(d1);
d2 = new DemandeFormation
{
IdDemandeFormation = 2,
Libelle = "Formation React",
Description = "Demande de formation React avec Redux",
DemandeRH = false,
DateDemande = new DateTime(2020, 2, 22, 9, 0, 0),
Etat = EtatDemande.EnAttente,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep13
};
epContext.DemandeFormation.Add(d2);
d3 = new DemandeFormation
{
IdDemandeFormation = 3,
Libelle = "Formation C#",
Description = "Demande de formation C# avec WPF",
DemandeRH = false,
DateDemande = new DateTime(2020, 3, 22, 9, 0, 0),
Etat = EtatDemande.EnAttente,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep14
};
epContext.DemandeFormation.Add(d3);
d4 = new DemandeFormation
{
IdDemandeFormation = 4,
Libelle = "Formation C#",
Description = "Demande de formation C# avec WPF",
DemandeRH = false,
DateDemande = new DateTime(2020, 4, 22, 9, 0, 0),
Etat = EtatDemande.EnAttente,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep13
};
epContext.DemandeFormation.Add(d4);
d5 = new DemandeFormation
{
IdDemandeFormation = 5,
Libelle = "Formation C#",
Description = "Demande de formation C# avec WPF",
DemandeRH = false,
DateDemande = new DateTime(2020, 5, 22, 9, 0, 0),
Etat = EtatDemande.Validee,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep12
};
epContext.DemandeFormation.Add(d5);
d6 = new DemandeFormation
{
IdDemandeFormation = 6,
Libelle = "Formation Vb.Net",
Description = "Demande de formation Vb.Net avec WinForms",
DemandeRH = false,
DateDemande = new DateTime(2020, 6, 22, 9, 0, 0),
Etat = EtatDemande.Validee,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep15
};
epContext.DemandeFormation.Add(d6);
d7 = new DemandeFormation
{
IdDemandeFormation = 7,
Libelle = "Formation Vb.Net",
Description = "Demande de formation Vb.Net avec WinForms",
DemandeRH = false,
DateDemande = new DateTime(2020, 7, 22, 9, 0, 0),
Etat = EtatDemande.Validee,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep16
};
epContext.DemandeFormation.Add(d7);
d8 = new DemandeFormation
{
IdDemandeFormation = 8,
Libelle = "Formation SQL",
Description = "Demande de formation SQL avec SQL Server",
DemandeRH = false,
DateDemande = new DateTime(2020, 8, 22, 9, 0, 0),
Etat = EtatDemande.Validee,
CommentaireRefus = null,
DateDerniereReponse = null,
Ep = ep16
};
epContext.DemandeFormation.Add(d8);
d9 = new DemandeFormation
{
IdDemandeFormation = 9,
Libelle = "Formation PHP",
Description = "Demande de formation PHP avec Laravel",
DemandeRH = false,
DateDemande = new DateTime(2020, 9, 22, 9, 0, 0),
Etat = EtatDemande.Rejetee,
CommentaireRefus = "Aucune formation PHP pour le moment",
DateDerniereReponse = new DateTime(2020, 9, 27, 9, 0, 0),
Ep = ep17
};
epContext.DemandeFormation.Add(d9);
d10 = new DemandeFormation
{
IdDemandeFormation = 10,
Libelle = "Formation Vue.JS",
Description = "Demande de formation Vue.JS",
DemandeRH = false,
DateDemande = new DateTime(2020, 10, 22, 9, 0, 0),
Etat = EtatDemande.Rejetee,
CommentaireRefus = null,
DateDerniereReponse = new DateTime(2020, 10, 27, 9, 0, 0),
Ep = ep18
};
epContext.DemandeFormation.Add(d10);
d11 = new DemandeFormation
{
IdDemandeFormation = 11,
Libelle = "Formation SCRUM",
Description = "Demande de formation sur la méthode agile SCRUM",
DemandeRH = false,
DateDemande = new DateTime(2020, 11, 22, 9, 0, 0),
Etat = EtatDemande.Rejetee,
CommentaireRefus = null,
DateDerniereReponse = new DateTime(2020, 11, 27, 9, 0, 0),
Ep = ep19
};
epContext.DemandeFormation.Add(d11);
d12 = new DemandeFormation
{
IdDemandeFormation = 12,
Libelle = "Formation C#",
Description = "Demande de formation C# avec Xamarin",
DemandeRH = false,
DateDemande = new DateTime(2020, 12, 22, 9, 0, 0),
Etat = EtatDemande.Rejetee,
CommentaireRefus = null,
DateDerniereReponse = new DateTime(2020, 12, 27, 9, 0, 0),
Ep = ep20
};
epContext.DemandeFormation.Add(d12);
// Participation formation
ParticipationFormation p1, p2, p3, p4;
ParticipationFormation p5, p6, p7, p8;
ParticipationFormation p9, p10, p11, p12;
p1 = new ParticipationFormation
{
IdParticipationFormation = 1,
DateCreation = new DateTime(2020, 1, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d1.IdDemandeFormation,
DemandeFormation = d1,
Formation = f1
};
epContext.ParticipationFormation.Add(p1);
p2 = new ParticipationFormation
{
IdParticipationFormation = 2,
DateCreation = new DateTime(2020, 2, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d2.IdDemandeFormation,
DemandeFormation = d2,
Formation = f2
};
epContext.ParticipationFormation.Add(p2);
p3 = new ParticipationFormation
{
IdParticipationFormation = 3,
DateCreation = new DateTime(2020, 3, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d3.IdDemandeFormation,
DemandeFormation = d3,
Formation = f3
};
epContext.ParticipationFormation.Add(p3);
p4 = new ParticipationFormation
{
IdParticipationFormation = 4,
DateCreation = new DateTime(2020, 4, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d4.IdDemandeFormation,
DemandeFormation = d4,
Formation = f3
};
epContext.ParticipationFormation.Add(p4);
p5 = new ParticipationFormation
{
IdParticipationFormation = 5,
DateCreation = new DateTime(2020, 5, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d5.IdDemandeFormation,
DemandeFormation = d5,
Formation = f3
};
epContext.ParticipationFormation.Add(p5);
p6 = new ParticipationFormation
{
IdParticipationFormation = 6,
DateCreation = new DateTime(2020, 6, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d6.IdDemandeFormation,
DemandeFormation = d6,
Formation = f4
};
epContext.ParticipationFormation.Add(p6);
p7 = new ParticipationFormation
{
IdParticipationFormation = 7,
DateCreation = new DateTime(2020, 7, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d7.IdDemandeFormation,
DemandeFormation = d7,
Formation = f4
};
epContext.ParticipationFormation.Add(p7);
p8 = new ParticipationFormation
{
IdParticipationFormation = 8,
DateCreation = new DateTime(2020, 8, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d8.IdDemandeFormation,
DemandeFormation = d8,
Formation = f5
};
epContext.ParticipationFormation.Add(p8);
p9 = new ParticipationFormation
{
IdParticipationFormation = 9,
DateCreation = new DateTime(2020, 9, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d9.IdDemandeFormation,
DemandeFormation = d9,
Formation = f6
};
epContext.ParticipationFormation.Add(p9);
p10 = new ParticipationFormation
{
IdParticipationFormation = 10,
DateCreation = new DateTime(2020, 10, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d10.IdDemandeFormation,
DemandeFormation = d10,
Formation = f7
};
epContext.ParticipationFormation.Add(p10);
p11 = new ParticipationFormation
{
IdParticipationFormation = 11,
DateCreation = new DateTime(2020, 11, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d11.IdDemandeFormation,
DemandeFormation = d11,
Formation = f8
};
epContext.ParticipationFormation.Add(p11);
p12 = new ParticipationFormation
{
IdParticipationFormation = 12,
DateCreation = new DateTime(2020, 12, 25, 9, 0, 0),
EstEvaluee = false,
IdDemandeFormation = d12.IdDemandeFormation,
DemandeFormation = d12,
Formation = f9
};
epContext.ParticipationFormation.Add(p12);
epContext.SaveChanges(); epContext.SaveChanges();
} }

@ -159,6 +159,7 @@ namespace EPAServeur.Context
{ {
entity.HasKey(e => e.IdFormation); entity.HasKey(e => e.IdFormation);
entity.Property(e => e.IdFormation).ValueGeneratedOnAdd(); entity.Property(e => e.IdFormation).ValueGeneratedOnAdd();
entity.HasMany<ParticipationFormation>(e => e.ParticipationsFormation).WithOne(e => e.Formation);
}); });
modelBuilder.Entity<ModeFormation>(entity => modelBuilder.Entity<ModeFormation>(entity =>

@ -19,6 +19,16 @@ using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using IO.Swagger.DTO; using IO.Swagger.DTO;
using IO.Swagger.Enum; using IO.Swagger.Enum;
using EPAServeur.Attributes;
using EPAServeur.IServices;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using EPAServeur.Exceptions;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
@ -28,12 +38,23 @@ namespace IO.Swagger.Controllers
[ApiController] [ApiController]
public class EngagementsApiController : ControllerBase public class EngagementsApiController : ControllerBase
{ {
private readonly IEngagementService engagementService;
private readonly ILogger<EngagementsApiController> logger;
private readonly IWebHostEnvironment env;
public EngagementsApiController(IEngagementService _engagementService, ILogger<EngagementsApiController> _logger, IWebHostEnvironment _env)
{
engagementService = _engagementService;
logger = _logger;
env = _env;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <remarks>Récupérer la liste des engagements.</remarks> /// <remarks>Récupérer la liste des engagements.</remarks>
/// <param name="etatsEngagement">Etats de l&#x27;engagement</param>
/// <param name="idBUs">liste des ids des BU auxquelles les données sont rattachées</param> /// <param name="idBUs">liste des ids des BU auxquelles les données sont rattachées</param>
/// <param name="etatsEngagement">Etats de l&#x27;engagement</param>
/// <param name="asc">Indique si les données sont récupérées dans l&#x27;ordre croissant ou non</param> /// <param name="asc">Indique si les données sont récupérées dans l&#x27;ordre croissant ou non</param>
/// <param name="numPage">Numéro de la page du tableau à afficher</param> /// <param name="numPage">Numéro de la page du tableau à afficher</param>
/// <param name="parPAge">Nombre d’élément maximum à afficher dans le tableau</param> /// <param name="parPAge">Nombre d’élément maximum à afficher dans le tableau</param>
@ -45,41 +66,49 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/engagements")] [Route("/api/engagements")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetEngagements")] [SwaggerOperation("GetEngagements")]
[SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetEngagements([FromQuery]List<EtatEngagement> etatsEngagement, [FromQuery]List<long?> idBUs, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<IActionResult> GetEngagements([FromQuery][CannotBeEmpty] List<long> idBUs, [FromQuery]List<EtatEngagement> etatsEngagement, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<EngagementDTO>)); logger.LogInformation("Récupération de la liste des engagements.");
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable<EngagementDTO> engagements;
// return StatusCode(401, default(ErreurDTO));
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(403, default(ErreurDTO)); {
engagements = await engagementService.GetEngagementsAsync(idBUs, etatsEngagement, asc, numPage, parPAge, texte, tri);
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(500, default(ErreurDTO)); {
string exampleJson = null; Code = StatusCodes.Status500InternalServerError,
exampleJson = "[ {\n \"action\" : \"action\",\n \"id\" : 4,\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"dateLimite\" : \"2000-01-23T04:56:07.000+00:00\",\n \"etatEngagement\" : \"EnAttente\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"action\" : \"action\",\n \"id\" : 4,\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"dateLimite\" : \"2000-01-23T04:56:07.000+00:00\",\n \"etatEngagement\" : \"EnAttente\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; Message = "Une erreur inconnue est survenue sur le serveur."
};
var example = exampleJson != null return StatusCode(erreur.Code.Value, erreur);
? JsonConvert.DeserializeObject<List<EngagementDTO>>(exampleJson) }
: default(List<EngagementDTO>); //TODO: Change the data returned
return new ObjectResult(example); if (env.IsDevelopment())
logger.LogInformation("Liste des engagements récupérée.");
return Ok(engagements);
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <remarks>Récupérer le nombre total d’engagements.</remarks> /// <remarks>Récupérer le nombre total d’engagements.</remarks>
/// <param name="etatsEngagement">Etats de l&#x27;engagement</param>
/// <param name="idBUs">liste des ids des BU auxquelles les données sont rattachées</param> /// <param name="idBUs">liste des ids des BU auxquelles les données sont rattachées</param>
/// <param name="etatsEngagement">Etats de l&#x27;engagement</param>
/// <param name="asc">Indique si les données sont récupérées dans l&#x27;ordre croissant ou non</param> /// <param name="asc">Indique si les données sont récupérées dans l&#x27;ordre croissant ou non</param>
/// <param name="numPage">Numéro de la page du tableau à afficher</param> /// <param name="numPage">Numéro de la page du tableau à afficher</param>
/// <param name="parPAge">Nombre d’élément maximum à afficher dans le tableau</param> /// <param name="parPAge">Nombre d’élément maximum à afficher dans le tableau</param>
@ -91,33 +120,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/engagements/count")] [Route("/api/engagements/count")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetEngagementsCount")] [SwaggerOperation("GetEngagementsCount")]
[SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetEngagementsCount([FromQuery]List<EtatEngagement> etatsEngagement, [FromQuery]List<long?> idBUs, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<IActionResult> GetEngagementsCount([FromQuery][CannotBeEmpty]List<long> idBUs, [FromQuery]List<EtatEngagement> etatsEngagement, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(long?)); logger.LogInformation("Récupération du nombre total d'engagements.");
long count;
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(401, default(ErreurDTO)); {
count = await engagementService.GetEngagementsCountAsync(idBUs, etatsEngagement, asc, numPage, parPAge, texte, tri);
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(403, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(500, default(ErreurDTO)); }
string exampleJson = null;
exampleJson = "0";
var example = exampleJson != null if (env.IsDevelopment())
? JsonConvert.DeserializeObject<long?>(exampleJson) logger.LogInformation("Nombre total d'engagement récupéré.");
: default(long?); //TODO: Change the data returned
return new ObjectResult(example); return Ok(count);
} }
/// <summary> /// <summary>
@ -134,7 +171,7 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpPut] [HttpPut]
[Route("/api/engagements/{idEngagement}")] [Route("/api/engagements/{idEngagement}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("UpdateEngagement")] [SwaggerOperation("UpdateEngagement")]
[SwaggerResponse(statusCode: 200, type: typeof(EngagementDTO), description: "Engagement modifié avec succès")] [SwaggerResponse(statusCode: 200, type: typeof(EngagementDTO), description: "Engagement modifié avec succès")]
@ -143,32 +180,95 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")]
[SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")] [SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult UpdateEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) public virtual async Task<IActionResult> UpdateEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long idEngagement)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(EngagementDTO)); logger.LogInformation("Mise à jour de l'engagement d'id {idEngagement}.", idEngagement);
try
{
body = await engagementService.RepondreEngagementAsync(body, idEngagement);
}
catch (EngagementInvalidException e)
{
if (env.IsDevelopment())
logger.LogInformation(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status415UnsupportedMediaType,
Message = e.Message,
};
return StatusCode(erreur.Code.Value, erreur.Message);
}
catch (EngagementIncompatibleIdException e)
{
if (env.IsDevelopment())
logger.LogInformation(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status415UnsupportedMediaType,
Message = e.Message,
};
return StatusCode(erreur.Code.Value, erreur.Message);
}
catch (EngagementNotFoundException e)
{
if (env.IsDevelopment())
logger.LogInformation(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status404NotFound,
Message = e.Message
};
return NotFound(erreur);
}
catch (DbUpdateConcurrencyException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = string.Format("L'engagement {0} n'a pas pu être supprimé car il est pris par une autre ressource.", idEngagement)
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (DbUpdateException e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(401, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur est survenue sur le serveur lors de la suppression de l'engagement."
};
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(403, default(ErreurDTO)); }
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(404, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 415 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(415, default(ErreurDTO)); }
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(500, default(ErreurDTO)); logger.LogInformation("Update effectué avec succès.");
string exampleJson = null;
exampleJson = "{\n \"action\" : \"action\",\n \"id\" : 4,\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"dateLimite\" : \"2000-01-23T04:56:07.000+00:00\",\n \"etatEngagement\" : \"EnAttente\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}";
var example = exampleJson != null return Ok(body);
? JsonConvert.DeserializeObject<EngagementDTO>(exampleJson)
: default(EngagementDTO); //TODO: Change the data returned
return new ObjectResult(example);
} }
} }
} }

@ -18,6 +18,16 @@ using IO.Swagger.Attributes;
using IO.Swagger.Security; using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using IO.Swagger.DTO; using IO.Swagger.DTO;
using System.ComponentModel;
using EPAServeur.IServices;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using EPAServeur.Exceptions;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
@ -27,6 +37,17 @@ namespace IO.Swagger.Controllers
[ApiController] [ApiController]
public class FormationsApiController : ControllerBase public class FormationsApiController : ControllerBase
{ {
private readonly IFormationService formationService;
private readonly ILogger<FormationsApiController> logger;
private readonly IWebHostEnvironment env;
public FormationsApiController(IFormationService _formationService, ILogger<FormationsApiController> _logger, IWebHostEnvironment _env)
{
formationService = _formationService;
logger = _logger;
env = _env;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -39,7 +60,7 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpPost] [HttpPost]
[Route("/api/formations")] [Route("/api/formations")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("AddFormation")] [SwaggerOperation("AddFormation")]
[SwaggerResponse(statusCode: 201, type: typeof(FormationDTO), description: "Formation créée avec succès")] [SwaggerResponse(statusCode: 201, type: typeof(FormationDTO), description: "Formation créée avec succès")]
@ -47,29 +68,57 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")] [SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult AddFormation([FromBody]FormationDTO body) public virtual async Task<IActionResult> AddFormation([FromBody] FormationDTO body)
{ {
//TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(201, default(FormationDTO)); logger.LogInformation("Ajout d'une nouvelle formation.");
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(401, default(ErreurDTO)); {
body = await formationService.AddFormationAsync(body);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... }
// return StatusCode(403, default(ErreurDTO)); catch (FormationInvalidException e)
{
//TODO: Uncomment the next line to return response 415 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(415, default(ErreurDTO)); logger.LogInformation(e.Message);
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(500, default(ErreurDTO)); {
string exampleJson = null; Code = StatusCodes.Status500InternalServerError,
exampleJson = "{\n \"heure\" : 1,\n \"participations\" : [ {\n \"estEvaluee\" : true,\n \"dateCreation\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"id\" : 7,\n \"intitule\" : \"intitule\"\n }, {\n \"estEvaluee\" : true,\n \"dateCreation\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"id\" : 7,\n \"intitule\" : \"intitule\"\n } ],\n \"organisme\" : \"organisme\",\n \"origine\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n },\n \"estCertifiee\" : true,\n \"type\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n },\n \"intitule\" : \"intitule\",\n \"mode\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n },\n \"jour\" : 1,\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"estRealisee\" : true,\n \"id\" : 3,\n \"dateFin\" : \"2000-01-23T04:56:07.000+00:00\",\n \"idAgence\" : 7,\n \"statut\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n }\n}"; Message = e.Message,
};
var example = exampleJson != null
? JsonConvert.DeserializeObject<FormationDTO>(exampleJson) return StatusCode(erreur.Code.Value, erreur.Message);
: default(FormationDTO); //TODO: Change the data returned }
return new ObjectResult(example); catch (DbUpdateException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur est survenue sur le serveur lors de l'ajout de la formation.",
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (Exception e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur.",
};
return StatusCode(erreur.Code.Value, erreur);
}
if (env.IsDevelopment())
logger.LogInformation("Nouvelle formation ajoutée.");
return Created("", body);
} }
/// <summary> /// <summary>
@ -84,31 +133,76 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpDelete] [HttpDelete]
[Route("/api/formations/{idFormation}")] [Route("/api/formations/{idFormation}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("DeleteFormation")] [SwaggerOperation("DeleteFormation")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult DeleteFormation([FromRoute][Required]long? idFormation) public virtual async Task<IActionResult> DeleteFormation([FromRoute][Required] long idFormation)
{ {
//TODO: Uncomment the next line to return response 204 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(204); {
if (env.IsDevelopment())
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Suppresion de la formation {idFormation}.", idFormation);
// return StatusCode(401, default(ErreurDTO));
FormationDTO formation = await formationService.DeleteFormationByIdAsync(idFormation);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... }
// return StatusCode(403, default(ErreurDTO)); catch (FormationNotFoundException e)
{
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(404, default(ErreurDTO)); logger.LogInformation(e.Message);
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(500, default(ErreurDTO)); {
Code = StatusCodes.Status404NotFound,
throw new NotImplementedException(); Message = e.Message
};
return NotFound(erreur);
}
catch (DbUpdateConcurrencyException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = string.Format("La formation {0} n'a pas pu être supprimée car elle est prise par une autre ressource.", idFormation)
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (DbUpdateException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur est survenue sur le serveur lors de la suppression de la formation."
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (Exception e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
return StatusCode(erreur.Code.Value, erreur);
}
if (env.IsDevelopment())
logger.LogInformation("Formation {idFormation} supprimée avec succès.", idFormation);
return NoContent();
} }
/// <summary> /// <summary>
@ -123,7 +217,7 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/formations/{idFormation}")] [Route("/api/formations/{idFormation}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetFormationById")] [SwaggerOperation("GetFormationById")]
[SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")]
@ -131,29 +225,47 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetFormationById([FromRoute][Required]long? idFormation) public virtual async Task<IActionResult> GetFormationById([FromRoute][Required] long idFormation)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(FormationDTO)); logger.LogInformation("Récupération de la formation {idFormation}.", idFormation);
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... FormationDTO formationDTO;
// return StatusCode(401, default(ErreurDTO));
try
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... {
// return StatusCode(403, default(ErreurDTO)); formationDTO = await formationService.GetFormationByIdAsync(idFormation);
}
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... catch (FormationNotFoundException e)
// return StatusCode(404, default(ErreurDTO)); {
if (env.IsDevelopment())
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation(e.Message);
// return StatusCode(500, default(ErreurDTO));
string exampleJson = null; ErreurDTO erreurDTO = new ErreurDTO()
exampleJson = "{\n \"heure\" : 1,\n \"participations\" : [ {\n \"estEvaluee\" : true,\n \"dateCreation\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"id\" : 7,\n \"intitule\" : \"intitule\"\n }, {\n \"estEvaluee\" : true,\n \"dateCreation\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"id\" : 7,\n \"intitule\" : \"intitule\"\n } ],\n \"organisme\" : \"organisme\",\n \"origine\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n },\n \"estCertifiee\" : true,\n \"type\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n },\n \"intitule\" : \"intitule\",\n \"mode\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n },\n \"jour\" : 1,\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"estRealisee\" : true,\n \"id\" : 3,\n \"dateFin\" : \"2000-01-23T04:56:07.000+00:00\",\n \"idAgence\" : 7,\n \"statut\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n }\n}"; {
Code = StatusCodes.Status404NotFound,
var example = exampleJson != null Message = e.Message
? JsonConvert.DeserializeObject<FormationDTO>(exampleJson) };
: default(FormationDTO); //TODO: Change the data returned
return new ObjectResult(example); return NotFound(erreurDTO);
}
catch (Exception e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
return StatusCode(erreur.Code.Value, erreur);
}
if (env.IsDevelopment())
logger.LogInformation("Formation {idFormation} récupérée.", idFormation);
return Ok(formationDTO);
} }
/// <summary> /// <summary>
@ -175,33 +287,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/formations")] [Route("/api/formations")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetFormations")] [SwaggerOperation("GetFormations")]
[SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetFormations([FromQuery]long? idAgence, [FromQuery]List<int?> idStatuts, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri, [FromQuery]DateTime? dateDebut, [FromQuery]DateTime? dateFin) public virtual async Task<IActionResult> GetFormations([FromQuery] long? idAgence, [FromQuery] List<int?> idStatuts, [FromQuery] bool? asc, [FromQuery] int? numPage, [FromQuery][Range(5, 100)][DefaultValue(15)] int? parPAge, [FromQuery] string texte, [FromQuery] string tri, [FromQuery] DateTime? dateDebut, [FromQuery] DateTime? dateFin)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<FormationDetailsDTO>)); logger.LogInformation("Récupération de la liste des formations.");
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable<FormationDetailsDTO> formations;
// return StatusCode(401, default(ErreurDTO));
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(403, default(ErreurDTO)); {
formations = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin);
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(500, default(ErreurDTO)); {
string exampleJson = null; Code = StatusCodes.Status500InternalServerError,
exampleJson = "[ {\n \"nbParticipations\" : 6,\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"organisme\" : \"organisme\",\n \"id\" : 0,\n \"dateFin\" : \"2000-01-23T04:56:07.000+00:00\",\n \"origine\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n },\n \"estCertifiee\" : true,\n \"intitule\" : \"intitule\",\n \"statut\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n }\n}, {\n \"nbParticipations\" : 6,\n \"dateDebut\" : \"2000-01-23T04:56:07.000+00:00\",\n \"organisme\" : \"organisme\",\n \"id\" : 0,\n \"dateFin\" : \"2000-01-23T04:56:07.000+00:00\",\n \"origine\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n },\n \"estCertifiee\" : true,\n \"intitule\" : \"intitule\",\n \"statut\" : {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n }\n} ]"; Message = "Une erreur inconnue est survenue sur le serveur."
};
var example = exampleJson != null return StatusCode(erreur.Code.Value, erreur);
? JsonConvert.DeserializeObject<List<FormationDetailsDTO>>(exampleJson) }
: default(List<FormationDetailsDTO>); //TODO: Change the data returned
return new ObjectResult(example); if (env.IsDevelopment())
logger.LogInformation("Liste des formations récupérée.");
return Ok(formations);
} }
/// <summary> /// <summary>
@ -223,33 +343,42 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/formations/count")] [Route("/api/formations/count")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetFormationsCount")] [SwaggerOperation("GetFormationsCount")]
[SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetFormationsCount([FromQuery]long? idAgence, [FromQuery]List<int?> idStatuts, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri, [FromQuery]DateTime? dateDebut, [FromQuery]DateTime? dateFin) public virtual async Task<IActionResult> GetFormationsCount([FromQuery] long? idAgence, [FromQuery] List<int?> idStatuts, [FromQuery] int? numPage, [FromQuery][Range(5, 100)][DefaultValue(15)] int? parPAge, [FromQuery] string texte, [FromQuery] DateTime? dateDebut, [FromQuery] DateTime? dateFin)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(long?)); logger.LogInformation("Récupération du nombre total de formations.");
long count;
try
{
count = await formationService.GetFormationsCountAsync(idAgence, idStatuts, numPage, parPAge, texte, dateDebut, dateFin);
}
catch (Exception e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(401, default(ErreurDTO)); }
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(403, default(ErreurDTO)); logger.LogInformation("Nombre total de formations récupéré.");
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return Ok(count);
// return StatusCode(500, default(ErreurDTO));
string exampleJson = null;
exampleJson = "0";
var example = exampleJson != null
? JsonConvert.DeserializeObject<long?>(exampleJson)
: default(long?); //TODO: Change the data returned
return new ObjectResult(example);
} }
/// <summary> /// <summary>
@ -262,33 +391,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/modesformation")] [Route("/api/modesformation")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetModesFormation")] [SwaggerOperation("GetModesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<ModeFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<ModeFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetModesFormation() public virtual async Task<IActionResult> GetModesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<ModeFormationDTO>)); logger.LogInformation("Récupération de la liste des modes de formation.");
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable<ModeFormationDTO> modeFormations;
// return StatusCode(401, default(ErreurDTO));
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(403, default(ErreurDTO)); {
modeFormations = await formationService.GetModesFormationAsync();
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(500, default(ErreurDTO)); {
string exampleJson = null; Code = StatusCodes.Status500InternalServerError,
exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n} ]"; Message = "Une erreur inconnue est survenue sur le serveur."
};
var example = exampleJson != null return StatusCode(erreur.Code.Value, erreur);
? JsonConvert.DeserializeObject<List<ModeFormationDTO>>(exampleJson) }
: default(List<ModeFormationDTO>); //TODO: Change the data returned
return new ObjectResult(example); if (env.IsDevelopment())
logger.LogInformation("Liste des modes de formation récupérée.");
return Ok(modeFormations);
} }
/// <summary> /// <summary>
@ -301,33 +438,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/originesformation")] [Route("/api/originesformation")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetOriginesFormation")] [SwaggerOperation("GetOriginesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<OrigineFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<OrigineFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetOriginesFormation() public virtual async Task<IActionResult> GetOriginesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<OrigineFormationDTO>)); logger.LogInformation("Récupération de la liste des origines de formation.");
IEnumerable<OrigineFormationDTO> origineFormations;
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(401, default(ErreurDTO)); {
origineFormations = await formationService.GetOriginesFormationAsync();
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(403, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(500, default(ErreurDTO)); }
string exampleJson = null;
exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 2\n} ]";
var example = exampleJson != null if (env.IsDevelopment())
? JsonConvert.DeserializeObject<List<OrigineFormationDTO>>(exampleJson) logger.LogInformation("Liste des origines de formation récupérée.");
: default(List<OrigineFormationDTO>); //TODO: Change the data returned
return new ObjectResult(example); return Ok(origineFormations);
} }
/// <summary> /// <summary>
@ -340,33 +485,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/statutsformation")] [Route("/api/statutsformation")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetStatutsFormation")] [SwaggerOperation("GetStatutsFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<StatutFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<StatutFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetStatutsFormation() public virtual async Task<IActionResult> GetStatutsFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<StatutFormationDTO>)); logger.LogInformation("Récupération de la liste des statuts de formation.");
IEnumerable<StatutFormationDTO> statutFormations;
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(401, default(ErreurDTO)); {
statutFormations = await formationService.GetStatutsFormationAsync();
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(403, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(500, default(ErreurDTO)); }
string exampleJson = null;
exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 4\n} ]";
var example = exampleJson != null if (env.IsDevelopment())
? JsonConvert.DeserializeObject<List<StatutFormationDTO>>(exampleJson) logger.LogInformation("Liste des statuts de formation récupérée.");
: default(List<StatutFormationDTO>); //TODO: Change the data returned
return new ObjectResult(example); return Ok(statutFormations);
} }
/// <summary> /// <summary>
@ -379,33 +532,41 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpGet] [HttpGet]
[Route("/api/typesformation")] [Route("/api/typesformation")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetTypesFormation")] [SwaggerOperation("GetTypesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<TypeFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<TypeFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "L’utilisateur souhaitant accéder à la ressource n’a pas les droits d’accès suffisants")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult GetTypesFormation() public virtual async Task<IActionResult> GetTypesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200, default(List<TypeFormationDTO>)); logger.LogInformation("Récupération de la liste des types de formation.");
IEnumerable<TypeFormationDTO> typeFormations;
try
{
typeFormations = await formationService.GetTypesFormationAsync();
}
catch (Exception e)
{
logger.LogError(e.Message);
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(401, default(ErreurDTO)); {
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return StatusCode(erreur.Code.Value, erreur);
// return StatusCode(403, default(ErreurDTO)); }
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(500, default(ErreurDTO)); logger.LogInformation("Liste des types de formation récupérée.");
string exampleJson = null;
exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n} ]";
var example = exampleJson != null return Ok(typeFormations);
? JsonConvert.DeserializeObject<List<TypeFormationDTO>>(exampleJson)
: default(List<TypeFormationDTO>); //TODO: Change the data returned
return new ObjectResult(example);
} }
/// <summary> /// <summary>
@ -422,7 +583,7 @@ namespace IO.Swagger.Controllers
/// <response code="500">Une erreur est survenue sur le serveur</response> /// <response code="500">Une erreur est survenue sur le serveur</response>
[HttpPut] [HttpPut]
[Route("/api/formations/{idFormation}")] [Route("/api/formations/{idFormation}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("UpdateFormation")] [SwaggerOperation("UpdateFormation")]
[SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L&#x27;utilisateur souhaitant accéder à la ressource n&#x27;est pas authentifié")]
@ -430,27 +591,95 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n&#x27;a pas été trouvée")]
[SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")] [SwaggerResponse(statusCode: 415, type: typeof(ErreurDTO), description: "L’opération ne peut pas être effectuée car certaines données sont manquantes")]
[SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")]
public virtual IActionResult UpdateFormation([FromBody]FormationDTO body, [FromRoute][Required]long? idFormation) public virtual async Task<IActionResult> UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long idFormation)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(200); logger.LogInformation("Mise à jour de la formation d'id {idFormation}.", idFormation);
//TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... try
// return StatusCode(401, default(ErreurDTO)); {
body = await formationService.UpdateFormationAsync(idFormation, body);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... }
// return StatusCode(403, default(ErreurDTO)); catch (FormationIncompatibleIdException e)
{
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... if (env.IsDevelopment())
// return StatusCode(404, default(ErreurDTO)); logger.LogInformation(e.Message);
//TODO: Uncomment the next line to return response 415 or use other options such as return this.NotFound(), return this.BadRequest(..), ... ErreurDTO erreur = new ErreurDTO()
// return StatusCode(415, default(ErreurDTO)); {
Code = StatusCodes.Status415UnsupportedMediaType,
//TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... Message = e.Message,
// return StatusCode(500, default(ErreurDTO)); };
throw new NotImplementedException(); return StatusCode(erreur.Code.Value, erreur.Message);
}
catch (FormationInvalidException e)
{
if (env.IsDevelopment())
logger.LogInformation(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status415UnsupportedMediaType,
Message = e.Message,
};
return StatusCode(erreur.Code.Value, erreur.Message);
}
catch (FormationNotFoundException e)
{
if (env.IsDevelopment())
logger.LogInformation(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status404NotFound,
Message = e.Message
};
return NotFound(erreur);
}
catch (DbUpdateConcurrencyException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = string.Format("La formation {0} n'a pas pu être supprimée car elle est prise par une autre ressource.", idFormation)
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (DbUpdateException e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur est survenue sur le serveur lors de la suppression de la formation."
};
return StatusCode(erreur.Code.Value, erreur);
}
catch (Exception e)
{
logger.LogError(e.Message);
ErreurDTO erreur = new ErreurDTO()
{
Code = StatusCodes.Status500InternalServerError,
Message = "Une erreur inconnue est survenue sur le serveur."
};
return StatusCode(erreur.Code.Value, erreur);
}
if (env.IsDevelopment())
logger.LogInformation("Update effectué avec succès");
return Ok(body);
} }
} }
} }

@ -92,8 +92,8 @@ namespace IO.Swagger.DTO
/// </summary> /// </summary>
/// <value>Indique si la formation est certifiée ou non</value> /// <value>Indique si la formation est certifiée ou non</value>
[Required] [Required]
[DataMember(Name="estCertifie")] [DataMember(Name="estCertifiee")]
public bool? EstCertifie { get; set; } public bool? EstCertifiee { get; set; }
/// <summary> /// <summary>
/// Returns the string presentation of the object /// Returns the string presentation of the object
@ -111,7 +111,7 @@ namespace IO.Swagger.DTO
sb.Append(" Organisme: ").Append(Organisme).Append("\n"); sb.Append(" Organisme: ").Append(Organisme).Append("\n");
sb.Append(" NbParticipations: ").Append(NbParticipations).Append("\n"); sb.Append(" NbParticipations: ").Append(NbParticipations).Append("\n");
sb.Append(" Origine: ").Append(Origine).Append("\n"); sb.Append(" Origine: ").Append(Origine).Append("\n");
sb.Append(" EstCertifie: ").Append(EstCertifie).Append("\n"); sb.Append(" EstCertifie: ").Append(EstCertifiee).Append("\n");
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
@ -189,9 +189,9 @@ namespace IO.Swagger.DTO
Origine.Equals(other.Origine) Origine.Equals(other.Origine)
) && ) &&
( (
EstCertifie == other.EstCertifie || EstCertifiee == other.EstCertifiee ||
EstCertifie != null && EstCertifiee != null &&
EstCertifie.Equals(other.EstCertifie) EstCertifiee.Equals(other.EstCertifiee)
); );
} }
@ -221,8 +221,8 @@ namespace IO.Swagger.DTO
hashCode = hashCode * 59 + NbParticipations.GetHashCode(); hashCode = hashCode * 59 + NbParticipations.GetHashCode();
if (Origine != null) if (Origine != null)
hashCode = hashCode * 59 + Origine.GetHashCode(); hashCode = hashCode * 59 + Origine.GetHashCode();
if (EstCertifie != null) if (EstCertifiee != null)
hashCode = hashCode * 59 + EstCertifie.GetHashCode(); hashCode = hashCode * 59 + EstCertifiee.GetHashCode();
return hashCode; return hashCode;
} }
} }

@ -7,10 +7,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.7" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.21" /> <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.21" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="RestSharp" Version="106.11.4" /> <PackageReference Include="RestSharp" Version="106.11.4" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" /> <PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />

@ -39,7 +39,7 @@ namespace IO.Swagger.Enum
[EnumMember(Value = "DatesProposees")] [EnumMember(Value = "DatesProposees")]
DatesProposees = 3, DatesProposees = 3,
/// <summary> /// <summary>
/// Indique qu’il s’agit d’un EPS /// Le collaborateur a choisi une date, il ne reste plus qu'à attendre l'entretien
/// </summary> /// </summary>
[EnumMember(Value = "AttenteEntretien")] [EnumMember(Value = "AttenteEntretien")]
AttenteEntretien = 4, AttenteEntretien = 4,

@ -5,10 +5,10 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsque l'id de l'engagement avec les données à mettre à jour et l'id de l'engagement à mettre sont différents /// Exception qui est levée lorsque l'id de l'engagement avec les données à mettre à jour et l'id de l'engagement à mettre sont différents
/// </summary> /// </summary>
public class EngagementIncompatibleIdException : Exception public class EngagementIncompatibleIdException : Exception
{ {
/// <summary> /// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementIncompatibleIdException"/> class. /// Initialise une nouvelle instance de la classe <see cref="EngagementIncompatibleIdException"/> class.

@ -5,10 +5,10 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'un engagement est invalide /// Exception qui est levée lorsqu'un engagement est invalide
/// </summary> /// </summary>
public class EngagementInvalidException : Exception public class EngagementInvalidException : Exception
{ {
/// <summary> /// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementInvalidException"/> class. /// Initialise une nouvelle instance de la classe <see cref="EngagementInvalidException"/> class.

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'un engagement n'a pas été trouvé /// Exception qui est levée lorsqu'un engagement n'a pas été trouvé
/// </summary> /// </summary>
public class EngagementNotFoundException : Exception public class EngagementNotFoundException : Exception
{ {

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsque l'id de la formation avec les données à mettre à jour et l'id de la formation dans la base de données sont différents /// Exception qui est levée lorsque l'id de la formation avec les données à mettre à jour et l'id de la formation dans la base de données sont différents
/// </summary> /// </summary>
public class FormationIncompatibleIdException : Exception public class FormationIncompatibleIdException : Exception
{ {

@ -5,10 +5,10 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'une formation est invalide /// Exception qui est levée lorsqu'une formation est invalide
/// </summary> /// </summary>
public class FormationInvalidException : Exception public class FormationInvalidException : Exception
{ {
/// <summary> /// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationInvalidException"/> class. /// Initialise une nouvelle instance de la classe <see cref="FormationInvalidException"/> class.

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'une formation n'a pas été trouvée /// Exception qui est levée lorsqu'une formation n'a pas été trouvée
/// </summary> /// </summary>
public class FormationNotFoundException : Exception public class FormationNotFoundException : Exception
{ {

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'un mode de formation n'a pas été trouvé /// Exception qui est levée lorsqu'un mode de formation n'a pas été trouvé
/// </summary> /// </summary>
public class ModeFormationNotFoundException : Exception public class ModeFormationNotFoundException : Exception
{ {

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'une origine de formation n'a pas été trouvée /// Exception qui est levée lorsqu'une origine de formation n'a pas été trouvée
/// </summary> /// </summary>
public class OrigineFormationNotFoundException : Exception public class OrigineFormationNotFoundException : Exception
{ {

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'un statut de formation n'a pas été trouvé /// Exception qui est levée lorsqu'un statut de formation n'a pas été trouvé
/// </summary> /// </summary>
public class StatutFormationNotFoundException : Exception public class StatutFormationNotFoundException : Exception
{ {

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace EPAServeur.Exceptions namespace EPAServeur.Exceptions
{ {
/// <summary> /// <summary>
/// Exception à jeter lorsqu'un type de formation n'a pas été trouvé /// Exception qui est levée lorsqu'un type de formation n'a pas été trouvé
/// </summary> /// </summary>
public class TypeFormationNotFoundException : Exception public class TypeFormationNotFoundException : Exception
{ {

@ -1,5 +1,6 @@
using EPAServeur.Context; using EPAServeur.Context;
using IO.Swagger.DTO; using IO.Swagger.DTO;
using IO.Swagger.Enum;
using IO.Swagger.ModelCollaborateur; using IO.Swagger.ModelCollaborateur;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -10,16 +11,8 @@ namespace EPAServeur.IServices
{ {
public interface IEngagementService public interface IEngagementService
{ {
Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(List<long> idBUs, List<EtatEngagement> etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri);
IEnumerable<EngagementDTO> GetEngagements(bool? asc, int? numPage, int? parPAge, string texte, string tri); Task<long> GetEngagementsCountAsync(List<long> idBUs, List<EtatEngagement> etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri); Task<EngagementDTO> RepondreEngagementAsync(EngagementDTO engagement, long idEngagement);
IEnumerable<EngagementDTO> GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri);
IEnumerable<EngagementDTO> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri);
EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement);
Task<EngagementDTO> RepondreEngagementAsync(EngagementDTO engagement, long? idEngagement);
} }
} }

@ -10,31 +10,17 @@ namespace EPAServeur.IServices
{ {
public interface IFormationService public interface IFormationService
{ {
FormationDTO GetFormationById(long? idFormation); Task<FormationDTO> GetFormationByIdAsync(long idFormation);
Task<FormationDTO> GetFormationByIdAsync(long? idFormation); Task<IEnumerable<FormationDetailsDTO>> GetFormationsAsync(long? idAgence, List<int?> idStatuts, bool? asc, int? numPage, int? parPage, string texte, string tri, DateTime? dateDebut, DateTime? dateFin);
IEnumerable<FormationDTO> GetFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri); Task<long> GetFormationsCountAsync(long? idAgence, List<int?> idStatuts, int? numPage, int? parPage, string texte, DateTime? dateDebut, DateTime? dateFin);
Task<IEnumerable<FormationDTO>> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri);
IEnumerable<FormationDTO> GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
IEnumerable<FormationDTO> GetFormationRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetFormationRealiseesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
IEnumerable<FormationDTO> GetProchainesFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
IEnumerable<ModeFormationDTO> GetModesFormation();
Task<IEnumerable<ModeFormationDTO>> GetModesFormationAsync(); Task<IEnumerable<ModeFormationDTO>> GetModesFormationAsync();
IEnumerable<OrigineFormationDTO> GetOriginesFormation();
Task<IEnumerable<OrigineFormationDTO>> GetOriginesFormationAsync(); Task<IEnumerable<OrigineFormationDTO>> GetOriginesFormationAsync();
IEnumerable<StatutFormationDTO> GetStatutsFormation();
Task<IEnumerable<StatutFormationDTO>> GetStatutsFormationAsync(); Task<IEnumerable<StatutFormationDTO>> GetStatutsFormationAsync();
IEnumerable<TypeFormationDTO> GetTypesFormation();
Task<IEnumerable<TypeFormationDTO>> GetTypesFormationAsync(); Task<IEnumerable<TypeFormationDTO>> GetTypesFormationAsync();
FormationDTO AddFormation(FormationDTO formationDTO);
Task<FormationDTO> AddFormationAsync(FormationDTO formationDTO); Task<FormationDTO> AddFormationAsync(FormationDTO formationDTO);
FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO); Task<FormationDTO> UpdateFormationAsync(long idFormation, FormationDTO formationDTO);
Task<FormationDTO> UpdateFormationAsync(long? idFormation, FormationDTO formationDTO); Task<FormationDTO> DeleteFormationByIdAsync(long idFormation);
FormationDTO DeleteFormationById(long? idFormation);
Task<FormationDTO> DeleteFormationByIdAsync(long? idFormation);
} }
} }

@ -80,5 +80,10 @@ namespace EPAServeur.Models.Formation
/// Type de formation qui est lié à la formation /// Type de formation qui est lié à la formation
/// </summary> /// </summary>
public TypeFormation TypeFormation { get; set; } public TypeFormation TypeFormation { get; set; }
/// <summary>
/// Liste des participations qui sont liées à la formation
/// </summary>
public List<ParticipationFormation> ParticipationsFormation { get; set; }
} }
} }

@ -2,15 +2,11 @@
using EPAServeur.Exceptions; using EPAServeur.Exceptions;
using EPAServeur.IServices; using EPAServeur.IServices;
using EPAServeur.Models.EP; using EPAServeur.Models.EP;
using EPAServeur.Models.Formation;
using EPAServeur.Models.SaisieChamp;
using IO.Swagger.DTO; using IO.Swagger.DTO;
using IO.Swagger.Enum; using IO.Swagger.Enum;
using IO.Swagger.ModelCollaborateur;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -20,9 +16,42 @@ namespace EPAServeur.Services
{ {
#region Variables #region Variables
/// <summary>
/// Accès et gestion de la base de données
/// </summary>
private readonly EpContext epContext; private readonly EpContext epContext;
/// <summary>
/// Accès et service collaborateur
/// </summary>
private readonly ICollaborateurService collaborateurService; private readonly ICollaborateurService collaborateurService;
private readonly IReferentEPService referentService;
/// <summary>
/// Nombre d'éléments min à afficher par page
/// </summary>
private readonly int minParPage = 5;
/// <summary>
/// Nom d'éléments max à affichar par page
/// </summary>
private readonly int maxParPage = 100;
/// <summary>
/// Nombre d'éléments à afficher par défaut par page
/// </summary>
private readonly int defaultParPage = 15;
/// <summary>
/// Numéro de page min à afficher par défaut
/// </summary>
private readonly int defaultNumPage = 1;
/// <summary>
/// Ordonnancement par défaut
/// </summary>
private readonly bool defaultAsc = true;
#endregion #endregion
#region Contructeurs #region Contructeurs
@ -31,260 +60,270 @@ namespace EPAServeur.Services
/// Constructeur de la classe EngagementService /// Constructeur de la classe EngagementService
/// </summary> /// </summary>
/// <param name="_epContext"></param> /// <param name="_epContext"></param>
public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService, IReferentEPService _referentService) public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService)
{ {
epContext = _epContext; epContext = _epContext;
collaborateurService = _collaborateurService; collaborateurService = _collaborateurService;
referentService = _referentService;
} }
#endregion #endregion
#region Méthodes Service #region Méthodes Service
public IEnumerable<EngagementDTO> GetEngagements(bool? asc, int? numPage, int? parPAge, string texte, string tri) /// <summary>
/// Récupérer la liste des engagements de manière asynchrone
/// </summary>
/// <param name="etatsEngagement"></param>
/// <param name="idBUs"></param>
/// <param name="asc"></param>
/// <param name="numPage"></param>
/// <param name="parPage"></param>
/// <param name="texte"></param>
/// <param name="tri"></param>
/// <returns></returns>
public async Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(List<long> idBUs, List<EtatEngagement> etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri)
{ {
IQueryable<Engagement> query;
IEnumerable<Engagement> engagements; IEnumerable<Engagement> engagements;
IEnumerable<EngagementDTO> engagementDTOs;
IEnumerable<CollaborateurDTO> collaborateurDTOs;
if (texte == null) query = epContext.Engagement.Include(engagement => engagement.Ep);
texte = ""; query = IdBUsFilter(query, idBUs);
else query = EtatsEngagementFilter(query, etatsEngagement);
texte = texte.ToLower(); query = ActionFilter(query, texte);
query = OrderByColumn(query, asc, tri);
int skip = (numPage.Value - 1) * parPAge.Value; query = SkipAndTake(query, parPage, numPage);
int take = parPAge.Value;
engagements = epContext.Engagement.Include(engagement => engagement.Ep).Skip(skip).Take(take); engagements = await query.ToListAsync();
if (engagements == null || engagements.Count() == 0) collaborateurDTOs = await GetCollaborateurDTOs(engagements);
return new List<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); engagementDTOs = engagements.Select(engagement => GetEngagementDTO(engagement, collaborateurDTOs));
return engagementDTOs; return engagementDTOs;
} }
public async Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) public async Task<long> GetEngagementsCountAsync(List<long> idBUs, List<EtatEngagement> etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri)
{ {
IEnumerable<Engagement> engagements; IQueryable<Engagement> query;
long count;
if (texte == null)
texte = "";
else
texte = texte.ToLower();
int skip = (numPage.Value - 1) * parPAge.Value;
int take = parPAge.Value;
engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Skip(skip).Take(take).ToListAsync();
if (engagements == null || engagements.Count() == 0) query = epContext.Engagement.Include(engagement => engagement.Ep);
return new List<EngagementDTO>(); query = IdBUsFilter(query, idBUs);
query = EtatsEngagementFilter(query, etatsEngagement);
query = ActionFilter(query, texte);
query = OrderByColumn(query, asc, tri);
query = SkipAndTake(query, parPage, numPage);
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); count = await query.CountAsync();
var results = await Task.WhenAll(engagementDTOs);
return results; return count;
} }
public IEnumerable<EngagementDTO> GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, string texte, string tri) /// <summary>
/// Donner une réponse à un engagement de manière asynchrone
/// </summary>
/// <param name="engagementDTO"></param>
/// <param name="idEngagement"></param>
/// <returns></returns>
public async Task<EngagementDTO> RepondreEngagementAsync(EngagementDTO engagementDTO, long idEngagement)
{ {
IEnumerable<Engagement> engagements; IEnumerable<CollaborateurDTO> collaborateurDTOs;
Engagement engagement;
if (texte == null)
texte = "";
else
texte = texte.ToLower();
int skip = (numPage.Value - 1) * parPAge.Value;
int take = parPAge.Value;
engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.EtatEngagement == EtatEngagement.EnAttente).Skip(skip).Take(take).ToList(); IsEngagementValide(engagementDTO);
if (engagements == null || engagements.Count() == 0) if (!engagementDTO.Id.HasValue || engagementDTO.Id.Value != idEngagement)
return new List<EngagementDTO>(); throw new EngagementIncompatibleIdException("L'id de l'engagement à mettre à jour et l'engagement à mettre à jour sont incompatible.");
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.IdEngagement == idEngagement);
return engagementDTOs;
}
public async Task<IEnumerable<EngagementDTO>> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) if (engagement == null)
{ throw new EngagementNotFoundException();
IEnumerable<Engagement> engagements;
if (texte == null)
texte = "";
else
texte = texte.ToLower();
int skip = (numPage.Value - 1) * parPAge.Value;
int take = parPAge.Value;
engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.EtatEngagement == EtatEngagement.EnAttente).Skip(skip).Take(take).ToListAsync(); collaborateurDTOs = await GetCollaborateurDTOs(engagement);
if (engagements == null || engagements.Count() == 0) engagement = SetReponseEngagement(engagement, engagementDTO);
return new List<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); await epContext.SaveChangesAsync();
var results = await Task.WhenAll(engagementDTOs);
return results; return GetEngagementDTO(engagement, collaborateurDTOs);
} }
public IEnumerable<EngagementDTO> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, string texte, string tri)
{
IEnumerable<Engagement> engagements;
if (texte == null) #endregion
texte = "";
else
texte = texte.ToLower();
int skip = (numPage.Value - 1) * parPAge.Value; #region Méthodes Privée
int take = parPAge.Value; /// <summary>
/// Vérifier si un objet EngagementDTO est valide pour ajout ou mise à jour
/// </summary>
/// <remarks> Un objet EngagementDTO est valide si l'action, le dispositif, la modalité et la date limite n'est pas null, si l'EP est signé, et si l'EP est présent dans la base de données.</remarks>
/// <param name="formation"></param>
/// <exception cref="EPAServeur.Exceptions.EngagementInvalidException"></exception>
private void IsEngagementValide(EngagementDTO engagementDTO)
{
// Vérifier que l'engagement n'est pas null
if (engagementDTO == null)
throw new EngagementInvalidException("Aucun engagement n'a été reçu.");
engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.EtatEngagement == EtatEngagement.Respecte && engagement.Modalite.ToLower().Contains(texte)).Skip(skip).Take(take); // Vérfier que l'engagement a bien un EP
if (engagementDTO.Ep == null || !engagementDTO.Ep.Id.HasValue)
throw new EngagementInvalidException("Impossible de répondre à un engagement sans EP.");
if (engagements == null || engagements.Count() == 0) // Vérfier que l'ep a bien été signé par le collaborateur
return new List<EngagementDTO>(); if (engagementDTO.Ep.Statut != StatutEp.Signe)
throw new EngagementInvalidException("Impossible de répondre à un engagement d'un EP qui n'est pas en cours et qui n'a pas été signé par le collaborateur.");
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); // Vérifier que l'engagement a bien une action
if (string.IsNullOrWhiteSpace(engagementDTO.Action))
throw new EngagementInvalidException("L'action de l'engagement doit contenir au moins 1 caractère.");
return engagementDTOs; // Vérifier que l'engagement a bien un dispositif
} if (string.IsNullOrWhiteSpace(engagementDTO.Dispositif))
throw new EngagementInvalidException("Le dispostif de l'engagement doit contenir au moins 1 caractère.");
public async Task<IEnumerable<EngagementDTO>> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) // Vérifier que l'engagement a bien une modalité
{ if (string.IsNullOrWhiteSpace(engagementDTO.Modalite))
IEnumerable<Engagement> engagements; throw new EngagementInvalidException("La modalité de l'engagement doit contenir au moins 1 caractère.");
if (texte == null)
texte = "";
else
texte = texte.ToLower();
int skip = (numPage.Value - 1) * parPAge.Value;
int take = parPAge.Value;
engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.EtatEngagement == EtatEngagement.Respecte && engagement.Modalite.ToLower().Contains(texte)).Skip(skip).Take(take).ToListAsync(); // Vérifier que l'engagement a bien une date limite
if (!engagementDTO.DateLimite.HasValue)
throw new EngagementInvalidException("Impossible de répondre à l'engagement sans date limite.");
if (engagements == null || engagements.Count() == 0) // Vérifier que l'engagement a bien raison expliquant pourquoi l'engagement n'est pas réalisable lorsque l'état de l'engagement n'est pas réalisable
return new List<EngagementDTO>(); if (engagementDTO.EtatEngagement == EtatEngagement.NonRealisable && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable))
throw new EngagementInvalidException("Impossible de répondre à l'engagement, une raison doit être rensignée lorsqu'un engagement n'est pas réalisé.");
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement));
var results = await Task.WhenAll(engagementDTOs);
return results; // Vérfier que l'EP lié à l'engagement est présent dans la BDD
if (!epContext.Ep.Any(ep => ep.IdEP == engagementDTO.Ep.Id.Value))
throw new EngagementInvalidException("L'EP n'existe pas.");
} }
/// <summary> /// <summary>
/// Donner une réponse à un engagement /// Ajouter un ordonnancement croissant ou décroissant sur colonne
/// </summary> /// </summary>
/// <param name="engagementDTO"></param> /// <param name="query"></param>
/// <param name="idEngagement"></param> /// <param name="idStatuts"></param>
/// <returns></returns> /// <returns></returns>
public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) private IQueryable<Engagement> OrderByColumn(IQueryable<Engagement> query, bool? asc, string columnName)
{ {
if (!asc.HasValue)
asc = defaultAsc;
if (!IsEngagementValide(engagementDTO)) if (string.IsNullOrWhiteSpace(columnName))
throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); {
if (asc.Value)
if (engagementDTO.EtatEngagement == EtatEngagement.NonRealisable && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) return query.OrderBy(p => p.Action);
throw new EngagementInvalidException("Impossible de répondre à l'engagement, une raison doit être rensignée lorsqu'un engagement n'est pas réalisé.");
if (engagementDTO == null && !engagementDTO.Id.HasValue && engagementDTO.Id.Value != idEngagement)
throw new EngagementIncompatibleIdException();
Engagement engagement = epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefault(engagement => engagement.IdEngagement == idEngagement);
if (engagement == null)
throw new EngagementNotFoundException();
engagement.EtatEngagement = engagementDTO.EtatEngagement; return query.OrderByDescending(p => p.Action);
}
switch (engagement.EtatEngagement) switch (columnName.ToLower())
{ {
case EtatEngagement.Respecte: case "action":
engagement.EtatEngagement = engagementDTO.EtatEngagement; if (asc.Value)
engagement.RaisonNonRealisable = null; return query.OrderBy(p => p.Action);
break;
case EtatEngagement.NonRealisable: return query.OrderByDescending(p => p.Action);
engagement.EtatEngagement = engagementDTO.EtatEngagement; case "dispositif":
engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; if (asc.Value)
break; return query.OrderBy(p => p.Dispositif);
return query.OrderByDescending(p => p.Dispositif);
case "modalite":
if (asc.Value)
return query.OrderBy(p => p.Modalite);
return query.OrderByDescending(p => p.Modalite);
case "date":
if (asc.Value)
return query.OrderBy(p => p.DateLimite);
return query.OrderByDescending(p => p.DateLimite);
default: default:
engagement.EtatEngagement = engagementDTO.EtatEngagement; if (asc.Value)
engagement.RaisonNonRealisable = null; return query.OrderBy(p => p.Action);
break;
return query.OrderByDescending(p => p.Action);
} }
}
epContext.SaveChanges(); /// <summary>
/// Ajouter un filtre pour récupérer les engagements en fonction de plusieurs identifiants de Business Unit
/// </summary>
/// <param name="query"></param>
/// <param name="idBUs"></param>
/// <returns></returns>
/// <exception cref="EPAServeur.Exceptions.EngagementInvalidException"></exception>
private IQueryable<Engagement> IdBUsFilter(IQueryable<Engagement> query, List<long> idBUs)
{
if (idBUs == null || idBUs.Count == 0)
throw new EngagementInvalidException("Aucune Business Unit n'a été reçu.");
return GetEngagementDTO(engagement); return query.Where(engagement => idBUs.Contains(engagement.Ep.IdBu));
} }
/// <summary> /// <summary>
/// Donner une réponse à un engagement de manière asynchrone /// Ajouter un filtre pour récupérer les engagements en fonction de plusieurs états d'engagement
/// </summary> /// </summary>
/// <param name="engagementDTO"></param> /// <param name="query"></param>
/// <param name="idEngagement"></param> /// <param name="idBUs"></param>
/// <returns></returns> /// <returns></returns>
public async Task<EngagementDTO> RepondreEngagementAsync(EngagementDTO engagementDTO, long? idEngagement) private IQueryable<Engagement> EtatsEngagementFilter(IQueryable<Engagement> query, List<EtatEngagement> etatsEngagement)
{ {
if (etatsEngagement == null || etatsEngagement.Count <= 0)
return query;
if (!IsEngagementValide(engagementDTO)) return query.Where(engagement => etatsEngagement.Contains(engagement.EtatEngagement));
throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); }
if (engagementDTO.EtatEngagement == EtatEngagement.NonRealisable && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) /// <summary>
throw new EngagementInvalidException("Impossible de répondre à l'engagement, une raison doit être rensignée lorsqu'un engagement n'est pas réalisé."); /// Ajouter un filtre pour récupérer les engagements en fonction d'une action
/// </summary>
/// <param name="query"></param>
/// <param name="intitule"></param>
/// <returns></returns>
private IQueryable<Engagement> ActionFilter(IQueryable<Engagement> query, string action)
{
if (string.IsNullOrWhiteSpace(action))
return query;
return query.Where(engagement => engagement.Action.ToLower().Contains(action.ToLower()));
}
Engagement engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.IdEngagement == idEngagement); /// <summary>
/// Ajouter une pagination
/// </summary>
/// <param name="query"></param>
/// <param name="parPage"></param>
/// <param name="numPage"></param>
/// <returns></returns>
private IQueryable<Engagement> SkipAndTake(IQueryable<Engagement> query, int? parPage, int? numPage)
{
int skip, take;
if (engagement == null) if (!parPage.HasValue || parPage.Value < minParPage || parPage.Value > maxParPage)
throw new EngagementNotFoundException(); parPage = defaultParPage;
engagement.EtatEngagement = engagementDTO.EtatEngagement; if (!numPage.HasValue || numPage.Value <= 0)
numPage = defaultNumPage;
switch (engagement.EtatEngagement) skip = (numPage.Value - 1) * parPage.Value;
{ take = parPage.Value;
case EtatEngagement.Respecte:
engagement.EtatEngagement = engagementDTO.EtatEngagement;
engagement.RaisonNonRealisable = null;
break;
case EtatEngagement.NonRealisable:
engagement.EtatEngagement = engagementDTO.EtatEngagement;
engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable;
break;
default:
engagement.EtatEngagement = engagementDTO.EtatEngagement;
engagement.RaisonNonRealisable = null;
break;
}
await epContext.SaveChangesAsync();
return await GetEngagementDTOAsync(engagement); return query.Skip(skip).Take(take);
} }
#endregion
#region Méthodes Privée
private bool IsEngagementValide(EngagementDTO engagementDTO)
{
return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DateLimite == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null);
}
#region Object to DTO #region Object to DTO
/// <summary> /// <summary>
/// Récupère un objet EngagementDTO en fonction d'un objet Engagement /// Récupère un objet EngagementDTO en fonction d'un objet Engagement et d'une liste de CollaborateurDTO
/// </summary> /// </summary>
/// <param name="engagement"></param> /// <param name="engagement"></param>
/// <returns></returns> /// <returns></returns>
private EngagementDTO GetEngagementDTO(Engagement engagement) private EngagementDTO GetEngagementDTO(Engagement engagement, IEnumerable<CollaborateurDTO> collaborateurDTOs)
{ {
EngagementDTO engagementDTO = new EngagementDTO() EngagementDTO engagementDTO = new EngagementDTO()
{ {
@ -295,80 +334,67 @@ namespace EPAServeur.Services
Modalite = engagement.Modalite, Modalite = engagement.Modalite,
RaisonNonRealisable = engagement.RaisonNonRealisable, RaisonNonRealisable = engagement.RaisonNonRealisable,
EtatEngagement = engagement.EtatEngagement, EtatEngagement = engagement.EtatEngagement,
Ep = GetEpInformationDTO(engagement.Ep) Ep = GetEpInformationDTO(engagement.Ep, collaborateurDTOs)
}; };
return engagementDTO; return engagementDTO;
} }
/// <summary> /// <summary>
/// Récupère un objet EngagementDTO en fonction d'un objet Engagement /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents. Retourne null si l'engagement est null.
/// </summary> /// </summary>
/// <param name="engagement"></param> /// <param name="typeFormation"></param>
/// <returns></returns> /// <returns></returns>
private async Task<EngagementDTO> GetEngagementDTOAsync(Engagement engagement) private async Task<IEnumerable<CollaborateurDTO>> GetCollaborateurDTOs(Engagement engagement)
{ {
EngagementDTO engagementDTO = new EngagementDTO() List<Guid?> guids = new List<Guid?>();
{
Id = engagement.IdEngagement,
Action = engagement.Action,
DateLimite = engagement.DateLimite,
Dispositif = engagement.Dispositif,
Modalite = engagement.Modalite,
RaisonNonRealisable = engagement.RaisonNonRealisable,
EtatEngagement = engagement.EtatEngagement,
Ep = await GetEpInformationDTOAsync(engagement.Ep)
};
return engagementDTO; guids.Add((Guid?)engagement.Ep.IdCollaborateur);
guids.Add(engagement.Ep.IdReferent);
return await collaborateurService.GetCollaborateurDTOsAsync(guids); ;
} }
/// <summary> /// <summary>
/// Récupère un objet EpInformationDTO en fonction d'un objet Ep /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents. Retourne null s'il n'y a aucun engagement.
/// </summary> /// </summary>
/// <param name="ep"></param> /// <param name="typeFormation"></param>
/// <returns></returns> /// <returns></returns>
private EpInformationDTO GetEpInformationDTO(Ep ep) private async Task<IEnumerable<CollaborateurDTO>> GetCollaborateurDTOs(IEnumerable<Engagement> engagements)
{ {
EpInformationDTO epInformationDTO = new EpInformationDTO() if (!engagements.Any())
{ return null;
Id = ep.IdEP,
Type = ep.TypeEP,
Statut = ep.Statut,
DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire,
//Collaborateur = collaborateurService.GetCollaborateurById(ep.IdCollaborateur),
//Referent = referentService.GetReferentById(ep.IdReferent)
//Ajouter la date de disponibilité
};
return epInformationDTO; List<Guid?> guids = engagements.SelectMany(engagement => new[] { (Guid?)engagement.Ep.IdCollaborateur, engagement.Ep.IdReferent }).ToList();
return await collaborateurService.GetCollaborateurDTOsAsync(guids);
} }
/// <summary> /// <summary>
/// Récupère un objet EpInformationDTO en fonction d'un objet Ep /// Récupère un objet EpInformationDTO en fonction d'un objet Ep et d'une liste de CollaborateurDTO
/// </summary> /// </summary>
/// <param name="ep"></param> /// <param name="ep"></param>
/// <returns></returns> /// <returns></returns>
private async Task<EpInformationDTO> GetEpInformationDTOAsync(Ep ep) private EpInformationDTO GetEpInformationDTO(Ep ep, IEnumerable<CollaborateurDTO> collaborateurDTOs)
{ {
CollaborateurDTO collaborateur;
CollaborateurDTO referent;
collaborateur = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdCollaborateur);
referent = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdReferent);
EpInformationDTO epInformationDTO = new EpInformationDTO() EpInformationDTO epInformationDTO = new EpInformationDTO()
{ {
Id = ep.IdEP, Id = ep.IdEP,
Type = ep.TypeEP, Type = ep.TypeEP,
Statut = ep.Statut, Statut = ep.Statut,
DateDisponibilite = ep.DateDisponibilite,
DatePrevisionnelle = ep.DatePrevisionnelle, DatePrevisionnelle = ep.DatePrevisionnelle,
Obligatoire = ep.Obligatoire Obligatoire = ep.Obligatoire,
//Ajouter la date de disponibilité Collaborateur = collaborateur,
Referent = referent,
}; };
var collaborateur = collaborateurService.GetCollaborateurByIdAsync(ep.IdCollaborateur);
var referent = collaborateurService.GetCollaborateurByIdAsync(ep.IdReferent);
await Task.WhenAll(collaborateur, referent);
epInformationDTO.Collaborateur = collaborateur.Result;
epInformationDTO.Referent = referent.Result;
return epInformationDTO; return epInformationDTO;
} }
@ -378,51 +404,31 @@ namespace EPAServeur.Services
#region DTO to Object #region DTO to Object
/// <summary> /// <summary>
/// Modifie un objet Engagement en fonction d'un objet FormationDTO /// Modifie la réponse d'un objet Engagement en fonction d'un objet EngagementDTO
/// </summary> /// </summary>
/// <param name="engagement"></param> /// <param name="engagement"></param>
/// <param name="engagementDTO"></param> /// <param name="engagementDTO"></param>
/// <returns></returns> /// <returns></returns>
private Engagement SetEngagement(Engagement engagement, EngagementDTO engagementDTO) private Engagement SetReponseEngagement(Engagement engagement, EngagementDTO engagementDTO)
{ {
engagement.Action = engagementDTO.Action;
engagement.DateLimite = engagementDTO.DateLimite.Value;
engagement.Dispositif = engagementDTO.Dispositif;
engagement.Modalite = engagementDTO.Modalite;
engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable;
engagement.EtatEngagement = engagementDTO.EtatEngagement; engagement.EtatEngagement = engagementDTO.EtatEngagement;
engagement.Ep = GetEp(engagementDTO.Ep);
switch (engagement.EtatEngagement)
return engagement;
}
/// <summary>
/// Récupère un objet Ep en fonction d'un objet EpDTO
/// </summary>
/// <param name="origineFormationDTO"></param>
/// <returns></returns>
private Ep GetEp(EpInformationDTO epInformationDTO)
{
if (epInformationDTO == null)
return null;
Ep ep = new Ep()
{ {
IdEP = epInformationDTO.Id.Value, case EtatEngagement.NonRealisable:
TypeEP = epInformationDTO.Type, engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable;
Statut = epInformationDTO.Statut, break;
DatePrevisionnelle = epInformationDTO.DatePrevisionnelle.Value, case EtatEngagement.DateLimitePassee:
Obligatoire = epInformationDTO.Obligatoire.Value, engagement.RaisonNonRealisable = "La date limite pour respecter l'engagement est passée.";
IdReferent = epInformationDTO.Referent.Id.Value, break;
IdCollaborateur = epInformationDTO.Collaborateur.Id.Value, default:
// Ajouter la date de disponibilité engagement.RaisonNonRealisable = null;
}; break;
}
return ep; return engagement;
} }
#endregion #endregion
#endregion #endregion

File diff suppressed because it is too large Load Diff

@ -42,7 +42,8 @@ namespace EPAServeur
}); });
}); });
services.AddControllers(); services.AddControllers().AddNewtonsoftJson();
services.AddAuthentication(options => services.AddAuthentication(options =>
{ {

Loading…
Cancel
Save