From e97d88cceedec6c48c3afcad1c1491b683f2db35 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:30:29 +0100 Subject: [PATCH 01/28] MAJ de la description --- .../Exceptions/EngagementIncompatibleIdException.cs | 8 ++++---- EPAServeur/Exceptions/EngagementInvalidException.cs | 8 ++++---- EPAServeur/Exceptions/EngagementNotFoundException.cs | 2 +- EPAServeur/Exceptions/FormationIncompatibleIdException.cs | 2 +- EPAServeur/Exceptions/FormationInvalidException.cs | 8 ++++---- EPAServeur/Exceptions/FormationNotFoundException.cs | 2 +- EPAServeur/Exceptions/ModeFormationNotFoundException.cs | 2 +- .../Exceptions/OrigineFormationNotFoundException.cs | 2 +- EPAServeur/Exceptions/StatutFormationNotFoundException.cs | 2 +- EPAServeur/Exceptions/TypeFormationNotFoundException.cs | 2 +- 10 files changed, 19 insertions(+), 19 deletions(-) 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 { From bb67f315cd402cdcbf970f9ce9e7e2ffa757caf4 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:34:52 +0100 Subject: [PATCH 02/28] MAJ des TU suite aux modifications des exceptions dans le service formation --- .../Services/FormationServiceTests.cs | 796 ++++-------------- 1 file changed, 169 insertions(+), 627 deletions(-) diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index fd124db..d60667a 100644 --- a/EPAServeur.Tests/Services/FormationServiceTests.cs +++ b/EPAServeur.Tests/Services/FormationServiceTests.cs @@ -50,49 +50,7 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetFormationById et GetFormationByIdAsync - - [Test] - public void GetFormationById_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - FormationDTO formationDTO = formationService.GetFormationById(1); - - // Assert - Assert.AreEqual(1, formationDTO.Id); - Assert.AreEqual("Formation1", 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("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); - } - - [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); - } - + #region Tests GetFormationByIdAsync [Test] public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() { @@ -107,7 +65,7 @@ namespace EPAServeur.Tests.Services Assert.AreEqual("Formation1", 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, 9, 17), formationDTO.DateFin); Assert.AreEqual(2, formationDTO.Heure); Assert.AreEqual(1, formationDTO.Jour); Assert.AreEqual("Organisme1", formationDTO.Organisme); @@ -121,14 +79,13 @@ namespace EPAServeur.Tests.Services [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); // Act - AsyncTestDelegate throwException = () => formationService.GetFormationByIdAsync(value); + AsyncTestDelegate throwException = () => formationService.GetFormationByIdAsync(idFormation); // Assert Assert.ThrowsAsync(typeof(FormationNotFoundException), throwException); @@ -136,271 +93,263 @@ 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, "formation1", 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); + 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(true, "intitule")] + [TestCase(true, null)] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleCroissant(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = formationService.GetFormations(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()); + Assert.AreEqual("Formation1", formationDTOs.First().Intitule); + Assert.AreEqual("Formation9", formationDTOs.Last().Intitule); + } - [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(false, "intitule")] + [TestCase(false, null)] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleDecroissant(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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.Less(0, formationDTOs.Count()); + Assert.AreEqual("Formation9", formationDTOs.First().Intitule); + Assert.AreEqual("Formation1", formationDTOs.Last().Intitule); + } - [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, "statut")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParStatutCroissant(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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("Annulée", formationDTOs.First().Statut.Libelle); + Assert.AreEqual("Replanifiée", formationDTOs.Last().Statut.Libelle); - #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, "statut")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParStatutDecroissant(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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("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 void GetFormationAnnulees_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); // 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("Demande collaborateur", formationDTOs.First().Origine.Libelle); + Assert.AreEqual("Formation réglementaire", formationDTOs.Last().Origine.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, "origine")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParOrigineDecroissante(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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("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 async Task GetFormationAnnuleesAsync_PasseDesParamsInvalides_RetourneZeroFormationAnnulees(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); // 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(new DateTime(2020, 04, 6, 9, 0, 0), formationDTOs.First().DateDebut); + Assert.AreEqual(new DateTime(2020, 11, 18, 10, 0, 0), formationDTOs.Last().DateDebut); - #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, "date")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParDateDecroissante(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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(new DateTime(2020, 11, 18, 10, 0, 0), formationDTOs.First().DateDebut); + Assert.AreEqual(new DateTime(2020, 04, 6, 9, 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 void GetFormationRealisee_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); // 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(false, formationDTOs.First().EstCertifiee); + Assert.AreEqual(true, formationDTOs.Last().EstCertifiee); + } - [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, "certification")] + public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParCertificationDecroissante(bool? asc, string tri) { // Arrange FormationService formationService = new FormationService(epContext); // 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(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 async Task GetFormationRealiseeAsync_PasseDesParamsInvalides_RetourneZeroFormationRealisees(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); // Act - IEnumerable formationDTOs = await formationService.GetFormationRealiseesAsync(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()); - } - - #endregion + Assert.Greater(formationDTOs.First().DateDebut, dateDebut); + Assert.GreaterOrEqual(formationDTOs.Last().DateDebut, dateDebut); - #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("2020-10-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeFin_RetourneDesFormationsAvecUneDateDeFinInferieur(DateTime dateFin) { // Arrange FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = formationService.GetProchainesFormation(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 void GetProchainesFormation_PasseDesParamsInvalides_RetourneZeroProchaineFormation(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + [TestCase("2020-10-01", "2020-11-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutEtUneDateDeFin_RetourneDesFormationsAvecUneDateDeDebutSuperieurUneDateDeFinInferieur(DateTime dateDebut, DateTime dateFin) { // Arrange FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = formationService.GetProchainesFormation(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); + + Assert.GreaterOrEqual(formationDTOs.Last().DateDebut, dateDebut); + Assert.LessOrEqual(formationDTOs.Last().DateFin, dateFin); + } - [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-11-01", "2020-10-01")] + public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutSuperieurEtUneDateDeFinInferieur_RetourneZeroFormation(DateTime dateDebut, DateTime dateFin) { // Arrange FormationService formationService = new FormationService(epContext); // 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.Less(0, formationDTOs.Count()); + Assert.AreEqual(0, formationDTOs.Count()); } - [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(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); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; + // Act - IEnumerable formationDTOs = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); // Assert Assert.AreEqual(0, formationDTOs.Count()); @@ -408,54 +357,76 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetModesFormation et GetModesFormationAsync + #region Tests GetFormationsCountAsync - [Test] - public void GetModesFormation_RetourneTousLesModesDeFormation() + [TestCase(1, new int[] { 1, 2, 3 }, 1, 5, "formation", "2020-09-30", "2020-11-30")] + [TestCase(1, new int[] { 1 }, 1, 5, "formation1", 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); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; // Act - IEnumerable modeFormationDTOs = formationService.GetModesFormation(); + long count = await formationService.GetFormationsCountAsync(idAgence, idStatuts, numPage, parPAge, texte, 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.Less(0, count); } - [Test] - public async Task GetModesFormationAsync_RetourneTousLesModesDeFormation() + [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); + List idStatuts; + + if (arrIdStatuts != null) + idStatuts = arrIdStatuts.Select(x => (int?)x).ToList(); + else + idStatuts = null; // Act - IEnumerable modeFormationDTOs = await formationService.GetModesFormationAsync(); + long count = await formationService.GetFormationsCountAsync(idAgence, idStatuts, numPage, parPAge, texte, 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, count); } #endregion - #region Tests GetOriginesFormation et GetOriginesFormationAsync + + #region Tests GetModesFormationAsync [Test] - public void GetOriginesFormation_RetourneToutesLesOriginesDeFormation() + public async Task GetModesFormationAsync_RetourneTousLesModesDeFormation() { // Arrange FormationService formationService = new FormationService(epContext); // Act - IEnumerable origineFormationDTOs = formationService.GetOriginesFormation(); + IEnumerable modeFormationDTOs = await formationService.GetModesFormationAsync(); // Assert - Assert.IsNotNull(origineFormationDTOs); - Assert.AreEqual(4, origineFormationDTOs.Count()); // Nombre total d'origine 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 GetOriginesAsyncFormation_RetourneToutesLesOriginesDeFormation() { @@ -472,21 +443,7 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetStatutsFormation et GetStatutsFormationAsync - - [Test] - public void GetStatutsFormation_RetourneTousLesStatutsDeFormation() - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - IEnumerable statutFormationDTOs = formationService.GetStatutsFormation(); - - // Assert - Assert.IsNotNull(statutFormationDTOs); - Assert.AreEqual(4, statutFormationDTOs.Count()); // Nombre total de statut de formation dans la classe DataSeeder le 2020-10-31 - } + #region Tests GetStatutsFormationAsync [Test] public async Task GetStatutsFormationAsyncFormation_RetourneTousLesStatutsDeFormation() @@ -504,21 +461,7 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests GetTypesFormation et GetTypesFormationAsync - - [Test] - public void GetTypesFormation_RetourneTousLesTypesDeFormation() - { - // Arrange - FormationService formationService = new FormationService(epContext); - - // Act - IEnumerable typeFormationDTOs = formationService.GetTypesFormation(); - - // Assert - Assert.IsNotNull(typeFormationDTOs); - Assert.AreEqual(4, typeFormationDTOs.Count()); // Nombre total de type de formation dans la classe DataSeeder le 2020-10-31 - } + #region Tests GetTypesFormationAsync [Test] public async Task GetTypesFormationAsync_RetourneTousLesTypesDeFormation() @@ -536,60 +479,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")] @@ -644,22 +534,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() { @@ -676,57 +550,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")] @@ -776,52 +599,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")] @@ -870,61 +647,10 @@ namespace EPAServeur.Tests.Services #endregion - #region Tests UpdateFormation et 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) - { - // 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(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); - } + #region Tests UpdateFormationAsync [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) + 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) @@ -987,57 +713,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) - { - - // 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(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) + 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 @@ -1075,45 +751,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) { @@ -1153,46 +791,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) @@ -1224,10 +823,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,24 +836,7 @@ 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); @@ -1271,21 +853,7 @@ namespace EPAServeur.Tests.Services [TestCase(0)] [TestCase(-1)] - public void DeleteFormationById_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) + public void DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdInvalide_LeveUneFormationNotFoundException(long idFormation) { // Arrange FormationService formationService = new FormationService(epContext); @@ -1297,32 +865,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 From db7eff40a85791957b45d429e8535b0147e59c7e Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:35:55 +0100 Subject: [PATCH 03/28] =?UTF-8?q?MAJ=20du=20jeu=20de=20donn=C3=A9es=20pour?= =?UTF-8?q?=20la=20partie=20formation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Context/DataSeeder.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/EPAServeur/Context/DataSeeder.cs b/EPAServeur/Context/DataSeeder.cs index e91a242..8403d4d 100644 --- a/EPAServeur/Context/DataSeeder.cs +++ b/EPAServeur/Context/DataSeeder.cs @@ -358,7 +358,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" }; @@ -446,7 +446,7 @@ namespace EPAServeur.Context Intitule = "Formation1", DateDebut = new DateTime(2020, 9, 16, 10, 0, 0), - DateFin = new DateTime(2020, 9, 16), + DateFin = new DateTime(2020, 9, 17), IdAgence = 1, Heure = 2, Jour = 1, @@ -569,7 +569,7 @@ namespace EPAServeur.Context f8 = new Formation { - Intitule = "Formation2", + Intitule = "Formation8", DateDebut = new DateTime(2020, 11, 18, 10, 0, 0), DateFin = new DateTime(2020, 11, 20), IdAgence = 1, @@ -612,7 +612,7 @@ namespace EPAServeur.Context ModeFormation = modePresentiel, TypeFormation = typeInterne, Organisme = "Organisme4", - Origine = origineFormationClient, + Origine = origineFormationReglementaire, Statut = statutAnnule, EstCertifiee = false }; @@ -629,7 +629,7 @@ namespace EPAServeur.Context ModeFormation = modePresentiel, TypeFormation = typeInterne, Organisme = "Organisme1", - Origine = origineFormationClient, + Origine = origineFormationReglementaire, Statut = statutAnnule, EstCertifiee = false }; From 23f8b6994067324c3f61ed016adfb8e3dcfab822 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:39:43 +0100 Subject: [PATCH 04/28] Ajout des TU pour l'api formation --- .../Controllers/FormationApiTests.cs | 526 ++++++++++++++++-- 1 file changed, 471 insertions(+), 55 deletions(-) diff --git a/EPAServeur.Tests/Controllers/FormationApiTests.cs b/EPAServeur.Tests/Controllers/FormationApiTests.cs index bf8a76d..199b129 100644 --- a/EPAServeur.Tests/Controllers/FormationApiTests.cs +++ b/EPAServeur.Tests/Controllers/FormationApiTests.cs @@ -13,6 +13,11 @@ 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; namespace EPAServeur.Tests.Controllers { @@ -21,9 +26,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 +36,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 +62,20 @@ namespace EPAServeur.Tests.Controllers entity.State = EntityState.Detached; } - // Instanciation du service qui sera utilisé dans le controleur - formationService = new FormationService(epContext); + + 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 +83,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); - // Arrange + // Assert + Assert.IsInstanceOf(okResult.Result); + } - // Act - // Assert + [Test] + public void GetFormationById_PasseEnParamUnIdConnu_RetourneLaBonneFormation() + { + // Arrange + FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); + long idFormation = 1; - #endregion + // Act + var okResult = formationsApiController.GetFormationById(idFormation).Result as OkObjectResult; - #region Tests GetFormationAnnulees + // Assert + Assert.IsInstanceOf(okResult.Value); + Assert.AreEqual(idFormation, (okResult.Value as FormationDTO).Id); + } + #endregion - // 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 = 1; + int idLastFormation = 5; + + // 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.IsInstanceOf(okResult.Result); + } - // Assert + [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 } From bccb8846e6ea35f29058b67aab82ebed5835d77c Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:44:14 +0100 Subject: [PATCH 05/28] =?UTF-8?q?MAJ=20des=20Try/catch=20afin=20de=20renvo?= =?UTF-8?q?yer=20un=20StatusCode=20compos=C3=A9=20d'un=20objet=20ErreurDTO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Controllers/FormationsApi.cs | 644 ++++++++++++++++-------- 1 file changed, 436 insertions(+), 208 deletions(-) diff --git a/EPAServeur/Controllers/FormationsApi.cs b/EPAServeur/Controllers/FormationsApi.cs index 38166bb..f2ed436 100644 --- a/EPAServeur/Controllers/FormationsApi.cs +++ b/EPAServeur/Controllers/FormationsApi.cs @@ -18,15 +18,35 @@ 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; 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; + } + /// /// /// @@ -47,29 +67,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); } /// @@ -91,24 +139,69 @@ 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 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(); } /// @@ -131,29 +224,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 = null; + + 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); } /// @@ -182,26 +293,34 @@ namespace IO.Swagger.Controllers [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 = null; + + 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 +342,42 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations/count")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [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 = 0; + + 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); + } /// @@ -269,26 +397,34 @@ namespace IO.Swagger.Controllers [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 = null; + + 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); } /// @@ -308,26 +444,34 @@ namespace IO.Swagger.Controllers [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 = null; + + 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); } /// @@ -347,26 +491,34 @@ namespace IO.Swagger.Controllers [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 = null; + + 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); } /// @@ -386,26 +538,34 @@ namespace IO.Swagger.Controllers [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 = null; + + 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); } /// @@ -430,27 +590,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); } } } From 8f4fb19e8157dd9f3ff46182be7e5b27bc672675 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:54:12 +0100 Subject: [PATCH 06/28] =?UTF-8?q?MAJ=20des=20param=C3=A8tres=20nullable=20?= =?UTF-8?q?dans=20les=20signatures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/IServices/IFormationService.cs | 24 +++++------------------ 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/EPAServeur/IServices/IFormationService.cs b/EPAServeur/IServices/IFormationService.cs index 4a5e172..0fbf2f3 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); } } From a8e8b85b0a40df8f2dc7934581750d8802635fe2 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 10:57:34 +0100 Subject: [PATCH 07/28] MAJ du service formation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Modification des exceptions en ajoutant des messages directement de le service. Création de méthodes privées afin d'éviter les redondances de code. Utilisation de l'interface IQueryable afin d'améliorer les performances du serveur web en utilisant les ressources de la BDD. --- EPAServeur/Services/FormationService.cs | 817 ++++++++---------------- 1 file changed, 265 insertions(+), 552 deletions(-) diff --git a/EPAServeur/Services/FormationService.cs b/EPAServeur/Services/FormationService.cs index 378fc7a..1ef4934 100644 --- a/EPAServeur/Services/FormationService.cs +++ b/EPAServeur/Services/FormationService.cs @@ -15,8 +15,36 @@ namespace EPAServeur.Services { #region Variables + /// + /// Accès et gestion de la base de données + /// private readonly EpContext epContext; + /// + /// 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 @@ -34,31 +62,12 @@ namespace EPAServeur.Services #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) @@ -67,425 +76,85 @@ namespace EPAServeur.Services .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); } /// - /// 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; - 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); - } + .Include(formation => formation.TypeFormation); - 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(); + query = IdStatutsFilter(query, idStatuts); - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + query = IdAgenceFilter(query, idAgence); - 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(); - } - - else - { - - 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(); - } - - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); - - return formationDTOs; - } - - /// - /// 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; + query = IntituleFilter(query, texte); - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + query = DateFilter(query, dateDebut, dateFin); - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + query = OrderByColumn(query, asc, tri); - 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); + query = SkipAndTake(query, parPage, numPage); - } - 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 => GetFormationDTO(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; + IQueryable query; + long count; - 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 == 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); - 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 = IntituleFilter(query, texte); - formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + query = IdStatutsFilter(query, idStatuts); - return formationDTOs; - } + query = IdAgenceFilter(query, idAgence); - /// - /// Récupérer les modes de formation - /// - /// - public IEnumerable GetModesFormation() - { - IEnumerable modeFormations; - IEnumerable modeFormationDTOs; + query = DateFilter(query, dateDebut, dateFin); - modeFormations = epContext.ModeFormation; + query = SkipAndTake(query, parPage, numPage); - modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); + count = await query.CountAsync(); - return modeFormationDTOs; + return count; } /// @@ -496,6 +165,7 @@ namespace EPAServeur.Services { IEnumerable modeFormations; IEnumerable modeFormationDTOs; + modeFormations = await epContext.ModeFormation.ToListAsync(); modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); @@ -503,22 +173,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 +189,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 +205,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 /// @@ -599,30 +221,6 @@ namespace EPAServeur.Services return typeFormationDTOs; } - /// - /// Ajouter une formation - /// - /// - /// - public FormationDTO AddFormation(FormationDTO formationDTO) - { - if (!IsFormationValide(formationDTO)) - throw new FormationInvalidException(); - - Formation formation = new Formation(); - formation = SetFormation(formation, formationDTO); - - epContext.StatutFormation.Attach(formation.Statut); - epContext.OrigineFormation.Attach(formation.Origine); - epContext.ModeFormation.Attach(formation.ModeFormation); - epContext.TypeFormation.Attach(formation.TypeFormation); - epContext.Add(formation); - - epContext.SaveChanges(); - - return GetFormationDTO(formation); - } - /// /// Ajouter une formation de manière asynchrone /// @@ -630,8 +228,7 @@ namespace EPAServeur.Services /// public async Task AddFormationAsync(FormationDTO formationDTO) { - if (!await IsFormationValideAsync(formationDTO)) - throw new FormationInvalidException(); + IsFormationValide(formationDTO); Formation formation = new Formation(); formation = SetFormation(formation, formationDTO); @@ -648,143 +245,259 @@ namespace EPAServeur.Services } /// - /// Modifier une formation + /// Modifier une formation de manière asynchrone /// /// /// /// - public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) + public async Task UpdateFormationAsync(long idFormation, FormationDTO formationDTO) { - if (!IsFormationValide(formationDTO)) - throw new FormationInvalidException(); - if (!formationDTO.Id.HasValue || formationDTO.Id.Value != idFormation) - throw new FormationIncompatibleIdException(); + throw new FormationIncompatibleIdException("L'id de la formation a mettre à jour et la formation a mettre à jour sont incompatble."); + + IsFormationValide(formationDTO); - 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.SaveChanges(); + formation = SetFormation(formation, formationDTO); + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } /// - /// Modifier une formation de manière asynchrone + /// Supprimer une formation de manière asynchrone /// /// - /// /// - public async Task UpdateFormationAsync(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 = await epContext.Formation.FindAsync(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)); + + epContext.Remove(formation); - formation = SetFormation(formation, formationDTO); await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } + #endregion + #region Méthodes Privée /// - /// Supprimer une formation + /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour /// - /// - /// - public FormationDTO DeleteFormationById(long? idFormation) + /// 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 (!idFormation.HasValue) - throw new FormationIncompatibleIdException(); + // Vérifier que la formation n'est pas null + if (formation == null) + throw new FormationInvalidException("Aucune formation n'a été reçue"); + // 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 = epContext.Formation.Find(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) - throw new FormationNotFoundException(); + // 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."); - epContext.Remove(formation); + // 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."); - epContext.SaveChanges(); + // 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."); - return GetFormationDTO(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 de manière asynchrone + /// Ajouter un ordonnancement croissant ou décroissant sur colonne /// - /// + /// + /// /// - public async Task DeleteFormationByIdAsync(long? idFormation) + private IQueryable OrderByColumn(IQueryable query, bool? asc, string columnName) { - if (!idFormation.HasValue) - throw new FormationIncompatibleIdException(); - - Formation formation = await epContext.Formation.FindAsync(idFormation.Value); + if (!asc.HasValue) + asc = defaultAsc; - if (formation == null) - throw new FormationNotFoundException(); + switch (columnName) + { + 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); + //(A faire lorsque la gestion des participations aux formations sera terminée) + //case "participants": + // return query; + default: + if (asc.Value) + return query.OrderBy(p => p.Intitule); + else + return query.OrderByDescending(p => p.Intitule); + } + } - epContext.Remove(formation); + /// + /// 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) + return query.Where(formation => idStatuts.Contains(formation.Statut.IdStatutFormation)); + else + return query; + } - await epContext.SaveChangesAsync(); + /// + /// 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; + } - return GetFormationDTO(formation); + /// + /// 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; } - #endregion - #region Méthodes Privée /// - /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour + /// Ajouter un filtre pour récupérer les formations en fonction d'un intervalle de date /// - /// 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 IQueryable DateFilter(IQueryable query, DateTime? dateDebut, DateTime? dateFin) { - 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)); + 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; + } /// - /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour + /// Ajouter une pagination /// - /// 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) + /// + /// + /// + /// + private IQueryable SkipAndTake(IQueryable query, int? parPage, int? numPage) { - 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)); + int skip, take; + + if (!parPage.HasValue || parPage.Value < minParPage || parPage.Value > maxParPage) + parPage = defaultParPage; + + if (!numPage.HasValue || numPage.Value <= 0) + numPage = defaultNumPage; + + + skip = (numPage.Value - 1) * parPage.Value; + take = parPage.Value; + + return query.Skip(skip).Take(take); } + + #region Object to DTO /// - /// Récupère un objet FormationDTO en fonction d'un objet Formation + /// Récuperer un objet FormationDTO en fonction d'un objet Formation /// /// /// @@ -811,7 +524,7 @@ namespace EPAServeur.Services } /// - /// Récupère un objet OrigineFormationDTO en fonction d'un objet OrigineFormation + /// Récuperer un objet OrigineFormationDTO en fonction d'un objet OrigineFormation /// /// /// @@ -828,7 +541,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 +558,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 /// /// /// @@ -861,7 +574,7 @@ 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 /// /// /// @@ -882,7 +595,7 @@ namespace EPAServeur.Services #region DTO to Object /// - /// Modifie un objet Formation en fonction d'un objet FormationDTO + /// Modifier un objet Formation en fonction d'un objet FormationDTO /// /// /// @@ -906,7 +619,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 +634,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 +649,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 +664,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 /// /// /// From 5b8e5b043a8b817be8ffeece0bed89aca5be2df8 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 14 Jan 2021 11:05:56 +0100 Subject: [PATCH 08/28] Ajout du package Moq pour les tests unitaires --- EPAServeur.Tests/EPAServeur.Tests.csproj | 5 +++++ EPAServeur.Tests/Properties/launchSettings.json | 7 +++++++ 2 files changed, 12 insertions(+) create mode 100644 EPAServeur.Tests/Properties/launchSettings.json 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 From cf0c099bcd30ca56bfb2db11da03c0cf72948978 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 1 Feb 2021 16:47:05 +0100 Subject: [PATCH 09/28] =?UTF-8?q?Ajout=20du=20jeu=20de=20donn=C3=A9es=20fi?= =?UTF-8?q?ctif=20pour=20les=20participations=20aux=20formations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Context/DataSeeder.cs | 566 ++++++++++++++++++++++++++++--- 1 file changed, 514 insertions(+), 52 deletions(-) diff --git a/EPAServeur/Context/DataSeeder.cs b/EPAServeur/Context/DataSeeder.cs index 8403d4d..f76d731 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(); } /// @@ -443,10 +443,10 @@ namespace EPAServeur.Context f1 = new Formation { - Intitule = "Formation1", - - DateDebut = new DateTime(2020, 9, 16, 10, 0, 0), - DateFin = new DateTime(2020, 9, 17), + 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 +461,10 @@ namespace EPAServeur.Context f2 = new Formation { - Intitule = "Formation2", - - DateDebut = new DateTime(2020, 10, 5, 14, 0, 0), - DateFin = new DateTime(2020, 10, 9), + 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 +479,10 @@ namespace EPAServeur.Context f3 = new Formation { - Intitule = "Formation3", - - DateDebut = new DateTime(2020, 9, 21, 14, 0, 0), - DateFin = new DateTime(2020, 9, 21), + 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 +497,10 @@ namespace EPAServeur.Context f4 = new Formation { - Intitule = "Formation4", - - DateDebut = new DateTime(2020, 05, 11, 14, 0, 0), - DateFin = new DateTime(2020, 05, 11), + 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 +515,10 @@ namespace EPAServeur.Context f5 = new Formation { - Intitule = "Formation5", - - DateDebut = new DateTime(2020, 08, 1, 13, 0, 0), - DateFin = new DateTime(2020, 08, 3), + 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 +533,10 @@ namespace EPAServeur.Context f6 = new Formation { - Intitule = "Formation6", - - DateDebut = new DateTime(2020, 9, 30, 9, 0, 0), - DateFin = new DateTime(2020, 10, 1), + 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 +551,10 @@ namespace EPAServeur.Context f7 = new Formation { - Intitule = "Formation7", - - DateDebut = new DateTime(2020, 10, 5, 10, 0, 0), - DateFin = new DateTime(2020, 10, 8), + 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 +569,9 @@ namespace EPAServeur.Context f8 = new Formation { - Intitule = "Formation8", - DateDebut = new DateTime(2020, 11, 18, 10, 0, 0), - DateFin = new DateTime(2020, 11, 20), + 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 +586,7 @@ namespace EPAServeur.Context f9 = new Formation { - Intitule = "Formation9", + 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 +603,7 @@ namespace EPAServeur.Context f10 = new Formation { - Intitule = "Formation10", + Intitule = "Architecture Microservices – Les fondamentaux", DateDebut = new DateTime(2020, 8, 3, 14, 0, 0), DateFin = new DateTime(2020, 8, 3), IdAgence = 1, @@ -620,7 +620,7 @@ namespace EPAServeur.Context f11 = new Formation { - Intitule = "Formation11", + Intitule = "Formation Clean Architecture .Net Core", DateDebut = new DateTime(2020, 04, 6, 9, 0, 0), DateFin = new DateTime(2020, 04, 11), IdAgence = 1, @@ -636,24 +636,486 @@ namespace EPAServeur.Context 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + 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 + { + DateCreation = new DateTime(2020, 12, 25, 9, 0, 0), + EstEvaluee = false, + IdDemandeFormation = d12.IdDemandeFormation, + DemandeFormation = d12, + Formation = f9 + }; + epContext.ParticipationFormation.Add(p12); + + epContext.SaveChanges(); } + /// + /// Insère un jeu de données fictif pour les demandes de formation + /// + /// + public static void AddDemandesFormation(EpContext epContext) + { + + } + /// /// Insère un jeu de données fictif pour les champs /// From ff98567d1e98ae117c32a66c091b780c159ae941 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 1 Feb 2021 16:53:49 +0100 Subject: [PATCH 10/28] MAJ des tests unitaires --- .../Controllers/FormationApiTests.cs | 4 +- .../Services/FormationServiceTests.cs | 77 +++++++++++++++---- 2 files changed, 64 insertions(+), 17 deletions(-) diff --git a/EPAServeur.Tests/Controllers/FormationApiTests.cs b/EPAServeur.Tests/Controllers/FormationApiTests.cs index 199b129..eb056ae 100644 --- a/EPAServeur.Tests/Controllers/FormationApiTests.cs +++ b/EPAServeur.Tests/Controllers/FormationApiTests.cs @@ -148,8 +148,8 @@ namespace EPAServeur.Tests.Controllers FormationsApiController formationsApiController = new FormationsApiController(formationService, new NullLogger(), mockEnvironment.Object); List idStatuts = new List { 1, 2, 3 }; int nbFormation = 5; - int idFirstFormation = 1; - int idLastFormation = 5; + int idFirstFormation = 5; + int idLastFormation = 1; // Act var okResult = formationsApiController.GetFormations(1, idStatuts, true, 1, 5, "formation", null, null, null).Result as OkObjectResult; diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index d60667a..7349820 100644 --- a/EPAServeur.Tests/Services/FormationServiceTests.cs +++ b/EPAServeur.Tests/Services/FormationServiceTests.cs @@ -62,10 +62,10 @@ namespace EPAServeur.Tests.Services // 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, 17), 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); @@ -96,11 +96,11 @@ namespace EPAServeur.Tests.Services #region Tests GetFormationsAsync [TestCase(1, new int[] { 1, 2, 3 }, true, 1, 5, "formation", null, null, null)] - [TestCase(1, new int[] { 1 }, false, 1, 5, "formation1", 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)] + [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 @@ -119,6 +119,53 @@ namespace EPAServeur.Tests.Services Assert.Less(0, formationDTOs.Count()); } + [TestCase(1, 5)] + [TestCase(1, 10)] + public async Task GetFormationsAsync_PasseEnParamNumPageEtParPage_RetourneLaPremierePageDesFormations(int? numPage, int? parPAge) + { + // Arrange + FormationService formationService = new FormationService(epContext); + + // Act + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); + + // Assert + Assert.AreEqual(parPAge, formationDTOs.Count()); + } + + [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); + 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(null, null, null, numPage, parPAge, null, null, null, null); + + // Assert + Assert.AreEqual(nbFormationDeuxiemePage, formationDTOs.Count()); + } + [TestCase(true, "intitule")] [TestCase(true, null)] public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleCroissant(bool? asc, string tri) @@ -130,8 +177,8 @@ namespace EPAServeur.Tests.Services IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual("Formation1", formationDTOs.First().Intitule); - Assert.AreEqual("Formation9", formationDTOs.Last().Intitule); + 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); } @@ -146,8 +193,8 @@ namespace EPAServeur.Tests.Services IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual("Formation9", formationDTOs.First().Intitule); - Assert.AreEqual("Formation1", formationDTOs.Last().Intitule); + 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); } @@ -221,8 +268,8 @@ namespace EPAServeur.Tests.Services IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(new DateTime(2020, 04, 6, 9, 0, 0), formationDTOs.First().DateDebut); - Assert.AreEqual(new DateTime(2020, 11, 18, 10, 0, 0), formationDTOs.Last().DateDebut); + 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); } @@ -236,8 +283,8 @@ namespace EPAServeur.Tests.Services IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert - Assert.AreEqual(new DateTime(2020, 11, 18, 10, 0, 0), formationDTOs.First().DateDebut); - Assert.AreEqual(new DateTime(2020, 04, 6, 9, 0, 0), formationDTOs.Last().DateDebut); + 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); } @@ -302,7 +349,7 @@ namespace EPAServeur.Tests.Services } - [TestCase("2020-10-01", "2020-11-01")] + [TestCase("2020-11-01", "2020-12-01")] public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutEtUneDateDeFin_RetourneDesFormationsAvecUneDateDeDebutSuperieurUneDateDeFinInferieur(DateTime dateDebut, DateTime dateFin) { // Arrange @@ -360,7 +407,7 @@ namespace EPAServeur.Tests.Services #region Tests GetFormationsCountAsync [TestCase(1, new int[] { 1, 2, 3 }, 1, 5, "formation", "2020-09-30", "2020-11-30")] - [TestCase(1, new int[] { 1 }, 1, 5, "formation1", null, null)] + [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)] From 29970bc54ff1faa7358fa41a73ee1fa0ee63b8c9 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Wed, 3 Feb 2021 08:52:38 +0100 Subject: [PATCH 11/28] Ajout de la liste des participations dans le model Formation --- EPAServeur/Context/EpContext.cs | 1 + EPAServeur/Models/Formation/Formation.cs | 5 +++++ 2 files changed, 6 insertions(+) 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/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; } } } From d08a86bb9bc93872f78a648796b7bd1d0b0cbd22 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Wed, 3 Feb 2021 08:54:41 +0100 Subject: [PATCH 12/28] Remplacement du DTO FormationDTO par FormationDetailsDTO --- .../Services/FormationServiceTests.cs | 36 +++++++++---------- EPAServeur/Controllers/FormationsApi.cs | 2 +- EPAServeur/IServices/IFormationService.cs | 2 +- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index 7349820..9881639 100644 --- a/EPAServeur.Tests/Services/FormationServiceTests.cs +++ b/EPAServeur.Tests/Services/FormationServiceTests.cs @@ -113,7 +113,7 @@ namespace EPAServeur.Tests.Services idStatuts = null; // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); // Assert Assert.Less(0, formationDTOs.Count()); @@ -127,7 +127,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); // Assert Assert.AreEqual(parPAge, formationDTOs.Count()); @@ -160,7 +160,7 @@ namespace EPAServeur.Tests.Services } // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); // Assert Assert.AreEqual(nbFormationDeuxiemePage, formationDTOs.Count()); @@ -174,7 +174,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Apprendre C# et le développement de logiciels avec WPF", formationDTOs.First().Intitule); @@ -190,7 +190,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Formation Xamarin, Développer des applications mobiles en C# pour iOS et Android", formationDTOs.First().Intitule); @@ -205,7 +205,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Annulée", formationDTOs.First().Statut.Libelle); @@ -220,7 +220,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Replanifiée", formationDTOs.First().Statut.Libelle); @@ -235,7 +235,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Demande collaborateur", formationDTOs.First().Origine.Libelle); @@ -250,7 +250,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual("Formation réglementaire", formationDTOs.First().Origine.Libelle); @@ -265,7 +265,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual(new DateTime(2020, 1, 25, 10, 0, 0), formationDTOs.First().DateDebut); @@ -280,7 +280,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual(new DateTime(2020, 12, 25, 14, 0, 0), formationDTOs.First().DateDebut); @@ -295,7 +295,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual(false, formationDTOs.First().EstCertifiee); @@ -310,7 +310,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); // Assert Assert.AreEqual(true, formationDTOs.First().EstCertifiee); @@ -326,7 +326,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, null); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, null); // Assert Assert.Greater(formationDTOs.First().DateDebut, dateDebut); @@ -341,7 +341,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, null, dateFin); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, null, dateFin); // Assert Assert.Less(formationDTOs.First().DateFin, dateFin); @@ -356,7 +356,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); // Assert Assert.Greater(formationDTOs.First().DateDebut, dateDebut); @@ -374,7 +374,7 @@ namespace EPAServeur.Tests.Services FormationService formationService = new FormationService(epContext); // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); // Assert Assert.AreEqual(0, formationDTOs.Count()); @@ -396,7 +396,7 @@ namespace EPAServeur.Tests.Services // Act - IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); + IEnumerable formationDTOs = await formationService.GetFormationsAsync(idAgence, idStatuts, asc, numPage, parPAge, texte, tri, dateDebut, dateFin); // Assert Assert.AreEqual(0, formationDTOs.Count()); diff --git a/EPAServeur/Controllers/FormationsApi.cs b/EPAServeur/Controllers/FormationsApi.cs index f2ed436..52e9203 100644 --- a/EPAServeur/Controllers/FormationsApi.cs +++ b/EPAServeur/Controllers/FormationsApi.cs @@ -298,7 +298,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des formations."); - IEnumerable formations = null; + IEnumerable formations = null; try { diff --git a/EPAServeur/IServices/IFormationService.cs b/EPAServeur/IServices/IFormationService.cs index 0fbf2f3..099e065 100644 --- a/EPAServeur/IServices/IFormationService.cs +++ b/EPAServeur/IServices/IFormationService.cs @@ -11,7 +11,7 @@ namespace EPAServeur.IServices public interface IFormationService { 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> 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(); Task> GetOriginesFormationAsync(); From 695562391a90bfc4429979fe26884cccbe9d9f53 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Wed, 3 Feb 2021 08:56:01 +0100 Subject: [PATCH 13/28] =?UTF-8?q?Renommage=20de=20la=20propri=C3=A9t=C3=A9?= =?UTF-8?q?=20EstCertifie?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/DTO/FormationDetailsDTO.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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; } } From 7b7546bc19224fd9c8df5e20bb6850ba7625b254 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Wed, 3 Feb 2021 08:57:28 +0100 Subject: [PATCH 14/28] Ajout de la liste des participations sans les collaborateurs ni les EP --- EPAServeur/Services/FormationService.cs | 79 +++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 6 deletions(-) diff --git a/EPAServeur/Services/FormationService.cs b/EPAServeur/Services/FormationService.cs index 1ef4934..2c25d60 100644 --- a/EPAServeur/Services/FormationService.cs +++ b/EPAServeur/Services/FormationService.cs @@ -73,6 +73,9 @@ namespace EPAServeur.Services .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) @@ -91,17 +94,18 @@ namespace EPAServeur.Services /// Texte permettant d'identifier l'objet rechercher /// Colonne du tableau sur lequel le tri s'effectue /// - public async Task> GetFormationsAsync(long? idAgence, List idStatuts, bool? asc, int? numPage, int? parPage, string texte, string tri, DateTime? dateDebut, DateTime? dateFin) + 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; query = epContext.Formation .Include(formation => formation.Statut) .Include(formation => formation.ModeFormation) .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); + .Include(formation => formation.TypeFormation) + .Include(formation => formation.ParticipationsFormation); query = IdStatutsFilter(query, idStatuts); @@ -117,7 +121,7 @@ namespace EPAServeur.Services formations = await query.ToListAsync(); - formationDTOs = formations.Select(formation => GetFormationDTO(formation)); + formationDTOs = formations.Select(formation => GetFormationDetailsDTO(formation)); return formationDTOs; } @@ -140,7 +144,8 @@ namespace EPAServeur.Services .Include(formation => formation.Statut) .Include(formation => formation.ModeFormation) .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); + .Include(formation => formation.TypeFormation) + .Include(formation => formation.ParticipationsFormation); query = IntituleFilter(query, texte); @@ -517,7 +522,31 @@ namespace EPAServeur.Services Origine = GetOrigineFormationDTO(formation.Origine), Statut = GetStatutFormationDTO(formation.Statut), Mode = GetModeFormationDTO(formation.ModeFormation), - Type = GetTypeFormationDTO(formation.TypeFormation) + Type = GetTypeFormationDTO(formation.TypeFormation), + Participations = GetParticipationsFormationDTO(formation.ParticipationsFormation) + }; + + return formationDTO; + } + + /// + /// 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; @@ -573,6 +602,7 @@ namespace EPAServeur.Services }; return modeFormationDTO; } + /// /// Récuperer un objet TypeFormationDTO en fonction d'un objet TypeFormation /// @@ -590,6 +620,43 @@ namespace EPAServeur.Services return typeFormationDTO; } + /// + /// Récuperer une liste de ParticipationFormationDTO en fonction d'une liste de ParticipationFormation + /// + /// + /// + private List GetParticipationsFormationDTO(List participationsFormation) + { + List participationFormationDTOs; + + if (participationsFormation == null || participationsFormation.Count == 0) + return null; + + participationFormationDTOs = participationsFormation.Select(participationFormation => GetParticipationFormationDTO(participationFormation)).ToList(); + + return participationFormationDTOs; + } + + /// + /// Récuperer un objet ParticipationFormationDTO en fonction d'un objet ParticipationFormation + /// + /// + /// + private ParticipationFormationDTO GetParticipationFormationDTO(ParticipationFormation participationFormation) + { + if (participationFormation == null) + return null; + ParticipationFormationDTO participationFormationDTO = new ParticipationFormationDTO() + { + Id = participationFormation.IdParticipationFormation, + DateCreation = participationFormation.DateCreation, + Intitule = participationFormation.Formation.Intitule, + DateDebut= participationFormation.Formation.DateDebut, + Statut = GetStatutFormationDTO(participationFormation.Formation.Statut), + }; + return participationFormationDTO; + } + #endregion #region DTO to Object From 17d7fc77783a20e3ad917678dc3a52055cd7b22d Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 4 Feb 2021 08:51:55 +0100 Subject: [PATCH 15/28] =?UTF-8?q?Ajout=20des=20id=20dans=20la=20m=C3=A9tho?= =?UTF-8?q?de=20AddFormation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Context/DataSeeder.cs | 53 ++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/EPAServeur/Context/DataSeeder.cs b/EPAServeur/Context/DataSeeder.cs index b041022..4e9ddc0 100644 --- a/EPAServeur/Context/DataSeeder.cs +++ b/EPAServeur/Context/DataSeeder.cs @@ -443,6 +443,7 @@ namespace EPAServeur.Context f1 = new Formation { + IdFormation = 1, Intitule = "Formation Mainframe Complète", DateDebut = new DateTime(2020, 1, 25, 10, 0, 0), @@ -461,6 +462,7 @@ namespace EPAServeur.Context f2 = new Formation { + IdFormation = 2, Intitule = "Formation professionnelle React + Redux", DateDebut = new DateTime(2020, 2, 25, 14, 0, 0), @@ -479,6 +481,7 @@ namespace EPAServeur.Context f3 = new Formation { + IdFormation = 3, Intitule = "Apprendre C# et le développement de logiciels avec WPF", DateDebut = new DateTime(2020, 5, 25, 14, 0, 0), @@ -497,6 +500,7 @@ namespace EPAServeur.Context f4 = new Formation { + IdFormation = 4, Intitule = "Formation Visual Basic.Net - Initiation + Approfondissement", DateDebut = new DateTime(2020, 7, 25, 14, 0, 0), @@ -515,6 +519,7 @@ namespace EPAServeur.Context f5 = new Formation { + IdFormation = 5, Intitule = "Formation Conception, langage SQL : Les fondamentaux", DateDebut = new DateTime(2020, 8, 25, 14, 0, 0), @@ -533,6 +538,7 @@ namespace EPAServeur.Context f6 = new Formation { + IdFormation = 6, Intitule = "Formation Laravel 5.x, Développement WEB en PHP", DateDebut = new DateTime(2020, 9, 25, 14, 0, 0), @@ -551,6 +557,7 @@ namespace EPAServeur.Context f7 = new Formation { + IdFormation = 7, Intitule = "Formation d’initiation aux Méthodes Agiles – Scrum", DateDebut = new DateTime(2020, 11, 25, 14, 0, 0), @@ -569,6 +576,7 @@ namespace EPAServeur.Context f8 = new Formation { + 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), @@ -586,6 +594,7 @@ namespace EPAServeur.Context f9 = new Formation { + 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), @@ -603,6 +612,7 @@ namespace EPAServeur.Context f10 = new Formation { + IdFormation = 10, Intitule = "Architecture Microservices – Les fondamentaux", DateDebut = new DateTime(2020, 8, 3, 14, 0, 0), DateFin = new DateTime(2020, 8, 3), @@ -620,6 +630,7 @@ namespace EPAServeur.Context f11 = new Formation { + IdFormation = 11, Intitule = "Formation Clean Architecture .Net Core", DateDebut = new DateTime(2020, 04, 6, 9, 0, 0), DateFin = new DateTime(2020, 04, 11), @@ -647,6 +658,7 @@ namespace EPAServeur.Context ep12 = new Ep { + IdEP = 12, IdCollaborateur = Guid.Parse("842650db-a548-4472-a3af-4c5fff3c1ab8"), IdReferent = Guid.Parse("aa36f34c-9041-42f5-9db3-6536fe7f1696"), IdBu = 2, @@ -664,6 +676,7 @@ namespace EPAServeur.Context ep13 = new Ep { + IdEP = 13, IdCollaborateur = Guid.Parse("301ba7f3-095e-4912-8998-a7c942dc5f23"), IdReferent = Guid.Parse("ea027734-ff0f-4308-8879-133a09fb3c46"), IdBu = 2, @@ -681,6 +694,7 @@ namespace EPAServeur.Context ep14 = new Ep { + IdEP = 14, IdCollaborateur = Guid.Parse("a0f40e2a-cc03-4032-a627-5389e1281c64"), IdReferent = Guid.Parse("56e3d82d-4be4-4449-a1f7-b4004b6bd186"), IdBu = 2, @@ -699,6 +713,7 @@ namespace EPAServeur.Context ep15 = new Ep { + IdEP = 15, IdCollaborateur = Guid.Parse("4f3fcd23-a1e4-4c9e-afa2-d06ca9216491"), IdReferent = Guid.Parse("25d2b0ce-5c95-4ccc-98bb-63b06c4ee4ad"), IdBu = 2, @@ -715,6 +730,7 @@ namespace EPAServeur.Context ep16 = new Ep { + IdEP = 16, IdCollaborateur = Guid.Parse("0968ccd3-1ef5-4041-83f3-1c76afb02bbf"), IdReferent = Guid.Parse("01ee85ff-d7f3-494b-b1de-26ced8fbfa0d"), IdBu = 2, @@ -733,6 +749,7 @@ namespace EPAServeur.Context ep17 = new Ep { + IdEP = 17, IdCollaborateur = Guid.Parse("e7820f92-eab1-42f5-ae96-5c16e71ff1e6"), IdReferent = Guid.Parse("d4fc247b-015a-44d6-8f3e-a52f0902d2bf"), IdBu = 2, @@ -751,6 +768,7 @@ namespace EPAServeur.Context ep18 = new Ep { + IdEP = 18, IdCollaborateur = Guid.Parse("1429be5b-9125-482c-80c4-c1d34afbd8d2"), IdReferent = Guid.Parse("3f276ab8-727a-4e26-ad5d-4d296158688e"), IdBu = 2, @@ -769,6 +787,7 @@ namespace EPAServeur.Context ep19 = new Ep { + IdEP = 19, IdCollaborateur = Guid.Parse("13fbe621-1bc9-4f04-afde-b54ca076e239"), IdReferent = Guid.Parse("f1d14915-89f7-4c1a-a8e1-4148ed7d81d7"), IdBu = 2, @@ -787,6 +806,7 @@ namespace EPAServeur.Context ep20 = new Ep { + IdEP = 20, IdCollaborateur = Guid.Parse("b5254c6c-7caa-435f-a4bb-e0cf92559832"), IdReferent = Guid.Parse("dfea9a3c-7896-444d-9aa0-61ae536091c1"), IdBu = 2, @@ -810,6 +830,7 @@ namespace EPAServeur.Context d1 = new DemandeFormation { + IdDemandeFormation = 1, Libelle = "Formation Cobol", Description = "Demande de formation Cobol avec Mainframe", DemandeRH = false, @@ -824,6 +845,7 @@ namespace EPAServeur.Context d2 = new DemandeFormation { + IdDemandeFormation = 2, Libelle = "Formation React", Description = "Demande de formation React avec Redux", DemandeRH = false, @@ -838,6 +860,7 @@ namespace EPAServeur.Context d3 = new DemandeFormation { + IdDemandeFormation = 3, Libelle = "Formation C#", Description = "Demande de formation C# avec WPF", DemandeRH = false, @@ -852,6 +875,7 @@ namespace EPAServeur.Context d4 = new DemandeFormation { + IdDemandeFormation = 4, Libelle = "Formation C#", Description = "Demande de formation C# avec WPF", DemandeRH = false, @@ -866,6 +890,7 @@ namespace EPAServeur.Context d5 = new DemandeFormation { + IdDemandeFormation = 5, Libelle = "Formation C#", Description = "Demande de formation C# avec WPF", DemandeRH = false, @@ -880,6 +905,7 @@ namespace EPAServeur.Context d6 = new DemandeFormation { + IdDemandeFormation = 6, Libelle = "Formation Vb.Net", Description = "Demande de formation Vb.Net avec WinForms", DemandeRH = false, @@ -894,6 +920,7 @@ namespace EPAServeur.Context d7 = new DemandeFormation { + IdDemandeFormation = 7, Libelle = "Formation Vb.Net", Description = "Demande de formation Vb.Net avec WinForms", DemandeRH = false, @@ -908,6 +935,7 @@ namespace EPAServeur.Context d8 = new DemandeFormation { + IdDemandeFormation = 8, Libelle = "Formation SQL", Description = "Demande de formation SQL avec SQL Server", DemandeRH = false, @@ -922,6 +950,7 @@ namespace EPAServeur.Context d9 = new DemandeFormation { + IdDemandeFormation = 9, Libelle = "Formation PHP", Description = "Demande de formation PHP avec Laravel", DemandeRH = false, @@ -936,6 +965,7 @@ namespace EPAServeur.Context d10 = new DemandeFormation { + IdDemandeFormation = 10, Libelle = "Formation Vue.JS", Description = "Demande de formation Vue.JS", DemandeRH = false, @@ -950,6 +980,7 @@ namespace EPAServeur.Context d11 = new DemandeFormation { + IdDemandeFormation = 11, Libelle = "Formation SCRUM", Description = "Demande de formation sur la méthode agile SCRUM", DemandeRH = false, @@ -964,6 +995,7 @@ namespace EPAServeur.Context d12 = new DemandeFormation { + IdDemandeFormation = 12, Libelle = "Formation C#", Description = "Demande de formation C# avec Xamarin", DemandeRH = false, @@ -985,6 +1017,7 @@ namespace EPAServeur.Context p1 = new ParticipationFormation { + IdParticipationFormation = 1, DateCreation = new DateTime(2020, 1, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d1.IdDemandeFormation, @@ -995,6 +1028,7 @@ namespace EPAServeur.Context p2 = new ParticipationFormation { + IdParticipationFormation = 2, DateCreation = new DateTime(2020, 2, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d2.IdDemandeFormation, @@ -1005,6 +1039,7 @@ namespace EPAServeur.Context p3 = new ParticipationFormation { + IdParticipationFormation = 3, DateCreation = new DateTime(2020, 3, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d3.IdDemandeFormation, @@ -1015,6 +1050,7 @@ namespace EPAServeur.Context p4 = new ParticipationFormation { + IdParticipationFormation = 4, DateCreation = new DateTime(2020, 4, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d4.IdDemandeFormation, @@ -1025,6 +1061,7 @@ namespace EPAServeur.Context p5 = new ParticipationFormation { + IdParticipationFormation = 5, DateCreation = new DateTime(2020, 5, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d5.IdDemandeFormation, @@ -1035,6 +1072,7 @@ namespace EPAServeur.Context p6 = new ParticipationFormation { + IdParticipationFormation = 6, DateCreation = new DateTime(2020, 6, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d6.IdDemandeFormation, @@ -1045,6 +1083,7 @@ namespace EPAServeur.Context p7 = new ParticipationFormation { + IdParticipationFormation = 7, DateCreation = new DateTime(2020, 7, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d7.IdDemandeFormation, @@ -1055,6 +1094,7 @@ namespace EPAServeur.Context p8 = new ParticipationFormation { + IdParticipationFormation = 8, DateCreation = new DateTime(2020, 8, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d8.IdDemandeFormation, @@ -1065,6 +1105,7 @@ namespace EPAServeur.Context p9 = new ParticipationFormation { + IdParticipationFormation = 9, DateCreation = new DateTime(2020, 9, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d9.IdDemandeFormation, @@ -1075,6 +1116,7 @@ namespace EPAServeur.Context p10 = new ParticipationFormation { + IdParticipationFormation = 10, DateCreation = new DateTime(2020, 10, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d10.IdDemandeFormation, @@ -1085,6 +1127,7 @@ namespace EPAServeur.Context p11 = new ParticipationFormation { + IdParticipationFormation = 11, DateCreation = new DateTime(2020, 11, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d11.IdDemandeFormation, @@ -1095,6 +1138,7 @@ namespace EPAServeur.Context p12 = new ParticipationFormation { + IdParticipationFormation = 12, DateCreation = new DateTime(2020, 12, 25, 9, 0, 0), EstEvaluee = false, IdDemandeFormation = d12.IdDemandeFormation, @@ -1107,15 +1151,6 @@ namespace EPAServeur.Context epContext.SaveChanges(); } - /// - /// Insère un jeu de données fictif pour les demandes de formation - /// - /// - public static void AddDemandesFormation(EpContext epContext) - { - - } - /// /// Insère un jeu de données fictif pour les champs /// From 6747f231fe75a1cb70b0b45acc297c5029d88b0f Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 4 Feb 2021 08:57:27 +0100 Subject: [PATCH 16/28] =?UTF-8?q?Nettoyage=20du=20code=20+=20D=C3=A9commen?= =?UTF-8?q?ter=20l'attribut=20Authorize?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Controllers/FormationsApi.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/EPAServeur/Controllers/FormationsApi.cs b/EPAServeur/Controllers/FormationsApi.cs index 52e9203..b641701 100644 --- a/EPAServeur/Controllers/FormationsApi.cs +++ b/EPAServeur/Controllers/FormationsApi.cs @@ -216,7 +216,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations/{idFormation}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetFormationById")] [SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")] @@ -229,7 +229,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la formation {idFormation}.", idFormation); - FormationDTO formationDTO = null; + FormationDTO formationDTO; try { @@ -298,7 +298,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des formations."); - IEnumerable formations = null; + IEnumerable formations; try { @@ -342,7 +342,7 @@ namespace IO.Swagger.Controllers /// Une erreur est survenue sur le serveur [HttpGet] [Route("/api/formations/count")] - //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetFormationsCount")] [SwaggerResponse(statusCode: 200, type: typeof(long?), description: "OK")] @@ -354,7 +354,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération du nombre total de formations."); - long count = 0; + long count; try { @@ -402,7 +402,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des modes de formation."); - IEnumerable modeFormations = null; + IEnumerable modeFormations; try { @@ -449,7 +449,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des origines de formation."); - IEnumerable origineFormations = null; + IEnumerable origineFormations; try { @@ -496,7 +496,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des statuts de formation."); - IEnumerable statutFormations = null; + IEnumerable statutFormations; try { @@ -543,7 +543,7 @@ namespace IO.Swagger.Controllers if (env.IsDevelopment()) logger.LogInformation("Récupération de la liste des types de formation."); - IEnumerable typeFormations = null; + IEnumerable typeFormations; try { From 5e3870ec6ea7aad78eb598e8836f5764339ae264 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 4 Feb 2021 08:58:30 +0100 Subject: [PATCH 17/28] Ajout du service Collaborateur --- .../Controllers/FormationApiTests.cs | 12 +-- .../Services/FormationServiceTests.cs | 80 ++++++++++--------- 2 files changed, 49 insertions(+), 43 deletions(-) diff --git a/EPAServeur.Tests/Controllers/FormationApiTests.cs b/EPAServeur.Tests/Controllers/FormationApiTests.cs index eb056ae..fb8ae37 100644 --- a/EPAServeur.Tests/Controllers/FormationApiTests.cs +++ b/EPAServeur.Tests/Controllers/FormationApiTests.cs @@ -18,6 +18,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using EPAServeur.IServices; using Moq; +using IO.Swagger.ApiCollaborateur; namespace EPAServeur.Tests.Controllers { @@ -62,7 +63,8 @@ namespace EPAServeur.Tests.Controllers entity.State = EntityState.Detached; } - + services.AddScoped(); + services.AddScoped(); services.AddScoped(); // Récupère le service qui sera utilsé pour tester le contrôleur @@ -155,10 +157,10 @@ namespace EPAServeur.Tests.Controllers 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); + 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); } #endregion diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index 9881639..eea69fd 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(); @@ -55,7 +59,7 @@ namespace EPAServeur.Tests.Services public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act FormationDTO formationDTO = await formationService.GetFormationByIdAsync(1); @@ -82,7 +86,7 @@ namespace EPAServeur.Tests.Services public void GetFormationByIdAsync_PasseEnParamUnIdInexistantDansLeJeuDeDonneesFictif_LeveUneFormationNotFoundException(long idFormation) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.GetFormationByIdAsync(idFormation); @@ -104,7 +108,7 @@ namespace EPAServeur.Tests.Services 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) @@ -124,7 +128,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, null, numPage, parPAge, null, null, null, null); @@ -140,7 +144,7 @@ namespace EPAServeur.Tests.Services 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) @@ -171,7 +175,7 @@ namespace EPAServeur.Tests.Services 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(null, null, asc, null, null, null, tri, null, null); @@ -187,7 +191,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -202,7 +206,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -217,7 +221,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -232,7 +236,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -247,7 +251,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -262,7 +266,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -277,7 +281,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -292,7 +296,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -307,7 +311,7 @@ namespace EPAServeur.Tests.Services 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 = await formationService.GetFormationsAsync(null, null, asc, null, null, null, tri, null, null); @@ -323,7 +327,7 @@ namespace EPAServeur.Tests.Services public async Task GetFormationsAsync_PasseEnParamUneDateDeDebut_RetourneDesFormationsAvecUneDateDeDebutSuperieur(DateTime dateDebut) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, null); @@ -338,7 +342,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, null, null, null, null, null, null, dateFin); @@ -353,7 +357,7 @@ namespace EPAServeur.Tests.Services 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.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); @@ -371,7 +375,7 @@ namespace EPAServeur.Tests.Services public async Task GetFormationsAsync_PasseEnParamUneDateDeDebutSuperieurEtUneDateDeFinInferieur_RetourneZeroFormation(DateTime dateDebut, DateTime dateFin) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable formationDTOs = await formationService.GetFormationsAsync(null, null, null, null, null, null, null, dateDebut, dateFin); @@ -386,7 +390,7 @@ namespace EPAServeur.Tests.Services 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) @@ -415,7 +419,7 @@ namespace EPAServeur.Tests.Services 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) @@ -436,7 +440,7 @@ namespace EPAServeur.Tests.Services 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) @@ -460,7 +464,7 @@ namespace EPAServeur.Tests.Services public async Task GetModesFormationAsync_RetourneTousLesModesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable modeFormationDTOs = await formationService.GetModesFormationAsync(); @@ -478,7 +482,7 @@ namespace EPAServeur.Tests.Services public async Task GetOriginesAsyncFormation_RetourneToutesLesOriginesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable origineFormationDTOs = await formationService.GetOriginesFormationAsync(); @@ -496,7 +500,7 @@ namespace EPAServeur.Tests.Services public async Task GetStatutsFormationAsyncFormation_RetourneTousLesStatutsDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable statutFormationDTOs = await formationService.GetStatutsFormationAsync(); @@ -514,7 +518,7 @@ namespace EPAServeur.Tests.Services public async Task GetTypesFormationAsync_RetourneTousLesTypesDeFormation() { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act IEnumerable typeFormationDTOs = await formationService.GetTypesFormationAsync(); @@ -559,7 +563,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); @@ -588,7 +592,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); @@ -637,7 +641,7 @@ namespace EPAServeur.Tests.Services EstCertifiee = false }; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.AddFormationAsync(formation); @@ -683,7 +687,7 @@ namespace EPAServeur.Tests.Services EstCertifiee = false }; - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); // Act AsyncTestDelegate throwException = () => formationService.AddFormationAsync(formation); @@ -709,7 +713,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(idFormation); @@ -773,7 +777,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(idFormation); @@ -812,7 +816,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); @@ -850,7 +854,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 { @@ -886,7 +890,7 @@ namespace EPAServeur.Tests.Services public async Task DeleteFormationByIdAsync_SupprimeUneFormationAvecUnIdValide_FormationSupprimeAvecSucces(long idFormation) { // Arrange - FormationService formationService = new FormationService(epContext); + FormationService formationService = new FormationService(epContext, collaborateurService); bool existFormation = true; // Act @@ -903,7 +907,7 @@ namespace EPAServeur.Tests.Services 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); From 71e8c9b538cca93de8f2f2204d6070d0b35edc8c Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 4 Feb 2021 08:59:58 +0100 Subject: [PATCH 18/28] =?UTF-8?q?R=C3=A9cup=C3=A9ration=20des=20collaborat?= =?UTF-8?q?eurs=20et=20des=20Ep=20pour=20les=20participations=20aux=20form?= =?UTF-8?q?ations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Services/FormationService.cs | 158 +++++++++++++++++++++--- 1 file changed, 141 insertions(+), 17 deletions(-) diff --git a/EPAServeur/Services/FormationService.cs b/EPAServeur/Services/FormationService.cs index 2c25d60..fc35640 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; @@ -20,6 +21,11 @@ namespace EPAServeur.Services /// private readonly EpContext epContext; + /// + /// Accès et service collaborateur + /// + private readonly ICollaborateurService collaborateurService; + /// /// Nombre d'éléments min à afficher par page /// @@ -53,9 +59,10 @@ namespace EPAServeur.Services /// Constructeur de la classe FormationService /// /// - public FormationService(EpContext _epContext) + public FormationService(EpContext _epContext, ICollaborateurService _collaborateurService) { epContext = _epContext; + collaborateurService = _collaborateurService; } #endregion @@ -81,7 +88,12 @@ namespace EPAServeur.Services if (formation == null) throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.",idFormation)); - return GetFormationDTO(formation); + if (formation.ParticipationsFormation.Count == 0) + return GetFormationDTO(formation); + + IEnumerable collaborateurDTOs = await GetCollaborateurDTOs(formation.ParticipationsFormation); + + return GetFormationDTO(formation, collaborateurDTOs); } /// @@ -375,7 +387,15 @@ namespace EPAServeur.Services if (!asc.HasValue) asc = defaultAsc; - switch (columnName) + if (string.IsNullOrWhiteSpace(columnName)) + { + if (asc.Value) + return query.OrderBy(p => p.Intitule); + else + return query.OrderByDescending(p => p.Intitule); + } + + switch (columnName.ToLower()) { case "intitule": if (asc.Value) @@ -402,9 +422,6 @@ namespace EPAServeur.Services return query.OrderBy(p => p.EstCertifiee); else return query.OrderByDescending(p => p.EstCertifiee); - //(A faire lorsque la gestion des participations aux formations sera terminée) - //case "participants": - // return query; default: if (asc.Value) return query.OrderBy(p => p.Intitule); @@ -421,7 +438,7 @@ namespace EPAServeur.Services /// private IQueryable IdStatutsFilter(IQueryable query, List idStatuts) { - if (idStatuts != null && idStatuts.Count > 0) + if (idStatuts != null && idStatuts.Count > 0 && idStatuts.First().HasValue) return query.Where(formation => idStatuts.Contains(formation.Statut.IdStatutFormation)); else return query; @@ -523,7 +540,35 @@ namespace EPAServeur.Services Statut = GetStatutFormationDTO(formation.Statut), Mode = GetModeFormationDTO(formation.ModeFormation), Type = GetTypeFormationDTO(formation.TypeFormation), - Participations = GetParticipationsFormationDTO(formation.ParticipationsFormation) + }; + + return formationDTO; + } + + /// + /// 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, IEnumerable collaborateurDTOs) + { + 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, + EstRealisee = formation.EstRealisee, + Origine = GetOrigineFormationDTO(formation.Origine), + Statut = GetStatutFormationDTO(formation.Statut), + Mode = GetModeFormationDTO(formation.ModeFormation), + Type = GetTypeFormationDTO(formation.TypeFormation), + Participations = GetParticipationsFormationDTO(formation.ParticipationsFormation, collaborateurDTOs) }; return formationDTO; @@ -621,42 +666,120 @@ namespace EPAServeur.Services } /// - /// Récuperer une liste de ParticipationFormationDTO en fonction d'une liste de ParticipationFormation + /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents /// /// /// - private List GetParticipationsFormationDTO(List participationsFormation) + 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 + /// + /// + /// + private List GetParticipationsFormationDTO(List participationsFormation, IEnumerable collaborateurDTOs) { List participationFormationDTOs; - if (participationsFormation == null || participationsFormation.Count == 0) + if (participationsFormation == null || participationsFormation.Count == 0 || collaborateurDTOs == null || !collaborateurDTOs.Any()) return null; - participationFormationDTOs = participationsFormation.Select(participationFormation => GetParticipationFormationDTO(participationFormation)).ToList(); + 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 + /// Récuperer un objet ParticipationFormationDTO en fonction d'un objet ParticipationFormation et d'une liste de CollaborateurDTO /// /// /// - private ParticipationFormationDTO GetParticipationFormationDTO(ParticipationFormation participationFormation) + private ParticipationFormationDTO GetParticipationFormationDTO(ParticipationFormation participationFormation, IEnumerable collaborateurDTOs) { - if (participationFormation == null) - return null; ParticipationFormationDTO participationFormationDTO = new ParticipationFormationDTO() { Id = participationFormation.IdParticipationFormation, DateCreation = participationFormation.DateCreation, Intitule = participationFormation.Formation.Intitule, - DateDebut= participationFormation.Formation.DateDebut, + 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) + { + CollaborateurDTO collaborateur; + + if (participationFormation == null) + return null; + + if (collaborateurDTOs == null || !collaborateurDTOs.Any()) + collaborateur = null; + else + collaborateur = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == participationFormation.DemandeFormation.Ep.IdCollaborateur); + + return collaborateur; + } + + /// + /// 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; + + if (ep == null) + return null; + + if (collaborateurDTOs == null || !collaborateurDTOs.Any()) + { + collaborateur = null; + referent = null; + } + else + { + 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 @@ -677,6 +800,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); From e8d4bb2961d3adad59d05a81e751067ea273f75d Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 4 Feb 2021 10:28:09 +0100 Subject: [PATCH 19/28] =?UTF-8?q?Tests=20effectu=C3=A9s=20pour=20la=20part?= =?UTF-8?q?ie=20ParticipationFormation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Services/FormationServiceTests.cs | 29 +++++++++++++++ EPAServeur/Services/FormationService.cs | 36 ++++--------------- 2 files changed, 36 insertions(+), 29 deletions(-) diff --git a/EPAServeur.Tests/Services/FormationServiceTests.cs b/EPAServeur.Tests/Services/FormationServiceTests.cs index eea69fd..9dccbe2 100644 --- a/EPAServeur.Tests/Services/FormationServiceTests.cs +++ b/EPAServeur.Tests/Services/FormationServiceTests.cs @@ -80,6 +80,33 @@ namespace EPAServeur.Tests.Services Assert.AreEqual(new TypeFormationDTO { Id = 3, Libelle = "E-learning" }, formationDTO.Type); } + [Test] + public async Task GetFormationByIdAsync_PasseEnParamUnIdExistantDansLeJeuDeDonneesFictif_RetourneUneFormationSansParticipation() + { + // Arrange + FormationService formationService = new FormationService(epContext, collaborateurService); + long idFormation = 11; + + // Act + FormationDTO formationDTO = await formationService.GetFormationByIdAsync(idFormation); + + // Assert + Assert.AreEqual(idFormation, formationDTO.Id); + Assert.AreEqual("Formation Clean Architecture .Net Core", formationDTO.Intitule); + Assert.AreEqual(1, formationDTO.IdAgence); + 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.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)] @@ -172,6 +199,7 @@ namespace EPAServeur.Tests.Services [TestCase(true, "intitule")] [TestCase(true, null)] + [TestCase(true, "toto")] public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleCroissant(bool? asc, string tri) { // Arrange @@ -188,6 +216,7 @@ namespace EPAServeur.Tests.Services [TestCase(false, "intitule")] [TestCase(false, null)] + [TestCase(false, "toto")] public async Task GetFormationsAsync_PasseEnParamAscEtTri_RetourneDesFormationsOrdonnanceeParIntituleDecroissant(bool? asc, string tri) { // Arrange diff --git a/EPAServeur/Services/FormationService.cs b/EPAServeur/Services/FormationService.cs index fc35640..2cd314d 100644 --- a/EPAServeur/Services/FormationService.cs +++ b/EPAServeur/Services/FormationService.cs @@ -86,10 +86,8 @@ namespace EPAServeur.Services .FirstOrDefaultAsync(formation => formation.IdFormation == idFormation); if (formation == null) - throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.",idFormation)); + throw new FormationNotFoundException(string.Format("Aucune formation trouvée avec l'id suivant: {0}.", idFormation)); - if (formation.ParticipationsFormation.Count == 0) - return GetFormationDTO(formation); IEnumerable collaborateurDTOs = await GetCollaborateurDTOs(formation.ParticipationsFormation); @@ -666,7 +664,7 @@ namespace EPAServeur.Services } /// - /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents + /// Récuperer une liste de CollaborateurDTO contenant les collaborateurs et les référents. Retourne null s'il n'y a aucune participation. /// /// /// @@ -681,7 +679,7 @@ namespace EPAServeur.Services } /// - /// Récuperer une liste de ParticipationFormationDTO en fonction d'une liste de ParticipationFormation et d'une liste de CollaborateurDTO + /// 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. /// /// /// @@ -695,7 +693,7 @@ namespace EPAServeur.Services participationFormationDTOs = participationsFormation.Select(participationFormation => GetParticipationFormationDTO(participationFormation, collaborateurDTOs)) .OrderBy(participationFormation => participationFormation.Collaborateur.Nom) .ThenBy(participationFormation => participationFormation.Collaborateur.Prenom).ToList(); - + return participationFormationDTOs; } @@ -727,17 +725,7 @@ namespace EPAServeur.Services /// private CollaborateurDTO GetCollaborateurDTO(ParticipationFormation participationFormation, IEnumerable collaborateurDTOs) { - CollaborateurDTO collaborateur; - - if (participationFormation == null) - return null; - - if (collaborateurDTOs == null || !collaborateurDTOs.Any()) - collaborateur = null; - else - collaborateur = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == participationFormation.DemandeFormation.Ep.IdCollaborateur); - - return collaborateur; + return collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == participationFormation.DemandeFormation.Ep.IdCollaborateur); } /// @@ -750,19 +738,9 @@ namespace EPAServeur.Services CollaborateurDTO collaborateur; CollaborateurDTO referent; - if (ep == null) - return null; - if (collaborateurDTOs == null || !collaborateurDTOs.Any()) - { - collaborateur = null; - referent = null; - } - else - { - collaborateur = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdCollaborateur); - referent = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdReferent); - } + collaborateur = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdCollaborateur); + referent = collaborateurDTOs.FirstOrDefault(collaborateurDTO => collaborateurDTO.Id == ep.IdReferent); EpInformationDTO epInformationDTO = new EpInformationDTO() { From 6aae6cc0a419c981a44eb18d3fb8e6dd49b08c07 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Tue, 9 Feb 2021 17:58:15 +0100 Subject: [PATCH 20/28] MAJ de la description d'AttenteEntretien --- EPAServeur/Enum/StatutEp.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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, From bcc0ddb5d9117463eb25c12ff57b9198c44a6ac2 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:49:22 +0100 Subject: [PATCH 21/28] =?UTF-8?q?Mise=20=C3=A0=20jour=20du=20jeu=20de=20do?= =?UTF-8?q?nn=C3=A9es=20fictif=20pour=20la=20partie=20Engagement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Context/DataSeeder.cs | 202 +++++++++++++++++++++++++------ 1 file changed, 164 insertions(+), 38 deletions(-) diff --git a/EPAServeur/Context/DataSeeder.cs b/EPAServeur/Context/DataSeeder.cs index a478ee0..92be406 100644 --- a/EPAServeur/Context/DataSeeder.cs +++ b/EPAServeur/Context/DataSeeder.cs @@ -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(); } From 0fdb651fddf52abb4b17153ffd8a59a205693c7c Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:51:23 +0100 Subject: [PATCH 22/28] Configuration du package Microsoft.AspNetCore.Mvc.NewtonsoftJson --- EPAServeur/EPAServeur.csproj | 2 +- EPAServeur/Startup.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) 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/Startup.cs b/EPAServeur/Startup.cs index 887dfc8..cacfb6b 100644 --- a/EPAServeur/Startup.cs +++ b/EPAServeur/Startup.cs @@ -42,7 +42,8 @@ namespace EPAServeur }); }); - services.AddControllers(); + services.AddControllers().AddNewtonsoftJson(); + services.AddAuthentication(options => { From 92a68a26ccddea12187caf7890506acadf249385 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:55:44 +0100 Subject: [PATCH 23/28] =?UTF-8?q?Mise=20=C3=A0=20jour=20des=20signatures?= =?UTF-8?q?=20de=20l'interface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/IServices/IEngagementService.cs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) 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); } } From 170b806e40a892976be1aa55e6a919f8f8d1eac0 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:57:12 +0100 Subject: [PATCH 24/28] =?UTF-8?q?Mise=20=C3=A0=20jour=20des=20endpoints=20?= =?UTF-8?q?+=20Ajout=20des=20droits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Controllers/EngagementsApi.cs | 208 +++++++++++++++++------ 1 file changed, 154 insertions(+), 54 deletions(-) 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); } } } From a1ca68302785057b39e371b08ce7e693ca290d9f Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:58:04 +0100 Subject: [PATCH 25/28] =?UTF-8?q?Mise=20=C3=A0=20jour=20des=20m=C3=A9thode?= =?UTF-8?q?s=20du=20service?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EPAServeur/Services/EngagementService.cs | 514 ++++++++++++----------- 1 file changed, 260 insertions(+), 254 deletions(-) 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 From 74ca7f067ba0a6af37c06acc563864877977b7a9 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 15:59:18 +0100 Subject: [PATCH 26/28] =?UTF-8?q?Cr=C3=A9ation=20des=20tests=20unitaires?= =?UTF-8?q?=20pour=20la=20partie=20Engagement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/EngagementsApiTests.cs | 340 ++++++++++ .../Services/EngagementServiceTests.cs | 637 ++++++++++++++++++ 2 files changed, 977 insertions(+) create mode 100644 EPAServeur.Tests/Controllers/EngagementsApiTests.cs create mode 100644 EPAServeur.Tests/Services/EngagementServiceTests.cs 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/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 From 70808c29664dcb66acf6101d533007480b2d2293 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 16:00:24 +0100 Subject: [PATCH 27/28] =?UTF-8?q?Cr=C3=A9ation=20d'un=20attribut=20pour=20?= =?UTF-8?q?valider=20une=20collection=20qui=20est=20pass=C3=A9e=20en=20par?= =?UTF-8?q?am=C3=A8tre=20d'un=20endpoint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'attribut CannotBeEmpty vérifie que la liste n'est pas nulle et que la liste contient au moins 1 élément. L'api renvoie une erreur 400 (BadRequest) dans le cas contraire. --- .../Attributes/CannotBeEmptyAttribute.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 EPAServeur/Attributes/CannotBeEmptyAttribute.cs 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(); + } + } +} From f056c41133df9a88732c420b067aca851bd74990 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 11 Feb 2021 16:11:06 +0100 Subject: [PATCH 28/28] Ajout des droits RH dans l'API formation --- EPAServeur/Controllers/FormationsApi.cs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/EPAServeur/Controllers/FormationsApi.cs b/EPAServeur/Controllers/FormationsApi.cs index b641701..5ec93ff 100644 --- a/EPAServeur/Controllers/FormationsApi.cs +++ b/EPAServeur/Controllers/FormationsApi.cs @@ -27,6 +27,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authentication.JwtBearer; namespace IO.Swagger.Controllers { @@ -59,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")] @@ -132,7 +133,7 @@ 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é")] @@ -216,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")] @@ -286,7 +287,7 @@ 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")] @@ -342,7 +343,7 @@ 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")] @@ -390,7 +391,7 @@ 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")] @@ -437,7 +438,7 @@ 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")] @@ -484,7 +485,7 @@ 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")] @@ -531,7 +532,7 @@ 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")] @@ -582,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é")]