diff --git a/EPAServeur.Tests/Controllers/EngagementsApiTests.cs b/EPAServeur.Tests/Controllers/EngagementsApiTests.cs new file mode 100644 index 0000000..c2de69f --- /dev/null +++ b/EPAServeur.Tests/Controllers/EngagementsApiTests.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 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() + .UseInMemoryDatabase("server_ep_test") + .Options; + + services.AddDbContext(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(); + services.AddScoped(); + services.AddScoped(); + + // Récupère le service qui sera utilsé pour tester le contrôleur + var serviceProvider = services.BuildServiceProvider(); + engagementService = serviceProvider.GetService(); + + // Simule l'interface IWebHostEnvironment avec Moq + mockEnvironment = new Mock(); + + 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(), mockEnvironment.Object); + List idBUs = new List { 1, 2 }; + + // Act + var okResult = engagementsApiController.GetEngagements(idBUs, null, true, 1, 5, null, null); + + // Assert + Assert.IsInstanceOf(okResult.Result); + } + + [Test] + public void GetEngagements_PasseDesParamsPresentsDansLaBDD_RetourneLesCinqPremiersEngagements() + { + // Arrange + EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger(), mockEnvironment.Object); + List idBUs = new List { 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>(okResult.Value); + Assert.AreEqual(nbEngagement, (okResult.Value as IEnumerable).Count()); + Assert.AreEqual(idFirstEngagement, (okResult.Value as IEnumerable).First().Id); + Assert.AreEqual(idLastEngagement, (okResult.Value as IEnumerable).Last().Id); + } + + #endregion + + #region Tests GetEngagementsCount + + [Test] + public void GetEngagementsCount_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult() + { + // Arrange + EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger(), mockEnvironment.Object); + List idBUs = new List { 1, 2 }; + + // Act + var okResult = engagementsApiController.GetEngagementsCount(idBUs, null, true, 1, 5, null, null); + + // Assert + Assert.IsInstanceOf(okResult.Result); + } + + [Test] + public void GetEngagementsCount_PasseDesParamsPresentsDansLaBDD_RetourneLeBonNombreDEngagement() + { + // Arrange + EngagementsApiController engagementsApiController = new EngagementsApiController(engagementService, new NullLogger(), mockEnvironment.Object); + List idBUs = new List { 1, 2 }; + int nbEngagement = 5; + + // Act + var okResult = engagementsApiController.GetEngagementsCount(idBUs, null, true, 1, 5, null, null).Result as OkObjectResult; + + // Assert + Assert.IsInstanceOf(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(), 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.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(), 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.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(), 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.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(), 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.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(), 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(okObjectResult.Value); + Assert.AreEqual(reponse, (okObjectResult.Value as EngagementDTO).EtatEngagement); + } + + #endregion + + } +} \ No newline at end of file diff --git a/EPAServeur.Tests/Controllers/FormationApiTests.cs b/EPAServeur.Tests/Controllers/FormationApiTests.cs index bf8a76d..fb8ae37 100644 --- a/EPAServeur.Tests/Controllers/FormationApiTests.cs +++ b/EPAServeur.Tests/Controllers/FormationApiTests.cs @@ -13,6 +13,12 @@ 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; namespace EPAServeur.Tests.Controllers { @@ -21,9 +27,9 @@ namespace EPAServeur.Tests.Controllers { #region Variables - private FormationService formationService; - private readonly ILogger logger; - + private IFormationService formationService; + private Mock mockEnvironment; + private EpContext epContext; #endregion #region Setup @@ -31,12 +37,17 @@ namespace EPAServeur.Tests.Controllers [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() .UseInMemoryDatabase("server_ep_test") .Options; - EpContext epContext = new EpContext(optionBuider); + services.AddDbContext(b => b.UseInMemoryDatabase("server_ep_test")); + + epContext = new EpContext(optionBuider); epContext.Database.EnsureDeleted(); epContext.Database.EnsureCreated(); @@ -52,8 +63,21 @@ namespace EPAServeur.Tests.Controllers entity.State = EntityState.Detached; } - // Instanciation du service qui sera utilisé dans le controleur - formationService = new FormationService(epContext); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + // Récupère le service qui sera utilsé pour tester le contrôleur + var serviceProvider = services.BuildServiceProvider(); + formationService = serviceProvider.GetService(); + + // Simule l'interface IWebHostEnvironment avec Moq + mockEnvironment = new Mock(); + + mockEnvironment + .Setup(m => m.EnvironmentName) + .Returns("Development"); + } #endregion @@ -61,127 +85,521 @@ namespace EPAServeur.Tests.Controllers #region Tests GetFormationById [Test] - public void GetFormationById_PasseEnParamUnIdPresentDansLaBDD_RetourneUnObjetOkResult() + public void GetById_PasseEnParamUnIdInconnu_RetourneUnObjetNotFoundResult() { - //// Arrange - //FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger()); + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); - // // Act - // var okResult = formationsApiController.GetFormationById(1); + // Act + var notFoundResult = formationsApiController.GetFormationById(99999); - //// Assert - //Assert.IsInstanceOf(okResult.Result); + // Assert + Assert.IsInstanceOf(notFoundResult.Result); } - - #endregion + [Test] + public void GetFormationById_PasseEnParamUnIdConnu_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); - #region Tests GetFormations + // Act + var okResult = formationsApiController.GetFormationById(1); + + // Assert + Assert.IsInstanceOf(okResult.Result); + } - // Arrange - // Act + [Test] + public void GetFormationById_PasseEnParamUnIdConnu_RetourneLaBonneFormation() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + long idFormation = 1; - // Assert + // Act + var okResult = formationsApiController.GetFormationById(idFormation).Result as OkObjectResult; + // Assert + Assert.IsInstanceOf(okResult.Value); + Assert.AreEqual(idFormation, (okResult.Value as FormationDTO).Id); + } #endregion - #region Tests GetFormationAnnulees - - // Arrange + #region Tests GetFormations - // Act + [Test] + public void GetFormations_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + List idStatuts = new List { 1, 2, 3 }; - // Assert + // Act + var okResult = formationsApiController.GetFormations(1, idStatuts, true, 1, 5, "formation", null, null, null); - #endregion + // Assert + Assert.IsInstanceOf(okResult.Result); + } - #region Tests GetFormationRealisee + [Test] + public void GetFormations_PasseDesParamsPresentsDansLaBDD_RetourneLesCinqPremieresFormations() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + List idStatuts = new List { 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>(okResult.Value); + Assert.AreEqual(nbFormation, (okResult.Value as IEnumerable).Count()); + Assert.AreEqual(idFirstFormation, (okResult.Value as IEnumerable).First().Id); + Assert.AreEqual(idLastFormation, (okResult.Value as IEnumerable).Last().Id); + } - // Arrange + #endregion - // Act + #region Tests GetFormationsCount - // Assert + [Test] + public void GetFormationsCount_PasseDesParamsPresentsDansLaBDD_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + List idStatuts = new List { 1, 2, 3 }; - #endregion + // Act + var okResult = formationsApiController.GetFormationsCount(1, idStatuts, 1, 5, "formation", null, null); - #region Tests GetProchainesFormation + // Assert + Assert.IsInstanceOf(okResult.Result); + } - // Arrange + [Test] + public void GetFormationsCount_PasseDesParamsPresentsDansLaBDD_RetourneLeBonNombreDeFormation() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + List idStatuts = new List { 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(okResult.Value); + Assert.AreEqual(nbFormation, (long)okResult.Value); + } #endregion #region Tests GetModesFormation - // Arrange - // Act + [Test] + public void GetModesFormation_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + + // Act + var okResult = formationsApiController.GetModesFormation(); - // Assert + // Assert + Assert.IsInstanceOf(okResult.Result); + } + + [Test] + public void GetModesFormation_RetourneTousLesModes() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int nbModeFormation = 4; + // Act + var okResult = formationsApiController.GetModesFormation().Result as OkObjectResult; + + // Assert + Assert.IsInstanceOf>(okResult.Value); + Assert.AreEqual(nbModeFormation, (okResult.Value as IEnumerable).Count()); + } #endregion #region Tests GetOriginesFormation - // Arrange + [Test] + public void GetOriginesFormation_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); - // Act + // Act + var okResult = formationsApiController.GetOriginesFormation(); - // Assert + // Assert + Assert.IsInstanceOf(okResult.Result); + } + + [Test] + public void GetOriginesFormation_RetourneToutesLesOrigines() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int nbOrigineFormation = 4; + // Act + var okResult = formationsApiController.GetOriginesFormation().Result as OkObjectResult; + + // Assert + Assert.IsInstanceOf>(okResult.Value); + Assert.AreEqual(nbOrigineFormation, (okResult.Value as IEnumerable).Count()); + } #endregion #region Tests GetStatutsFormation - // Arrange + [Test] + public void GetStatusFormation_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + + // Act + var okResult = formationsApiController.GetStatutsFormation(); - // Act + // Assert + Assert.IsInstanceOf(okResult.Result); + } - // Assert + [Test] + public void GetStatutsFormation_RetourneTousLesStatuts() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int nbStatutFormation = 4; + // Act + var okResult = formationsApiController.GetStatutsFormation().Result as OkObjectResult; + + // Assert + Assert.IsInstanceOf>(okResult.Value); + Assert.AreEqual(nbStatutFormation, (okResult.Value as IEnumerable).Count()); + } #endregion #region Tests GetTypesFormation - // Arrange + [Test] + public void GetTypesFormation_RetourneUnObjetOkResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); - // Act + // Act + var okResult = formationsApiController.GetTypesFormation(); + + // Assert + Assert.IsInstanceOf(okResult.Result); + } - // Assert + [Test] + public void GetTypesFormation_RetourneTousLesTypes() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int nbTypeFormation = 4; + // Act + var okResult = formationsApiController.GetTypesFormation().Result as OkObjectResult; + + // Assert + Assert.IsInstanceOf>(okResult.Value); + Assert.AreEqual(nbTypeFormation, (okResult.Value as IEnumerable).Count()); + } #endregion #region Tests AddFormation - // Arrange + [Test] + public void AddFormation_AjouteUneFormationAvecDesObjetsEnfantsInvalides_RetourneUnObjetObjectResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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.Result); + } + + [Test] + public void AddFormation_AjouteUneFormationValide_RetourneUnObjetCreatedResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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.Result); + } - // Act + [Test] + public void AddFormation_AjouteUneFormationValide_RetourneLaFormationCreee() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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(createdResult.Value); + Assert.AreEqual("Test Formation", (createdResult.Value as FormationDTO).Intitule); + } #endregion #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(), 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.Result); + } + + [Test] + public async Task UpdateFormation_ModifieUneFormationAvecDesObjetsEnfantsInvalides_RetourneUnObjetObjectResultDansCatchFormationIncompatibleIdException() + { + // Arrange + long idFormation = 1; + string nouvelleIntitule = "Formation modifiée"; + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation); + + idFormation = 2; + formation.Intitule = nouvelleIntitule; + + // Act + var objectResult = formationsApiController.UpdateFormation(formation, idFormation); + + // Assert + Assert.IsInstanceOf(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(), 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.Result); + } + + [Test] + public async Task UpdateFormation_ModifieUneFormationValide_RetourneUnObjetOkObjectResult() + { + // Arrange + long idFormation = 1; + string nouvelleIntitule = "Formation modifiée"; + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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.Result); + } + + [Test] + public async Task UpdateFormation_ModifieUneFormationValide_RetourneLaFormationModifiee() + { + // Arrange + long idFormation = 1; + string nouvelleIntitule = "Formation modifiée"; + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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(okObjectResult.Value); + Assert.AreEqual(nouvelleIntitule, (okObjectResult.Value as FormationDTO).Intitule); + } #endregion #region Tests DeleteFormationById - // Arrange + [Test] + public void DeleteFormation_PasseEnParamUnIdFormationInexistant_RetourneUnObjetNotFoundObjectResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int idFormation = 999; + + // Act + var notFoundObjectResult = formationsApiController.DeleteFormation(idFormation); + + // Assert + Assert.IsInstanceOf(notFoundObjectResult.Result); + } + + [Test] + public void DeleteFormation_PasseEnParamUnIdFormationExistant_RetourneUnObjetNoContentResult() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + int idFormation = 1; - // Act + // Act + var noContentResult = formationsApiController.DeleteFormation(idFormation); + + // Assert + Assert.IsInstanceOf(noContentResult.Result); + } + + [Test] + public async Task DeleteFormation_PasseEnParamUnIdFormationExistant_SupprimeBienUneFormation() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), 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 } diff --git a/EPAServeur.Tests/EPAServeur.Tests.csproj b/EPAServeur.Tests/EPAServeur.Tests.csproj index 50b948f..5aabbe5 100644 --- a/EPAServeur.Tests/EPAServeur.Tests.csproj +++ b/EPAServeur.Tests/EPAServeur.Tests.csproj @@ -11,6 +11,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -20,4 +21,8 @@ + + + + diff --git a/EPAServeur.Tests/Properties/launchSettings.json b/EPAServeur.Tests/Properties/launchSettings.json new file mode 100644 index 0000000..cd5042e --- /dev/null +++ b/EPAServeur.Tests/Properties/launchSettings.json @@ -0,0 +1,7 @@ +{ + "profiles": { + "EPAServeur.Tests": { + "commandName": "Project" + } + } +} \ No newline at end of file diff --git a/EPAServeur.Tests/Services/EngagementServiceTests.cs b/EPAServeur.Tests/Services/EngagementServiceTests.cs new file mode 100644 index 0000000..8c25bc7 --- /dev/null +++ b/EPAServeur.Tests/Services/EngagementServiceTests.cs @@ -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() + .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 idBUs = arrIdBUs.Select(x => x).ToList(); + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + List etatEngagements = arrEtatsEngagement.Select(x => x).ToList(); + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + + // Act + IEnumerable 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 idBUs = new List() { 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 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 idBUs = new List() { 1, 2, 3 }; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = true; + string tri = "dispositif"; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = false; + string tri = "dispositif"; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = true; + string tri = "modalite"; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = false; + string tri = "modalite"; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = true; + string tri = "date"; + + // Act + IEnumerable 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 idBUs = new List() { 1, 2, 3 }; + bool? asc = false; + string tri = "date"; + + // Act + IEnumerable 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 idBUs; + + if (arrIdBUs != null) + idBUs = arrIdBUs.Select(x => x).ToList(); + else + idBUs = new List(); + + // Act + IEnumerable 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 idBUs = new List(); + + // 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 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 idBUs; + + if (arrIdBUs != null) + idBUs = arrIdBUs.Select(x => x).ToList(); + else + idBUs = new List(); + + // 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 idBUs; + + if (arrIdBUs != null) + idBUs = arrIdBUs.Select(x => x).ToList(); + else + idBUs = new List(); + + // 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 + } +} \ No newline at end of file diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index fd124db..9dccbe2 100644 --- a/EPAServeur.Tests/Services/FormationServiceTests.cs +++ b/EPAServeur.Tests/Services/FormationServiceTests.cs @@ -1,7 +1,9 @@ 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 Microsoft.EntityFrameworkCore; using NUnit.Framework; @@ -18,7 +20,8 @@ namespace EPAServeur.Tests.Services #region Variables private EpContext epContext; - + private ICollaborateurApi collaborateurApi; + private ICollaborateurService collaborateurService; #endregion #region Setup @@ -32,7 +35,8 @@ namespace EPAServeur.Tests.Services .Options; epContext = new EpContext(optionBuider); - + collaborateurApi = new CollaborateurApi(); + collaborateurService = new CollaborateurService(collaborateurApi, epContext); epContext.Database.EnsureDeleted(); epContext.Database.EnsureCreated(); epContext.SaveChanges(); @@ -50,23 +54,22 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetFormationById et GetFormationByIdAsync - + #region Tests GetFormationByIdAsync [Test] - public void GetFormationById_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() + public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - FormationDTO formationDTO = formationService.GetFormationById(1); + FormationDTO formationDTO = await formationService.GetFormationByIdAsync(1); // Assert Assert.AreEqual(1, formationDTO.Id); - Assert.AreEqual("Formation1", formationDTO.Intitule); + Assert.AreEqual("Formation Mainframe Complète", formationDTO.Intitule); Assert.AreEqual(1, formationDTO.IdAgence); - Assert.AreEqual(new DateTime(2020, 9, 16, 10, 0, 0), formationDTO.DateDebut); - Assert.AreEqual(new DateTime(2020, 9, 16), formationDTO.DateFin); + Assert.AreEqual(new DateTime(2020, 1, 25, 10, 0, 0), formationDTO.DateDebut); + Assert.AreEqual(new DateTime(2020, 1, 27), formationDTO.DateFin); Assert.AreEqual(2, formationDTO.Heure); Assert.AreEqual(1, formationDTO.Jour); Assert.AreEqual("Organisme1", formationDTO.Organisme); @@ -77,58 +80,43 @@ namespace EPAServeur.Tests.Services Assert.AreEqual(new TypeFormationDTO { Id = 3, Libelle = "E-learning" }, formationDTO.Type); } - [TestCase(-1)] - [TestCase(0)] - [TestCase(999999)] - [TestCase(null)] - public void GetFormationById_PasseEnParamUnIdInexistantDansLeJeuDeDonneesFictif_LeveUneFormationNotFoundException(long? value) - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.GetFormationById(value); - - // Assert - Assert.Throws(typeof(FormationNotFoundException), throwException); - } - [Test] - public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() + public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormationSansParticipation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + long idFormation = 11; // Act - FormationDTO formationDTO = await formationService.GetFormationByIdAsync(1); + FormationDTO formationDTO = await formationService.GetFormationByIdAsync(idFormation); // Assert - Assert.AreEqual(1, formationDTO.Id); - Assert.AreEqual("Formation1", formationDTO.Intitule); + Assert.AreEqual(idFormation, formationDTO.Id); + Assert.AreEqual("Formation Clean Architecture .Net Core", formationDTO.Intitule); Assert.AreEqual(1, formationDTO.IdAgence); - Assert.AreEqual(new DateTime(2020, 9, 16, 10, 0, 0), formationDTO.DateDebut); - Assert.AreEqual(new DateTime(2020, 9, 16), formationDTO.DateFin); - Assert.AreEqual(2, formationDTO.Heure); - Assert.AreEqual(1, formationDTO.Jour); + Assert.AreEqual(new DateTime(2020, 04, 6, 9, 0, 0), formationDTO.DateDebut); + Assert.AreEqual(new DateTime(2020, 04, 11), formationDTO.DateFin); + Assert.AreEqual(15, formationDTO.Heure); + Assert.AreEqual(5, formationDTO.Jour); Assert.AreEqual("Organisme1", formationDTO.Organisme); Assert.False(formationDTO.EstCertifiee); - Assert.AreEqual(new OrigineFormationDTO { Id = 2, Libelle = "Exigence client" }, formationDTO.Origine); - Assert.AreEqual(new StatutFormationDTO { Id = 1, Libelle = "Planifiée" }, formationDTO.Statut); - Assert.AreEqual(new ModeFormationDTO { Id = 4, Libelle = "E-learning" }, formationDTO.Mode); - Assert.AreEqual(new TypeFormationDTO { Id = 3, Libelle = "E-learning" }, formationDTO.Type); + Assert.IsNull(formationDTO.Participations); + Assert.AreEqual(new OrigineFormationDTO { Id = 4, Libelle = "Formation réglementaire" }, formationDTO.Origine); + Assert.AreEqual(new StatutFormationDTO { Id = 4, Libelle = "Annulée" }, formationDTO.Statut); + Assert.AreEqual(new ModeFormationDTO { Id = 3, Libelle = "Présentiel" }, formationDTO.Mode); + Assert.AreEqual(new TypeFormationDTO { Id = 2, Libelle = "Interne" }, formationDTO.Type); } [TestCase(-1)] [TestCase(0)] [TestCase(999999)] - [TestCase(null)] - public void GetFormationByIdAsync_PasseEnParamUnIdInexistantDansLeJeuDeDonneesFictif_LeveUneFormationNotFoundException(long? value) + public void GetFormationByIdAsync_PasseEnParamUnIdInexistantDansLeJeuDeDonneesFictif_LeveUneFormationNotFoundException(long idFormation) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - AsyncTestDelegate throwException = () => formationService.GetFormationByIdAsync(value); + AsyncTestDelegate throwException = () => formationService.GetFormationByIdAsync(idFormation); // Assert Assert.ThrowsAsync(typeof(FormationNotFoundException), throwException); @@ -136,395 +124,430 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetFormations et GetFormationsAsync + #region Tests GetFormationsAsync - [TestCase(true, 1, 5, 1, 1, "formation", null)] - [TestCase(false, 1, 5, 1, 1, "formation1", null)] - [TestCase(null, 2, 10, null, null, null, null)] - [TestCase(null, 1, 10, null, 1, null, null)] - [TestCase(null, 1, 10, 1, null, "for", null)] - public void GetFormations_PasseDesParamsValides_RetourneDesFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) + [TestCase(1, new int[] { 1, 2, 3 }, true, 1, 5, "formation", null, null, null)] + [TestCase(1, new int[] { 1 }, false, 1, 5, "Formation Mainframe Complète", null, null, null)] + [TestCase(null, null, null, 2, 10, null, null, null, null)] + [TestCase(null, new int[] { 1 }, null, 1, 10, null, null, null, null)] + [TestCase(1, null, null, 1, 10, "for", null, null, null)] + [TestCase(1, new int[] { }, null, 1, 10, "for", null, null, null)] + public async Task GetFormationsAsync_PasseDesParamsValides_RetourneDesFormations(long? idAgence, int[] arrIdStatuts, bool? asc, int? numPage, int? parPAge, string texte, string tri, DateTime? dateDebut, DateTime? dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; // Act - IEnumerable formationDTOs = formationService.GetFormations(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); // Assert Assert.Less(0, formationDTOs.Count()); } - [TestCase(true, 1, 15, 1, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, 0, null, null)] - public void GetFormations_PasseDesParamsInvalides_RetourneZeroFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) + [TestCase(1, 5)] + [TestCase(1, 10)] + public async Task GetFormationsAsync_PasseEnParamNumPageEtParPage_RetourneLaPremierePageDesFormations(int? numPage, int? parPAge) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetFormations(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); + Assert.AreEqual(parPAge, formationDTOs.Count()); } - [TestCase(true, 1, 5, 1, 1, "formation", null)] - [TestCase(false, 1, 5, 1, 1, "formation1", null)] - [TestCase(null, 2, 10, null, null, null, null)] - [TestCase(null, 1, 10, null, 1, null, null)] - [TestCase(null, 1, 10, 1, null, "for", null)] - public async Task GetFormationsAsync_PasseDesParamsValides_RetourneDesFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) + [TestCase(2, 5)] + [TestCase(2, 6)] + [TestCase(2, 10)] + [TestCase(2, 15)] + public async Task GetFormationsAsync_PasseEnParamNumPageEtParPage_RetourneLaDeuxiemePageDesFormations(int? numPage, int? parPAge) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + int? nbFormationDeuxiemePage; + + switch (parPAge) + { + case 5: + nbFormationDeuxiemePage = 5; + break; + case 6: + nbFormationDeuxiemePage = 5; + break; + case 10: + nbFormationDeuxiemePage = 1; + break; + default: + nbFormationDeuxiemePage = 0; + break; + } // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual(nbFormationDeuxiemePage, formationDTOs.Count()); } - [TestCase(true, 1, 15, 1, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, 0, null, null)] - public async Task GetFormationsAsync_PasseDesParamsInvalides_RetourneZeroFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) + [TestCase(true, "intitule")] + [TestCase(true, null)] + [TestCase(true, "toto")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleCroissant(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); - } - - #endregion + Assert.AreEqual("Apprendre C# et le développement de logiciels avec WPF", formationDTOs.First().Intitule); + Assert.AreEqual("Formation Xamarin, Développer des applications mobiles en C# pour iOS et Android", formationDTOs.Last().Intitule); - #region Tests GetFormationAnnulees et GetFormationAnnuleesAsync + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation10", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public void GetFormationAnnulees_PasseDesParamsValides_RetourneDesFormationsAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(false, "intitule")] + [TestCase(false, null)] + [TestCase(false, "toto")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleDecroissant(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual("Formation Xamarin, Développer des applications mobiles en C# pour iOS et Android", formationDTOs.First().Intitule); + Assert.AreEqual("Apprendre C# et le développement de logiciels avec WPF", formationDTOs.Last().Intitule); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public void GetFormationAnnulees_PasseDesParamsInvalides_RetourneZeroFormationAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(true, "statut")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParStatutCroissant(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); + Assert.AreEqual("Annulée", formationDTOs.First().Statut.Libelle); + Assert.AreEqual("Replanifiée", formationDTOs.Last().Statut.Libelle); + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation1", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public async Task GetFormationAnnuleesAsync_PasseDesParamsValides_RetourneDesFormationsAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(false, "statut")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParStatutDecroissant(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual("Replanifiée", formationDTOs.First().Statut.Libelle); + Assert.AreEqual("Annulée", formationDTOs.Last().Statut.Libelle); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public async Task GetFormationAnnuleesAsync_PasseDesParamsInvalides_RetourneZeroFormationAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(true, "origine")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParOrigineCroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); - } - - #endregion + Assert.AreEqual("Demande collaborateur", formationDTOs.First().Origine.Libelle); + Assert.AreEqual("Formation réglementaire", formationDTOs.Last().Origine.Libelle); - #region Tests GetFormationRealisee et GetFormationRealiseeAsync + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation4", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public void GetFormationRealisee_PasseDesParamsValides_RetourneDesFormationsRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(false, "origine")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParOrigineDecroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetFormationRealisees(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual("Formation réglementaire", formationDTOs.First().Origine.Libelle); + Assert.AreEqual("Demande collaborateur", formationDTOs.Last().Origine.Libelle); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public void GetFormationRealisee_PasseDesParamsInvalides_RetourneZeroFormationRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(true, "date")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParDateCroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetFormationRealisees(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); + Assert.AreEqual(new DateTime(2020, 1, 25, 10, 0, 0), formationDTOs.First().DateDebut); + Assert.AreEqual(new DateTime(2020, 12, 25, 14, 0, 0), formationDTOs.Last().DateDebut); + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation4", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public async Task GetFormationRealiseeAsync_PasseDesParamsValides_RetourneDesFormationsRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(false, "date")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParDateDecroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetFormationRealiseesAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual(new DateTime(2020, 12, 25, 14, 0, 0), formationDTOs.First().DateDebut); + Assert.AreEqual(new DateTime(2020, 1, 25, 10, 0, 0), formationDTOs.Last().DateDebut); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public async Task GetFormationRealiseeAsync_PasseDesParamsInvalides_RetourneZeroFormationRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(true, "certification")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParCertificationCroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetFormationRealiseesAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); - } - - #endregion + Assert.AreEqual(false, formationDTOs.First().EstCertifiee); + Assert.AreEqual(true, formationDTOs.Last().EstCertifiee); - #region Tests GetProchainesFormation et GetProchainesFormationAsync + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation1", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public void GetProchainesFormation_PasseDesParamsValides_RetourneDesProchainesFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase(false, "certification")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParCertificationDecroissante(bool? asc, string tri) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.AreEqual(true, formationDTOs.First().EstCertifiee); + Assert.AreEqual(false, formationDTOs.Last().EstCertifiee); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public void GetProchainesFormation_PasseDesParamsInvalides_RetourneZeroProchaineFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + + [TestCase("2020-10-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeDebut_RetourneDesFormationsAvecUneDateDeDebutSuperieur(DateTime dateDebut) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, null); // Assert - Assert.AreEqual(0, formationDTOs.Count()); + Assert.Greater(formationDTOs.First().DateDebut, dateDebut); + Assert.GreaterOrEqual(formationDTOs.Last().DateDebut, dateDebut); + } - [TestCase(true, 1, 5, 1, "formation", null)] - [TestCase(false, 1, 5, 1, "formation1", null)] - [TestCase(null, 2, 1, null, null, null)] - [TestCase(null, 1, 10, null, null, null)] - [TestCase(null, 1, 10, 1, "for", null)] - public async Task GetProchainesFormationAsync_PasseDesParamsValides_RetourneDesProchainesFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase("2020-10-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeFin_RetourneDesFormationsAvecUneDateDeFinInferieur(DateTime dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, null, dateFin); // Assert - Assert.Less(0, formationDTOs.Count()); + Assert.Less(formationDTOs.First().DateFin, dateFin); + Assert.LessOrEqual(formationDTOs.Last().DateFin, dateFin); + } - [TestCase(true, 1, 15, 1, "azerty", null)] - [TestCase(null, -1, -1, -1, "azerty", null)] - [TestCase(null, 0, 0, 0, null, null)] - public async Task GetProchainesFormationAsync_PasseDesParamsInvalides_RetourneZeroProchaineFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase("2020-11-01", "2020-12-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutEtUneDateDeFin_RetourneDesFormationsAvecUneDateDeDebutSuperieurUneDateDeFinInferieur(DateTime dateDebut, DateTime dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable formationDTOs = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); // Assert - Assert.AreEqual(0, formationDTOs.Count()); - } + Assert.Greater(formationDTOs.First().DateDebut, dateDebut); + Assert.Less(formationDTOs.First().DateFin, dateFin); - #endregion + Assert.GreaterOrEqual(formationDTOs.Last().DateDebut, dateDebut); + Assert.LessOrEqual(formationDTOs.Last().DateFin, dateFin); - #region Tests GetModesFormation et GetModesFormationAsync + } - [Test] - public void GetModesFormation_RetourneTousLesModesDeFormation() + [TestCase("2020-11-01", "2020-10-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutSuperieurEtUneDateDeFinInferieur_RetourneZeroFormation(DateTime dateDebut, DateTime dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable modeFormationDTOs = formationService.GetModesFormation(); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); // Assert - Assert.IsNotNull(modeFormationDTOs); - Assert.AreEqual(4, modeFormationDTOs.Count()); // Nombre total de mode de formation dans la classe DataSeeder le 2020-10-31 + Assert.AreEqual(0, formationDTOs.Count()); } - [Test] - public async Task GetModesFormationAsync_RetourneTousLesModesDeFormation() + [TestCase(1, new int[] { 1 }, true, 1, 15, "azerty", null, null, null)] + [TestCase(-1, new int[] { -1 }, null, -1, -1, "azerty", null, null, null)] + [TestCase(0, new int[] { 0 }, null, 0, 0, null, null, null, null)] + public async Task GetFormationsAsync_PasseDesParamsInvalides_RetourneZeroFormation(long? idAgence, int[] arrIdStatuts, bool? asc, int? numPage, int? parPAge, string texte, string tri, DateTime? dateDebut, DateTime? dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; + // Act - IEnumerable modeFormationDTOs = await formationService.GetModesFormationAsync(); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); // Assert - Assert.IsNotNull(modeFormationDTOs); - Assert.AreEqual(4, modeFormationDTOs.Count()); // Nombre total de mode de formation dans la classe DataSeeder le 2020-10-31 + Assert.AreEqual(0, formationDTOs.Count()); } #endregion - #region Tests GetOriginesFormation et GetOriginesFormationAsync + #region Tests GetFormationsCountAsync - [Test] - public void GetOriginesFormation_RetourneToutesLesOriginesDeFormation() + [TestCase(1, new int[] { 1, 2, 3 }, 1, 5, "formation", "2020-09-30", "2020-11-30")] + [TestCase(1, new int[] { 1 }, 1, 5, "Formation Mainframe Complète", null, null)] + [TestCase(null, null, 2, 10, null, null, null)] + [TestCase(null, new int[] { 1 }, 1, 10, null, null, null)] + [TestCase(1, null, 1, 10, "for", null, null)] + [TestCase(1, new int[] { }, 1, 10, "for", null, null)] + public async Task GetFormationsCountAsync_PasseDesParamsValides_RetourneLeNombreTotalDeFormations(long? idAgence, int[] arrIdStatuts, int? numPage, int? parPAge, string texte, DateTime? dateDebut, DateTime? dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; // Act - IEnumerable origineFormationDTOs = formationService.GetOriginesFormation(); + long count = await formationService.GetFormationsCountAsync(idAgence, idStatuts, numPage, parPAge, texte, dateDebut, dateFin); // Assert - Assert.IsNotNull(origineFormationDTOs); - Assert.AreEqual(4, origineFormationDTOs.Count()); // Nombre total d'origine de formation dans la classe DataSeeder le 2020-10-31 + Assert.Less(0, count); } - [Test] - public async Task GetOriginesAsyncFormation_RetourneToutesLesOriginesDeFormation() + [TestCase(1, new int[] { 1 }, 1, 15, "azerty", null, null)] + [TestCase(-1, new int[] { -1 }, -1, -1, "azerty", null, null)] + [TestCase(0, new int[] { 0 }, 0, 0, null, null, null)] + public async Task GetFormationsCountAsync_PasseDesParamsInvalides_RetourneZero(long? idAgence, int[] arrIdStatuts, int? numPage, int? parPAge, string texte, DateTime? dateDebut, DateTime? dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; // Act - IEnumerable origineFormationDTOs = await formationService.GetOriginesFormationAsync(); + long count = await formationService.GetFormationsCountAsync(idAgence, idStatuts, numPage, parPAge, texte, dateDebut, dateFin); // Assert - Assert.IsNotNull(origineFormationDTOs); - Assert.AreEqual(4, origineFormationDTOs.Count()); // Nombre total d'origine de formation dans la classe DataSeeder le 2020-10-31 + Assert.AreEqual(0, count); } #endregion - #region Tests GetStatutsFormation et GetStatutsFormationAsync + + #region Tests GetModesFormationAsync [Test] - public void GetStatutsFormation_RetourneTousLesStatutsDeFormation() + public async Task GetModesFormationAsync_RetourneTousLesModesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable statutFormationDTOs = formationService.GetStatutsFormation(); + IEnumerable modeFormationDTOs = await formationService.GetModesFormationAsync(); // Assert - Assert.IsNotNull(statutFormationDTOs); - Assert.AreEqual(4, statutFormationDTOs.Count()); // Nombre total de statut de formation dans la classe DataSeeder le 2020-10-31 + Assert.IsNotNull(modeFormationDTOs); + Assert.AreEqual(4, modeFormationDTOs.Count()); // Nombre total de mode de formation dans la classe DataSeeder le 2020-10-31 } + #endregion + + #region Tests GetOriginesFormationAsync + [Test] - public async Task GetStatutsFormationAsyncFormation_RetourneTousLesStatutsDeFormation() + public async Task GetOriginesAsyncFormation_RetourneToutesLesOriginesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable statutFormationDTOs = await formationService.GetStatutsFormationAsync(); + IEnumerable origineFormationDTOs = await formationService.GetOriginesFormationAsync(); // Assert - Assert.IsNotNull(statutFormationDTOs); - Assert.AreEqual(4, statutFormationDTOs.Count()); // Nombre total de statut de formation dans la classe DataSeeder le 2020-10-31 + Assert.IsNotNull(origineFormationDTOs); + Assert.AreEqual(4, origineFormationDTOs.Count()); // Nombre total d'origine de formation dans la classe DataSeeder le 2020-10-31 } #endregion - #region Tests GetTypesFormation et GetTypesFormationAsync + #region Tests GetStatutsFormationAsync [Test] - public void GetTypesFormation_RetourneTousLesTypesDeFormation() + public async Task GetStatutsFormationAsyncFormation_RetourneTousLesStatutsDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act - IEnumerable typeFormationDTOs = formationService.GetTypesFormation(); + IEnumerable statutFormationDTOs = await formationService.GetStatutsFormationAsync(); // Assert - Assert.IsNotNull(typeFormationDTOs); - Assert.AreEqual(4, typeFormationDTOs.Count()); // Nombre total de type de formation dans la classe DataSeeder le 2020-10-31 + Assert.IsNotNull(statutFormationDTOs); + Assert.AreEqual(4, statutFormationDTOs.Count()); // Nombre total de statut de formation dans la classe DataSeeder le 2020-10-31 } + #endregion + + #region Tests GetTypesFormationAsync + [Test] public async Task GetTypesFormationAsync_RetourneTousLesTypesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable typeFormationDTOs = await formationService.GetTypesFormationAsync(); @@ -536,60 +559,7 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests AddFormation et AddFormationAsync - - [TestCase(1, 1, 3, 1, 1, "Test ajout formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "Test ajout formation", "Apside", "2020-10-31", "2020-10-31")] - [TestCase(1, 1, 3, 1, 1, "Test ajout formation", "Apside", "2020-11-02", "2020-11-02")] - public void AddFormation_AjouteUneFormationValide_FormationAjouteeAvecSucces(int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationDTO formation = new FormationDTO - { - Intitule = intitule, - IdAgence = idAgence, - DateDebut = dateDebut, - DateFin = dateFin, - Heure = 2, - Jour = 1, - Mode = modeExterne, - Type = typeELearning, - Organisme = organisme, - Origine = origineFormationCollaborateur, - Statut = statutPlanifie, - EstCertifiee = false - }; - - FormationService formationService = new FormationService(epContext); - - // Act - FormationDTO formationAjoute = formationService.AddFormation(formation); - - // Assert - Assert.IsNotNull(formationAjoute); - Assert.AreEqual(12, formationAjoute.Id); - Assert.AreEqual(formation.Intitule, formationAjoute.Intitule); - Assert.AreEqual(formation.IdAgence, formationAjoute.IdAgence); - Assert.AreEqual(formation.DateDebut, formationAjoute.DateDebut); - Assert.AreEqual(formation.DateFin, formationAjoute.DateFin); - Assert.AreEqual(formation.Heure, formationAjoute.Heure); - Assert.AreEqual(formation.Jour, formationAjoute.Jour); - Assert.AreEqual(formation.Mode, formationAjoute.Mode); - Assert.AreEqual(formation.Type, formationAjoute.Type); - Assert.AreEqual(formation.Organisme, formationAjoute.Organisme); - Assert.AreEqual(formation.Origine, formationAjoute.Origine); - Assert.AreEqual(formation.Statut, formationAjoute.Statut); - Assert.AreEqual(formation.EstCertifiee, formationAjoute.EstCertifiee); - } + #region Tests AddFormationAsync [TestCase(1, 1, 3, 1, 1, "Test ajout formation", "Apside", "2020-10-31", "2020-11-02")] [TestCase(1, 1, 3, 1, 1, "Test ajout formation", "Apside", "2020-10-31", "2020-10-31")] @@ -622,7 +592,7 @@ namespace EPAServeur.Tests.Services EstCertifiee = false }; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act FormationDTO formationAjoute = await formationService.AddFormationAsync(formation); @@ -644,22 +614,6 @@ namespace EPAServeur.Tests.Services Assert.AreEqual(formation.EstCertifiee, formationAjoute.EstCertifiee); } - [Test] - public void AddFormation_AjouteUneFormationNull_LeveUneFormationInvalidException() - { - - // Arrange - FormationDTO formation = null; - - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.AddFormation(formation); - - // Assert - Assert.Throws(typeof(FormationInvalidException), throwException); - } - [Test] public void AddFormationAsync_AjouteUneFormationNull_LeveUneFormationInvalidException() { @@ -667,7 +621,7 @@ namespace EPAServeur.Tests.Services // Arrange FormationDTO formation = null; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.AddFormationAsync(formation); @@ -676,57 +630,6 @@ namespace EPAServeur.Tests.Services Assert.ThrowsAsync(typeof(FormationInvalidException), throwException); } - [TestCase(1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-10-30")] - [TestCase(0, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 0, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 0, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 0, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 0, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "Test Formation", "", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, null, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, null, "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "Test Formation", null, "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "Test Formation", "Apside", null, "2020-11-02")] - [TestCase(1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", null)] - public void AddFormation_AjouteUneFormationAvecDesProprietesInvalides_LeveUneFormationInvalidException(int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationDTO formation = new FormationDTO - { - Intitule = intitule, - IdAgence = idAgence, - DateDebut = dateDebut, - DateFin = dateFin, - Heure = 2, - Jour = 1, - Mode = modeExterne, - Type = typeELearning, - Organisme = organisme, - Origine = origineFormationCollaborateur, - Statut = statutPlanifie, - EstCertifiee = false - }; - - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.AddFormation(formation); - - // Assert - Assert.Throws(typeof(FormationInvalidException), throwException); - } - [TestCase(1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-10-30")] [TestCase(0, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] [TestCase(1, 0, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] @@ -767,7 +670,7 @@ namespace EPAServeur.Tests.Services EstCertifiee = false }; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.AddFormationAsync(formation); @@ -776,52 +679,6 @@ namespace EPAServeur.Tests.Services Assert.ThrowsAsync(typeof(FormationInvalidException), throwException); } - [TestCase(0, 1, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 0, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 0, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 3, 0, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(null, 1, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, null, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, null, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 3, null, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 3, 1, "Externez", "Planifiée", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 3, 1, "Externe", "Planifiées", "E-learning", "Demande collaborateur")] - [TestCase(1, 1, 3, 1, "Externe", "Planifiée", "E-learnings", "Demande collaborateur")] - [TestCase(1, 1, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateurs")] - public void AddFormation_AjouteUneFormationAvecDesObjetsEnfantsInvalides_LeveUneFormationInvalidException(int? idMode, int? idStatut, int? idType, int? idOrigine, string libelleMode, string libelleStatut, string libelleType, string libelleOrigine) - { - - // Arrange - ModeFormationDTO modeExterne = new ModeFormationDTO { Id = idMode, Libelle = libelleMode }; - StatutFormationDTO statutPlanifie = new StatutFormationDTO { Id = idStatut, Libelle = libelleStatut }; - TypeFormationDTO typeELearning = new TypeFormationDTO { Id = idType, Libelle = libelleType }; - OrigineFormationDTO origineFormationCollaborateur = new OrigineFormationDTO { Id = idOrigine, Libelle = libelleOrigine }; - - 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 - }; - - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.AddFormation(formation); - - // Assert - Assert.Throws(typeof(FormationInvalidException), throwException); - } - [TestCase(0, 1, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] [TestCase(1, 0, 3, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] [TestCase(1, 1, 0, 1, "Externe", "Planifiée", "E-learning", "Demande collaborateur")] @@ -859,7 +716,7 @@ namespace EPAServeur.Tests.Services EstCertifiee = false }; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.AddFormationAsync(formation); @@ -870,10 +727,10 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests UpdateFormation et UpdateFormationAsync + #region Tests UpdateFormationAsync [TestCase(1, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - public void UpdateFormation_ModifieUneFormationValide_FormationModifieeAvecSucces(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) + public async Task UpdateFormationAsync_ModifieUneFormationValide_FormationModifieeAvecSucces(long idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) { // Arrange ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) @@ -885,58 +742,7 @@ namespace EPAServeur.Tests.Services OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - FormationService formationService = new FormationService(epContext); - - FormationDTO formation = formationService.GetFormationById(idFormation); - - formation.Intitule = intitule; - formation.IdAgence = idAgence; - formation.DateDebut = dateDebut; - formation.DateFin = dateFin; - formation.Heure = 2; - formation.Jour = 1; - formation.Mode = modeExterne; - formation.Type = typeELearning; - formation.Organisme = organisme; - formation.Origine = origineFormationCollaborateur; - formation.Statut = statutPlanifie; - formation.EstCertifiee = false; - - - // Act - FormationDTO formationModifie = formationService.UpdateFormation(idFormation, formation); - - // Assert - Assert.IsNotNull(formationModifie); - Assert.AreEqual(idFormation, formationModifie.Id); - Assert.AreEqual(formation.Intitule, formationModifie.Intitule); - Assert.AreEqual(formation.IdAgence, formationModifie.IdAgence); - Assert.AreEqual(formation.DateDebut, formationModifie.DateDebut); - Assert.AreEqual(formation.DateFin, formationModifie.DateFin); - Assert.AreEqual(formation.Heure, formationModifie.Heure); - Assert.AreEqual(formation.Jour, formationModifie.Jour); - Assert.AreEqual(formation.Mode, formationModifie.Mode); - Assert.AreEqual(formation.Type, formationModifie.Type); - Assert.AreEqual(formation.Organisme, formationModifie.Organisme); - Assert.AreEqual(formation.Origine, formationModifie.Origine); - Assert.AreEqual(formation.Statut, formationModifie.Statut); - Assert.AreEqual(formation.EstCertifiee, formationModifie.EstCertifiee); - } - - [TestCase(1, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - public async Task UpdateFormationAsync_ModifieUneFormationValide_FormationModifieeAvecSucces(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation); @@ -987,7 +793,7 @@ namespace EPAServeur.Tests.Services [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", null, "2020-10-31", "2020-11-02")] [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "Apside", null, "2020-11-02")] [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", null)] - public void UpdateFormation_ModifieUneFormationAvecDesProprietesInvalides_LeveUneFormationInvalidException(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) + public async Task UpdateFormationAsync_ModifieUneFormationAvecDesProprietesInvalides_LeveUneFormationInvalidException(long idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) { // Arrange @@ -1000,57 +806,7 @@ namespace EPAServeur.Tests.Services OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - FormationService formationService = new FormationService(epContext); - - FormationDTO formation = formationService.GetFormationById(idFormation); - - formation.Intitule = intitule; - formation.IdAgence = idAgence; - formation.DateDebut = dateDebut; - formation.DateFin = dateFin; - formation.Heure = 2; - formation.Jour = 1; - formation.Mode = modeExterne; - formation.Type = typeELearning; - formation.Organisme = organisme; - formation.Origine = origineFormationCollaborateur; - formation.Statut = statutPlanifie; - formation.EstCertifiee = false; - - // Act - TestDelegate throwException = () => formationService.UpdateFormation(idFormation, formation); - - // Assert - Assert.Throws(typeof(FormationInvalidException), throwException); - } - - [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-10-30")] - [TestCase(1, 0, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 0, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 0, 1, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 0, 1, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 0, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, "", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, null, "Test Formation", "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, null, "Apside", "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", null, "2020-10-31", "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "Apside", null, "2020-11-02")] - [TestCase(1, 1, 1, 3, 1, 1, "Test Formation", "Apside", "2020-10-31", null)] - public async Task UpdateFormationAsync_ModifieUneFormationAvecDesProprietesInvalides_LeveUneFormationInvalidException(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); FormationDTO formation = await formationService.GetFormationByIdAsync(idFormation); @@ -1075,45 +831,7 @@ namespace EPAServeur.Tests.Services } [TestCase(2, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - [TestCase(null, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - public void UpdateFormation_ModifieUneFormationAvecUnIdIncorrecte_LeveUneFormationIncompatibleIdException(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationService formationService = new FormationService(epContext); - - FormationDTO formation = formationService.GetFormationById(1); - - formation.Id = idFormation; - formation.Intitule = intitule; - formation.IdAgence = idAgence; - formation.DateDebut = dateDebut; - formation.DateFin = dateFin; - formation.Heure = 2; - formation.Jour = 1; - formation.Mode = modeExterne; - formation.Type = typeELearning; - formation.Organisme = organisme; - formation.Origine = origineFormationCollaborateur; - formation.Statut = statutPlanifie; - formation.EstCertifiee = false; - - // Act - TestDelegate throwException = () => formationService.UpdateFormation(1, formation); - - // Assert - Assert.Throws(typeof(FormationIncompatibleIdException), throwException); - } - - [TestCase(2, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] + [TestCase(0, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] [TestCase(null, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] public async Task UpdateFormationAsync_ModifieUneFormationAvecUnIdIncorrecte_LeveUneFormationIncompatibleIdException(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) { @@ -1127,7 +845,7 @@ namespace EPAServeur.Tests.Services OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); FormationDTO formation = await formationService.GetFormationByIdAsync(1); @@ -1153,46 +871,7 @@ namespace EPAServeur.Tests.Services } [TestCase(0, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - public void UpdateFormation_ModifieUneFormationAvecUnIdInexistant_RetourneUnObjetNull(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) - { - // Arrange - ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) - .Select(mode => new ModeFormationDTO { Id = mode.IdModeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - StatutFormationDTO statutPlanifie = epContext.StatutFormation.Where(mode => mode.IdStatutFormation == idStatut) - .Select(mode => new StatutFormationDTO { Id = mode.IdStatutFormation, Libelle = mode.Libelle }).FirstOrDefault(); - TypeFormationDTO typeELearning = epContext.TypeFormation.Where(mode => mode.IdTypeFormation == idType) - .Select(mode => new TypeFormationDTO { Id = mode.IdTypeFormation, Libelle = mode.Libelle }).FirstOrDefault(); - OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) - .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - - FormationService formationService = new FormationService(epContext); - - FormationDTO formation = new FormationDTO - { - Id = idFormation, - Intitule = intitule, - IdAgence = idAgence, - DateDebut = dateDebut, - DateFin = dateFin, - Heure = 2, - Jour = 1, - Mode = modeExterne, - Type = typeELearning, - Organisme = organisme, - Origine = origineFormationCollaborateur, - Statut = statutPlanifie, - EstCertifiee = false - }; - - // Act - FormationDTO formationModifie = formationService.UpdateFormation(idFormation, formation); - - // Assert - Assert.IsNull(formationModifie); - } - - [TestCase(0, 2, 2, 1, 1, 2, "Test modification formation", "Apside", "2020-10-31", "2020-11-04")] - public async Task UpdateFormationAsync_ModifieUneFormationAvecUnIdInexistant_RetourneUnObjetNull(long? idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) + public void UpdateFormationAsync_ModifieUneFormationAvecUnIdInexistant_RetourneUnObjetNull(long idFormation, int? idMode, int? idStatut, int? idType, int? idOrigine, long? idAgence, string intitule, string organisme, DateTime? dateDebut, DateTime? dateFin) { // Arrange ModeFormationDTO modeExterne = epContext.ModeFormation.Where(mode => mode.IdModeFormation == idMode) @@ -1204,7 +883,7 @@ namespace EPAServeur.Tests.Services OrigineFormationDTO origineFormationCollaborateur = epContext.OrigineFormation.Where(mode => mode.IdOrigineFormation == idOrigine) .Select(mode => new OrigineFormationDTO { Id = mode.IdOrigineFormation, Libelle = mode.Libelle }).FirstOrDefault(); - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); FormationDTO formation = new FormationDTO { @@ -1224,10 +903,10 @@ namespace EPAServeur.Tests.Services }; // Act - FormationDTO formationModifie = await formationService.UpdateFormationAsync(idFormation, formation); + AsyncTestDelegate throwException = () => formationService.UpdateFormationAsync(idFormation, formation); // Assert - Assert.IsNull(formationModifie); + Assert.ThrowsAsync(typeof(FormationNotFoundException), throwException); } @@ -1237,27 +916,10 @@ namespace EPAServeur.Tests.Services [TestCase(1)] [TestCase(2)] - public void DeleteFormationById_SupprimeUneFormationAvecUnIdValide_FormationSupprimeAvecSucces(long? idFormation) - { - // Arrange - FormationService formationService = new FormationService(epContext); - bool existFormation = true; - - // Act - FormationDTO formationSupprime = formationService.DeleteFormationById(idFormation); - - existFormation = epContext.Formation.Any(formation => formation.IdFormation == formationSupprime.Id.Value); - - // Assert - Assert.IsFalse(existFormation); - } - - [TestCase(1)] - [TestCase(2)] - public async Task DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdValide_FormationSupprimeAvecSucces(long? idFormation) + public async Task DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdValide_FormationSupprimeAvecSucces(long idFormation) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); bool existFormation = true; // Act @@ -1271,24 +933,10 @@ namespace EPAServeur.Tests.Services [TestCase(0)] [TestCase(-1)] - public void DeleteFormationById_SupprimeUneFormationAvecUnIdInvalide_LeveUneFormationNotFoundException(long? idFormation) + public void DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdInvalide_LeveUneFormationNotFoundException(long idFormation) { // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.DeleteFormationById(idFormation); - - // Assert - Assert.Throws(typeof(FormationNotFoundException), throwException); - } - - [TestCase(0)] - [TestCase(-1)] - public void DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdInvalide_LeveUneFormationNotFoundException(long? idFormation) - { - // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.DeleteFormationByIdAsync(idFormation); @@ -1297,32 +945,6 @@ namespace EPAServeur.Tests.Services Assert.ThrowsAsync(typeof(FormationNotFoundException), throwException); } - [Test] - public void DeleteFormationById_SupprimeUneFormationAvecUnIdNull_LeveUneFormationIncompatibleIdException() - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - TestDelegate throwException = () => formationService.DeleteFormationById(null); - - // Assert - Assert.Throws(typeof(FormationIncompatibleIdException), throwException); - } - - [Test] - public void DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdNull_LeveUneFormationIncompatibleIdException() - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - AsyncTestDelegate throwException = () => formationService.DeleteFormationByIdAsync(null); - - // Assert - Assert.ThrowsAsync(typeof(FormationIncompatibleIdException), throwException); - } - #endregion } } \ No newline at end of file diff --git a/EPAServeur/Attributes/CannotBeEmptyAttribute.cs b/EPAServeur/Attributes/CannotBeEmptyAttribute.cs new file mode 100644 index 0000000..b785ba1 --- /dev/null +++ b/EPAServeur/Attributes/CannotBeEmptyAttribute.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections; +using System.ComponentModel.DataAnnotations; + +namespace EPAServeur.Attributes +{ + /// + /// Specifies that a collection of a specified type must have at least one element. + /// + [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(); + } + } +} diff --git a/EPAServeur/Context/DataSeeder.cs b/EPAServeur/Context/DataSeeder.cs index 5396148..92be406 100644 --- a/EPAServeur/Context/DataSeeder.cs +++ b/EPAServeur/Context/DataSeeder.cs @@ -23,7 +23,7 @@ namespace EPAServeur.Context AddTypesEntretien(epContext); AddFormations(epContext); - + //AVoir un tableau pour dire combien de demande de formations seront faites pour chaque EP //Avoir un tableau pour dire combien de demande de Participation seront faites et accepter (max : 11) @@ -64,18 +64,18 @@ namespace EPAServeur.Context TypeEntretien typeSite, typeClient, typeVisio, typeTelephone; typeSite = new TypeEntretien { Libelle = "Sur site" }; - epContext.TypeEntretien.Add(typeSite); + epContext.TypeEntretien.Add(typeSite); typeClient = new TypeEntretien { Libelle = "Chez le client" }; - epContext.TypeEntretien.Add(typeClient); + epContext.TypeEntretien.Add(typeClient); typeVisio = new TypeEntretien { Libelle = "Visioconférence" }; - epContext.TypeEntretien.Add(typeVisio); + epContext.TypeEntretien.Add(typeVisio); typeTelephone = new TypeEntretien { Libelle = "Téléphonique" }; - epContext.TypeEntretien.Add(typeTelephone); + epContext.TypeEntretien.Add(typeTelephone); - epContext.SaveChanges(); + epContext.SaveChanges(); } /// @@ -256,63 +256,70 @@ namespace EPAServeur.Context ep9 = new Ep { - IdCollaborateur = Guid.Parse("59a8becb-bc0a-4d3d-adb1-8a8bd13c48c9"), - IdReferent = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), - IdBu = 2, - Fonction = "Dev", + IdEP = 9, + IdCollaborateur = Guid.Parse("842650db-a548-4472-a3af-4c5fff3c1ab8"), + IdReferent = Guid.Parse("aa36f34c-9041-42f5-9db3-6536fe7f1696"), + IdBu = 1, + Fonction = "Ingénieur en Etudes et Développement", TypeEP = TypeEp.EPA, NumeroEp = 1, - DateCreation = new DateTime(2017, 7, 7), - DatePrevisionnelle = new DateTime(2018, 7, 8), + DateCreation = new DateTime(2020, 7, 7), + DatePrevisionnelle = new DateTime(2020, 7, 8), Obligatoire = false, Statut = StatutEp.Signe, CV = "CV.pdf", - DateSaisie = new DateTime(2018, 6, 20) + DateSaisie = new DateTime(2020, 7, 20) }; epContext.Ep.Add(ep9); ep10 = new Ep { - IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), - IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), - IdBu = 2, - Fonction = "Dev", - TypeEP = TypeEp.EPA, + IdEP = 10, + IdCollaborateur = Guid.Parse("301ba7f3-095e-4912-8998-a7c942dc5f23"), + IdReferent = Guid.Parse("ea027734-ff0f-4308-8879-133a09fb3c46"), + IdBu = 3, + Fonction = "Ingénieur en Etudes et Développement", + TypeEP = TypeEp.EPS, NumeroEp = 1, - DateCreation = new DateTime(2017, 7, 7), - DatePrevisionnelle = new DateTime(2018, 7, 8), + DateCreation = new DateTime(2020, 6, 1), + DatePrevisionnelle = new DateTime(2020, 9, 25), Obligatoire = false, Statut = StatutEp.Signe, CV = "CV.pdf", - DateSaisie = new DateTime(2018, 6, 20) + DateSaisie = new DateTime(2020, 10, 5) }; epContext.Ep.Add(ep10); ep11 = new Ep { - IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), - IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), + IdEP = 11, + IdCollaborateur = Guid.Parse("a0f40e2a-cc03-4032-a627-5389e1281c64"), + IdReferent = Guid.Parse("c199024f-5960-4c11-8e34-f9947d589284"), IdBu = 2, - Fonction = "Dev", + Fonction = "Ingénieur en Etudes et Développement", TypeEP = TypeEp.EPA, NumeroEp = 1, - DateCreation = new DateTime(2018, 1, 7), - DatePrevisionnelle = new DateTime(2018, 1, 6), + DateCreation = new DateTime(2020, 10, 15), + DatePrevisionnelle = new DateTime(2020, 12, 4), Obligatoire = false, - Statut = StatutEp.Signe, + Statut = StatutEp.SignatureReferent, CV = "CV.pdf", - DateSaisie = new DateTime(2018, 6, 20) + DateSaisie = new DateTime(2020, 12, 10) }; 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 { - Action = "Je m'engage à...", - Dispositif = "interne", - Modalite = "Modalite", - DateLimite = new DateTime(2017, 7, 7), + IdEngagement = 1, + 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.EnAttente, RaisonNonRealisable = null, Ep = ep9 @@ -321,28 +328,147 @@ namespace EPAServeur.Context engagement2 = new Engagement { - Action = "Je m'engage à faire...", - Dispositif = "externe", - Modalite = "Modalite 2", - DateLimite = new DateTime(2017, 7, 8), + IdEngagement = 2, + Action = "Je m'engage à attribuer une progression salariale.", + Dispositif = "Demande d'augmentation RH.", + Modalite = "Hors temps", + DateLimite = new DateTime(2020, 9, 1), EtatEngagement = EtatEngagement.EnAttente, RaisonNonRealisable = null, - Ep = ep10 + Ep = ep9 }; epContext.Engagement.Add(engagement2); engagement3 = new Engagement { - Action = "Je m'engage à faire...", - Dispositif = "externe", - Modalite = "Modalite 3", - DateLimite = new DateTime(2017, 7, 8), + IdEngagement = 3, + Action = "Je m'engage à réaliser des points hebdomadaires avec l'équipe pour renforcer le lien social.", + Dispositif = "Planifier un point hebdomadaire sur Teams.", + Modalite = "Sur temps de travail", + DateLimite = new DateTime(2020, 9, 1), EtatEngagement = EtatEngagement.EnAttente, - RaisonNonRealisable = "Aucune formation disponible", - Ep = ep11 + RaisonNonRealisable = null, + Ep = ep9 }; 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(); } @@ -358,7 +484,7 @@ namespace EPAServeur.Context statutPlanifie = new StatutFormation { IdStatutFormation = 1, Libelle = "Planifiée" }; epContext.StatutFormation.Add(statutPlanifie); - statutReplanifie = new StatutFormation { IdStatutFormation = 2, Libelle = "Replanifié" }; + statutReplanifie = new StatutFormation { IdStatutFormation = 2, Libelle = "Replanifiée" }; epContext.StatutFormation.Add(statutReplanifie); statutRealise = new StatutFormation { IdStatutFormation = 3, Libelle = "Réalisée" }; @@ -443,10 +569,11 @@ namespace EPAServeur.Context f1 = new Formation { - Intitule = "Formation1", - - DateDebut = new DateTime(2020, 9, 16, 10, 0, 0), - DateFin = new DateTime(2020, 9, 16), + IdFormation = 1, + Intitule = "Formation Mainframe Complète", + + DateDebut = new DateTime(2020, 1, 25, 10, 0, 0), + DateFin = new DateTime(2020, 1, 27), IdAgence = 1, Heure = 2, Jour = 1, @@ -461,10 +588,11 @@ namespace EPAServeur.Context f2 = new Formation { - Intitule = "Formation2", - - DateDebut = new DateTime(2020, 10, 5, 14, 0, 0), - DateFin = new DateTime(2020, 10, 9), + IdFormation = 2, + Intitule = "Formation professionnelle React + Redux", + + DateDebut = new DateTime(2020, 2, 25, 14, 0, 0), + DateFin = new DateTime(2020, 2, 27), IdAgence = 1, Heure = 10, Jour = 5, @@ -479,10 +607,11 @@ namespace EPAServeur.Context f3 = new Formation { - Intitule = "Formation3", - - DateDebut = new DateTime(2020, 9, 21, 14, 0, 0), - DateFin = new DateTime(2020, 9, 21), + IdFormation = 3, + Intitule = "Apprendre C# et le développement de logiciels avec WPF", + + DateDebut = new DateTime(2020, 5, 25, 14, 0, 0), + DateFin = new DateTime(2020, 5, 27), IdAgence = 1, Heure = 4, Jour = 2, @@ -497,10 +626,11 @@ namespace EPAServeur.Context f4 = new Formation { - Intitule = "Formation4", - - DateDebut = new DateTime(2020, 05, 11, 14, 0, 0), - DateFin = new DateTime(2020, 05, 11), + IdFormation = 4, + Intitule = "Formation Visual Basic.Net - Initiation + Approfondissement", + + DateDebut = new DateTime(2020, 7, 25, 14, 0, 0), + DateFin = new DateTime(2020, 7, 27), IdAgence = 1, Heure = 3, Jour = 1, @@ -515,10 +645,11 @@ namespace EPAServeur.Context f5 = new Formation { - Intitule = "Formation5", - - DateDebut = new DateTime(2020, 08, 1, 13, 0, 0), - DateFin = new DateTime(2020, 08, 3), + IdFormation = 5, + Intitule = "Formation Conception, langage SQL : Les fondamentaux", + + DateDebut = new DateTime(2020, 8, 25, 14, 0, 0), + DateFin = new DateTime(2020, 8, 27), IdAgence = 1, Heure = 6, Jour = 2, @@ -533,10 +664,11 @@ namespace EPAServeur.Context f6 = new Formation { - Intitule = "Formation6", - - DateDebut = new DateTime(2020, 9, 30, 9, 0, 0), - DateFin = new DateTime(2020, 10, 1), + IdFormation = 6, + Intitule = "Formation Laravel 5.x, Développement WEB en PHP", + + DateDebut = new DateTime(2020, 9, 25, 14, 0, 0), + DateFin = new DateTime(2020, 9, 27), IdAgence = 1, Heure = 4, Jour = 2, @@ -551,10 +683,11 @@ namespace EPAServeur.Context f7 = new Formation { - Intitule = "Formation7", - - DateDebut = new DateTime(2020, 10, 5, 10, 0, 0), - DateFin = new DateTime(2020, 10, 8), + IdFormation = 7, + Intitule = "Formation d’initiation aux Méthodes Agiles – Scrum", + + DateDebut = new DateTime(2020, 11, 25, 14, 0, 0), + DateFin = new DateTime(2020, 11, 27), IdAgence = 1, Heure = 6, Jour = 5, @@ -569,9 +702,10 @@ namespace EPAServeur.Context f8 = new Formation { - Intitule = "Formation2", - DateDebut = new DateTime(2020, 11, 18, 10, 0, 0), - DateFin = new DateTime(2020, 11, 20), + IdFormation = 8, + Intitule = "Formation Xamarin, Développer des applications mobiles en C# pour iOS et Android", + DateDebut = new DateTime(2020, 12, 25, 14, 0, 0), + DateFin = new DateTime(2020, 12, 27), IdAgence = 1, Heure = 6, Jour = 3, @@ -586,7 +720,8 @@ namespace EPAServeur.Context 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), DateFin = new DateTime(2020, 11, 15), IdAgence = 1, @@ -603,7 +738,8 @@ namespace EPAServeur.Context f10 = new Formation { - Intitule = "Formation10", + IdFormation = 10, + Intitule = "Architecture Microservices – Les fondamentaux", DateDebut = new DateTime(2020, 8, 3, 14, 0, 0), DateFin = new DateTime(2020, 8, 3), IdAgence = 1, @@ -612,7 +748,7 @@ namespace EPAServeur.Context ModeFormation = modePresentiel, TypeFormation = typeInterne, Organisme = "Organisme4", - Origine = origineFormationClient, + Origine = origineFormationReglementaire, Statut = statutAnnule, EstCertifiee = false }; @@ -620,7 +756,8 @@ namespace EPAServeur.Context f11 = new Formation { - Intitule = "Formation11", + IdFormation = 11, + Intitule = "Formation Clean Architecture .Net Core", DateDebut = new DateTime(2020, 04, 6, 9, 0, 0), DateFin = new DateTime(2020, 04, 11), IdAgence = 1, @@ -629,28 +766,514 @@ namespace EPAServeur.Context ModeFormation = modePresentiel, TypeFormation = typeInterne, Organisme = "Organisme1", - Origine = origineFormationClient, + Origine = origineFormationReglementaire, Statut = statutAnnule, EstCertifiee = false }; 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 = { }; */ + // 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(); } diff --git a/EPAServeur/Context/EpContext.cs b/EPAServeur/Context/EpContext.cs index 4f37516..ce485c3 100644 --- a/EPAServeur/Context/EpContext.cs +++ b/EPAServeur/Context/EpContext.cs @@ -159,6 +159,7 @@ namespace EPAServeur.Context { entity.HasKey(e => e.IdFormation); entity.Property(e => e.IdFormation).ValueGeneratedOnAdd(); + entity.HasMany(e => e.ParticipationsFormation).WithOne(e => e.Formation); }); modelBuilder.Entity(entity => diff --git a/EPAServeur/Controllers/EngagementsApi.cs b/EPAServeur/Controllers/EngagementsApi.cs index 95ba16a..0408661 100644 --- a/EPAServeur/Controllers/EngagementsApi.cs +++ b/EPAServeur/Controllers/EngagementsApi.cs @@ -19,6 +19,16 @@ using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; 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 { @@ -28,12 +38,23 @@ namespace IO.Swagger.Controllers [ApiController] public class EngagementsApiController : ControllerBase { + private readonly IEngagementService engagementService; + private readonly ILogger logger; + private readonly IWebHostEnvironment env; + + public EngagementsApiController(IEngagementService _engagementService, ILogger _logger, IWebHostEnvironment _env) + { + engagementService = _engagementService; + logger = _logger; + env = _env; + } + /// /// /// /// Récupérer la liste des engagements. - /// Etats de l'engagement /// liste des ids des BU auxquelles les données sont rattachées + /// Etats de l'engagement /// Indique si les données sont récupérées dans l'ordre croissant ou non /// Numéro de la page du tableau à afficher /// Nombre d’élément maximum à afficher dans le tableau @@ -45,41 +66,49 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/engagements")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetEngagements")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetEngagements([FromQuery]List etatsEngagement, [FromQuery]List idBUs, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetEngagements([FromQuery][CannotBeEmpty] List idBUs, [FromQuery]List 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(..), ... - // return StatusCode(200, default(List)); + if (env.IsDevelopment()) + 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(..), ... - // return StatusCode(401, default(ErreurDTO)); + IEnumerable engagements; - //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)); + try + { + 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - 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}, {\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} ]"; + ErreurDTO erreur = new ErreurDTO() + { + Code = StatusCodes.Status500InternalServerError, + Message = "Une erreur inconnue est survenue sur le serveur." + }; - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + return StatusCode(erreur.Code.Value, erreur); + } + + if (env.IsDevelopment()) + logger.LogInformation("Liste des engagements récupérée."); + + return Ok(engagements); } /// /// /// /// Récupérer le nombre total d’engagements. - /// Etats de l'engagement /// liste des ids des BU auxquelles les données sont rattachées + /// Etats de l'engagement /// Indique si les données sont récupérées dans l'ordre croissant ou non /// Numéro de la page du tableau à afficher /// Nombre d’élément maximum à afficher dans le tableau @@ -91,33 +120,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/engagements/count")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetEngagementsCount")] [SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetEngagementsCount([FromQuery]List etatsEngagement, [FromQuery]List idBUs, [FromQuery]bool? asc, [FromQuery]int? numPage, [FromQuery][Range(5, 100)]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetEngagementsCount([FromQuery][CannotBeEmpty]List idBUs, [FromQuery]List 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(..), ... - // return StatusCode(200, default(long?)); + if (env.IsDevelopment()) + 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(..), ... - // return StatusCode(401, default(ErreurDTO)); + try + { + 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(..), ... - // return StatusCode(403, default(ErreurDTO)); + ErreurDTO erreur = new 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(500, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "0"; + return StatusCode(erreur.Code.Value, erreur); + } - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(long?); //TODO: Change the data returned - return new ObjectResult(example); + if (env.IsDevelopment()) + logger.LogInformation("Nombre total d'engagement récupéré."); + + return Ok(count); } /// @@ -134,7 +171,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpPut] [Route("/api/engagements/{idEngagement}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("UpdateEngagement")] [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'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: 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 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(..), ... - // return StatusCode(200, default(EngagementDTO)); + if (env.IsDevelopment()) + 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(..), ... - // return StatusCode(401, default(ErreurDTO)); + ErreurDTO erreur = new 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(403, default(ErreurDTO)); + return StatusCode(erreur.Code.Value, erreur); + } + 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(..), ... - // return StatusCode(404, default(ErreurDTO)); + ErreurDTO erreur = new 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(415, default(ErreurDTO)); + return StatusCode(erreur.Code.Value, erreur); + } - //TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(500, default(ErreurDTO)); - 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}"; + if (env.IsDevelopment()) + logger.LogInformation("Update effectué avec succès."); - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(EngagementDTO); //TODO: Change the data returned - return new ObjectResult(example); + return Ok(body); } } } diff --git a/EPAServeur/Controllers/FormationsApi.cs b/EPAServeur/Controllers/FormationsApi.cs index 38166bb..5ec93ff 100644 --- a/EPAServeur/Controllers/FormationsApi.cs +++ b/EPAServeur/Controllers/FormationsApi.cs @@ -18,15 +18,36 @@ using IO.Swagger.Attributes; using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; 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 -{ +{ /// /// /// [ApiController] public class FormationsApiController : ControllerBase - { + { + private readonly IFormationService formationService; + private readonly ILogger logger; + private readonly IWebHostEnvironment env; + + public FormationsApiController(IFormationService _formationService, ILogger _logger, IWebHostEnvironment _env) + { + formationService = _formationService; + logger = _logger; + env = _env; + } + /// /// /// @@ -39,7 +60,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpPost] [Route("/api/formations")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("AddFormation")] [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: 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")] - public virtual 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(..), ... - // return StatusCode(201, default(FormationDTO)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 415 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - 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}"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(FormationDTO); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task AddFormation([FromBody] FormationDTO body) + { + if (env.IsDevelopment()) + logger.LogInformation("Ajout d'une nouvelle formation."); + + try + { + body = await formationService.AddFormationAsync(body); + } + catch (FormationInvalidException e) + { + if (env.IsDevelopment()) + logger.LogInformation(e.Message); + + ErreurDTO erreur = new ErreurDTO() + { + Code = StatusCodes.Status500InternalServerError, + Message = e.Message, + }; + + return StatusCode(erreur.Code.Value, erreur.Message); + } + 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); } /// @@ -84,31 +133,76 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpDelete] [Route("/api/formations/{idFormation}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("DeleteFormation")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 404, type: typeof(ErreurDTO), description: "La ressource n'a pas été trouvée")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual 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(..), ... - // return StatusCode(204); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(404, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(500, default(ErreurDTO)); - - throw new NotImplementedException(); + public virtual async Task DeleteFormation([FromRoute][Required] long idFormation) + { + try + { + if (env.IsDevelopment()) + logger.LogInformation("Suppresion de la formation {idFormation}.", idFormation); + + FormationDTO formation = await formationService.DeleteFormationByIdAsync(idFormation); + } + 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("Formation {idFormation} supprimée avec succès.", idFormation); + + return NoContent(); } /// @@ -123,7 +217,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations/{idFormation}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetFormationById")] [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: 404, type: typeof(ErreurDTO), description: "La ressource n'a pas été trouvée")] [SwaggerResponse(statusCode: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual 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(..), ... - // return StatusCode(200, default(FormationDTO)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(404, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 500 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - 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}"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(FormationDTO); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetFormationById([FromRoute][Required] long idFormation) + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la formation {idFormation}.", idFormation); + + FormationDTO formationDTO; + + try + { + formationDTO = await formationService.GetFormationByIdAsync(idFormation); + } + catch (FormationNotFoundException e) + { + if (env.IsDevelopment()) + logger.LogInformation(e.Message); + + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = StatusCodes.Status404NotFound, + Message = e.Message + }; + + 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); } /// @@ -175,33 +287,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetFormations")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetFormations([FromQuery]long? idAgence, [FromQuery]List 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) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - 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} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetFormations([FromQuery] long? idAgence, [FromQuery] List 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) + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la liste des formations."); + + IEnumerable formations; + + try + { + formations = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, 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." + }; + + return StatusCode(erreur.Code.Value, erreur); + } + + if (env.IsDevelopment()) + logger.LogInformation("Liste des formations récupérée."); + + return Ok(formations); } /// @@ -223,33 +343,42 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations/count")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetFormationsCount")] [SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetFormationsCount([FromQuery]long? idAgence, [FromQuery]List 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) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(long?)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "0"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(long?); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetFormationsCount([FromQuery] long? idAgence, [FromQuery] List idStatuts, [FromQuery] int? numPage, [FromQuery][Range(5, 100)][DefaultValue(15)] int? parPAge, [FromQuery] string texte, [FromQuery] DateTime? dateDebut, [FromQuery] DateTime? dateFin) + { + if (env.IsDevelopment()) + 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." + }; + + return StatusCode(erreur.Code.Value, erreur); + } + + if (env.IsDevelopment()) + logger.LogInformation("Nombre total de formations récupéré."); + + return Ok(count); + } /// @@ -262,33 +391,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/modesformation")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetModesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetModesFormation() - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 1\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetModesFormation() + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la liste des modes de formation."); + + IEnumerable modeFormations; + + try + { + modeFormations = await formationService.GetModesFormationAsync(); + } + 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("Liste des modes de formation récupérée."); + + return Ok(modeFormations); } /// @@ -301,33 +438,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/originesformation")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetOriginesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetOriginesFormation() - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // 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 - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetOriginesFormation() + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la liste des origines de formation."); + + IEnumerable origineFormations; + + try + { + origineFormations = await formationService.GetOriginesFormationAsync(); + } + 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("Liste des origines de formation récupérée."); + + return Ok(origineFormations); } /// @@ -340,33 +485,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/statutsformation")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetStatutsFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetStatutsFormation() - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // 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 - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetStatutsFormation() + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la liste des statuts de formation."); + + IEnumerable statutFormations; + + try + { + statutFormations = await formationService.GetStatutsFormationAsync(); + } + 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("Liste des statuts de formation récupérée."); + + return Ok(statutFormations); } /// @@ -379,33 +532,41 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/typesformation")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("GetTypesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual IActionResult GetTypesFormation() - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n}, {\n \"libelle\" : \"libelle\",\n \"id\" : 6\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetTypesFormation() + { + if (env.IsDevelopment()) + logger.LogInformation("Récupération de la liste des types de formation."); + + IEnumerable typeFormations; + + try + { + typeFormations = await formationService.GetTypesFormationAsync(); + } + 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("Liste des types de formation récupérée."); + + return Ok(typeFormations); } /// @@ -422,7 +583,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpPut] [Route("/api/formations/{idFormation}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "RH")] [ValidateModelState] [SwaggerOperation("UpdateFormation")] [SwaggerResponse(statusCode: 401, type: typeof(ErreurDTO), description: "L'utilisateur souhaitant accéder à la ressource n'est pas authentifié")] @@ -430,27 +591,95 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "La ressource n'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: 500, type: typeof(ErreurDTO), description: "Une erreur est survenue sur le serveur")] - public virtual 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(..), ... - // return StatusCode(200); - - //TODO: Uncomment the next line to return response 401 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(404, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 415 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // 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(..), ... - // return StatusCode(500, default(ErreurDTO)); - - throw new NotImplementedException(); + public virtual async Task UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long idFormation) + { + if (env.IsDevelopment()) + logger.LogInformation("Mise à jour de la formation d'id {idFormation}.", idFormation); + + try + { + body = await formationService.UpdateFormationAsync(idFormation, body); + } + catch (FormationIncompatibleIdException 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 (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); } } } diff --git a/EPAServeur/DTO/FormationDetailsDTO.cs b/EPAServeur/DTO/FormationDetailsDTO.cs index 0a269c1..6d818e9 100644 --- a/EPAServeur/DTO/FormationDetailsDTO.cs +++ b/EPAServeur/DTO/FormationDetailsDTO.cs @@ -92,8 +92,8 @@ namespace IO.Swagger.DTO /// /// Indique si la formation est certifiée ou non [Required] - [DataMember(Name="estCertifie")] - public bool? EstCertifie { get; set; } + [DataMember(Name="estCertifiee")] + public bool? EstCertifiee { get; set; } /// /// Returns the string presentation of the object @@ -111,7 +111,7 @@ namespace IO.Swagger.DTO sb.Append(" Organisme: ").Append(Organisme).Append("\n"); sb.Append(" NbParticipations: ").Append(NbParticipations).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"); return sb.ToString(); } @@ -189,9 +189,9 @@ namespace IO.Swagger.DTO Origine.Equals(other.Origine) ) && ( - EstCertifie == other.EstCertifie || - EstCertifie != null && - EstCertifie.Equals(other.EstCertifie) + EstCertifiee == other.EstCertifiee || + EstCertifiee != null && + EstCertifiee.Equals(other.EstCertifiee) ); } @@ -221,8 +221,8 @@ namespace IO.Swagger.DTO hashCode = hashCode * 59 + NbParticipations.GetHashCode(); if (Origine != null) hashCode = hashCode * 59 + Origine.GetHashCode(); - if (EstCertifie != null) - hashCode = hashCode * 59 + EstCertifie.GetHashCode(); + if (EstCertifiee != null) + hashCode = hashCode * 59 + EstCertifiee.GetHashCode(); return hashCode; } } diff --git a/EPAServeur/EPAServeur.csproj b/EPAServeur/EPAServeur.csproj index 6f38212..a72dab4 100644 --- a/EPAServeur/EPAServeur.csproj +++ b/EPAServeur/EPAServeur.csproj @@ -7,10 +7,10 @@ + - diff --git a/EPAServeur/Enum/StatutEp.cs b/EPAServeur/Enum/StatutEp.cs index 6f95570..4c93d06 100644 --- a/EPAServeur/Enum/StatutEp.cs +++ b/EPAServeur/Enum/StatutEp.cs @@ -39,7 +39,7 @@ namespace IO.Swagger.Enum [EnumMember(Value = "DatesProposees")] DatesProposees = 3, /// - /// Indique qu’il s’agit d’un EPS + /// Le collaborateur a choisi une date, il ne reste plus qu'à attendre l'entretien /// [EnumMember(Value = "AttenteEntretien")] AttenteEntretien = 4, diff --git a/EPAServeur/Exceptions/EngagementIncompatibleIdException.cs b/EPAServeur/Exceptions/EngagementIncompatibleIdException.cs index d11a25b..eaf497f 100644 --- a/EPAServeur/Exceptions/EngagementIncompatibleIdException.cs +++ b/EPAServeur/Exceptions/EngagementIncompatibleIdException.cs @@ -5,10 +5,10 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { - /// - /// Exception à jeter lorsque l'id de l'engagement avec les données à mettre à jour et l'id de l'engagement à mettre sont différents - /// - public class EngagementIncompatibleIdException : Exception + /// + /// 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 + /// + public class EngagementIncompatibleIdException : Exception { /// /// Initialise une nouvelle instance de la classe class. diff --git a/EPAServeur/Exceptions/EngagementInvalidException.cs b/EPAServeur/Exceptions/EngagementInvalidException.cs index 15e974a..6c94aa9 100644 --- a/EPAServeur/Exceptions/EngagementInvalidException.cs +++ b/EPAServeur/Exceptions/EngagementInvalidException.cs @@ -5,10 +5,10 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { - /// - /// Exception à jeter lorsqu'un engagement est invalide - /// - public class EngagementInvalidException : Exception + /// + /// Exception qui est levée lorsqu'un engagement est invalide + /// + public class EngagementInvalidException : Exception { /// /// Initialise une nouvelle instance de la classe class. diff --git a/EPAServeur/Exceptions/EngagementNotFoundException.cs b/EPAServeur/Exceptions/EngagementNotFoundException.cs index 365f553..9e959cf 100644 --- a/EPAServeur/Exceptions/EngagementNotFoundException.cs +++ b/EPAServeur/Exceptions/EngagementNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// Exception à jeter lorsqu'un engagement n'a pas été trouvé + /// Exception qui est levée lorsqu'un engagement n'a pas été trouvé /// public class EngagementNotFoundException : Exception { diff --git a/EPAServeur/Exceptions/FormationIncompatibleIdException.cs b/EPAServeur/Exceptions/FormationIncompatibleIdException.cs index 99dcaf2..ffee42c 100644 --- a/EPAServeur/Exceptions/FormationIncompatibleIdException.cs +++ b/EPAServeur/Exceptions/FormationIncompatibleIdException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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 /// public class FormationIncompatibleIdException : Exception { diff --git a/EPAServeur/Exceptions/FormationInvalidException.cs b/EPAServeur/Exceptions/FormationInvalidException.cs index 8b72fe2..9e0ff33 100644 --- a/EPAServeur/Exceptions/FormationInvalidException.cs +++ b/EPAServeur/Exceptions/FormationInvalidException.cs @@ -5,10 +5,10 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { - /// - /// Exception à jeter lorsqu'une formation est invalide - /// - public class FormationInvalidException : Exception + /// + /// Exception qui est levée lorsqu'une formation est invalide + /// + public class FormationInvalidException : Exception { /// /// Initialise une nouvelle instance de la classe class. diff --git a/EPAServeur/Exceptions/FormationNotFoundException.cs b/EPAServeur/Exceptions/FormationNotFoundException.cs index 93fdcc9..a9e59dc 100644 --- a/EPAServeur/Exceptions/FormationNotFoundException.cs +++ b/EPAServeur/Exceptions/FormationNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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 /// public class FormationNotFoundException : Exception { diff --git a/EPAServeur/Exceptions/ModeFormationNotFoundException.cs b/EPAServeur/Exceptions/ModeFormationNotFoundException.cs index c3c1f4a..4269223 100644 --- a/EPAServeur/Exceptions/ModeFormationNotFoundException.cs +++ b/EPAServeur/Exceptions/ModeFormationNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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é /// public class ModeFormationNotFoundException : Exception { diff --git a/EPAServeur/Exceptions/OrigineFormationNotFoundException.cs b/EPAServeur/Exceptions/OrigineFormationNotFoundException.cs index 26438b6..cfa5d8e 100644 --- a/EPAServeur/Exceptions/OrigineFormationNotFoundException.cs +++ b/EPAServeur/Exceptions/OrigineFormationNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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 /// public class OrigineFormationNotFoundException : Exception { diff --git a/EPAServeur/Exceptions/StatutFormationNotFoundException.cs b/EPAServeur/Exceptions/StatutFormationNotFoundException.cs index 66c7167..171c017 100644 --- a/EPAServeur/Exceptions/StatutFormationNotFoundException.cs +++ b/EPAServeur/Exceptions/StatutFormationNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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é /// public class StatutFormationNotFoundException : Exception { diff --git a/EPAServeur/Exceptions/TypeFormationNotFoundException.cs b/EPAServeur/Exceptions/TypeFormationNotFoundException.cs index 54f1de8..393d02b 100644 --- a/EPAServeur/Exceptions/TypeFormationNotFoundException.cs +++ b/EPAServeur/Exceptions/TypeFormationNotFoundException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// 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é /// public class TypeFormationNotFoundException : Exception { diff --git a/EPAServeur/IServices/IEngagementService.cs b/EPAServeur/IServices/IEngagementService.cs index bc94629..3d22f92 100644 --- a/EPAServeur/IServices/IEngagementService.cs +++ b/EPAServeur/IServices/IEngagementService.cs @@ -1,5 +1,6 @@ using EPAServeur.Context; using IO.Swagger.DTO; +using IO.Swagger.Enum; using IO.Swagger.ModelCollaborateur; using System; using System.Collections.Generic; @@ -10,16 +11,8 @@ namespace EPAServeur.IServices { public interface IEngagementService { - - IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, string texte, string tri); - Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri); - IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, string texte, string tri); - Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri); - IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, string texte, string tri); - Task> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri); - - EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement); - Task RepondreEngagementAsync(EngagementDTO engagement, long? idEngagement); - + Task> GetEngagementsAsync(List idBUs, List etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri); + Task GetEngagementsCountAsync(List idBUs, List etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri); + Task RepondreEngagementAsync(EngagementDTO engagement, long idEngagement); } } diff --git a/EPAServeur/IServices/IFormationService.cs b/EPAServeur/IServices/IFormationService.cs index 4a5e172..099e065 100644 --- a/EPAServeur/IServices/IFormationService.cs +++ b/EPAServeur/IServices/IFormationService.cs @@ -10,31 +10,17 @@ namespace EPAServeur.IServices { public interface IFormationService { - FormationDTO GetFormationById(long? idFormation); - Task GetFormationByIdAsync(long? idFormation); - IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri); - Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri); - IEnumerable GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - Task> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetFormationRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - Task> GetFormationRealiseesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetProchainesFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - Task> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetModesFormation(); + Task GetFormationByIdAsync(long idFormation); + Task> GetFormationsAsync(long? idAgence, List idStatuts, bool? asc, int? numPage, int? parPage, string texte, string tri, DateTime? dateDebut, DateTime? dateFin); + Task GetFormationsCountAsync(long? idAgence, List idStatuts, int? numPage, int? parPage, string texte, DateTime? dateDebut, DateTime? dateFin); Task> GetModesFormationAsync(); - IEnumerable GetOriginesFormation(); Task> GetOriginesFormationAsync(); - IEnumerable GetStatutsFormation(); Task> GetStatutsFormationAsync(); - IEnumerable GetTypesFormation(); Task> GetTypesFormationAsync(); - FormationDTO AddFormation(FormationDTO formationDTO); Task AddFormationAsync(FormationDTO formationDTO); - FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO); - Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO); - FormationDTO DeleteFormationById(long? idFormation); - Task DeleteFormationByIdAsync(long? idFormation); + Task UpdateFormationAsync(long idFormation, FormationDTO formationDTO); + Task DeleteFormationByIdAsync(long idFormation); } } diff --git a/EPAServeur/Models/Formation/Formation.cs b/EPAServeur/Models/Formation/Formation.cs index 5c51cdd..16afbcd 100644 --- a/EPAServeur/Models/Formation/Formation.cs +++ b/EPAServeur/Models/Formation/Formation.cs @@ -80,5 +80,10 @@ namespace EPAServeur.Models.Formation /// Type de formation qui est lié à la formation /// public TypeFormation TypeFormation { get; set; } + + /// + /// Liste des participations qui sont liées à la formation + /// + public List ParticipationsFormation { get; set; } } } diff --git a/EPAServeur/Services/EngagementService.cs b/EPAServeur/Services/EngagementService.cs index b5f6a69..ad750a5 100644 --- a/EPAServeur/Services/EngagementService.cs +++ b/EPAServeur/Services/EngagementService.cs @@ -2,15 +2,11 @@ using EPAServeur.Exceptions; using EPAServeur.IServices; using EPAServeur.Models.EP; -using EPAServeur.Models.Formation; -using EPAServeur.Models.SaisieChamp; using IO.Swagger.DTO; using IO.Swagger.Enum; -using IO.Swagger.ModelCollaborateur; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Threading.Tasks; @@ -20,9 +16,42 @@ namespace EPAServeur.Services { #region Variables + + /// + /// Accès et gestion de la base de données + /// private readonly EpContext epContext; + + /// + /// Accès et service collaborateur + /// private readonly ICollaborateurService collaborateurService; - private readonly IReferentEPService referentService; + + /// + /// Nombre d'éléments min à afficher par page + /// + private readonly int minParPage = 5; + + /// + /// Nom d'éléments max à affichar par page + /// + private readonly int maxParPage = 100; + + /// + /// Nombre d'éléments à afficher par défaut par page + /// + private readonly int defaultParPage = 15; + + /// + /// Numéro de page min à afficher par défaut + /// + private readonly int defaultNumPage = 1; + + /// + /// Ordonnancement par défaut + /// + private readonly bool defaultAsc = true; + #endregion #region Contructeurs @@ -31,260 +60,270 @@ namespace EPAServeur.Services /// Constructeur de la classe EngagementService /// /// - public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService, IReferentEPService _referentService) + public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService) { epContext = _epContext; collaborateurService = _collaborateurService; - referentService = _referentService; } #endregion #region Méthodes Service - public IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, string texte, string tri) + /// + /// Récupérer la liste des engagements de manière asynchrone + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetEngagementsAsync(List idBUs, List etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri) { + IQueryable query; IEnumerable engagements; + IEnumerable engagementDTOs; + IEnumerable collaborateurDTOs; - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + query = epContext.Engagement.Include(engagement => engagement.Ep); + query = IdBUsFilter(query, idBUs); + query = EtatsEngagementFilter(query, etatsEngagement); + query = ActionFilter(query, texte); + query = OrderByColumn(query, asc, tri); + query = SkipAndTake(query, parPage, numPage); - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Skip(skip).Take(take); + engagements = await query.ToListAsync(); - if (engagements == null || engagements.Count() == 0) - return new List(); + collaborateurDTOs = await GetCollaborateurDTOs(engagements); - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + engagementDTOs = engagements.Select(engagement => GetEngagementDTO(engagement, collaborateurDTOs)); return engagementDTOs; } - public async Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) + public async Task GetEngagementsCountAsync(List idBUs, List etatsEngagement, bool? asc, int? numPage, int? parPage, string texte, string tri) { - IEnumerable 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).Skip(skip).Take(take).ToListAsync(); + IQueryable query; + long count; - if (engagements == null || engagements.Count() == 0) - return new List(); + query = epContext.Engagement.Include(engagement => engagement.Ep); + 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)); - var results = await Task.WhenAll(engagementDTOs); + count = await query.CountAsync(); - return results; + return count; } - public IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, string texte, string tri) + /// + /// Donner une réponse à un engagement de manière asynchrone + /// + /// + /// + /// + public async Task RepondreEngagementAsync(EngagementDTO engagementDTO, long idEngagement) { - IEnumerable engagements; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + IEnumerable collaborateurDTOs; + Engagement engagement; - 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) - return new List(); + if (!engagementDTO.Id.HasValue || engagementDTO.Id.Value != idEngagement) + 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)); - - return engagementDTOs; - } + engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.IdEngagement == idEngagement); - public async Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) - { - IEnumerable engagements; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + if (engagement == null) + throw new EngagementNotFoundException(); - 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) - return new List(); + engagement = SetReponseEngagement(engagement, engagementDTO); - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); - var results = await Task.WhenAll(engagementDTOs); + await epContext.SaveChangesAsync(); - return results; + return GetEngagementDTO(engagement, collaborateurDTOs); } - public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, string texte, string tri) - { - IEnumerable engagements; - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + #endregion - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + #region Méthodes Privée + /// + /// Vérifier si un objet EngagementDTO est valide pour ajout ou mise à jour + /// + /// 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. + /// + /// + 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) - return new List(); + // Vérfier que l'ep a bien été signé par le collaborateur + 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> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, string texte, string tri) - { - IEnumerable engagements; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + // Vérifier que l'engagement a bien une modalité + if (string.IsNullOrWhiteSpace(engagementDTO.Modalite)) + throw new EngagementInvalidException("La modalité de l'engagement doit contenir au moins 1 caractère."); - 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) - return new List(); - - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); - var results = await Task.WhenAll(engagementDTOs); + // 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 + 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é."); - 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."); } /// - /// Donner une réponse à un engagement + /// Ajouter un ordonnancement croissant ou décroissant sur colonne /// - /// - /// + /// + /// /// - public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) + private IQueryable OrderByColumn(IQueryable query, bool? asc, string columnName) { + if (!asc.HasValue) + asc = defaultAsc; - if (!IsEngagementValide(engagementDTO)) - throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); - - 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é."); - - 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(); + if (string.IsNullOrWhiteSpace(columnName)) + { + if (asc.Value) + return query.OrderBy(p => p.Action); - engagement.EtatEngagement = engagementDTO.EtatEngagement; + return query.OrderByDescending(p => p.Action); + } - switch (engagement.EtatEngagement) + switch (columnName.ToLower()) { - case EtatEngagement.Respecte: - engagement.EtatEngagement = engagementDTO.EtatEngagement; - engagement.RaisonNonRealisable = null; - break; - case EtatEngagement.NonRealisable: - engagement.EtatEngagement = engagementDTO.EtatEngagement; - engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; - break; + case "action": + if (asc.Value) + return query.OrderBy(p => p.Action); + + return query.OrderByDescending(p => p.Action); + case "dispositif": + if (asc.Value) + 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: - engagement.EtatEngagement = engagementDTO.EtatEngagement; - engagement.RaisonNonRealisable = null; - break; + if (asc.Value) + return query.OrderBy(p => p.Action); + + return query.OrderByDescending(p => p.Action); } + } - epContext.SaveChanges(); + /// + /// Ajouter un filtre pour récupérer les engagements en fonction de plusieurs identifiants de Business Unit + /// + /// + /// + /// + /// + private IQueryable IdBUsFilter(IQueryable query, List 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)); } - /// - /// 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 /// - /// - /// + /// + /// /// - public async Task RepondreEngagementAsync(EngagementDTO engagementDTO, long? idEngagement) + private IQueryable EtatsEngagementFilter(IQueryable query, List etatsEngagement) { + if (etatsEngagement == null || etatsEngagement.Count <= 0) + return query; - if (!IsEngagementValide(engagementDTO)) - throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); + return query.Where(engagement => etatsEngagement.Contains(engagement.EtatEngagement)); + } - 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é."); + /// + /// Ajouter un filtre pour récupérer les engagements en fonction d'une action + /// + /// + /// + /// + private IQueryable ActionFilter(IQueryable 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); + /// + /// Ajouter une pagination + /// + /// + /// + /// + /// + private IQueryable SkipAndTake(IQueryable query, int? parPage, int? numPage) + { + int skip, take; - if (engagement == null) - throw new EngagementNotFoundException(); + if (!parPage.HasValue || parPage.Value < minParPage || parPage.Value > maxParPage) + parPage = defaultParPage; - engagement.EtatEngagement = engagementDTO.EtatEngagement; + if (!numPage.HasValue || numPage.Value <= 0) + numPage = defaultNumPage; - switch (engagement.EtatEngagement) - { - 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(); + skip = (numPage.Value - 1) * parPage.Value; + take = parPage.Value; - 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 /// - /// 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 /// /// /// - private EngagementDTO GetEngagementDTO(Engagement engagement) + private EngagementDTO GetEngagementDTO(Engagement engagement, IEnumerable collaborateurDTOs) { EngagementDTO engagementDTO = new EngagementDTO() { @@ -295,80 +334,67 @@ namespace EPAServeur.Services Modalite = engagement.Modalite, RaisonNonRealisable = engagement.RaisonNonRealisable, EtatEngagement = engagement.EtatEngagement, - Ep = GetEpInformationDTO(engagement.Ep) + Ep = GetEpInformationDTO(engagement.Ep, collaborateurDTOs) }; return engagementDTO; } + /// - /// 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. /// - /// + /// /// - private async Task GetEngagementDTOAsync(Engagement engagement) + private async Task> GetCollaborateurDTOs(Engagement engagement) { - EngagementDTO engagementDTO = new EngagementDTO() - { - 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) - }; + List guids = new List(); - return engagementDTO; + guids.Add((Guid?)engagement.Ep.IdCollaborateur); + guids.Add(engagement.Ep.IdReferent); + + return await collaborateurService.GetCollaborateurDTOsAsync(guids); ; } /// - /// 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. /// - /// + /// /// - private EpInformationDTO GetEpInformationDTO(Ep ep) + private async Task> GetCollaborateurDTOs(IEnumerable engagements) { - EpInformationDTO epInformationDTO = new EpInformationDTO() - { - 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é - }; + if (!engagements.Any()) + return null; - return epInformationDTO; + List guids = engagements.SelectMany(engagement => new[] { (Guid?)engagement.Ep.IdCollaborateur, engagement.Ep.IdReferent }).ToList(); + + return await collaborateurService.GetCollaborateurDTOsAsync(guids); } /// - /// 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 /// /// /// - private async Task GetEpInformationDTOAsync(Ep ep) + private EpInformationDTO GetEpInformationDTO(Ep ep, IEnumerable 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() { Id = ep.IdEP, Type = ep.TypeEP, Statut = ep.Statut, + DateDisponibilite = ep.DateDisponibilite, DatePrevisionnelle = ep.DatePrevisionnelle, - Obligatoire = ep.Obligatoire - //Ajouter la date de disponibilité + Obligatoire = ep.Obligatoire, + 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; } @@ -378,51 +404,31 @@ namespace EPAServeur.Services #region DTO to Object /// - /// Modifie un objet Engagement en fonction d'un objet FormationDTO + /// Modifie la réponse d'un objet Engagement en fonction d'un objet EngagementDTO /// /// /// /// - 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.Ep = GetEp(engagementDTO.Ep); - - return engagement; - } - - /// - /// Récupère un objet Ep en fonction d'un objet EpDTO - /// - /// - /// - private Ep GetEp(EpInformationDTO epInformationDTO) - { - if (epInformationDTO == null) - return null; - - Ep ep = new Ep() + switch (engagement.EtatEngagement) { - IdEP = epInformationDTO.Id.Value, - TypeEP = epInformationDTO.Type, - Statut = epInformationDTO.Statut, - DatePrevisionnelle = epInformationDTO.DatePrevisionnelle.Value, - Obligatoire = epInformationDTO.Obligatoire.Value, - IdReferent = epInformationDTO.Referent.Id.Value, - IdCollaborateur = epInformationDTO.Collaborateur.Id.Value, - // Ajouter la date de disponibilité - }; - - return ep; + case EtatEngagement.NonRealisable: + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + break; + case EtatEngagement.DateLimitePassee: + engagement.RaisonNonRealisable = "La date limite pour respecter l'engagement est passée."; + break; + default: + engagement.RaisonNonRealisable = null; + break; + } + + return engagement; } - #endregion #endregion diff --git a/EPAServeur/Services/FormationService.cs b/EPAServeur/Services/FormationService.cs index 378fc7a..2cd314d 100644 --- a/EPAServeur/Services/FormationService.cs +++ b/EPAServeur/Services/FormationService.cs @@ -1,6 +1,7 @@ using EPAServeur.Context; using EPAServeur.Exceptions; using EPAServeur.IServices; +using EPAServeur.Models.EP; using EPAServeur.Models.Formation; using IO.Swagger.DTO; using Microsoft.EntityFrameworkCore; @@ -15,8 +16,41 @@ namespace EPAServeur.Services { #region Variables + /// + /// Accès et gestion de la base de données + /// private readonly EpContext epContext; + /// + /// Accès et service collaborateur + /// + private readonly ICollaborateurService collaborateurService; + + /// + /// Nombre d'éléments min à afficher par page + /// + private readonly int minParPage = 5; + + /// + /// Nom d'éléments max à affichar par page + /// + private readonly int maxParPage = 100; + + /// + /// Nombre d'éléments à afficher par défaut par page + /// + private readonly int defaultParPage = 15; + + /// + /// Numéro de page min à afficher par défaut + /// + private readonly int defaultNumPage = 1; + + /// + /// Ordonnancement par défaut + /// + private readonly bool defaultAsc = true; + #endregion #region Contructeurs @@ -25,467 +59,117 @@ namespace EPAServeur.Services /// Constructeur de la classe FormationService /// /// - public FormationService(EpContext _epContext) + public FormationService(EpContext _epContext, ICollaborateurService _collaborateurService) { epContext = _epContext; + collaborateurService = _collaborateurService; } #endregion #region Méthodes Service - /// - /// Récupérer une formation par son id - /// - /// - /// - public FormationDTO GetFormationById(long? idFormation) - { - Formation formation = epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation) - .FirstOrDefault(formation => formation.IdFormation == idFormation); - - if (formation == null) - throw new FormationNotFoundException(); - - return GetFormationDTO(formation); - } - /// /// Récupérer une formation par son id de manière asynchrone /// /// /// - public async Task GetFormationByIdAsync(long? idFormation) + public async Task GetFormationByIdAsync(long idFormation) { Formation formation = await epContext.Formation.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation) .Include(formation => formation.Origine) .Include(formation => formation.TypeFormation) + .Include(formation => formation.ParticipationsFormation) + .ThenInclude(participation => participation.DemandeFormation) + .ThenInclude(demande => demande.Ep) .FirstOrDefaultAsync(formation => formation.IdFormation == idFormation); if (formation == null) - throw new FormationNotFoundException(); + throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.", idFormation)); - return GetFormationDTO(formation); + + IEnumerable collaborateurDTOs = await GetCollaborateurDTOs(formation.ParticipationsFormation); + + return GetFormationDTO(formation, collaborateurDTOs); } /// - /// Récupérer la liste des formations + /// Récupérer la liste des formations de manière asynchrone /// /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau + /// Nombre d'éléments affiché sur chaque page du tableau /// id de l'agence à laquelle sont rattachées les données à récupérer /// Texte permettant d'identifier l'objet rechercher /// Colonne du tableau sur lequel le tri s'effectue /// - public IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) + public async Task> GetFormationsAsync(long? idAgence, List idStatuts, bool? asc, int? numPage, int? parPage, string texte, string tri, DateTime? dateDebut, DateTime? dateFin) { + IQueryable query; IEnumerable formations; - IEnumerable formationDTOs; + IEnumerable formationDTOs; - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (statutFormation != null && idAgence != null) - { - formations = epContext.Formation + query = epContext.Formation .Include(formation => formation.Statut) .Include(formation => formation.ModeFormation) .Include(formation => formation.Origine) .Include(formation => formation.TypeFormation) - .Where(formation => formation.Statut.IdStatutFormation == statutFormation && formation.IdAgence == idAgence).Skip(skip).Take(take); - } - else if (statutFormation != null && idAgence == null) - { - formations = epContext.Formation - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation) - .Where(formation => formation.Statut.IdStatutFormation == statutFormation).Skip(skip).Take(take); - } - else if (idAgence != null) - { - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - } - else - { - formations = epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - } - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// Récupérer la liste des formations de manière asynchrone - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public async Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, int? statutFormation, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (statutFormation != null && idAgence != null) - { - formations = await epContext.Formation - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation) - .Where(formation => formation.Statut.IdStatutFormation == statutFormation && formation.IdAgence == idAgence).Skip(skip).Take(take).ToListAsync(); - } - else if (statutFormation != null && idAgence == null) - { - formations = await epContext.Formation - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation) - .Where(formation => formation.Statut.IdStatutFormation == statutFormation).Skip(skip).Take(take).ToListAsync(); - } - else if (idAgence != null) - { - - formations = await epContext.Formation - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Where(formation => formation.IdAgence == idAgence).Skip(skip).Take(take).ToListAsync(); - - } - else - { - - formations = await epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - - } - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// Récupérer les formations annulées - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public IEnumerable GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (idAgence != null) - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.IdStatutFormation == 4) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - else - formations = epContext.Formation.Where(formation => formation.Statut.IdStatutFormation == 4) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// Récupérer les formations annulées de manière asynchrone - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public async Task> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (idAgence != null) - formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.IdStatutFormation == 4) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - else - formations = await epContext.Formation.Where(formation => formation.Statut.IdStatutFormation == 4) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// Récupérer les formations réalisées - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public IEnumerable GetFormationRealisees(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (idAgence != null) - { - - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.IdStatutFormation == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - } - - else - { - - formations = epContext.Formation.Where(formation => formation.Statut.IdStatutFormation == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - - } - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// Récupérer les formations réalisées de manière asynchrone - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public async Task> GetFormationRealiseesAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); - - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - - if (idAgence != null) - { - - formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.IdStatutFormation == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - } + .Include(formation => formation.ParticipationsFormation); - else - { + query = IdStatutsFilter(query, idStatuts); - formations = await epContext.Formation.Where(formation => formation.Statut.IdStatutFormation == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - } + query = IdAgenceFilter(query, idAgence); - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + query = IntituleFilter(query, texte); - return formationDTOs; - } + query = DateFilter(query, dateDebut, dateFin); - /// - /// Récupérer les formations plannifiées et replannifiées - /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue - /// - public IEnumerable GetProchainesFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) - { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + query = OrderByColumn(query, asc, tri); - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + query = SkipAndTake(query, parPage, numPage); - if (idAgence != null) - { - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.IdStatutFormation == 1 || formation.Statut.IdStatutFormation == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - - } - else - { - formations = epContext.Formation.Where(formation => (formation.Statut.IdStatutFormation == 1 || formation.Statut.IdStatutFormation == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take); - } + formations = await query.ToListAsync(); - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + formationDTOs = formations.Select(formation => GetFormationDetailsDTO(formation)); return formationDTOs; } /// - /// Récupérer les formations plannifiées et replannifiées de manère asynchrone + /// Récupérer le nombre total de formations de manière asynchrone /// - /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) /// Numéro de la page du tableau qui affiche les données - /// Nombre d'éléments affiché sur chaque page du tableau + /// Nombre d'éléments affiché sur chaque page du tableau /// id de l'agence à laquelle sont rattachées les données à récupérer /// Texte permettant d'identifier l'objet rechercher - /// Colonne du tableau sur lequel le tri s'effectue /// - public async Task> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + public async Task GetFormationsCountAsync(long? idAgence, List idStatuts, int? numPage, int? parPage, string texte, DateTime? dateDebut, DateTime? dateFin) { - IEnumerable formations; - IEnumerable formationDTOs; - - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + IQueryable query; + long count; - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; - if (idAgence != null) - { - formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.IdStatutFormation == 1 || formation.Statut.IdStatutFormation == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); + query = epContext.Formation + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation) + .Include(formation => formation.ParticipationsFormation); - } + query = IntituleFilter(query, texte); - else - { - formations = await epContext.Formation.Where(formation => (formation.Statut.IdStatutFormation == 1 || formation.Statut.IdStatutFormation == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).Skip(skip).Take(take).ToListAsync(); - } + query = IdStatutsFilter(query, idStatuts); - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + query = IdAgenceFilter(query, idAgence); - return formationDTOs; - } + query = DateFilter(query, dateDebut, dateFin); - /// - /// Récupérer les modes de formation - /// - /// - public IEnumerable GetModesFormation() - { - IEnumerable modeFormations; - IEnumerable modeFormationDTOs; + query = SkipAndTake(query, parPage, numPage); - modeFormations = epContext.ModeFormation; + count = await query.CountAsync(); - modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); - - return modeFormationDTOs; + return count; } /// @@ -496,6 +180,7 @@ namespace EPAServeur.Services { IEnumerable modeFormations; IEnumerable modeFormationDTOs; + modeFormations = await epContext.ModeFormation.ToListAsync(); modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); @@ -503,22 +188,6 @@ namespace EPAServeur.Services return modeFormationDTOs; } - /// - /// Récupérer les origines de formation - /// - /// - public IEnumerable GetOriginesFormation() - { - IEnumerable origineFormations; - IEnumerable origineFormationDTOs; - - origineFormations = epContext.OrigineFormation; - - origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); - - return origineFormationDTOs; - } - /// /// Récupérer les origines de formation de manière asynchrone /// @@ -535,22 +204,6 @@ namespace EPAServeur.Services return origineFormationDTOs; } - /// - /// Récupérer les statuts de formation - /// - /// - public IEnumerable GetStatutsFormation() - { - IEnumerable statutFormations; - IEnumerable statutFormationDTOs; - - statutFormations = epContext.StatutFormation; - - statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); - - return statutFormationDTOs; - } - /// /// Récupérer les statuts de formation de manière asynchrone /// @@ -567,22 +220,6 @@ namespace EPAServeur.Services return statutFormationDTOs; } - /// - /// Récupérer les types de formation - /// - /// - public IEnumerable GetTypesFormation() - { - IEnumerable typeFormations; - IEnumerable typeFormationDTOs; - - typeFormations = epContext.TypeFormation; - - typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); - - return typeFormationDTOs; - } - /// /// Récupérer les types de formation de manière asynchrone /// @@ -600,14 +237,13 @@ namespace EPAServeur.Services } /// - /// Ajouter une formation + /// Ajouter une formation de manière asynchrone /// /// /// - public FormationDTO AddFormation(FormationDTO formationDTO) + public async Task AddFormationAsync(FormationDTO formationDTO) { - if (!IsFormationValide(formationDTO)) - throw new FormationInvalidException(); + IsFormationValide(formationDTO); Formation formation = new Formation(); formation = SetFormation(formation, formationDTO); @@ -618,177 +254,301 @@ namespace EPAServeur.Services epContext.TypeFormation.Attach(formation.TypeFormation); epContext.Add(formation); - epContext.SaveChanges(); + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } /// - /// Ajouter une formation de manière asynchrone + /// Modifier une formation de manière asynchrone /// + /// /// /// - public async Task AddFormationAsync(FormationDTO formationDTO) + public async Task UpdateFormationAsync(long idFormation, FormationDTO formationDTO) { - if (!await IsFormationValideAsync(formationDTO)) - throw new FormationInvalidException(); + if (!formationDTO.Id.HasValue || formationDTO.Id.Value != idFormation) + throw new FormationIncompatibleIdException("L'id de la formation a mettre à jour et la formation a mettre à jour sont incompatble."); - Formation formation = new Formation(); - formation = SetFormation(formation, formationDTO); + IsFormationValide(formationDTO); + + Formation formation = await epContext.Formation.FindAsync(idFormation); + + if (formation == null) + throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.", idFormation)); - epContext.StatutFormation.Attach(formation.Statut); - epContext.OrigineFormation.Attach(formation.Origine); - epContext.ModeFormation.Attach(formation.ModeFormation); - epContext.TypeFormation.Attach(formation.TypeFormation); - epContext.Add(formation); + formation = SetFormation(formation, formationDTO); await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } /// - /// Modifier une formation + /// Supprimer une formation de manière asynchrone /// /// - /// /// - public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) + public async Task DeleteFormationByIdAsync(long idFormation) { - if (!IsFormationValide(formationDTO)) - throw new FormationInvalidException(); - - if (!formationDTO.Id.HasValue || formationDTO.Id.Value != idFormation) - throw new FormationIncompatibleIdException(); - - Formation formation = epContext.Formation.Find(idFormation.Value); + Formation formation = await epContext.Formation.FindAsync(idFormation); if (formation == null) - return null; + throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.", idFormation)); - formation = SetFormation(formation, formationDTO); + epContext.Remove(formation); - epContext.SaveChanges(); + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } + #endregion + #region Méthodes Privée /// - /// Modifier une formation de manière asynchrone + /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour /// - /// - /// - /// - public async Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO) + /// Un objet FormationDTO est valide si aucune de ses propriétés n'est à null,si la date de début de la formation est inférieur à la date de fin et si le statut, l'origine,le mode et le type sont présents dans la base de données + /// + /// true si l'objet est valide, false sinon + private void IsFormationValide(FormationDTO formation) { - if (!IsFormationValide(formationDTO)) - throw new FormationInvalidException(); + // Vérifier que la formation n'est pas null + if (formation == null) + throw new FormationInvalidException("Aucune formation n'a été reçue"); - if (!formationDTO.Id.HasValue || formationDTO.Id.Value != idFormation) - throw new FormationIncompatibleIdException(); + // Vérfier que la formation a bien un statut de formation + if (formation.Statut == null || !formation.Statut.Id.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans statut de formation."); - Formation formation = await epContext.Formation.FindAsync(idFormation.Value); + // Vérfier que la formation a bien un mode de formation + if (formation.Mode == null || !formation.Mode.Id.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans mode de formation."); - if (formation == null) - return null; + // Vérfier que la formation a bien une origine de formation + if (formation.Origine == null || !formation.Origine.Id.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans origine de formation."); - formation = SetFormation(formation, formationDTO); - await epContext.SaveChangesAsync(); + // Vérfier que la formation a bien un type de formation + if (formation.Type == null || !formation.Type.Id.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans type de formation."); - return GetFormationDTO(formation); + // Vérfier que la formation a bien une agence + if (!formation.IdAgence.HasValue || formation.IdAgence == 0) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans mode de formation."); + + // Vérifier que la formation a bien un intitulé + if (string.IsNullOrWhiteSpace(formation.Intitule)) + throw new FormationInvalidException("L'intitulé de la formation doit contenir au moins 1 caractère."); + + // Vérifier que la formation a bien un organisme + if (string.IsNullOrWhiteSpace(formation.Organisme)) + throw new FormationInvalidException("L'organisme de la formation doit contenir au moins 1 caractère."); + + // Vérifier que la formation a bien une date de début + if (!formation.DateDebut.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans date de début de formation."); + + // Vérifier que la formation a bien une date de fin + if (!formation.DateFin.HasValue) + throw new FormationInvalidException("Impossible d'enregistrer une formation sans date de fin de formation."); + + // Vérifier que la formation a bien une date de début inférieure à la date de fin + if (formation.DateDebut.Value > formation.DateFin.Value) + throw new FormationInvalidException("La date de début de la formation est supérieure à la date de fin."); + + // Vérfier que le statut de la formation est présent dans la BDD + if (!epContext.StatutFormation.Any(statut => statut.IdStatutFormation == formation.Statut.Id.Value && statut.Libelle == formation.Statut.Libelle)) + throw new FormationInvalidException("Le statut de la formation n'existe pas."); + + // Vérfier que le mode de la formation est présent dans la BDD + if (!epContext.ModeFormation.Any(mode => mode.IdModeFormation == formation.Mode.Id.Value && mode.Libelle == formation.Mode.Libelle)) + throw new FormationInvalidException("Le mode de la formation n'existe pas."); + + // Vérfier que l'orgine de la formation est présente dans la BDD + if (!epContext.OrigineFormation.Any(origine => origine.IdOrigineFormation == formation.Origine.Id.Value && origine.Libelle == formation.Origine.Libelle)) + throw new FormationInvalidException("L'origine de la formation n'existe pas."); + + // Vérfier que le type de la formation est présent dans la BDD + if (!epContext.TypeFormation.Any(type => type.IdTypeFormation == formation.Type.Id.Value && type.Libelle == formation.Type.Libelle)) + throw new FormationInvalidException("Le type de la formation n'existe pas."); } /// - /// Supprimer une formation + /// Ajouter un ordonnancement croissant ou décroissant sur colonne /// - /// + /// + /// /// - public FormationDTO DeleteFormationById(long? idFormation) + private IQueryable OrderByColumn(IQueryable query, bool? asc, string columnName) { - if (!idFormation.HasValue) - throw new FormationIncompatibleIdException(); + if (!asc.HasValue) + asc = defaultAsc; + if (string.IsNullOrWhiteSpace(columnName)) + { + if (asc.Value) + return query.OrderBy(p => p.Intitule); + else + return query.OrderByDescending(p => p.Intitule); + } - Formation formation = epContext.Formation.Find(idFormation.Value); + switch (columnName.ToLower()) + { + case "intitule": + if (asc.Value) + return query.OrderBy(p => p.Intitule); + else + return query.OrderByDescending(p => p.Intitule); + case "statut": + if (asc.Value) + return query.OrderBy(p => p.Statut.Libelle); + else + return query.OrderByDescending(p => p.Statut.Libelle); + case "origine": + if (asc.Value) + return query.OrderBy(p => p.Origine.Libelle); + else + return query.OrderByDescending(p => p.Origine.Libelle); + case "date": + if (asc.Value) + return query.OrderBy(p => p.DateDebut); + else + return query.OrderByDescending(p => p.DateDebut); + case "certification": + if (asc.Value) + return query.OrderBy(p => p.EstCertifiee); + else + return query.OrderByDescending(p => p.EstCertifiee); + default: + if (asc.Value) + return query.OrderBy(p => p.Intitule); + else + return query.OrderByDescending(p => p.Intitule); + } + } - if (formation == null) - throw new FormationNotFoundException(); + /// + /// Ajouter un filtre pour récupérer les formations en fonction de plusieurs identifiants de statut de formation + /// + /// + /// + /// + private IQueryable IdStatutsFilter(IQueryable query, List idStatuts) + { + if (idStatuts != null && idStatuts.Count > 0 && idStatuts.First().HasValue) + return query.Where(formation => idStatuts.Contains(formation.Statut.IdStatutFormation)); + else + return query; + } - epContext.Remove(formation); + /// + /// Ajouter un filtre pour récupérer les formations en fonction de l'identifiant d'une agence + /// + /// + /// + /// + private IQueryable IdAgenceFilter(IQueryable query, long? idAgence) + { + if (idAgence != null) + return query.Where(formation => formation.IdAgence == idAgence); + else + return query; + } - epContext.SaveChanges(); + /// + /// Ajouter un filtre pour récupérer les formations en fonction d'un intitulé + /// + /// + /// + /// + private IQueryable IntituleFilter(IQueryable query, string intitule) + { + if (!string.IsNullOrWhiteSpace(intitule)) + return query.Where(formation => formation.Intitule.ToLower().Contains(intitule.ToLower())); + else + return query; + } + + /// + /// Ajouter un filtre pour récupérer les formations en fonction d'un intervalle de date + /// + /// + /// + /// + /// + private IQueryable DateFilter(IQueryable query, DateTime? dateDebut, DateTime? dateFin) + { + if (dateDebut.HasValue && dateFin.HasValue) + return query.Where(formation => formation.DateDebut >= dateDebut.Value && formation.DateFin <= dateFin.Value.AddDays(1)); + else if (!dateDebut.HasValue && dateFin.HasValue) + return query.Where(formation => formation.DateFin <= dateFin.Value.AddDays(1)); + else if (dateDebut.HasValue && !dateFin.HasValue) + return query.Where(formation => formation.DateDebut >= dateDebut.Value); + else + return query; - return GetFormationDTO(formation); } /// - /// Supprimer une formation de manière asynchrone + /// Ajouter une pagination /// - /// + /// + /// + /// /// - public async Task DeleteFormationByIdAsync(long? idFormation) + private IQueryable SkipAndTake(IQueryable query, int? parPage, int? numPage) { - if (!idFormation.HasValue) - throw new FormationIncompatibleIdException(); + int skip, take; - Formation formation = await epContext.Formation.FindAsync(idFormation.Value); + if (!parPage.HasValue || parPage.Value < minParPage || parPage.Value > maxParPage) + parPage = defaultParPage; - if (formation == null) - throw new FormationNotFoundException(); + if (!numPage.HasValue || numPage.Value <= 0) + numPage = defaultNumPage; - epContext.Remove(formation); - await epContext.SaveChangesAsync(); + skip = (numPage.Value - 1) * parPage.Value; + take = parPage.Value; - return GetFormationDTO(formation); + return query.Skip(skip).Take(take); } - #endregion - #region Méthodes Privée + + #region Object to DTO /// - /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour + /// Récuperer un objet FormationDTO en fonction d'un objet Formation /// - /// Un objet FormationDTO est valide si aucune de ses propriétés n'est à null,si la date de début de la formation est inférieur à la date de fin et si le statut, l'origine,le mode et le type sont présents dans la base de données /// - /// true si l'objet est valide, false sinon - private bool IsFormationValide(FormationDTO formation) + /// + private FormationDTO GetFormationDTO(Formation formation) { - return !(formation == null || formation.Statut == null || formation.Mode == null || formation.Origine == null || formation.Type == null - || !formation.IdAgence.HasValue || formation.IdAgence == 0 - || string.IsNullOrWhiteSpace(formation.Intitule) || string.IsNullOrWhiteSpace(formation.Organisme) - || !formation.DateDebut.HasValue || !formation.DateFin.HasValue || formation.DateDebut.Value > formation.DateFin.Value - || !formation.Statut.Id.HasValue || !formation.Mode.Id.HasValue || !formation.Origine.Id.HasValue || !formation.Type.Id.HasValue - || !epContext.StatutFormation.Any(statut => statut.IdStatutFormation == formation.Statut.Id.Value && statut.Libelle == formation.Statut.Libelle) - || !epContext.ModeFormation.Any(mode => mode.IdModeFormation == formation.Mode.Id.Value && mode.Libelle == formation.Mode.Libelle) - || !epContext.OrigineFormation.Any(origine => origine.IdOrigineFormation == formation.Origine.Id.Value && origine.Libelle == formation.Origine.Libelle) - || !epContext.TypeFormation.Any(type => type.IdTypeFormation == formation.Type.Id.Value && type.Libelle == formation.Type.Libelle)); - } + FormationDTO formationDTO = new FormationDTO() + { + Id = formation.IdFormation, + Intitule = formation.Intitule, + IdAgence = formation.IdAgence, + DateDebut = formation.DateDebut, + DateFin = formation.DateFin, + Heure = formation.Heure, + Jour = formation.Jour, + Organisme = formation.Organisme, + EstCertifiee = formation.EstCertifiee, + Origine = GetOrigineFormationDTO(formation.Origine), + Statut = GetStatutFormationDTO(formation.Statut), + Mode = GetModeFormationDTO(formation.ModeFormation), + Type = GetTypeFormationDTO(formation.TypeFormation), + }; - /// - /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour - /// - /// Un objet FormationDTO est valide si aucune de ses propriétés n'est à null,si la date de début de la formation est inférieur à la date de fin et si le statut, l'origine,le mode et le type sont présents dans la base de données - /// - /// true si l'objet est valide, false sinon - private async Task IsFormationValideAsync(FormationDTO formation) - { - return !(formation == null || formation.Statut == null || formation.Mode == null || formation.Origine == null || formation.Type == null - || !formation.IdAgence.HasValue || formation.IdAgence == 0 - || string.IsNullOrWhiteSpace(formation.Intitule) || string.IsNullOrWhiteSpace(formation.Organisme) - || !formation.DateDebut.HasValue || !formation.DateFin.HasValue || formation.DateDebut.Value > formation.DateFin.Value - || !formation.Statut.Id.HasValue || !formation.Mode.Id.HasValue || !formation.Origine.Id.HasValue || !formation.Type.Id.HasValue - || ! await epContext.StatutFormation.AnyAsync(statut => statut.IdStatutFormation == formation.Statut.Id.Value && statut.Libelle == formation.Statut.Libelle) - || ! await epContext.ModeFormation.AnyAsync(mode => mode.IdModeFormation == formation.Mode.Id.Value && mode.Libelle == formation.Mode.Libelle) - || ! await epContext.OrigineFormation.AnyAsync(origine => origine.IdOrigineFormation == formation.Origine.Id.Value && origine.Libelle == formation.Origine.Libelle) - || ! await epContext.TypeFormation.AnyAsync(type => type.IdTypeFormation == formation.Type.Id.Value && type.Libelle == formation.Type.Libelle)); + return formationDTO; } - #region Object to DTO + /// - /// Récupère un objet FormationDTO en fonction d'un objet Formation + /// Récuperer un objet FormationDTO avec des participations en fonction d'un objet Formation et d'une liste de CollaborateurDTO /// /// /// - private FormationDTO GetFormationDTO(Formation formation) + private FormationDTO GetFormationDTO(Formation formation, IEnumerable collaborateurDTOs) { FormationDTO formationDTO = new FormationDTO() { @@ -801,17 +561,42 @@ namespace EPAServeur.Services Jour = formation.Jour, Organisme = formation.Organisme, EstCertifiee = formation.EstCertifiee, + EstRealisee = formation.EstRealisee, Origine = GetOrigineFormationDTO(formation.Origine), Statut = GetStatutFormationDTO(formation.Statut), Mode = GetModeFormationDTO(formation.ModeFormation), - Type = GetTypeFormationDTO(formation.TypeFormation) + Type = GetTypeFormationDTO(formation.TypeFormation), + Participations = GetParticipationsFormationDTO(formation.ParticipationsFormation, collaborateurDTOs) }; return formationDTO; } /// - /// Récupère un objet OrigineFormationDTO en fonction d'un objet OrigineFormation + /// Récuperer un objet FormationDetailsDTO en fonction d'un objet Formation + /// + /// + /// + private FormationDetailsDTO GetFormationDetailsDTO(Formation formation) + { + FormationDetailsDTO formationDTO = new FormationDetailsDTO() + { + Id = formation.IdFormation, + Intitule = formation.Intitule, + DateDebut = formation.DateDebut, + DateFin = formation.DateFin, + Organisme = formation.Organisme, + EstCertifiee = formation.EstCertifiee, + NbParticipations = formation.ParticipationsFormation.Count, + Origine = GetOrigineFormationDTO(formation.Origine), + Statut = GetStatutFormationDTO(formation.Statut), + }; + + return formationDTO; + } + + /// + /// Récuperer un objet OrigineFormationDTO en fonction d'un objet OrigineFormation /// /// /// @@ -828,7 +613,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet StatutFormationDTO en fonction d'un objet StatutFormation + /// Récuperer un objet StatutFormationDTO en fonction d'un objet StatutFormation /// /// /// @@ -845,7 +630,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet ModeFormationDTO en fonction d'un objet ModeFormation + /// Récuperer un objet ModeFormationDTO en fonction d'un objet ModeFormation /// /// /// @@ -860,8 +645,9 @@ namespace EPAServeur.Services }; return modeFormationDTO; } + /// - /// Récupère un objet TypeFormationDTO en fonction d'un objet TypeFormation + /// Récuperer un objet TypeFormationDTO en fonction d'un objet TypeFormation /// /// /// @@ -877,12 +663,107 @@ namespace EPAServeur.Services return typeFormationDTO; } + /// + /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents. Retourne null s'il n'y a aucune participation. + /// + /// + /// + private async Task> GetCollaborateurDTOs(List participationsFormation) + { + if (participationsFormation.Count == 0) + return null; + + List guids = participationsFormation.SelectMany(participationFormation => new[] { (Guid?)participationFormation.DemandeFormation.Ep.IdCollaborateur, participationFormation.DemandeFormation.Ep.IdReferent }).ToList(); + + return await collaborateurService.GetCollaborateurDTOsAsync(guids); ; + } + + /// + /// Récuperer une liste de ParticipationFormationDTO en fonction d'une liste de ParticipationFormation et d'une liste de CollaborateurDTO. Retourne null s'il n'y a aucune participation ou aucun collaborateur. + /// + /// + /// + private List GetParticipationsFormationDTO(List participationsFormation, IEnumerable collaborateurDTOs) + { + List participationFormationDTOs; + + if (participationsFormation == null || participationsFormation.Count == 0 || collaborateurDTOs == null || !collaborateurDTOs.Any()) + return null; + + participationFormationDTOs = participationsFormation.Select(participationFormation => GetParticipationFormationDTO(participationFormation, collaborateurDTOs)) + .OrderBy(participationFormation => participationFormation.Collaborateur.Nom) + .ThenBy(participationFormation => participationFormation.Collaborateur.Prenom).ToList(); + + return participationFormationDTOs; + } + + /// + /// Récuperer un objet ParticipationFormationDTO en fonction d'un objet ParticipationFormation et d'une liste de CollaborateurDTO + /// + /// + /// + private ParticipationFormationDTO GetParticipationFormationDTO(ParticipationFormation participationFormation, IEnumerable collaborateurDTOs) + { + ParticipationFormationDTO participationFormationDTO = new ParticipationFormationDTO() + { + Id = participationFormation.IdParticipationFormation, + DateCreation = participationFormation.DateCreation, + Intitule = participationFormation.Formation.Intitule, + DateDebut = participationFormation.Formation.DateDebut, + Statut = GetStatutFormationDTO(participationFormation.Formation.Statut), + Collaborateur = GetCollaborateurDTO(participationFormation, collaborateurDTOs), + Ep = GetEpInformationDTO(participationFormation.DemandeFormation.Ep, collaborateurDTOs) + }; + + return participationFormationDTO; + } + + /// + /// Récupère un objet CollaborateurDTO en fonction d'un objet ParticipationFormation et d'une liste de CollaborateurDTO + /// + /// + /// + private CollaborateurDTO GetCollaborateurDTO(ParticipationFormation participationFormation, IEnumerable collaborateurDTOs) + { + return collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == participationFormation.DemandeFormation.Ep.IdCollaborateur); + } + + /// + /// Récupère un objet EpInformationDTO en fonction d'un objet Ep et d'une liste de CollaborateurDTO + /// + /// + /// + private EpInformationDTO GetEpInformationDTO(Ep ep, IEnumerable 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() + { + Id = ep.IdEP, + Type = ep.TypeEP, + Statut = ep.Statut, + DateDisponibilite = ep.DateDisponibilite, + DatePrevisionnelle = ep.DatePrevisionnelle, + Obligatoire = ep.Obligatoire, + Collaborateur = collaborateur, + Referent = referent, + }; + + return epInformationDTO; + } + + #endregion #region DTO to Object /// - /// Modifie un objet Formation en fonction d'un objet FormationDTO + /// Modifier un objet Formation en fonction d'un objet FormationDTO /// /// /// @@ -897,6 +778,7 @@ namespace EPAServeur.Services formation.Jour = Convert.ToInt32(formationDTO.Jour.Value); formation.Organisme = formationDTO.Organisme; formation.EstCertifiee = formationDTO.EstCertifiee.Value; + //formation.EstRealisee = formationDTO.EstRealisee.Value; formation.Origine = GetOrigineFormation(formationDTO.Origine); formation.Statut = GetStatutFormation(formationDTO.Statut); formation.ModeFormation = GetModeFormation(formationDTO.Mode); @@ -906,7 +788,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet OrigineFormation en fonction d'un objet OrigineFormationDTO + /// Récuperer un objet OrigineFormation en fonction d'un objet OrigineFormationDTO /// /// /// @@ -921,7 +803,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet StatutFormation en fonction d'un objet StatutFormationDTO + /// Récuperer un objet StatutFormation en fonction d'un objet StatutFormationDTO /// /// /// @@ -936,7 +818,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet ModeFormation en fonction d'un objet ModeFormationDTO + /// Récuperer un objet ModeFormation en fonction d'un objet ModeFormationDTO /// /// /// @@ -951,7 +833,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet TypeFormation en fonction d'un objet TypeFormationDTO + /// Récuperer un objet TypeFormation en fonction d'un objet TypeFormationDTO /// /// /// diff --git a/EPAServeur/Startup.cs b/EPAServeur/Startup.cs index 17e2f5d..312e247 100644 --- a/EPAServeur/Startup.cs +++ b/EPAServeur/Startup.cs @@ -42,7 +42,8 @@ namespace EPAServeur }); }); - services.AddControllers(); + services.AddControllers().AddNewtonsoftJson(); + services.AddAuthentication(options => {