From 991401d4870512afc63fed67bf7fdd54cc89a0e1 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 11 Sep 2020 09:17:45 +0200 Subject: [PATCH 01/16] =?UTF-8?q?Cr=C3=A9ation=20du=20service=20Referent?= =?UTF-8?q?=20+=20impl=C3=A9mentation=20des=20m=C3=A9thodes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/ReferentsApi.cs | 150 ++++++++++++-------- IServices/IReferentService.cs | 20 +++ Services/ReferentService.cs | 253 ++++++++++++++++++++++++++++++++++ Startup.cs | 1 + 4 files changed, 365 insertions(+), 59 deletions(-) create mode 100644 IServices/IReferentService.cs create mode 100644 Services/ReferentService.cs diff --git a/Controllers/ReferentsApi.cs b/Controllers/ReferentsApi.cs index f4adbb0..af8dc61 100644 --- a/Controllers/ReferentsApi.cs +++ b/Controllers/ReferentsApi.cs @@ -11,53 +11,90 @@ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -using Swashbuckle.AspNetCore.SwaggerGen; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using IO.Swagger.Attributes; -using IO.Swagger.Security; -using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; +using EPAServeur.IServices; +using System.Net; +using Microsoft.AspNetCore.Authorization; +using IO.Swagger.Security; +using System.Linq; namespace IO.Swagger.Controllers -{ +{ /// /// /// [ApiController] public class ReferentsApiController : ControllerBase - { + { + private readonly IReferentService referentService; + + public ReferentsApiController(IReferentService _referentService) + { + referentService = _referentService; + } + /// /// /// - /// Récupérer la liste des référents d'un collaborateur + /// Récupérer un referent par son id + /// id referent + /// OK + /// Acces interdit + /// Ressource n'a pas été trouvée + [HttpGet] + [Route("/api/referents/{idReferent}")] + ////[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [ValidateModelState] + [SwaggerOperation("GetReferentById")] + [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] + [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] + [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] + public virtual IActionResult GetReferentById([FromRoute][Required]Guid? idReferent) + { + ReferentDTO referentDTO = referentService.GetReferentById(idReferent); + if (referentDTO == null) + { + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Le référent n'existe pas", + }; + return NotFound(erreurDTO); + } + return Ok(referentDTO); + } + + /// + /// + /// + /// Récupérer la liste de tous les referents /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// id collaborateur /// Numéro de la page du tableau qui affiche les données /// Nombre d'éléments affiché sur chaque page du tableau + /// Liste des fonctions des collaborateurs que l'on veut récupérer + /// id de l'agence à laquelle sont rattachées les données à récupérer + /// id de la business unit à 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 /// OK /// Acces interdit - /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents/collaborateur/{idCollaborateur}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferentByCollaborateur")] + [SwaggerOperation("GetReferents")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentByCollaborateur([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idCollaborateur, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) + public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [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)); //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)); string exampleJson = null; exampleJson = "[ {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}, {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n} ]"; @@ -70,73 +107,68 @@ namespace IO.Swagger.Controllers /// /// /// - /// Récupérer un referent par son id - /// id referent + /// Récupérer le référent actuel d'un collaborateur + /// id collaborateur /// OK /// Acces interdit /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents/{idReferent}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents/actuel/collaborateur/{idCollaborateur}")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferentById")] + [SwaggerOperation("GetReferentActuelCollaborateur")] [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentById([FromRoute][Required]Guid? idReferent) - { - //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(ReferentDTO)); - - //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)); - string exampleJson = null; - exampleJson = "{\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(ReferentDTO); //TODO: Change the data returned - return new ObjectResult(example); + public virtual IActionResult GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur) + { + ReferentDTO referentDTO = referentService.GetReferentActuelCollaborateur(idCollaborateur); + if (referentDTO == null) + { + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Aucun référent pour le collaborateur", + }; + return NotFound(erreurDTO); + } + return Ok(referentDTO); } /// /// /// - /// Récupérer la liste de tous les referents + /// Récupérer la liste des référents d'un collaborateur /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) + /// id collaborateur /// Numéro de la page du tableau qui affiche les données /// Nombre d'éléments affiché sur chaque page du tableau - /// Liste des fonctions des collaborateurs que l'on veut récupérer - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// id de la business unit à 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 /// OK /// Acces interdit + /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents/collaborateur/{idCollaborateur}")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferents")] + [SwaggerOperation("GetReferentByCollaborateur")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [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)); - - //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)); - string exampleJson = null; - exampleJson = "[ {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}, {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] + public virtual IActionResult GetReferentsByCollaborateur([FromQuery][Required()] bool? asc, [FromRoute][Required] Guid? idCollaborateur, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] string texte, [FromQuery] string tri) + { + IEnumerable referentDTO = referentService.GetReferentsByCollaborateur(asc,idCollaborateur,numPage,parPAge,texte,tri); + if (referentDTO.Count() == 0) + { + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Aucun référent pour le collaborateur", + }; + return NotFound(erreurDTO); + } + return Ok(referentDTO); } } } diff --git a/IServices/IReferentService.cs b/IServices/IReferentService.cs new file mode 100644 index 0000000..fe24257 --- /dev/null +++ b/IServices/IReferentService.cs @@ -0,0 +1,20 @@ +using EPAServeur.Context; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.IServices +{ + public interface IReferentService + { + ReferentDTO GetReferentById(Guid? id); + ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur); + IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); + + IEnumerable GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri); + + } +} diff --git a/Services/ReferentService.cs b/Services/ReferentService.cs new file mode 100644 index 0000000..68b9892 --- /dev/null +++ b/Services/ReferentService.cs @@ -0,0 +1,253 @@ +using EPAServeur.IServices; +using IO.Swagger.ApiCollaborateur; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace EPAServeur.Services +{ + public class ReferentService : IReferentService + { + #region Variables + private readonly IReferentApi referentApi; + + #endregion + + #region Contructeurs + public ReferentService(IReferentApi _referentApi) + { + referentApi = _referentApi; + } + + #endregion + + #region Méthodes Service + + /// + /// Récupère un référent par son id + /// + /// + /// + public ReferentDTO GetReferentById(Guid? id) + { + Referent referent = referentApi.ChercherRefId(id); + if (referent == null) + return null; + + return GetReferentDTO(referent); + } + + /// + /// Récupère un référent en fonction d'un collaborateur + /// + /// + /// + public ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur) + { + Referent referent = referentApi.ChercherRefActuelCollabId(idCollaborateur); + + if (referent == null) + return null; + + return GetReferentDTO(referent); + } + + /// + /// Récupère la liste des référents pour une agence + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + IEnumerable referents = null ; // A changer + IEnumerable referentDTOs = null; // A changer + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idBU != null) + { + + } + else + { + + } + + if (idAgence != null) + { + try + { + + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + + } + catch (Exception ex) + { + throw; + } + } + + + if (referents == null) + return new List(); + + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + + /// + /// Récupère la liste des référents pour un collaborateur + /// + /// + /// + /// + /// + /// + /// + /// + public IEnumerable GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri) + { + IEnumerable referents; + IEnumerable referentDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idCollaborateur == null) + return new List(); + + + referents = referentApi.ChercherRefCollabId(idCollaborateur); + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + #endregion + + #region Méthodes Privées + + #region Object to DTO + + /// + /// Récupère un objet AgenceDTO en fonction d'un objet Agence + /// + /// + /// + private AgenceDTO GetAgenceDTO(Agence agence) + { + if (agence == null) + return null; + AgenceDTO agenceDTO = new AgenceDTO() + { + Id = agence.Id, + Nom = agence.Nom, + Bu = new List() + }; + agenceDTO.Bu = agence.Bus.Select(bu => new BusinessUnitDTO() + { + Id = bu.Id, + Nom = bu.Nom + }).ToList(); + return agenceDTO; + } + + /// + /// Récupère un objet BusinessUnitDTO en fonction d'un objet BU + /// + /// + /// + private BusinessUnitDTO GetBusinessUnitDTO(BU businessUnit) + { + if (businessUnit == null) + return null; + BusinessUnitDTO businessUnitDTO = new BusinessUnitDTO() + { + Id = businessUnit.Id, + Nom = businessUnit.Nom, + Agence = GetAgenceDTO(businessUnit.Agence) + }; + return businessUnitDTO; + } + + /// + /// Récupère un objet CollaborateurDTO en fonction d'un objet Collaborateur + /// + /// + /// + private CollaborateurDTO GetCollaborateurDTO(Collaborateur collaborateur) + { + CollaborateurDTO collaborateurDTO = new CollaborateurDTO() + { + Id = collaborateur.Id, + Prenom = collaborateur.Prenom, + Nom = collaborateur.Nom, + MailApside = collaborateur.MailApside, + DateArrivee = collaborateur.DateArrivee, + + }; + collaborateurDTO.BusinessUnit = GetBusinessUnitDTO(collaborateur.BusinessUnit); + collaborateurDTO.Referent = GetReferentDTO(collaborateur.Referent); + return collaborateurDTO; + } + + /// + /// Récupère un objet ReferentDTO en fonction d'un objet Referent + /// + /// + /// + private ReferentDTO GetReferentDTO(Referent referent) + { + if (referent == null) + return null; + ReferentDTO referentDTO = new ReferentDTO() + { + Id = referent.Id, + Prenom = referent.Prenom, + Nom = referent.Nom, + MailApside = referent.MailApside + }; + return referentDTO; + } + #endregion + + #region DTO to Object + + #endregion + + #endregion + + + + + } +} diff --git a/Startup.cs b/Startup.cs index 7290f43..28e0eea 100644 --- a/Startup.cs +++ b/Startup.cs @@ -58,6 +58,7 @@ namespace EPAServeur services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); } From b0f6787f295bd2ad71c354bb87ccd48380d15d4e Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 11 Sep 2020 10:07:20 +0200 Subject: [PATCH 02/16] Modification des controles des listes nulles dans l'api formation --- Controllers/FormationsApi.cs | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index 561eb2e..07303c1 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -11,16 +11,12 @@ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -using Swashbuckle.AspNetCore.SwaggerGen; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using IO.Swagger.Attributes; -using IO.Swagger.Security; -using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; using EPAServeur.IServices; -using System.Reflection.Metadata.Ecma335; -using System.Runtime.InteropServices.WindowsRuntime; +using System.Linq; namespace IO.Swagger.Controllers { @@ -55,14 +51,6 @@ namespace IO.Swagger.Controllers FormationDTO nouvelleFormation = formationService.AddFormation(body); return Created("", nouvelleFormation); - //if (body.Id != null && body.Id > 0) - //{ - // return StatusCode(201, body); - //} - //else - //{ - // return NotFound(); - //} } /// @@ -89,6 +77,7 @@ namespace IO.Swagger.Controllers }; return NotFound(erreur); } + return NoContent(); } @@ -117,7 +106,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri); - if (formations == null) + if (formations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -186,7 +175,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormationRealisee(asc, numPage, parPAge, idAgence, texte, tri); - if (formations == null) + if (formations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -224,7 +213,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormations(asc, numPage, parPAge, idAgence, texte, tri); - if (formations == null) + if (formations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -254,7 +243,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable modeFormations = formationService.GetModesFormation(); - if (modeFormations == null) + if (modeFormations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -284,7 +273,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable origineFormations = formationService.GetOriginesFormation(); - if (origineFormations == null) + if (origineFormations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -322,7 +311,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri); - if (formations == null) + if (formations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -352,7 +341,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable statutFormations = formationService.GetStatutsFormation(); - if (statutFormations == null) + if (statutFormations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { @@ -382,7 +371,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable typeFormations = formationService.GetTypesFormation(); - if (typeFormations == null) + if (typeFormations.Count() == 0) { ErreurDTO erreur = new ErreurDTO() { From 52977a45204c6abfa25aad103e5332bebf0479f4 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 11 Sep 2020 16:34:02 +0200 Subject: [PATCH 03/16] Modification des noms de variables dans le service formation et l'api formation --- Controllers/FormationsApi.cs | 18 ++++++++--------- IServices/IFormationService.cs | 6 +++--- Services/FormationService.cs | 36 ++++++++++++++++++++++------------ 3 files changed, 36 insertions(+), 24 deletions(-) diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index 9cfa4f1..812c683 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -106,7 +106,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri); - if (formations.Count() == 0) + if (formations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -175,7 +175,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormationRealisee(asc, numPage, parPAge, idAgence, texte, tri); - if (formations.Count() == 0) + if (formations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -213,7 +213,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetFormations(asc, numPage, parPAge, idAgence, texte, tri); - if (formations.Count() == 0) + if (formations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -243,7 +243,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable modeFormations = formationService.GetModesFormation(); - if (modeFormations.Count() == 0) + if (modeFormations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -273,7 +273,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable origineFormations = formationService.GetOriginesFormation(); - if (origineFormations.Count() == 0) + if (origineFormations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -311,7 +311,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable formations = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri); - if (formations.Count() == 0) + if (formations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -341,7 +341,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable statutFormations = formationService.GetStatutsFormation(); - if (statutFormations.Count() == 0) + if (statutFormations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -371,7 +371,7 @@ namespace IO.Swagger.Controllers { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable typeFormations = formationService.GetTypesFormation(); - if (typeFormations.Count() == 0) + if (typeFormations == null) { ErreurDTO erreur = new ErreurDTO() { @@ -401,7 +401,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long? idFormation) { - FormationDTO formation = formationService.UpdateFormation(body); + FormationDTO formation = formationService.UpdateFormation(idFormation, body); if (formation == null) { formation = formationService.AddFormation(body); diff --git a/IServices/IFormationService.cs b/IServices/IFormationService.cs index dbe8278..2e5b0c5 100644 --- a/IServices/IFormationService.cs +++ b/IServices/IFormationService.cs @@ -10,7 +10,7 @@ namespace EPAServeur.IServices { public interface IFormationService { - FormationDTO GetFormationById(long? id); + FormationDTO GetFormationById(long? idFormation); IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); @@ -22,7 +22,7 @@ namespace EPAServeur.IServices IEnumerable GetTypesFormation(); FormationDTO AddFormation(FormationDTO formationDTO); - FormationDTO UpdateFormation(FormationDTO formationDTO); - bool DeleteFormationById(long? id); + FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO); + bool DeleteFormationById(long? idFormation); } } diff --git a/Services/FormationService.cs b/Services/FormationService.cs index 775bf3d..6d1a36a 100644 --- a/Services/FormationService.cs +++ b/Services/FormationService.cs @@ -35,15 +35,15 @@ namespace EPAServeur.Services /// /// Récupérer une formation par son id /// - /// + /// /// - public FormationDTO GetFormationById(long? 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.Id == id); + .FirstOrDefault(formation => formation.Id == idFormation); if (formation == null) return null; @@ -106,7 +106,7 @@ namespace EPAServeur.Services if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -150,7 +150,7 @@ namespace EPAServeur.Services .Include(formation => formation.TypeFormation); if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -214,7 +214,7 @@ namespace EPAServeur.Services if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -268,7 +268,7 @@ namespace EPAServeur.Services } if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -292,6 +292,9 @@ namespace EPAServeur.Services throw; } + if (modeFormations == null) + return null; + modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); return modeFormationDTOs; @@ -315,6 +318,9 @@ namespace EPAServeur.Services throw; } + if (origineFormations == null) + return null; + origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); return origineFormationDTOs; @@ -339,6 +345,9 @@ namespace EPAServeur.Services throw; } + if (statutFormations == null) + return null; + statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); return statutFormationDTOs; @@ -362,6 +371,9 @@ namespace EPAServeur.Services throw; } + if (typeFormations == null) + return null; + typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); return typeFormationDTOs; @@ -404,9 +416,9 @@ namespace EPAServeur.Services /// /// /// - public FormationDTO UpdateFormation(FormationDTO formationDTO) + public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) { - Formation formation = epContext.Formation.FirstOrDefault(formation => formation.Id == formationDTO.Id); + Formation formation = epContext.Formation.Find(idFormation); if (formation == null) { @@ -429,11 +441,11 @@ namespace EPAServeur.Services /// /// Supprimer une formation /// - /// + /// /// - public bool DeleteFormationById(long? id) + public bool DeleteFormationById(long? idFormation) { - Formation formation = epContext.Formation.FirstOrDefault(formation => formation.Id == id); + Formation formation = epContext.Formation.Find(idFormation); if (formation == null) return false; From 7221f86417627d0e8fd662a51e627a4e0974d9f5 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 11 Sep 2020 16:37:20 +0200 Subject: [PATCH 04/16] Modification des noms de variables dans le service referent et l'api referent --- IServices/IReferentService.cs | 2 +- Services/ReferentService.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/IServices/IReferentService.cs b/IServices/IReferentService.cs index fe24257..f54ce36 100644 --- a/IServices/IReferentService.cs +++ b/IServices/IReferentService.cs @@ -10,7 +10,7 @@ namespace EPAServeur.IServices { public interface IReferentService { - ReferentDTO GetReferentById(Guid? id); + ReferentDTO GetReferentById(Guid? idReferent); ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur); IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); diff --git a/Services/ReferentService.cs b/Services/ReferentService.cs index 68b9892..b9563a9 100644 --- a/Services/ReferentService.cs +++ b/Services/ReferentService.cs @@ -28,11 +28,11 @@ namespace EPAServeur.Services /// /// Récupère un référent par son id /// - /// + /// /// - public ReferentDTO GetReferentById(Guid? id) + public ReferentDTO GetReferentById(Guid? idReferent) { - Referent referent = referentApi.ChercherRefId(id); + Referent referent = referentApi.ChercherRefId(idReferent); if (referent == null) return null; From 2144a10458f0d1d29c0bf768e4ee04c707e684cf Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 11 Sep 2020 16:38:54 +0200 Subject: [PATCH 05/16] Modification des commentaires dans le service formation --- Services/FormationService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Services/FormationService.cs b/Services/FormationService.cs index 6d1a36a..aaf7796 100644 --- a/Services/FormationService.cs +++ b/Services/FormationService.cs @@ -414,6 +414,7 @@ namespace EPAServeur.Services /// /// Modifier une formation /// + /// /// /// public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) From cd6439a643782e4d0ec336b1c46d21fa8b37ed7a Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Wed, 16 Sep 2020 15:57:46 +0200 Subject: [PATCH 06/16] Ajout du service engagement et de l'api engagement --- ApiCollaborateur/ReferentApi.cs | 4 +- Context/EpContext.cs | 98 +++++++--- Controllers/EngagementsApi.cs | 99 +++++----- DTO/EpInformationDTO.cs | 4 +- IServices/IEngagementService.cs | 20 ++ Models/EP/Ep.cs | 4 +- Services/EngagementService.cs | 323 ++++++++++++++++++++++++++++++++ Startup.cs | 2 +- 8 files changed, 472 insertions(+), 82 deletions(-) create mode 100644 IServices/IEngagementService.cs create mode 100644 Services/EngagementService.cs diff --git a/ApiCollaborateur/ReferentApi.cs b/ApiCollaborateur/ReferentApi.cs index d36c4f1..795807f 100644 --- a/ApiCollaborateur/ReferentApi.cs +++ b/ApiCollaborateur/ReferentApi.cs @@ -986,7 +986,7 @@ namespace IO.Swagger.ApiCollaborateur if (refId == null) throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); - var localVarPath = "/referent/{refId}"; + var localVarPath = "/referents/{refId}"; var localVarPathParams = new Dictionary(); var localVarQueryParams = new List>(); var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); @@ -1052,7 +1052,7 @@ namespace IO.Swagger.ApiCollaborateur if (refId == null) throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); - var localVarPath = "/referent/{refId}"; + var localVarPath = "/referents/{refId}"; var localVarPathParams = new Dictionary(); var localVarQueryParams = new List>(); var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); diff --git a/Context/EpContext.cs b/Context/EpContext.cs index 9221c12..3ca5964 100644 --- a/Context/EpContext.cs +++ b/Context/EpContext.cs @@ -506,14 +506,14 @@ namespace EPAServeur.Context //COM --> Commercial //DEL --> Delivery // 10 EP - /* + Ep ep; - DemandeFormation df; - ParticipationFormation pf; + //DemandeFormation df; + //ParticipationFormation pf; ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "COM1", + IdCollaborateur = Guid.Parse("1ec99fde-f756-11ea-adc1-0242ac120002"), + IdReferent = Guid.Parse("1ec9a204-f756-11ea-adc1-0242ac120002"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -526,20 +526,20 @@ namespace EPAServeur.Context CV = "CV.pdf", DateSaisie = new DateTime(2018, 6, 20) }; - df = new DemandeFormation - { - Description = "Description formation", - DemandeRH = false, - DateDemande = new DateTime(2018, 7, 8), - }; + //df = new DemandeFormation + //{ + // Description = "Description formation", + // DemandeRH = false, + // DateDemande = new DateTime(2018, 7, 8), + //}; Ep.Add(ep); ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("779bf1cf-4d38-48fb-8550-3d583384523b"), + IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -556,8 +556,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("006226f6-51b2-4a02-a302-7447f7fccc04"), + IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -574,8 +574,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("f960f851-16b6-4631-952e-d05f38d8d80f"), + IdReferent = Guid.Parse("6aa62dcb-f7c9-4c0c-af40-e934a4d6a7eb"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -592,8 +592,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), + IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -610,8 +610,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), + IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -627,8 +627,8 @@ namespace EPAServeur.Context Ep.Add(ep); ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("9e1ee839-4477-4d64-9b4d-80654c97c39f"), + IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -645,8 +645,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("3f532f4c-a5c9-466c-b7c1-fdc6bc48780e"), + IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -663,8 +663,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("59a8becb-bc0a-4d3d-adb1-8a8bd13c48c9"), + IdReferent = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -681,8 +681,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), + IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -696,9 +696,47 @@ namespace EPAServeur.Context DateSaisie = new DateTime(2018, 6, 20) }; Ep.Add(ep); - */ + Engagement engagement; + engagement = new Engagement + { + Action = "Je m'engage à...", + Disposition = "interne", + Modalite = "Modalite", + DateLimite = new DateTime(2017, 7, 7), + Realise = false, + Realisable = true, + RaisonNonRealisable = null, + Ep = ep + }; + Engagement.Add(engagement); + + engagement = new Engagement + { + Action = "Je m'engage à faire...", + Disposition = "externe", + Modalite = "Modalite 2", + DateLimite = new DateTime(2017, 7, 8), + Realise = true, + Realisable = true, + RaisonNonRealisable = null, + Ep = ep + }; + Engagement.Add(engagement); + + engagement = new Engagement + { + Action = "Je m'engage à faire...", + Disposition = "externe", + Modalite = "Modalite 3", + DateLimite = new DateTime(2017, 7, 8), + Realise = null, + Realisable = null, + RaisonNonRealisable = "Aucune formation disponible", + Ep = ep + }; + Engagement.Add(engagement); //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) //La formation associée sera choisie de manière aléatoire parmi celles créées (pas grave si la cohérence niveau date est foireuse....) diff --git a/Controllers/EngagementsApi.cs b/Controllers/EngagementsApi.cs index d72dadb..3d7e71f 100644 --- a/Controllers/EngagementsApi.cs +++ b/Controllers/EngagementsApi.cs @@ -18,6 +18,7 @@ using IO.Swagger.Attributes; using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; +using EPAServeur.IServices; namespace IO.Swagger.Controllers { @@ -26,7 +27,13 @@ namespace IO.Swagger.Controllers /// [ApiController] public class EngagementsApiController : ControllerBase - { + { + private readonly IEngagementService engagementService; + + public EngagementsApiController(IEngagementService _engagementService) + { + engagementService = _engagementService; + } /// /// /// @@ -41,25 +48,26 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagements")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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)); + IEnumerable engagements = engagementService.GetEngagements(asc, numPage, parPAge, idAgence, texte, tri); + if (engagements == null) + { + ErreurDTO erreur = new ErreurDTO() + { + Code = "404", + Message = "Aucun engagement" + }; + return NotFound(erreur); + } - //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)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + return Ok(engagements); } /// @@ -76,25 +84,26 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements/enattente")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagementsEnAttente")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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)); + IEnumerable engagements = engagementService.GetEngagementsEnAttente(asc, numPage, parPAge, idAgence, texte, tri); + if (engagements == null) + { + ErreurDTO erreur = new ErreurDTO() + { + Code = "404", + Message = "Aucun engagement en attente" + }; + return NotFound(erreur); + } - //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)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + return Ok(engagements); } /// @@ -111,25 +120,26 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements/repondus")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagementsRepondus")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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)); + IEnumerable engagements = engagementService.GetEngagementsRepondus(asc, numPage, parPAge, idAgence, texte, tri); + if (engagements == null) + { + ErreurDTO erreur = new ErreurDTO() + { + Code = "404", + Message = "Aucun engagement en repondu" + }; + return NotFound(erreur); + } - //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)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + return Ok(engagements); } /// @@ -142,19 +152,18 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpPut] [Route("/api/engagements/{idEngagement}/repondre")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("RepondreEngagement")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult RepondreEngagement([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); + { + //if (body != null && body.Realise == false && string.IsNullOrWhiteSpace(body.RaisonNonRealisable)) + // return null; // A traiter ! Retourner une erreur - //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)); - - throw new NotImplementedException(); + EngagementDTO engagement = engagementService.RepondreEngagement(body, idEngagement); + + return Ok(engagement); } } } diff --git a/DTO/EpInformationDTO.cs b/DTO/EpInformationDTO.cs index 9188543..99b2ba4 100644 --- a/DTO/EpInformationDTO.cs +++ b/DTO/EpInformationDTO.cs @@ -38,14 +38,14 @@ namespace IO.Swagger.DTO /// [Required] [DataMember(Name="type")] - public int? Type { get; set; } + public string Type { get; set; } /// /// Gets or Sets Statut /// [Required] [DataMember(Name="statut")] - public int? Statut { get; set; } + public string Statut { get; set; } /// /// Gets or Sets DateDisponibilite diff --git a/IServices/IEngagementService.cs b/IServices/IEngagementService.cs new file mode 100644 index 0000000..789ffd8 --- /dev/null +++ b/IServices/IEngagementService.cs @@ -0,0 +1,20 @@ +using EPAServeur.Context; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.IServices +{ + public interface IEngagementService + { + + IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement); + + } +} diff --git a/Models/EP/Ep.cs b/Models/EP/Ep.cs index feb31a1..7423451 100644 --- a/Models/EP/Ep.cs +++ b/Models/EP/Ep.cs @@ -24,8 +24,8 @@ namespace EPAServeur.Models.EP public class Ep { public long Id { get; set; } - public string IdCollaborateur { get; set; } - public string IdReferent { get; set; } + public Guid IdCollaborateur { get; set; } + public Guid IdReferent { get; set; } public long IdAgence { get; set; } public long IdBu { get; set; } public string Fonction { get; set; } diff --git a/Services/EngagementService.cs b/Services/EngagementService.cs new file mode 100644 index 0000000..359ffeb --- /dev/null +++ b/Services/EngagementService.cs @@ -0,0 +1,323 @@ +using EPAServeur.Context; +using EPAServeur.IServices; +using EPAServeur.Models.EP; +using EPAServeur.Models.Formation; +using EPAServeur.Models.SaisieChamp; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace EPAServeur.Services +{ + public class EngagementService : IEngagementService + { + #region Variables + + private readonly EpContext epContext; + private readonly ICollaborateurService collaborateurService; + #endregion + + #region Contructeurs + + /// + /// Constructeur de la classe EngagementService + /// + /// + public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService) + { + epContext = _epContext; + collaborateurService = _collaborateurService; + } + + #endregion + + #region Méthodes Service + + public IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + IEnumerable engagementDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence); + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep); + } + catch (Exception ex) + { + throw; + } + } + + + if (engagements == null) + return null; + + engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + return engagementDTOs; + } + + public IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + IEnumerable engagementDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null); + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null); + } + catch (Exception ex) + { + throw; + } + } + + + if (engagements == null) + return null; + + engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + return engagementDTOs; + } + + public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + IEnumerable engagementDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise != null); + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null); + } + catch (Exception ex) + { + throw; + } + } + + + if (engagements == null) + return null; + + engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + return engagementDTOs; + } + + /// + /// Donner une réponse à un engagement + /// + /// + /// + /// + public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) + { + + if (!IsEngagementValide(engagementDTO)) + return null; + + if (engagementDTO.Id != idEngagement) + return null; + + if (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) + return null; // Créer une exception pour ce cas + + Engagement engagement = epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefault(engagement => engagement.Id == idEngagement); + + if (engagement == null) + return null; + + engagement.Realise = engagementDTO.Realise; + + if (engagement.Realise == false) + { + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + } + + epContext.SaveChanges(); + + return GetEngagementDTO(engagement); + } + + + #endregion + + #region Méthodes Privée + private bool IsEngagementValide(EngagementDTO engagementDTO) + { + return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null); + } + + #region Object to DTO + /// + /// Récupère un objet EngagementDTO en fonction d'un objet Engagement + /// + /// + /// + private EngagementDTO GetEngagementDTO(Engagement engagement) + { + EngagementDTO engagementDTO = new EngagementDTO() + { + Id = engagement.Id, + Action = engagement.Action, + DatePrevisionnelle = engagement.DateLimite, + Dispositif = engagement.Disposition, + Modalite = engagement.Modalite, + RaisonNonRealisable = engagement.RaisonNonRealisable, + Realisable = engagement.Realisable, + Realise = engagement.Realise, + Ep = GetEpInformationDTO(engagement.Ep) + }; + + return engagementDTO; + } + + /// + /// Récupère un objet EpInformationDTO en fonction d'un objet Ep + /// + /// + /// + private EpInformationDTO GetEpInformationDTO(Ep ep) + { + EpInformationDTO epInformationDTO = new EpInformationDTO() + { + Id = ep.Id, + Type = ep.TypeEP.ToString(), + Statut = ep.Statut.ToString(), + DatePrevisionnelle = ep.DatePrevisionnelle, + Obligatoire = ep.Obligatoire, + Collaborateur = collaborateurService.GetProfilById(ep.IdCollaborateur) + //Referent = null //collaborateurService.GetProfilById(ep.IdReferent) + //Ajouter la date de disponibilité + }; + + return epInformationDTO; + } + #endregion + + #region DTO to Object + + /// + /// Modifie un objet Engagement en fonction d'un objet FormationDTO + /// + /// + /// + /// + private Engagement SetEngagement(Engagement engagement, EngagementDTO engagementDTO) + { + engagement.Action = engagementDTO.Action; + engagement.DateLimite = engagementDTO.DatePrevisionnelle.Value; + engagement.Disposition = engagementDTO.Dispositif; + engagement.Modalite = engagementDTO.Modalite; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + engagement.Realisable = engagementDTO.Realisable; + engagement.Realise = engagementDTO.Realise; + 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; + + // Traiter + Enum.TryParse(epInformationDTO.Type, out TypeChamp typeChamp); + + Enum.TryParse(epInformationDTO.Statut, out StatutEP statutEP); + + Ep ep = new Ep() + { + Id = epInformationDTO.Id.Value, + TypeEP = typeChamp, + Statut = statutEP, + 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; + } + + + #endregion + + #endregion + + } +} diff --git a/Startup.cs b/Startup.cs index 28e0eea..efee6ce 100644 --- a/Startup.cs +++ b/Startup.cs @@ -59,7 +59,7 @@ namespace EPAServeur services.AddScoped(); services.AddScoped(); services.AddScoped(); - + services.AddScoped(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. From 6b3e8ec32a45670d37cb5e28b138714596316c09 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 17 Sep 2020 09:52:34 +0200 Subject: [PATCH 07/16] Ajout d'un test async dans le service engagement et de l'api engagement --- Controllers/EngagementsApi.cs | 9 ++-- IServices/IEngagementService.cs | 8 ++-- Services/EngagementService.cs | 80 +++++++++++++++++++++++++++------ 3 files changed, 76 insertions(+), 21 deletions(-) diff --git a/Controllers/EngagementsApi.cs b/Controllers/EngagementsApi.cs index 3d7e71f..46ce2ed 100644 --- a/Controllers/EngagementsApi.cs +++ b/Controllers/EngagementsApi.cs @@ -19,6 +19,7 @@ using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; using EPAServeur.IServices; +using System.Threading.Tasks; namespace IO.Swagger.Controllers { @@ -125,10 +126,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetEngagementsRepondus")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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(..), ... - IEnumerable engagements = engagementService.GetEngagementsRepondus(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable engagements = await engagementService.GetEngagementsRepondus(asc, numPage, parPAge, idAgence, texte, tri); if (engagements == null) { ErreurDTO erreur = new ErreurDTO() @@ -156,12 +157,12 @@ namespace IO.Swagger.Controllers [ValidateModelState] [SwaggerOperation("RepondreEngagement")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) + public virtual async Task RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) { //if (body != null && body.Realise == false && string.IsNullOrWhiteSpace(body.RaisonNonRealisable)) // return null; // A traiter ! Retourner une erreur - EngagementDTO engagement = engagementService.RepondreEngagement(body, idEngagement); + EngagementDTO engagement = await engagementService.RepondreEngagement(body, idEngagement); return Ok(engagement); } diff --git a/IServices/IEngagementService.cs b/IServices/IEngagementService.cs index 789ffd8..b47080c 100644 --- a/IServices/IEngagementService.cs +++ b/IServices/IEngagementService.cs @@ -11,10 +11,10 @@ namespace EPAServeur.IServices public interface IEngagementService { - IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement); + IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task RepondreEngagement(EngagementDTO engagement, long? idEngagement); } } diff --git a/Services/EngagementService.cs b/Services/EngagementService.cs index 359ffeb..dfb645b 100644 --- a/Services/EngagementService.cs +++ b/Services/EngagementService.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; namespace EPAServeur.Services { @@ -98,7 +99,7 @@ namespace EPAServeur.Services { try { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null); + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToList(); } catch (Exception ex) { @@ -109,7 +110,7 @@ namespace EPAServeur.Services { try { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null); + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToList(); } catch (Exception ex) { @@ -125,10 +126,10 @@ namespace EPAServeur.Services return engagementDTOs; } - public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + public async Task> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) { IEnumerable engagements; - IEnumerable engagementDTOs; + // engagementDTOs = new List(); if (texte == null) texte = ""; @@ -142,7 +143,7 @@ namespace EPAServeur.Services { try { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise != null); + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Modalite.ToLower().Contains(texte)); } catch (Exception ex) { @@ -153,7 +154,7 @@ namespace EPAServeur.Services { try { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null); + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)); } catch (Exception ex) { @@ -165,8 +166,14 @@ namespace EPAServeur.Services if (engagements == null) return null; - engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); - return engagementDTOs; + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); + //foreach (var engagement in engagements) + //{ + // engagementDTOs.Add(await GetEngagementDTOAsync(engagement)); + //} + + return results; } /// @@ -175,7 +182,7 @@ namespace EPAServeur.Services /// /// /// - public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) + public async Task RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) { if (!IsEngagementValide(engagementDTO)) @@ -202,7 +209,7 @@ namespace EPAServeur.Services epContext.SaveChanges(); - return GetEngagementDTO(engagement); + return await GetEngagementDTOAsync(engagement); } @@ -215,6 +222,7 @@ namespace EPAServeur.Services } #region Object to DTO + /// /// Récupère un objet EngagementDTO en fonction d'un objet Engagement /// @@ -238,12 +246,35 @@ namespace EPAServeur.Services return engagementDTO; } + /// + /// Récupère un objet EngagementDTO en fonction d'un objet Engagement + /// + /// + /// + private async Task GetEngagementDTOAsync(Engagement engagement) + { + EngagementDTO engagementDTO = new EngagementDTO() + { + Id = engagement.Id, + Action = engagement.Action, + DatePrevisionnelle = engagement.DateLimite, + Dispositif = engagement.Disposition, + Modalite = engagement.Modalite, + RaisonNonRealisable = engagement.RaisonNonRealisable, + Realisable = engagement.Realisable, + Realise = engagement.Realise, + Ep = await GetEpInformationDTOAsync(engagement.Ep) + }; + + return engagementDTO; + } + /// /// Récupère un objet EpInformationDTO en fonction d'un objet Ep /// /// /// - private EpInformationDTO GetEpInformationDTO(Ep ep) + private EpInformationDTO GetEpInformationDTO(Ep ep) { EpInformationDTO epInformationDTO = new EpInformationDTO() { @@ -252,13 +283,36 @@ namespace EPAServeur.Services Statut = ep.Statut.ToString(), DatePrevisionnelle = ep.DatePrevisionnelle, Obligatoire = ep.Obligatoire, - Collaborateur = collaborateurService.GetProfilById(ep.IdCollaborateur) - //Referent = null //collaborateurService.GetProfilById(ep.IdReferent) + Collaborateur = collaborateurService.GetCollaborateurById(ep.IdCollaborateur), + Referent = collaborateurService.GetCollaborateurById(ep.IdReferent) //Ajouter la date de disponibilité }; return epInformationDTO; } + + /// + /// Récupère un objet EpInformationDTO en fonction d'un objet Ep + /// + /// + /// + private async Task GetEpInformationDTOAsync(Ep ep) + { + EpInformationDTO epInformationDTO = new EpInformationDTO() + { + Id = ep.Id, + Type = ep.TypeEP.ToString(), + Statut = ep.Statut.ToString(), + DatePrevisionnelle = ep.DatePrevisionnelle, + Obligatoire = ep.Obligatoire, + Collaborateur = await collaborateurService.GetCollaborateurByIdAsync(ep.IdCollaborateur), + Referent = await collaborateurService.GetCollaborateurByIdAsync(ep.IdReferent) + //Ajouter la date de disponibilité + }; + + return epInformationDTO; + } + #endregion #region DTO to Object From 7ecb14ec5960ee10295d268013eefe419982a733 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Thu, 17 Sep 2020 10:57:52 +0200 Subject: [PATCH 08/16] =?UTF-8?q?Ajout=20des=20m=C3=A9thodes=20asynchrones?= =?UTF-8?q?=20dans=20le=20service=20collaborateurs,=20modification=20de=20?= =?UTF-8?q?l'api=20collaborateur=20en=20asynchrone,=20modification=20de=20?= =?UTF-8?q?epinformationDTO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/CollaborateursApi.cs | 21 +++-- DTO/EpInformationDTO.cs | 2 +- IServices/ICollaborateurService.cs | 7 ++ Services/CollaborateurService.cs | 141 +++++++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 11 deletions(-) diff --git a/Controllers/CollaborateursApi.cs b/Controllers/CollaborateursApi.cs index 53f2158..1e2f473 100644 --- a/Controllers/CollaborateursApi.cs +++ b/Controllers/CollaborateursApi.cs @@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging; using EPAServeur.Exceptions; using IO.Swagger.ClientCollaborateur; using Microsoft.AspNetCore.Server.Kestrel.Core; +using System.Threading.Tasks; namespace IO.Swagger.Controllers { @@ -55,7 +56,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateurById([FromRoute][Required]Guid? idCollaborateur) + public virtual async Task GetCollaborateurById([FromRoute][Required]Guid? idCollaborateur) { //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)); @@ -63,7 +64,7 @@ namespace IO.Swagger.Controllers CollaborateurDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetCollaborateurById(idCollaborateur); + collaborateurDTO = await collaborateurService.GetCollaborateurByIdAsync(idCollaborateur); } catch (ApiException) { @@ -103,7 +104,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateurByMail([FromRoute][Required]string mail) + public virtual async Task GetCollaborateurByMail([FromRoute][Required]string mail) { //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)); @@ -111,7 +112,7 @@ namespace IO.Swagger.Controllers CollaborateurDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetCollaborateurByMail(mail); + collaborateurDTO = await collaborateurService.GetCollaborateurByMailAsync(mail); } catch (CollaborateurNotFoundException) { @@ -156,7 +157,7 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetCollaborateurs")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetCollaborateurs([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetCollaborateurs([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) { //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)); @@ -164,7 +165,7 @@ namespace IO.Swagger.Controllers IEnumerable collaborateurs = null; try { - collaborateurs = collaborateurService.GetCollaborateurs(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri); + collaborateurs = await collaborateurService.GetCollaborateursAsync(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri); } catch(ApiException) { @@ -200,12 +201,12 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateursByReferent([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idReferent, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetCollaborateursByReferent([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idReferent, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) { //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)); logger.LogInformation("Récupération de la liste des collaborateurs du référent {idReferent}",idReferent); - IEnumerable collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); + IEnumerable collaborateurs = await collaborateurService.GetCollaborateursByReferentAsync(idReferent, asc, numPage, parPAge, texte, tri); try { collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); @@ -247,7 +248,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(ProfilDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetProfilCollaborateurByMail([FromRoute][Required]string mail) + public virtual async Task GetProfilCollaborateurByMailAsync([FromRoute][Required]string mail) { //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)); @@ -255,7 +256,7 @@ namespace IO.Swagger.Controllers ProfilDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetProfilByMail(mail); + collaborateurDTO = await collaborateurService.GetProfilByMailAsync(mail); } catch (ApiException) { diff --git a/DTO/EpInformationDTO.cs b/DTO/EpInformationDTO.cs index 9188543..3e287d6 100644 --- a/DTO/EpInformationDTO.cs +++ b/DTO/EpInformationDTO.cs @@ -80,7 +80,7 @@ namespace IO.Swagger.DTO /// [Required] [DataMember(Name="referent")] - public CollaborateurDTO Referent { get; set; } + public ReferentDTO Referent { get; set; } /// /// Returns the string presentation of the object diff --git a/IServices/ICollaborateurService.cs b/IServices/ICollaborateurService.cs index e556ccc..3a43321 100644 --- a/IServices/ICollaborateurService.cs +++ b/IServices/ICollaborateurService.cs @@ -12,10 +12,17 @@ namespace EPAServeur.IServices public interface ICollaborateurService { CollaborateurDTO GetCollaborateurById(Guid? id); + Task GetCollaborateurByIdAsync(Guid? id); CollaborateurDTO GetCollaborateurByMail(string mail); + Task GetCollaborateurByMailAsync(string mail); ProfilDTO GetProfilById(Guid? idCollaborateur); + Task GetProfilByIdAsync(Guid? idCollaborateur); ProfilDTO GetProfilByMail(string mail); + Task GetProfilByMailAsync(string mail); IEnumerable GetCollaborateurs(bool? asc, int? numPage, int? parPage, List fonctions, long? idAgence, long? idBU, string texte, string tri); + Task> GetCollaborateursAsync(bool? asc, int? numPage, int? parPage, List fonctions, long? idAgence, long? idBU, string texte, string tri); IEnumerable GetCollaborateursByReferent(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri); + Task> GetCollaborateursByReferentAsync(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri); + } } diff --git a/Services/CollaborateurService.cs b/Services/CollaborateurService.cs index 55d58b1..37137b6 100644 --- a/Services/CollaborateurService.cs +++ b/Services/CollaborateurService.cs @@ -47,6 +47,19 @@ namespace EPAServeur.Services return GetCollaborateurDTO(collaborateur); } + /// + /// Récupérer un collaborateur en fonction d'un id de manière asynchrone + /// + /// Identifiant du collaborateur à renvoyer + /// Le collaborateur corresponant à l'id en paramètre + public async Task GetCollaborateurByIdAsync(Guid? id) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(id); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetCollaborateurDTO(collaborateur); + } + /// /// Récupérer un collaborateur en fonction d'un mail /// @@ -60,6 +73,19 @@ namespace EPAServeur.Services return GetCollaborateurDTO(collaborateur); } + /// + /// Récupérer un collaborateur en fonction d'un mail de manière asynchrone + /// + /// Mail du collaborateur à renvoyer + /// Le collaborateur correspondant au mail en paramètre + public async Task GetCollaborateurByMailAsync(string mail) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetCollaborateurDTO(collaborateur); + } + /// /// Récupérer la liste de tous les collaborateurs /// @@ -103,6 +129,49 @@ namespace EPAServeur.Services return collaborateursDTO; } + /// + /// Récupérer la liste de tous les collaborateurs de manière asynchrone + /// + /// + /// Précise si la liste est trié dans l'ordre croissant ou décroissant + /// Numéro de la page qui est affiché du côté front + /// Nombre de collaborateurs à renvoyer + /// Liste des fonctions + /// id de l'agence à laquelle appartient les collaborateurs à récupérer + /// + /// permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// + /// idBU est à prendre en compte avant l'idAgence + /// idAgence n'est à prendre en compte que si idBU est nul + /// + /// + /// Renvoie la liste des collaborateurs en fonction des paramètres + public async Task> GetCollaborateursAsync(bool? asc, int? numPage, int? parPage, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + IEnumerable collaborateurs; + IEnumerable collaborateursDTO; + if (idBU != null) + collaborateurs = await collaborateurApi.ChercherCollabBUAsync(idBU); + else if (idAgence != null) + collaborateurs = await collaborateurApi.ChercherCollabAgenceAsync(idAgence); + else + collaborateurs = await collaborateurApi.ChercherCollabAsync(); + if (collaborateurs == null) + return new List(); + int skip = (numPage.Value - 1) * parPage.Value; + int take = parPage.Value; + collaborateursDTO = (from c in collaborateurs + where (c.Nom + " " + c.Prenom).ToLower().Contains(texte) || (c.Prenom + " " + c.Nom).ToLower().Contains(texte) + select GetCollaborateurDTO(c)).Skip(skip).Take(take); + + return collaborateursDTO; + } + /// /// Récupérer les collaborateurs d'un référent /// @@ -141,6 +210,44 @@ namespace EPAServeur.Services return collaborateursDTO; } + /// + /// Récupérer les collaborateurs d'un référent de manière asynchrone + /// + /// id du référent des collaborateurs à récupérer + /// Précise si la liste est trié dans l'ordre croissant ou décroissant + /// Numéro de la page qui est affiché du côté front + /// Nombre de collaborateurs à renvoyer + /// permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// Renvoyer les collaborateurs du référent dont l'id est passé en paramètre + public async Task> GetCollaborateursByReferentAsync(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri) + { + /* + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + stopwatch.Stop(); + Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); + stopwatch.Stop(); + Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + */ + Collaborateur referent = await collaborateurApi.ChercherCollabIdAsync(idReferent); + if (referent == null) + throw new ReferentNotFoundException(); + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + IEnumerable collaborateurs = await collaborateurApi.ChercherCollabRefAsync(idReferent); + int skip = (numPage.Value - 1) * parPage.Value; + int take = parPage.Value; + IEnumerable collaborateursDTO = (from c in collaborateurs + where (c.Nom + " " + c.Prenom).ToLower().Contains(texte) || (c.Prenom + " " + c.Nom).ToLower().Contains(texte) + select GetCollaborateurDTO(c)).Skip(skip).Take(take); + return collaborateursDTO; + } + /// /// Récupérer le profil d'un collaborateur par mail /// @@ -154,6 +261,19 @@ namespace EPAServeur.Services return GetProfilDTO(collaborateur); } + /// + /// Récupérer le profil d'un collaborateur par mail de manière asynchrone + /// + /// mail du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant au mail passé en paramètre + public async Task GetProfilByMailAsync(string mail) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetProfilDTO(collaborateur); + } + /// /// Récupérer un profil d'un collaborateur par l'id /// @@ -174,6 +294,27 @@ namespace EPAServeur.Services throw new CollaborateurNotFoundException(); return GetProfilDTO(collaborateur); } + + /// + /// Récupérer un profil d'un collaborateur par l'id de manière asynchrone + /// + /// id du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant à l'id passé en paramètre + public async Task GetProfilByIdAsync(Guid? idCollaborateur) + { + //Stopwatch stopwatch = new Stopwatch(); + //stopwatch.Start(); + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(idCollaborateur); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution GetProfil: {0}", stopwatch.Elapsed.TotalSeconds); + //stopwatch.Restart(); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetProfilDTO(collaborateur); + } #endregion #region DTO To Object From 2f716d22dd400c70ccb15411dae5ef563aa8fe26 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 18 Sep 2020 10:03:05 +0200 Subject: [PATCH 09/16] =?UTF-8?q?Ajout=20des=20m=C3=A9thodes=20asynchrones?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/ReferentsApi.cs | 29 ++---- IServices/IReferentService.cs | 4 + Services/ReferentService.cs | 183 +++++++++++++++++++++++++++++++--- 3 files changed, 183 insertions(+), 33 deletions(-) diff --git a/Controllers/ReferentsApi.cs b/Controllers/ReferentsApi.cs index af8dc61..764b287 100644 --- a/Controllers/ReferentsApi.cs +++ b/Controllers/ReferentsApi.cs @@ -20,6 +20,7 @@ using System.Net; using Microsoft.AspNetCore.Authorization; using IO.Swagger.Security; using System.Linq; +using System.Threading.Tasks; namespace IO.Swagger.Controllers { @@ -52,9 +53,9 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentById([FromRoute][Required]Guid? idReferent) + public virtual async Task GetReferentById([FromRoute][Required]Guid? idReferent) { - ReferentDTO referentDTO = referentService.GetReferentById(idReferent); + ReferentDTO referentDTO = await referentService.GetReferentByIdAsync(idReferent); if (referentDTO == null) { ErreurDTO erreurDTO = new ErreurDTO() @@ -89,19 +90,9 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [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)); - - //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)); - string exampleJson = null; - exampleJson = "[ {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}, {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + { + //IEnumerable referentDTOs = referentService.GetReferents(asc,numPage,parPAge,fonctions,idAgence,idBU,texte,tri); + return Ok(); } /// @@ -120,9 +111,9 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur) + public virtual async Task GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur) { - ReferentDTO referentDTO = referentService.GetReferentActuelCollaborateur(idCollaborateur); + ReferentDTO referentDTO = await referentService.GetReferentActuelCollaborateurAsync(idCollaborateur); if (referentDTO == null) { ErreurDTO erreurDTO = new ErreurDTO() @@ -156,9 +147,9 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentsByCollaborateur([FromQuery][Required()] bool? asc, [FromRoute][Required] Guid? idCollaborateur, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] string texte, [FromQuery] string tri) + public virtual async Task GetReferentsByCollaborateur([FromQuery][Required()] bool? asc, [FromRoute][Required] Guid? idCollaborateur, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] string texte, [FromQuery] string tri) { - IEnumerable referentDTO = referentService.GetReferentsByCollaborateur(asc,idCollaborateur,numPage,parPAge,texte,tri); + IEnumerable referentDTO = await referentService.GetReferentsByCollaborateurAsync(asc,idCollaborateur,numPage,parPAge,texte,tri); if (referentDTO.Count() == 0) { ErreurDTO erreurDTO = new ErreurDTO() diff --git a/IServices/IReferentService.cs b/IServices/IReferentService.cs index f54ce36..8cb68cb 100644 --- a/IServices/IReferentService.cs +++ b/IServices/IReferentService.cs @@ -11,10 +11,14 @@ namespace EPAServeur.IServices public interface IReferentService { ReferentDTO GetReferentById(Guid? idReferent); + Task GetReferentByIdAsync(Guid? idReferent); ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur); + Task GetReferentActuelCollaborateurAsync(Guid? idCollaborateur); IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); + Task> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); IEnumerable GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri); + Task> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri); } } diff --git a/Services/ReferentService.cs b/Services/ReferentService.cs index b9563a9..765e9da 100644 --- a/Services/ReferentService.cs +++ b/Services/ReferentService.cs @@ -5,6 +5,7 @@ using IO.Swagger.ModelCollaborateur; using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; namespace EPAServeur.Services { @@ -12,13 +13,14 @@ namespace EPAServeur.Services { #region Variables private readonly IReferentApi referentApi; - + private readonly ICollaborateurApi collaborateurApi; #endregion #region Contructeurs - public ReferentService(IReferentApi _referentApi) + public ReferentService(IReferentApi _referentApi, ICollaborateurApi _collaborateurApi) { referentApi = _referentApi; + collaborateurApi = _collaborateurApi; } #endregion @@ -39,6 +41,20 @@ namespace EPAServeur.Services return GetReferentDTO(referent); } + /// + /// Récupère un référent par son id de manière asynchrone + /// + /// + /// + public async Task GetReferentByIdAsync(Guid? idReferent) + { + Referent referent = await referentApi.ChercherRefIdAsync(idReferent); + if (referent == null) + return null; + + return GetReferentDTO(referent); + } + /// /// Récupère un référent en fonction d'un collaborateur /// @@ -54,19 +70,104 @@ namespace EPAServeur.Services return GetReferentDTO(referent); } - /// - /// Récupère la liste des référents pour une agence - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// + /// Récupère un référent en fonction d'un collaborateur de manière asynchrone + /// + /// + /// + public async Task GetReferentActuelCollaborateurAsync(Guid? idCollaborateur) + { + Referent referent = await referentApi.ChercherRefActuelCollabIdAsync(idCollaborateur); + + if (referent == null) + return null; + + return GetReferentDTO(referent); + } + /// + /// Récupère la liste des référents pour une agence + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + //IEnumerable collaborateurs; // A changer (Sera utilisé pour récupérer la liste des référents par fonction + IEnumerable referents = null; // A changer + IEnumerable referentDTOs = null; // A changer + //List ids = fonctions.Select(guid => (Guid?)Guid.Parse(guid)).ToList(); + + //collaborateurs = collaborateurApi.ChercherCollab(ids); + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idBU != null) + { + + } + else + { + + } + + if (idAgence != null) + { + try + { + + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + + } + catch (Exception ex) + { + throw; + } + } + + + if (referents == null) + return new List(); + + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + + /// + /// Récupère la liste des référents pour une agence de manière asynchrone + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + + public async Task> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) { IEnumerable referents = null ; // A changer IEnumerable referentDTOs = null; // A changer @@ -120,6 +221,7 @@ namespace EPAServeur.Services return referentDTOs; } + /// /// Récupère la liste des référents pour un collaborateur /// @@ -152,6 +254,40 @@ namespace EPAServeur.Services return referentDTOs; } + + /// + /// Récupère la liste des référents pour un collaborateur de manère asynchrone + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri) + { + IEnumerable referents; + IEnumerable referentDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idCollaborateur == null) + return new List(); + + + referents = await referentApi.ChercherRefCollabIdAsync(idCollaborateur); + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + #endregion #region Méthodes Privées @@ -238,6 +374,25 @@ namespace EPAServeur.Services }; return referentDTO; } + + /// + /// Récupère un objet ReferentDTO en fonction d'un objet Collaborateur + /// + /// + /// + private ReferentDTO GetReferentDTO(Collaborateur collaborateur) + { + if (collaborateur == null) + return null; + ReferentDTO referentDTO = new ReferentDTO() + { + Id = collaborateur.Id, + Prenom = collaborateur.Prenom, + Nom = collaborateur.Nom, + MailApside = collaborateur.MailApside + }; + return referentDTO; + } #endregion #region DTO to Object From 13c4fb74fd125c45f0474ae783dfca7f009129d3 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Fri, 18 Sep 2020 12:00:28 +0200 Subject: [PATCH 10/16] =?UTF-8?q?Ajout=20des=20m=C3=A9thodes=20asynchrones?= =?UTF-8?q?=20et=20modification=20du=20DTO=20FormationDetailsDTO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/FormationsApi.cs | 63 ++--- DTO/FormationDetailsDTO.cs | 7 + IServices/IFormationService.cs | 14 +- Services/FormationService.cs | 443 +++++++++++++++++++++++++++++++++ 4 files changed, 488 insertions(+), 39 deletions(-) diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index 812c683..8170e30 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -17,6 +17,7 @@ using IO.Swagger.Attributes; using IO.Swagger.DTO; using EPAServeur.IServices; using System.Linq; +using System.Threading.Tasks; namespace IO.Swagger.Controllers { @@ -46,9 +47,9 @@ namespace IO.Swagger.Controllers [ValidateModelState] [SwaggerOperation("AjouterFormation")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult AjouterFormation([FromBody] FormationDTO body) + public virtual async Task AjouterFormation([FromBody] FormationDTO body) { - FormationDTO nouvelleFormation = formationService.AddFormation(body); + FormationDTO nouvelleFormation = await formationService.AddFormationAsync(body); return Created("", nouvelleFormation); } @@ -66,9 +67,9 @@ namespace IO.Swagger.Controllers [ValidateModelState] [SwaggerOperation("DeleteFormation")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult DeleteFormation([FromRoute][Required] long? idFormation) + public virtual async Task DeleteFormation([FromRoute][Required] long? idFormation) { - if (!formationService.DeleteFormationById(idFormation)) + if ( ! await formationService.DeleteFormationByIdAsync(idFormation)) { ErreurDTO erreur = new ErreurDTO() { @@ -102,10 +103,10 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetFormationAnnulees([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [FromQuery] string texte, [FromQuery] string tri) + public virtual async Task GetFormationAnnulees([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formations = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -135,9 +136,9 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetFormationById([FromRoute][Required] long? idFormation) + public virtual async Task GetFormationById([FromRoute][Required] long? idFormation) { - FormationDTO formationDTO = formationService.GetFormationById(Convert.ToInt32(idFormation)); + FormationDTO formationDTO = await formationService.GetFormationByIdAsync(idFormation); if (formationDTO == null) { ErreurDTO erreurDTO = new ErreurDTO() @@ -171,10 +172,10 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetFormationRealisee([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [FromQuery] string texte, [FromQuery] string tri) + public virtual async Task GetFormationRealisee([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = formationService.GetFormationRealisee(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formations = await formationService.GetFormationRealiseeAsync(asc, numPage, parPAge, idAgence, texte, tri); if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -209,10 +210,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetFormations")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetFormations([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]int? idAgence, [FromQuery]int? statutFormation, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetFormations([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]int? idAgence, [FromQuery]int? statutFormation, [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(..), ... - IEnumerable formations = formationService.GetFormations(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formations = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, texte, tri); if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -239,10 +240,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetModesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetModesFormation() + public virtual async Task GetModesFormation() { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable modeFormations = formationService.GetModesFormation(); + IEnumerable modeFormations = await formationService.GetModesFormationAsync(); if (modeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -269,10 +270,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetOriginesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetOriginesFormation() + public virtual async Task GetOriginesFormation() { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable origineFormations = formationService.GetOriginesFormation(); + IEnumerable origineFormations = await formationService.GetOriginesFormationAsync(); if (origineFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -307,10 +308,10 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetProchainesFormation([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [FromQuery] string texte, [FromQuery] string tri) + public virtual async Task GetProchainesFormation([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri); + IEnumerable formations = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -337,10 +338,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetStatutsFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetStatutsFormation() + public virtual async Task GetStatutsFormation() { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable statutFormations = formationService.GetStatutsFormation(); + IEnumerable statutFormations = await formationService.GetStatutsFormationAsync(); if (statutFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -367,10 +368,10 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetTypesFormation")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetTypesFormation() + public virtual async Task GetTypesFormation() { //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable typeFormations = formationService.GetTypesFormation(); + IEnumerable typeFormations = await formationService.GetTypesFormationAsync(); if (typeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -399,29 +400,15 @@ namespace IO.Swagger.Controllers [ValidateModelState] [SwaggerOperation("UpdateFormation")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long? idFormation) + public virtual async Task UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long? idFormation) { - FormationDTO formation = formationService.UpdateFormation(idFormation, body); + FormationDTO formation = await formationService.UpdateFormationAsync(idFormation, body); if (formation == null) { formation = formationService.AddFormation(body); return Created("", formation); } return Ok(formation); - - - //switch (formationService.UpdateFormation(body)) - //{ - // case 0: - // return Ok(); - // case 1: - // return StatusCode(201); - // case 2: - // return Forbid(); - // default: - // return NotFound(); - //} - } } } diff --git a/DTO/FormationDetailsDTO.cs b/DTO/FormationDetailsDTO.cs index d125cb6..50e979f 100644 --- a/DTO/FormationDetailsDTO.cs +++ b/DTO/FormationDetailsDTO.cs @@ -66,6 +66,13 @@ namespace IO.Swagger.DTO [DataMember(Name="nbPartitipants")] public int? NbPartitipants { get; set; } + /// + /// Gets or Sets Origine + /// + [Required] + [DataMember(Name = "origine")] + public OrigineFormationDTO Origine { get; set; } + /// /// Gets or Sets Mode /// diff --git a/IServices/IFormationService.cs b/IServices/IFormationService.cs index 2e5b0c5..4a08b04 100644 --- a/IServices/IFormationService.cs +++ b/IServices/IFormationService.cs @@ -11,18 +11,30 @@ namespace EPAServeur.IServices public interface IFormationService { FormationDTO GetFormationById(long? idFormation); - + Task GetFormationByIdAsync(long? idFormation); IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + Task> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetFormationRealisee(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + Task> GetFormationRealiseeAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetProchainesFormation(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + Task> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetModesFormation(); + 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); bool DeleteFormationById(long? idFormation); + Task DeleteFormationByIdAsync(long? idFormation); + } } diff --git a/Services/FormationService.cs b/Services/FormationService.cs index aaf7796..150f207 100644 --- a/Services/FormationService.cs +++ b/Services/FormationService.cs @@ -6,6 +6,7 @@ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; namespace EPAServeur.Services { @@ -51,6 +52,25 @@ namespace EPAServeur.Services return GetFormationDTO(formation); } + /// + /// Récupérer une formation par son id de manière asynchrone + /// + /// + /// + public async Task GetFormationByIdAsync(long? idFormation) + { + Formation formation = await epContext.Formation.Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation) + .FirstOrDefaultAsync(formation => formation.Id == idFormation); + + if (formation == null) + return null; + + return GetFormationDTO(formation); + } + /// /// Récupérer la liste des formations /// @@ -113,6 +133,68 @@ namespace EPAServeur.Services 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, int? 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) + { + try + { + 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).ToListAsync(); + } + catch (Exception ex) + { + throw; + } + } + else + { + try + { + formations = await epContext.Formation.Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } + catch (Exception ex) + { + throw; + } + } + + + if (formations == null) + return null; + + formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + + return formationDTOs; + } + /// /// Récupérer les formations annulées /// @@ -157,6 +239,50 @@ namespace EPAServeur.Services 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, int? 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.Id == 4) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + else + formations = await epContext.Formation.Where(formation => formation.Statut.Id == 4) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + + if (formations == null) + return null; + + formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + + return formationDTOs; + } + /// /// Récupérer les formations réalisées /// @@ -221,6 +347,70 @@ namespace EPAServeur.Services 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> GetFormationRealiseeAsync(bool? asc, int? numPage, int? parPAge, int? 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) + { + try + { + formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } + catch (Exception ex) + { + throw; + } + } + + else + { + try + { + formations = await epContext.Formation.Where(formation => formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } + catch (Exception ex) + { + throw; + } + } + + + if (formations == null) + return null; + + 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 /// @@ -275,6 +465,60 @@ namespace EPAServeur.Services return formationDTOs; } + /// + /// Récupérer les formations plannifiées et replannifiées de manè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> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, int? 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) + try + { + formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } + catch (Exception ex) + { + throw; + } + + else + { + formations = await epContext.Formation.Where(formation => (formation.Statut.Id == 1 || formation.Statut.Id == 2)) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } + + if (formations == null) + return null; + + formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); + + return formationDTOs; + } + /// /// Récupérer les modes de formation /// @@ -300,6 +544,31 @@ namespace EPAServeur.Services return modeFormationDTOs; } + /// + /// Récupérer les modes de formation de manière asynchrone + /// + /// + public async Task> GetModesFormationAsync() + { + IEnumerable modeFormations; + IEnumerable modeFormationDTOs; + try + { + modeFormations = await epContext.ModeFormation.ToListAsync(); + } + catch (Exception ex) + { + throw; + } + + if (modeFormations == null) + return null; + + modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); + + return modeFormationDTOs; + } + /// /// Récupérer les origines de formation /// @@ -326,6 +595,32 @@ namespace EPAServeur.Services return origineFormationDTOs; } + /// + /// Récupérer les origines de formation de manière asynchrone + /// + /// + public async Task> GetOriginesFormationAsync() + { + IEnumerable origineFormations; + IEnumerable origineFormationDTOs; + + try + { + origineFormations = await epContext.OrigineFormation.ToListAsync(); + } + catch (Exception ex) + { + throw; + } + + if (origineFormations == null) + return null; + + origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); + + return origineFormationDTOs; + } + /// /// Récupérer les statuts de formation /// @@ -353,6 +648,33 @@ namespace EPAServeur.Services return statutFormationDTOs; } + /// + /// Récupérer les statuts de formation de manière asynchrone + /// + /// + public async Task> GetStatutsFormationAsync() + { + IEnumerable statutFormations; + IEnumerable statutFormationDTOs; + + try + { + statutFormations = await epContext.StatutFormation.ToListAsync(); + } + catch (Exception ex) + { + + throw; + } + + if (statutFormations == null) + return null; + + statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); + + return statutFormationDTOs; + } + /// /// Récupérer les types de formation /// @@ -379,6 +701,32 @@ namespace EPAServeur.Services return typeFormationDTOs; } + /// + /// Récupérer les types de formation de manière asynchrone + /// + /// + public async Task> GetTypesFormationAsync() + { + IEnumerable typeFormations; + IEnumerable typeFormationDTOs; + + try + { + typeFormations = await epContext.TypeFormation.ToListAsync(); + } + catch (Exception ex) + { + throw; + } + + if (typeFormations == null) + return null; + + typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); + + return typeFormationDTOs; + } + /// /// Ajouter une formation /// @@ -411,6 +759,38 @@ namespace EPAServeur.Services return GetFormationDTO(formation); } + /// + /// Ajouter une formation de manière asynchrone + /// + /// + /// + public async Task AddFormationAsync(FormationDTO formationDTO) + { + Formation formation = new Formation(); + formation = SetFormation(formation, formationDTO); + + if (formation.Statut != null) + { + epContext.StatutFormation.Attach(formation.Statut); + } + + epContext.OrigineFormation.Attach(formation.Origine); + epContext.ModeFormation.Attach(formation.ModeFormation); + epContext.TypeFormation.Attach(formation.TypeFormation); + epContext.Add(formation); + + try + { + await epContext.SaveChangesAsync(); + } + catch (Exception ex) + { + throw; + } + + return GetFormationDTO(formation); + } + /// /// Modifier une formation /// @@ -419,6 +799,11 @@ namespace EPAServeur.Services /// public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) { + if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) + { + return null; + } + Formation formation = epContext.Formation.Find(idFormation); if (formation == null) @@ -439,6 +824,39 @@ namespace EPAServeur.Services return GetFormationDTO(formation); } + /// + /// Modifier une formation de manière asynchrone + /// + /// + /// + /// + public async Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO) + { + if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) + { + return null; + } + + Formation formation = await epContext.Formation.FindAsync(idFormation); + + if (formation == null) + { + return null; + } + + formation = SetFormation(formation, formationDTO); + try + { + await epContext.SaveChangesAsync(); + } + catch (Exception ex) + { + throw; + } + + return GetFormationDTO(formation); + } + /// /// Supprimer une formation /// @@ -465,6 +883,31 @@ namespace EPAServeur.Services return true; } + /// + /// Supprimer une formation de manière asynchrone + /// + /// + /// + public async Task DeleteFormationByIdAsync(long? idFormation) + { + Formation formation = await epContext.Formation.FindAsync(idFormation); + + if (formation == null) + return false; + + epContext.Remove(formation); + + try + { + await epContext.SaveChangesAsync(); + } + catch (Exception) + { + throw; + } + + return true; + } #endregion #region Méthodes Privée From 3ec0c7fdf41f87a4cfac40150037b009494f9d72 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 13:43:31 +0200 Subject: [PATCH 11/16] Ajout des logs dans l'api formation --- Controllers/FormationsApi.cs | 282 +++++++++++- .../FormationIncompatibleIdException.cs | 40 ++ Exceptions/FormationInvalidException.cs | 40 ++ Exceptions/FormationNotFoundException.cs | 40 ++ Exceptions/ModeFormationNotFoundException.cs | 40 ++ .../OrigineFormationNotFoundException.cs | 40 ++ .../StatutFormationNotFoundException.cs | 40 ++ Exceptions/TypeFormationNotFoundException.cs | 40 ++ IServices/IFormationService.cs | 8 +- Services/FormationService.cs | 412 +++++++----------- 10 files changed, 695 insertions(+), 287 deletions(-) create mode 100644 Exceptions/FormationIncompatibleIdException.cs create mode 100644 Exceptions/FormationInvalidException.cs create mode 100644 Exceptions/FormationNotFoundException.cs create mode 100644 Exceptions/ModeFormationNotFoundException.cs create mode 100644 Exceptions/OrigineFormationNotFoundException.cs create mode 100644 Exceptions/StatutFormationNotFoundException.cs create mode 100644 Exceptions/TypeFormationNotFoundException.cs diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index 8170e30..6c58dde 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -18,6 +18,9 @@ using IO.Swagger.DTO; using EPAServeur.IServices; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using EPAServeur.Exceptions; +using Microsoft.EntityFrameworkCore; namespace IO.Swagger.Controllers { @@ -28,10 +31,12 @@ namespace IO.Swagger.Controllers public class FormationsApiController : ControllerBase { private readonly IFormationService formationService; + private readonly ILogger logger; - public FormationsApiController(IFormationService _formationService) + public FormationsApiController(IFormationService _formationService, ILogger _logger) { formationService = _formationService; + logger = _logger; } /// @@ -49,7 +54,28 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task AjouterFormation([FromBody] FormationDTO body) { - FormationDTO nouvelleFormation = await formationService.AddFormationAsync(body); + logger.LogInformation("Ajout d'une nouvelle formation."); + + FormationDTO nouvelleFormation = null; + + try + { + nouvelleFormation = await formationService.AddFormationAsync(body); + } + catch (FormationInvalidException) + { + logger.LogWarning("Des données sont manquants, la nouvelle formation ne peut pas être ajoutée."); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données durant l'ajout de la nouvelle formation."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de l'ajout de la formation note."); + } + + logger.LogInformation("Nouvelle formation ajoutée."); return Created("", nouvelleFormation); } @@ -69,15 +95,38 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task DeleteFormation([FromRoute][Required] long? idFormation) { - if ( ! await formationService.DeleteFormationByIdAsync(idFormation)) + try { + logger.LogInformation("Suppresion de la formation {idFormation}.", idFormation); + + FormationDTO formation = await formationService.DeleteFormationByIdAsync(idFormation); + } + catch (FormationNotFoundException) + { + logger.LogError("Impossible de supprimer la formation d'id {idFormation} car elle n'existe pas.", idFormation); + ErreurDTO erreur = new ErreurDTO() { Code = "404", Message = "Aucune formation trouvée" }; + return NotFound(erreur); } + catch (DbUpdateConcurrencyException) + { + logger.LogWarning("La formation {idFormation} n'a pas pu être supprimée car elle est prise par une autre ressource.", idFormation); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur a eu lieu, la formation {idFormation} n'a pas pu être supprimée.", idFormation); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la suppression de la formation {idFormation}.", idFormation); + } + + logger.LogInformation("Formation {idFormation} supprimée avec succès.", idFormation); return NoContent(); } @@ -105,8 +154,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetFormationAnnulees([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); + logger.LogInformation("Récupération de la liste des formations annulées."); + + IEnumerable formations = null; + + try + { + formations = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations annulées."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -114,9 +174,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucune formation annulée" }; + return NotFound(erreur); } + logger.LogInformation("Liste des formations annulées récupérée."); + return Ok(formations); } @@ -138,16 +201,41 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetFormationById([FromRoute][Required] long? idFormation) { - FormationDTO formationDTO = await formationService.GetFormationByIdAsync(idFormation); - if (formationDTO == null) + logger.LogInformation("Récupération de la formation {idFormation}.", idFormation); + + FormationDTO formationDTO = null; + + try + { + formationDTO = await formationService.GetFormationByIdAsync(idFormation); + } + catch (FormationNotFoundException) { + logger.LogError("Aucune formation ne correspond à l'id {idFormation} recherchée.", idFormation); + ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", Message = "La formation n'existe pas", }; + return NotFound(erreurDTO); } + catch (DbUpdateConcurrencyException) + { + logger.LogWarning("La formation {idFormation} n'a pas pu être récupérée car elle est prise par une autre ressource.", idFormation); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur a eu lieu, la formation {idFormation} n'a pas pu être récupérée.", idFormation); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la formation {idFormation}.", idFormation); + } + + logger.LogInformation("Formation {idFormation} récupérée.", idFormation); + return Ok(formationDTO); } @@ -174,8 +262,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetFormationRealisee([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = await formationService.GetFormationRealiseeAsync(asc, numPage, parPAge, idAgence, texte, tri); + logger.LogInformation("Récupération de la liste des formations réalisées."); + + IEnumerable formations = null; + + try + { + formations = await formationService.GetFormationRealiseeAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations réalisées."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -183,9 +282,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucune formation réalisée" }; + return NotFound(erreur); } + logger.LogInformation("Liste des formations réalisées récupérée."); + return Ok(formations); } @@ -210,10 +312,21 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetFormations")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual async Task GetFormations([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]int? idAgence, [FromQuery]int? statutFormation, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetFormations([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [FromQuery] int? statutFormation, [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(..), ... - IEnumerable formations = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, texte, tri); + logger.LogInformation("Récupération de la liste des formations."); + + IEnumerable formations = null; + + try + { + formations = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -221,9 +334,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucune formation" }; + return NotFound(erreur); } + logger.LogInformation("Liste des formations récupérée."); + return Ok(formations); } @@ -242,8 +358,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task GetModesFormation() { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable modeFormations = await formationService.GetModesFormationAsync(); + logger.LogInformation("Récupération de la liste des modes de formation."); + + IEnumerable modeFormations = null; + + try + { + modeFormations = await formationService.GetModesFormationAsync(); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des modes de formation."); + } + if (modeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -251,9 +378,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucun mode de formation" }; + return NotFound(erreur); } + logger.LogInformation("Liste des modes de formation récupérée."); + return Ok(modeFormations); } @@ -272,8 +402,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task GetOriginesFormation() { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable origineFormations = await formationService.GetOriginesFormationAsync(); + logger.LogInformation("Récupération de la liste des origines de formation."); + + IEnumerable origineFormations = null; + + try + { + origineFormations = await formationService.GetOriginesFormationAsync(); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des origines de formation."); + } + if (origineFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -284,6 +425,8 @@ namespace IO.Swagger.Controllers return NotFound(erreur); } + logger.LogInformation("Liste des origines de formation récupérée."); + return Ok(origineFormations); } @@ -310,8 +453,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetProchainesFormation([FromQuery][Required()] bool? asc, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] int? idAgence, [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(..), ... - IEnumerable formations = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); + logger.LogInformation("Récupération de la liste des prochaines formations."); + + IEnumerable formations = null; + + try + { + formations = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des prochaines formations."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -319,9 +473,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucune prochaine formation" }; + return NotFound(erreur); } + logger.LogInformation("Liste des prochaines formations récupérée."); + return Ok(formations); } @@ -340,8 +497,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task GetStatutsFormation() { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable statutFormations = await formationService.GetStatutsFormationAsync(); + logger.LogInformation("Récupération de la liste des statuts de formation."); + + IEnumerable statutFormations = null; + + try + { + statutFormations = await formationService.GetStatutsFormationAsync(); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des statuts de formation."); + } + if (statutFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -349,9 +517,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucun statut de formation" }; + return NotFound(erreur); } + logger.LogInformation("Liste des statuts de formation récupérée."); + return Ok(statutFormations); } @@ -370,8 +541,19 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task GetTypesFormation() { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - IEnumerable typeFormations = await formationService.GetTypesFormationAsync(); + logger.LogInformation("Récupération de la liste des types de formation."); + + IEnumerable typeFormations = null; + + try + { + typeFormations = await formationService.GetTypesFormationAsync(); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des types de formation."); + } + if (typeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -379,9 +561,12 @@ namespace IO.Swagger.Controllers Code = "404", Message = "Aucun type de formation" }; + return NotFound(erreur); } + logger.LogInformation("Liste des types de formation récupérée."); + return Ok(typeFormations); } @@ -402,12 +587,61 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long? idFormation) { - FormationDTO formation = await formationService.UpdateFormationAsync(idFormation, body); + logger.LogInformation("Mise à jour de la formation d'id {idFormation}.", idFormation); + + FormationDTO formation = null; + + try + { + formation = await formationService.UpdateFormationAsync(idFormation, body); + } + catch (FormationInvalidException) + { + logger.LogWarning("Des données sont manquants, la formation {idFormation} ne peut pas être mise à jour.", idFormation); + } + catch (FormationIncompatibleIdException) + { + logger.LogError("L'id de la formation à mettre à jour {body.Id} et l'id de la formation avec les nouvelles informations {idFormation} sont différents.", body.Id, idFormation); + } + catch (DbUpdateConcurrencyException) + { + logger.LogError("La formation {idFormation} n'a pas pu être mise à jour car elle est prise par une autre ressource.", idFormation); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données lors de la mise à jour de la formation {idFormation}.", idFormation); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la mise à jour de la formation {idFormation}.", idFormation); + } + if (formation == null) { - formation = formationService.AddFormation(body); + try + { + formation = await formationService.AddFormationAsync(body); + } + catch (FormationInvalidException) + { + logger.LogWarning("Des données sont manquants, la nouvelle formation ne peut pas être ajoutée."); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données durant l'ajout de la nouvelle formation."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de l'ajout de la formation note."); + } + + logger.LogInformation("Nouvelle formation ajoutée."); + return Created("", formation); } + + logger.LogInformation("Update effectué avec succès"); + return Ok(formation); } } diff --git a/Exceptions/FormationIncompatibleIdException.cs b/Exceptions/FormationIncompatibleIdException.cs new file mode 100644 index 0000000..2fc7201 --- /dev/null +++ b/Exceptions/FormationIncompatibleIdException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +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 à mettre sont différents + /// + public class FormationIncompatibleIdException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public FormationIncompatibleIdException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public FormationIncompatibleIdException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public FormationIncompatibleIdException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/FormationInvalidException.cs b/Exceptions/FormationInvalidException.cs new file mode 100644 index 0000000..0d5e444 --- /dev/null +++ b/Exceptions/FormationInvalidException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsq'une formation est invalide + /// + public class FormationInvalidException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public FormationInvalidException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public FormationInvalidException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public FormationInvalidException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/FormationNotFoundException.cs b/Exceptions/FormationNotFoundException.cs new file mode 100644 index 0000000..93fdcc9 --- /dev/null +++ b/Exceptions/FormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'une formation n'a pas été trouvée + /// + public class FormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public FormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public FormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public FormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/ModeFormationNotFoundException.cs b/Exceptions/ModeFormationNotFoundException.cs new file mode 100644 index 0000000..c3c1f4a --- /dev/null +++ b/Exceptions/ModeFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un mode de formation n'a pas été trouvé + /// + public class ModeFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public ModeFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public ModeFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public ModeFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/OrigineFormationNotFoundException.cs b/Exceptions/OrigineFormationNotFoundException.cs new file mode 100644 index 0000000..26438b6 --- /dev/null +++ b/Exceptions/OrigineFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'une origine de formation n'a pas été trouvée + /// + public class OrigineFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public OrigineFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public OrigineFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public OrigineFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/StatutFormationNotFoundException.cs b/Exceptions/StatutFormationNotFoundException.cs new file mode 100644 index 0000000..66c7167 --- /dev/null +++ b/Exceptions/StatutFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un statut de formation n'a pas été trouvé + /// + public class StatutFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public StatutFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public StatutFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public StatutFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/TypeFormationNotFoundException.cs b/Exceptions/TypeFormationNotFoundException.cs new file mode 100644 index 0000000..54f1de8 --- /dev/null +++ b/Exceptions/TypeFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un type de formation n'a pas été trouvé + /// + public class TypeFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public TypeFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public TypeFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public TypeFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/IServices/IFormationService.cs b/IServices/IFormationService.cs index 4a08b04..6b455c8 100644 --- a/IServices/IFormationService.cs +++ b/IServices/IFormationService.cs @@ -12,8 +12,8 @@ namespace EPAServeur.IServices { FormationDTO GetFormationById(long? idFormation); Task GetFormationByIdAsync(long? idFormation); - IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); - Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri); + Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri); IEnumerable GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); Task> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable GetFormationRealisee(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); @@ -33,8 +33,8 @@ namespace EPAServeur.IServices Task AddFormationAsync(FormationDTO formationDTO); FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO); Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO); - bool DeleteFormationById(long? idFormation); - Task DeleteFormationByIdAsync(long? idFormation); + FormationDTO DeleteFormationById(long? idFormation); + Task DeleteFormationByIdAsync(long? idFormation); } } diff --git a/Services/FormationService.cs b/Services/FormationService.cs index 150f207..f164303 100644 --- a/Services/FormationService.cs +++ b/Services/FormationService.cs @@ -1,4 +1,5 @@ using EPAServeur.Context; +using EPAServeur.Exceptions; using EPAServeur.IServices; using EPAServeur.Models.Formation; using IO.Swagger.DTO; @@ -47,7 +48,7 @@ namespace EPAServeur.Services .FirstOrDefault(formation => formation.Id == idFormation); if (formation == null) - return null; + throw new FormationNotFoundException(); return GetFormationDTO(formation); } @@ -66,7 +67,7 @@ namespace EPAServeur.Services .FirstOrDefaultAsync(formation => formation.Id == idFormation); if (formation == null) - return null; + throw new FormationNotFoundException(); return GetFormationDTO(formation); } @@ -81,7 +82,7 @@ namespace EPAServeur.Services /// 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, int? idAgence, string texte, string tri) + public IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri) { IEnumerable formations; IEnumerable formationDTOs; @@ -94,34 +95,38 @@ namespace EPAServeur.Services int skip = (numPage.Value - 1) * parPAge.Value; int take = parPAge.Value; - if (idAgence != null) + if (statutFormation != null && idAgence != null) { - try - { - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - catch (Exception ex) - { - throw; - } + formations = epContext.Formation + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation) + .Where(formation => formation.Statut.Id == statutFormation && formation.IdAgence == idAgence); + } + 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.Id == statutFormation); + } + 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); } else { - try - { - formations = epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - catch (Exception ex) - { - throw; - } + formations = epContext.Formation.Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation); } @@ -143,7 +148,7 @@ namespace EPAServeur.Services /// 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, int? idAgence, string texte, string tri) + public async Task> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri) { IEnumerable formations; IEnumerable formationDTOs; @@ -156,34 +161,42 @@ namespace EPAServeur.Services int skip = (numPage.Value - 1) * parPAge.Value; int take = parPAge.Value; - if (idAgence != null) + if (statutFormation != null && idAgence != null) { - try - { - 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).ToListAsync(); - } - catch (Exception ex) - { - throw; - } + formations = await epContext.Formation + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation) + .Where(formation => formation.Statut.Id == statutFormation && formation.IdAgence == idAgence).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.Id == statutFormation).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).ToListAsync(); + } else { - try - { - formations = await epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).ToListAsync(); - } - catch (Exception ex) - { - throw; - } + + formations = await epContext.Formation.Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + } @@ -308,34 +321,23 @@ namespace EPAServeur.Services if (idAgence != null) { - try - { - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - catch (Exception ex) - { - throw; - } + + formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation); } else { - try - { - formations = epContext.Formation.Where(formation => formation.Statut.Id == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - catch (Exception ex) - { - throw; - } + + formations = epContext.Formation.Where(formation => formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation); + } @@ -372,34 +374,22 @@ namespace EPAServeur.Services if (idAgence != null) { - try - { - formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).ToListAsync(); - } - catch (Exception ex) - { - throw; - } + + formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); } else { - try - { - formations = await epContext.Formation.Where(formation => formation.Statut.Id == 3) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).ToListAsync(); - } - catch (Exception ex) - { - throw; - } + + formations = await epContext.Formation.Where(formation => formation.Statut.Id == 3) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); } @@ -435,19 +425,14 @@ namespace EPAServeur.Services int take = parPAge.Value; if (idAgence != null) - try - { - formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - catch (Exception ex) - { - throw; - } + { + formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation); + } else { formations = epContext.Formation.Where(formation => (formation.Statut.Id == 1 || formation.Statut.Id == 2)) @@ -489,18 +474,14 @@ namespace EPAServeur.Services int take = parPAge.Value; if (idAgence != null) - try - { - formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) - .Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation).ToListAsync(); - } - catch (Exception ex) - { - throw; - } + { + formations = await epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation).ToListAsync(); + + } else { @@ -527,14 +508,8 @@ namespace EPAServeur.Services { IEnumerable modeFormations; IEnumerable modeFormationDTOs; - try - { - modeFormations = epContext.ModeFormation; - } - catch (Exception ex) - { - throw; - } + + modeFormations = epContext.ModeFormation; if (modeFormations == null) return null; @@ -552,14 +527,7 @@ namespace EPAServeur.Services { IEnumerable modeFormations; IEnumerable modeFormationDTOs; - try - { - modeFormations = await epContext.ModeFormation.ToListAsync(); - } - catch (Exception ex) - { - throw; - } + modeFormations = await epContext.ModeFormation.ToListAsync(); if (modeFormations == null) return null; @@ -578,14 +546,7 @@ namespace EPAServeur.Services IEnumerable origineFormations; IEnumerable origineFormationDTOs; - try - { - origineFormations = epContext.OrigineFormation; - } - catch (Exception ex) - { - throw; - } + origineFormations = epContext.OrigineFormation; if (origineFormations == null) return null; @@ -604,14 +565,7 @@ namespace EPAServeur.Services IEnumerable origineFormations; IEnumerable origineFormationDTOs; - try - { - origineFormations = await epContext.OrigineFormation.ToListAsync(); - } - catch (Exception ex) - { - throw; - } + origineFormations = await epContext.OrigineFormation.ToListAsync(); if (origineFormations == null) return null; @@ -630,15 +584,7 @@ namespace EPAServeur.Services IEnumerable statutFormations; IEnumerable statutFormationDTOs; - try - { - statutFormations = epContext.StatutFormation; - } - catch (Exception ex) - { - - throw; - } + statutFormations = epContext.StatutFormation; if (statutFormations == null) return null; @@ -657,15 +603,7 @@ namespace EPAServeur.Services IEnumerable statutFormations; IEnumerable statutFormationDTOs; - try - { - statutFormations = await epContext.StatutFormation.ToListAsync(); - } - catch (Exception ex) - { - - throw; - } + statutFormations = await epContext.StatutFormation.ToListAsync(); if (statutFormations == null) return null; @@ -684,14 +622,7 @@ namespace EPAServeur.Services IEnumerable typeFormations; IEnumerable typeFormationDTOs; - try - { - typeFormations = epContext.TypeFormation; - } - catch (Exception ex) - { - throw; - } + typeFormations = epContext.TypeFormation; if (typeFormations == null) return null; @@ -710,14 +641,7 @@ namespace EPAServeur.Services IEnumerable typeFormations; IEnumerable typeFormationDTOs; - try - { - typeFormations = await epContext.TypeFormation.ToListAsync(); - } - catch (Exception ex) - { - throw; - } + typeFormations = await epContext.TypeFormation.ToListAsync(); if (typeFormations == null) return null; @@ -734,27 +658,21 @@ namespace EPAServeur.Services /// public FormationDTO AddFormation(FormationDTO formationDTO) { + if (!IsFormationValide(formationDTO)) + throw new FormationInvalidException(); + Formation formation = new Formation(); formation = SetFormation(formation, formationDTO); if (formation.Statut != null) - { epContext.StatutFormation.Attach(formation.Statut); - } epContext.OrigineFormation.Attach(formation.Origine); epContext.ModeFormation.Attach(formation.ModeFormation); epContext.TypeFormation.Attach(formation.TypeFormation); epContext.Add(formation); - try - { - epContext.SaveChanges(); - } - catch (Exception ex) - { - throw; - } + epContext.SaveChanges(); return GetFormationDTO(formation); } @@ -766,27 +684,21 @@ namespace EPAServeur.Services /// public async Task AddFormationAsync(FormationDTO formationDTO) { + if (!IsFormationValide(formationDTO)) + throw new FormationInvalidException(); + Formation formation = new Formation(); formation = SetFormation(formation, formationDTO); if (formation.Statut != null) - { epContext.StatutFormation.Attach(formation.Statut); - } epContext.OrigineFormation.Attach(formation.Origine); epContext.ModeFormation.Attach(formation.ModeFormation); epContext.TypeFormation.Attach(formation.TypeFormation); epContext.Add(formation); - try - { - await epContext.SaveChangesAsync(); - } - catch (Exception ex) - { - throw; - } + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } @@ -799,27 +711,20 @@ namespace EPAServeur.Services /// public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) { - if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) - { - return null; - } + if (!IsFormationValide(formationDTO)) + throw new FormationInvalidException(); + + if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) + throw new FormationIncompatibleIdException(); Formation formation = epContext.Formation.Find(idFormation); if (formation == null) - { return null; - } formation = SetFormation(formation, formationDTO); - try - { - epContext.SaveChanges(); - } - catch (Exception ex) - { - throw; - } + + epContext.SaveChanges(); return GetFormationDTO(formation); } @@ -832,27 +737,19 @@ namespace EPAServeur.Services /// public async Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO) { + if (!IsFormationValide(formationDTO)) + throw new FormationInvalidException(); + if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) - { - return null; - } + throw new FormationIncompatibleIdException(); Formation formation = await epContext.Formation.FindAsync(idFormation); if (formation == null) - { return null; - } formation = SetFormation(formation, formationDTO); - try - { - await epContext.SaveChangesAsync(); - } - catch (Exception ex) - { - throw; - } + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } @@ -862,25 +759,19 @@ namespace EPAServeur.Services /// /// /// - public bool DeleteFormationById(long? idFormation) + public FormationDTO DeleteFormationById(long? idFormation) { Formation formation = epContext.Formation.Find(idFormation); if (formation == null) - return false; + throw new FormationNotFoundException(); epContext.Remove(formation); - try - { - epContext.SaveChanges(); - } - catch (Exception) - { - throw; - } - return true; + epContext.SaveChanges(); + + return GetFormationDTO(formation); } /// @@ -888,29 +779,32 @@ namespace EPAServeur.Services /// /// /// - public async Task DeleteFormationByIdAsync(long? idFormation) + public async Task DeleteFormationByIdAsync(long? idFormation) { Formation formation = await epContext.Formation.FindAsync(idFormation); if (formation == null) - return false; + throw new FormationNotFoundException(); epContext.Remove(formation); - try - { - await epContext.SaveChangesAsync(); - } - catch (Exception) - { - throw; - } + await epContext.SaveChangesAsync(); - return true; + return GetFormationDTO(formation); } #endregion #region Méthodes Privée + /// + /// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour + /// + /// Un objet FormationDTO est valide si aucune de ses propriétés n'est à null + /// + /// true si l'objet est valide, false sinon + private bool IsFormationValide(FormationDTO formation) + { + return !(formation == null || formation.IdAgence == null || formation.Intitule == null || formation.Organisme == null); + } #region Object to DTO /// From 9ed1697bf21197d68825a3586e4eac26b1548f9e Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 14:59:01 +0200 Subject: [PATCH 12/16] Ajout des logs dans l'api referent --- Controllers/ReferentsApi.cs | 97 +++++++++++++++-- Services/ReferentService.cs | 201 ++++++++++++++++++++---------------- 2 files changed, 199 insertions(+), 99 deletions(-) diff --git a/Controllers/ReferentsApi.cs b/Controllers/ReferentsApi.cs index 764b287..cf5c6ad 100644 --- a/Controllers/ReferentsApi.cs +++ b/Controllers/ReferentsApi.cs @@ -21,6 +21,9 @@ using Microsoft.AspNetCore.Authorization; using IO.Swagger.Security; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using IO.Swagger.ClientCollaborateur; +using EPAServeur.Exceptions; namespace IO.Swagger.Controllers { @@ -31,10 +34,12 @@ namespace IO.Swagger.Controllers public class ReferentsApiController : ControllerBase { private readonly IReferentService referentService; + private readonly ILogger logger; - public ReferentsApiController(IReferentService _referentService) + public ReferentsApiController(IReferentService _referentService, ILogger _logger) { referentService = _referentService; + logger = _logger; } /// @@ -55,16 +60,36 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetReferentById([FromRoute][Required]Guid? idReferent) { - ReferentDTO referentDTO = await referentService.GetReferentByIdAsync(idReferent); - if (referentDTO == null) + logger.LogInformation("Récupération du référent {idReferent}.", idReferent); + + ReferentDTO referentDTO = null; + + try + { + referentDTO = await referentService.GetReferentByIdAsync(idReferent); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le référent par son id {idReferent}.", idReferent); + } + catch (ReferentNotFoundException) { + logger.LogError("Le référent {idReferent} est introuvable.", idReferent); ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", Message = "Le référent n'existe pas", }; + return NotFound(erreurDTO); } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du référent {idReferent}.", idReferent); + } + + logger.LogInformation("Référent {idReferent} récupéré.", idReferent); + return Ok(referentDTO); } @@ -92,7 +117,7 @@ namespace IO.Swagger.Controllers public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) { //IEnumerable referentDTOs = referentService.GetReferents(asc,numPage,parPAge,fonctions,idAgence,idBU,texte,tri); - return Ok(); + return NoContent(); } /// @@ -113,16 +138,36 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur) { - ReferentDTO referentDTO = await referentService.GetReferentActuelCollaborateurAsync(idCollaborateur); - if (referentDTO == null) + logger.LogInformation("Récupération du référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + + ReferentDTO referentDTO = null; + + try + { + referentDTO = await referentService.GetReferentActuelCollaborateurAsync(idCollaborateur); + } + catch (ApiException) { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + } + catch (ReferentNotFoundException) + { + logger.LogError("Le référent actuel du collaborateur {idCollaborateur} est introuvable.", idCollaborateur); ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", - Message = "Aucun référent pour le collaborateur", + Message = "Aucun référent actuel pour le collaborateur", }; + return NotFound(erreurDTO); } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + } + + logger.LogInformation("Référent actuel du collaborateur {idCollaborateur} récupéré.", idCollaborateur); + return Ok(referentDTO); } @@ -149,17 +194,49 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual async Task GetReferentsByCollaborateur([FromQuery][Required()] bool? asc, [FromRoute][Required] Guid? idCollaborateur, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] string texte, [FromQuery] string tri) { - IEnumerable referentDTO = await referentService.GetReferentsByCollaborateurAsync(asc,idCollaborateur,numPage,parPAge,texte,tri); - if (referentDTO.Count() == 0) + logger.LogInformation("Récupération de la liste des référents du collaborateur {idCollaborateur}.", idCollaborateur); + + IEnumerable referentDTOs = null; + + try + { + referentDTOs = await referentService.GetReferentsByCollaborateurAsync(asc, idCollaborateur, numPage, parPAge, texte, tri); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service collaborateur lors de la récupération de la liste des référents du collaborateur {idReferent}.", idCollaborateur); + } + catch (CollaborateurNotFoundException) + { + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Le collaborateur n'existe pas", + }; + + return NotFound(erreurDTO); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération des référents du collaborateur {idCollaborateur}.", idCollaborateur); + } + + if (referentDTOs.Count() == 0) { + logger.LogInformation("Aucun référent pour le collaborateur {idCollaborateur}.", idCollaborateur); + ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", Message = "Aucun référent pour le collaborateur", }; + return NotFound(erreurDTO); } - return Ok(referentDTO); + + logger.LogInformation("Liste des référents du collaborateur {idCollaborateur} récupérée", idCollaborateur); + + return Ok(referentDTOs); } } } diff --git a/Services/ReferentService.cs b/Services/ReferentService.cs index 765e9da..dcabe51 100644 --- a/Services/ReferentService.cs +++ b/Services/ReferentService.cs @@ -1,4 +1,5 @@ -using EPAServeur.IServices; +using EPAServeur.Exceptions; +using EPAServeur.IServices; using IO.Swagger.ApiCollaborateur; using IO.Swagger.DTO; using IO.Swagger.ModelCollaborateur; @@ -35,8 +36,9 @@ namespace EPAServeur.Services public ReferentDTO GetReferentById(Guid? idReferent) { Referent referent = referentApi.ChercherRefId(idReferent); + if (referent == null) - return null; + throw new ReferentNotFoundException(); return GetReferentDTO(referent); } @@ -49,8 +51,9 @@ namespace EPAServeur.Services public async Task GetReferentByIdAsync(Guid? idReferent) { Referent referent = await referentApi.ChercherRefIdAsync(idReferent); + if (referent == null) - return null; + throw new ReferentNotFoundException(); return GetReferentDTO(referent); } @@ -65,7 +68,7 @@ namespace EPAServeur.Services Referent referent = referentApi.ChercherRefActuelCollabId(idCollaborateur); if (referent == null) - return null; + throw new ReferentNotFoundException(); return GetReferentDTO(referent); } @@ -80,10 +83,11 @@ namespace EPAServeur.Services Referent referent = await referentApi.ChercherRefActuelCollabIdAsync(idCollaborateur); if (referent == null) - return null; + throw new ReferentNotFoundException(); return GetReferentDTO(referent); } + /// /// Récupère la liste des référents pour une agence /// @@ -95,63 +99,64 @@ namespace EPAServeur.Services /// /// /// - /// - + /// public IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) { - //IEnumerable collaborateurs; // A changer (Sera utilisé pour récupérer la liste des référents par fonction - IEnumerable referents = null; // A changer - IEnumerable referentDTOs = null; // A changer - //List ids = fonctions.Select(guid => (Guid?)Guid.Parse(guid)).ToList(); + throw new NotImplementedException(); - //collaborateurs = collaborateurApi.ChercherCollab(ids); - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + ////IEnumerable collaborateurs; // A changer (Sera utilisé pour récupérer la liste des référents par fonction + //IEnumerable referents = null; // A changer + //IEnumerable referentDTOs = null; // A changer + ////List ids = fonctions.Select(guid => (Guid?)Guid.Parse(guid)).ToList(); - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + ////collaborateurs = collaborateurApi.ChercherCollab(ids); + //if (texte == null) + // texte = ""; + //else + // texte = texte.ToLower(); - if (idBU != null) - { + //int skip = (numPage.Value - 1) * parPAge.Value; + //int take = parPAge.Value; - } - else - { + //if (idBU != null) + //{ - } + //} + //else + //{ - if (idAgence != null) - { - try - { - - } - catch (Exception ex) - { - throw; - } - } - else - { - try - { + //} - } - catch (Exception ex) - { - throw; - } - } + //if (idAgence != null) + //{ + // try + // { + // } + // catch (Exception ex) + // { + // throw; + // } + //} + //else + //{ + // try + // { - if (referents == null) - return new List(); + // } + // catch (Exception ex) + // { + // throw; + // } + //} - referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); - return referentDTOs; + //if (referents == null) + // return new List(); + + //referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + //return referentDTOs; } /// @@ -169,56 +174,58 @@ namespace EPAServeur.Services public async Task> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) { - IEnumerable referents = null ; // A changer - IEnumerable referentDTOs = null; // A changer + throw new NotImplementedException(); - if (texte == null) - texte = ""; - else - texte = texte.ToLower(); + //IEnumerable referents = null ; // A changer + //IEnumerable referentDTOs = null; // A changer - int skip = (numPage.Value - 1) * parPAge.Value; - int take = parPAge.Value; + //if (texte == null) + // texte = ""; + //else + // texte = texte.ToLower(); - if (idBU != null) - { + //int skip = (numPage.Value - 1) * parPAge.Value; + //int take = parPAge.Value; - } - else - { + //if (idBU != null) + //{ - } + //} + //else + //{ - if (idAgence != null) - { - try - { - - } - catch (Exception ex) - { - throw; - } - } - else - { - try - { - - } - catch (Exception ex) - { - throw; - } - } + //} + //if (idAgence != null) + //{ + // try + // { - if (referents == null) - return new List(); + // } + // catch (Exception ex) + // { + // throw; + // } + //} + //else + //{ + // try + // { - referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + // } + // catch (Exception ex) + // { + // throw; + // } + //} - return referentDTOs; + + //if (referents == null) + // return new List(); + + //referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + //return referentDTOs; } @@ -248,8 +255,16 @@ namespace EPAServeur.Services if (idCollaborateur == null) return new List(); + Collaborateur collaborateur = collaborateurApi.ChercherCollabId(idCollaborateur); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); referents = referentApi.ChercherRefCollabId(idCollaborateur); + + if (referents == null) + return new List(); + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); return referentDTOs; @@ -281,8 +296,16 @@ namespace EPAServeur.Services if (idCollaborateur == null) return new List(); + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(idCollaborateur); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); referents = await referentApi.ChercherRefCollabIdAsync(idCollaborateur); + + if (referents == null) + return new List(); + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); return referentDTOs; From c6d69a0d2021db1d96ef6f65be54e0f2242d07c0 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 16:20:39 +0200 Subject: [PATCH 13/16] =?UTF-8?q?Ajout=20des=20t=C3=A2ches=20asynchrones?= =?UTF-8?q?=20dans=20le=20service=20engagement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- IServices/IEngagementService.cs | 11 +- Services/EngagementService.cs | 220 ++++++++++++++++++++------------ 2 files changed, 145 insertions(+), 86 deletions(-) diff --git a/IServices/IEngagementService.cs b/IServices/IEngagementService.cs index b47080c..cbf5d6c 100644 --- a/IServices/IEngagementService.cs +++ b/IServices/IEngagementService.cs @@ -12,9 +12,14 @@ namespace EPAServeur.IServices { IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - Task> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); - Task RepondreEngagement(EngagementDTO engagement, long? idEngagement); + Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + + EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement); + Task RepondreEngagementAsync(EngagementDTO engagement, long? idEngagement); } } diff --git a/Services/EngagementService.cs b/Services/EngagementService.cs index dfb645b..320b0de 100644 --- a/Services/EngagementService.cs +++ b/Services/EngagementService.cs @@ -20,6 +20,7 @@ namespace EPAServeur.Services private readonly EpContext epContext; private readonly ICollaborateurService collaborateurService; + private readonly IReferentService referentService; #endregion #region Contructeurs @@ -28,10 +29,11 @@ namespace EPAServeur.Services /// Constructeur de la classe EngagementService /// /// - public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService) + public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService, IReferentService _referentService) { epContext = _epContext; collaborateurService = _collaborateurService; + referentService = _referentService; } #endregion @@ -41,7 +43,6 @@ namespace EPAServeur.Services public IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) { IEnumerable engagements; - IEnumerable engagementDTOs; if (texte == null) texte = ""; @@ -52,40 +53,46 @@ namespace EPAServeur.Services int take = parPAge.Value; if (idAgence != null) - { - try - { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence); - } - catch (Exception ex) - { - throw; - } - } + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence); else - { - try - { - engagements = epContext.Engagement.Include(engagement => engagement.Ep); - } - catch (Exception ex) - { - throw; - } - } + engagements = epContext.Engagement.Include(engagement => engagement.Ep); + if (engagements == null) + return null; + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, 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 (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).ToListAsync(); if (engagements == null) return null; - engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + return engagementDTOs; } public IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) { IEnumerable engagements; - IEnumerable engagementDTOs; if (texte == null) texte = ""; @@ -96,40 +103,47 @@ namespace EPAServeur.Services int take = parPAge.Value; if (idAgence != null) - { - try - { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToList(); - } - catch (Exception ex) - { - throw; - } - } + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToList(); else - { - try - { - engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToList(); - } - catch (Exception ex) - { - throw; - } - } + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToList(); + + if (engagements == null) + return null; + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, 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 (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToListAsync(); if (engagements == null) return null; - engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + return engagementDTOs; } - public async Task> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) { IEnumerable engagements; - // engagementDTOs = new List(); if (texte == null) texte = ""; @@ -140,38 +154,41 @@ namespace EPAServeur.Services int take = parPAge.Value; if (idAgence != null) - { - try - { engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Modalite.ToLower().Contains(texte)); - } - catch (Exception ex) - { - throw; - } - } else - { - try - { engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)); - } - catch (Exception ex) - { - throw; - } - } if (engagements == null) return null; - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, 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 (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Modalite.ToLower().Contains(texte)).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)).ToListAsync(); + + if (engagements == null) + return null; + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); var results = await Task.WhenAll(engagementDTOs); - //foreach (var engagement in engagements) - //{ - // engagementDTOs.Add(await GetEngagementDTOAsync(engagement)); - //} return results; } @@ -182,18 +199,15 @@ namespace EPAServeur.Services /// /// /// - public async Task RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) + public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) { - + if (!IsEngagementValide(engagementDTO)) return null; if (engagementDTO.Id != idEngagement) return null; - if (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) - return null; // Créer une exception pour ce cas - Engagement engagement = epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefault(engagement => engagement.Id == idEngagement); if (engagement == null) @@ -209,6 +223,40 @@ namespace EPAServeur.Services epContext.SaveChanges(); + return GetEngagementDTO(engagement); + } + + + /// + /// Donner une réponse à un engagement de manière asynchrone + /// + /// + /// + /// + public async Task RepondreEngagementAsync(EngagementDTO engagementDTO, long? idEngagement) + { + + if (!IsEngagementValide(engagementDTO)) + return null; + + if (engagementDTO.Id != idEngagement) + return null; + + Engagement engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.Id == idEngagement); + + if (engagement == null) + return null; + + engagement.Realise = engagementDTO.Realise; + + if (engagement.Realise == false) + { + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + } + + await epContext.SaveChangesAsync(); + return await GetEngagementDTOAsync(engagement); } @@ -218,11 +266,11 @@ namespace EPAServeur.Services #region Méthodes Privée private bool IsEngagementValide(EngagementDTO engagementDTO) { - return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null); + return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null || (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable))); } #region Object to DTO - + /// /// Récupère un objet EngagementDTO en fonction d'un objet Engagement /// @@ -274,7 +322,7 @@ namespace EPAServeur.Services /// /// /// - private EpInformationDTO GetEpInformationDTO(Ep ep) + private EpInformationDTO GetEpInformationDTO(Ep ep) { EpInformationDTO epInformationDTO = new EpInformationDTO() { @@ -284,7 +332,7 @@ namespace EPAServeur.Services DatePrevisionnelle = ep.DatePrevisionnelle, Obligatoire = ep.Obligatoire, Collaborateur = collaborateurService.GetCollaborateurById(ep.IdCollaborateur), - Referent = collaborateurService.GetCollaborateurById(ep.IdReferent) + Referent = referentService.GetReferentById(ep.IdReferent) //Ajouter la date de disponibilité }; @@ -304,11 +352,17 @@ namespace EPAServeur.Services Type = ep.TypeEP.ToString(), Statut = ep.Statut.ToString(), DatePrevisionnelle = ep.DatePrevisionnelle, - Obligatoire = ep.Obligatoire, - Collaborateur = await collaborateurService.GetCollaborateurByIdAsync(ep.IdCollaborateur), - Referent = await collaborateurService.GetCollaborateurByIdAsync(ep.IdReferent) + Obligatoire = ep.Obligatoire //Ajouter la date de disponibilité }; + var collaborateur = collaborateurService.GetCollaborateurByIdAsync(ep.IdCollaborateur); + var referent = referentService.GetReferentByIdAsync(ep.IdReferent); + + await Task.WhenAll(collaborateur, referent); + + epInformationDTO.Collaborateur = collaborateur.Result; + epInformationDTO.Referent = referent.Result; + return epInformationDTO; } @@ -368,7 +422,7 @@ namespace EPAServeur.Services return ep; } - + #endregion #endregion From 79828d46b13d303451d43eff400f1e44da8df5bd Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 17:49:49 +0200 Subject: [PATCH 14/16] Ajout des logs dans l'api engagement --- Controllers/EngagementsApi.cs | 127 +++++++++++++----- .../EngagementIncompatibleIdException.cs | 40 ++++++ Exceptions/EngagementInvalidException.cs | 40 ++++++ Exceptions/EngagementNotFoundException.cs | 40 ++++++ Services/EngagementService.cs | 92 ++++++++----- 5 files changed, 272 insertions(+), 67 deletions(-) create mode 100644 Exceptions/EngagementIncompatibleIdException.cs create mode 100644 Exceptions/EngagementInvalidException.cs create mode 100644 Exceptions/EngagementNotFoundException.cs diff --git a/Controllers/EngagementsApi.cs b/Controllers/EngagementsApi.cs index 46ce2ed..30814e3 100644 --- a/Controllers/EngagementsApi.cs +++ b/Controllers/EngagementsApi.cs @@ -20,6 +20,9 @@ using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; using EPAServeur.IServices; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using EPAServeur.Exceptions; +using Microsoft.EntityFrameworkCore; namespace IO.Swagger.Controllers { @@ -30,10 +33,13 @@ namespace IO.Swagger.Controllers public class EngagementsApiController : ControllerBase { private readonly IEngagementService engagementService; + private readonly ILogger logger; - public EngagementsApiController(IEngagementService _engagementService) + + public EngagementsApiController(IEngagementService _engagementService, ILogger _logger) { engagementService = _engagementService; + logger = _logger; } /// /// @@ -54,20 +60,27 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetEngagements")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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(..), ... - IEnumerable engagements = engagementService.GetEngagements(asc, numPage, parPAge, idAgence, texte, tri); - if (engagements == null) + logger.LogInformation("Récupération de la liste des engagements."); + + IEnumerable engagements = null; + + try { - ErreurDTO erreur = new ErreurDTO() - { - Code = "404", - Message = "Aucun engagement" - }; - return NotFound(erreur); + engagements = await engagementService.GetEngagementsAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements."); } + logger.LogInformation("Liste des engagements récupérée."); + return Ok(engagements); } @@ -90,20 +103,27 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetEngagementsEnAttente")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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(..), ... - IEnumerable engagements = engagementService.GetEngagementsEnAttente(asc, numPage, parPAge, idAgence, texte, tri); - if (engagements == null) + logger.LogInformation("Récupération de la liste des engagements en attente."); + + IEnumerable engagements = null; + + try { - ErreurDTO erreur = new ErreurDTO() - { - Code = "404", - Message = "Aucun engagement en attente" - }; - return NotFound(erreur); + engagements = await engagementService.GetEngagementsEnAttenteAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements en attente est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements en attente."); } + logger.LogInformation("Liste des engagements en attente récupérée."); + return Ok(engagements); } @@ -128,17 +148,24 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [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(..), ... - IEnumerable engagements = await engagementService.GetEngagementsRepondus(asc, numPage, parPAge, idAgence, texte, tri); - if (engagements == null) + logger.LogInformation("Récupération de la liste des engagements répondus."); + + IEnumerable engagements = null; + + try { - ErreurDTO erreur = new ErreurDTO() - { - Code = "404", - Message = "Aucun engagement en repondu" - }; - return NotFound(erreur); + engagements = await engagementService.GetEngagementsRepondusAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements répondus est invalide."); } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements répondus."); + } + + logger.LogInformation("Liste des engagements répondus récupérée."); return Ok(engagements); } @@ -159,11 +186,43 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual async Task RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) { - //if (body != null && body.Realise == false && string.IsNullOrWhiteSpace(body.RaisonNonRealisable)) - // return null; // A traiter ! Retourner une erreur + logger.LogInformation("Tentative de mise à jour de l'engagement {idEngagement}.", idEngagement); + + EngagementDTO engagement = null; + + try + { + engagement = await engagementService.RepondreEngagementAsync(body, idEngagement); + } + catch (EngagementInvalidException ex) + { + logger.LogWarning("Des données sont manquants, l'engagement {idEngagement} ne peut pas être mise à jour.", idEngagement); + ErreurDTO erreur = new ErreurDTO() + { + Code = "400", + Message = ex.Message + }; + return BadRequest(erreur); + } + catch (EngagementIncompatibleIdException) + { + logger.LogError("L'id de l'engagement à mettre à jour {body.Id} et l'id de l'engagement avec les nouvelles informations {idEngagement} sont différents.", body.Id, idEngagement); + } + catch (DbUpdateConcurrencyException) + { + logger.LogError("L'engagement {idEngagement} n'a pas pu être mise à jour car il est pris par une autre ressource.", idEngagement); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données lors de la mise à jour de l'engagement {idEngagement}.", idEngagement); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la mise à jour de l'engagement {idEngagement}.", idEngagement); + } + + logger.LogInformation("Mise à jour de l'engagement {idEngagement} réussie."); - EngagementDTO engagement = await engagementService.RepondreEngagement(body, idEngagement); - return Ok(engagement); } } diff --git a/Exceptions/EngagementIncompatibleIdException.cs b/Exceptions/EngagementIncompatibleIdException.cs new file mode 100644 index 0000000..d11a25b --- /dev/null +++ b/Exceptions/EngagementIncompatibleIdException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +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 + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementIncompatibleIdException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementIncompatibleIdException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementIncompatibleIdException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/EngagementInvalidException.cs b/Exceptions/EngagementInvalidException.cs new file mode 100644 index 0000000..15e974a --- /dev/null +++ b/Exceptions/EngagementInvalidException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un engagement est invalide + /// + public class EngagementInvalidException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementInvalidException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementInvalidException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementInvalidException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/EngagementNotFoundException.cs b/Exceptions/EngagementNotFoundException.cs new file mode 100644 index 0000000..365f553 --- /dev/null +++ b/Exceptions/EngagementNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un engagement n'a pas été trouvé + /// + public class EngagementNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Services/EngagementService.cs b/Services/EngagementService.cs index 320b0de..cab7c58 100644 --- a/Services/EngagementService.cs +++ b/Services/EngagementService.cs @@ -1,4 +1,5 @@ using EPAServeur.Context; +using EPAServeur.Exceptions; using EPAServeur.IServices; using EPAServeur.Models.EP; using EPAServeur.Models.Formation; @@ -57,8 +58,8 @@ namespace EPAServeur.Services else engagements = epContext.Engagement.Include(engagement => engagement.Ep); - if (engagements == null) - return null; + if (engagements == null || engagements.Count() == 0) + return new List(); var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); @@ -82,12 +83,13 @@ namespace EPAServeur.Services else engagements = await epContext.Engagement.Include(engagement => engagement.Ep).ToListAsync(); - if (engagements == null) - return null; + if (engagements == null || engagements.Count() == 0) + return new List(); - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); - return engagementDTOs; + return results; } public IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) @@ -107,8 +109,8 @@ namespace EPAServeur.Services else engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToList(); - if (engagements == null) - return null; + if (engagements == null || engagements.Count() == 0) + return new List(); var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); @@ -132,13 +134,13 @@ namespace EPAServeur.Services else engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToListAsync(); + if (engagements == null || engagements.Count() == 0) + return new List(); - if (engagements == null) - return null; + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); - var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); - - return engagementDTOs; + return results; } public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) @@ -158,9 +160,8 @@ namespace EPAServeur.Services else engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)); - - if (engagements == null) - return null; + if (engagements == null || engagements.Count() == 0) + return new List(); var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); @@ -184,8 +185,8 @@ namespace EPAServeur.Services else engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)).ToListAsync(); - if (engagements == null) - return null; + 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); @@ -203,22 +204,36 @@ namespace EPAServeur.Services { if (!IsEngagementValide(engagementDTO)) - return null; + throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); + + if (engagementDTO.Realise == false && 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(); - if (engagementDTO.Id != idEngagement) - return null; Engagement engagement = epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefault(engagement => engagement.Id == idEngagement); if (engagement == null) - return null; + throw new EngagementNotFoundException(); engagement.Realise = engagementDTO.Realise; - if (engagement.Realise == false) + switch (engagement.Realise) { - engagement.Realisable = engagementDTO.Realisable; - engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + case true: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = null; + break; + case false: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + break; + default: + engagement.Realisable = null; + engagement.RaisonNonRealisable = null; + break; } epContext.SaveChanges(); @@ -237,22 +252,33 @@ namespace EPAServeur.Services { if (!IsEngagementValide(engagementDTO)) - return null; + throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); + + if (engagementDTO.Realise == false && 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.Id != idEngagement) - return null; Engagement engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.Id == idEngagement); if (engagement == null) - return null; + throw new EngagementNotFoundException(); engagement.Realise = engagementDTO.Realise; - if (engagement.Realise == false) + switch (engagement.Realise) { - engagement.Realisable = engagementDTO.Realisable; - engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + case true: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = null; + break; + case false: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + break; + default: + engagement.Realisable = null; + engagement.RaisonNonRealisable = null; + break; } await epContext.SaveChangesAsync(); @@ -266,7 +292,7 @@ namespace EPAServeur.Services #region Méthodes Privée private bool IsEngagementValide(EngagementDTO engagementDTO) { - return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null || (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable))); + return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null); } #region Object to DTO From f97cce68b4a88ea8a6ce2786cbeb152df2c489e0 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 18:05:53 +0200 Subject: [PATCH 15/16] =?UTF-8?q?Modification=20de=20la=20m=C3=A9thode=20G?= =?UTF-8?q?ET=20GetCollaborateursByReferent=20en=20async?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/CollaborateursApi.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Controllers/CollaborateursApi.cs b/Controllers/CollaborateursApi.cs index 1e2f473..29a4dbe 100644 --- a/Controllers/CollaborateursApi.cs +++ b/Controllers/CollaborateursApi.cs @@ -206,11 +206,11 @@ namespace IO.Swagger.Controllers //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)); logger.LogInformation("Récupération de la liste des collaborateurs du référent {idReferent}",idReferent); - IEnumerable collaborateurs = await collaborateurService.GetCollaborateursByReferentAsync(idReferent, asc, numPage, parPAge, texte, tri); + IEnumerable collaborateurs = null; try { - collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); - } + collaborateurs = await collaborateurService.GetCollaborateursByReferentAsync(idReferent, asc, numPage, parPAge, texte, tri); + } catch (ApiException) { logger.LogError("Une erreur est survenue lors de la communication avec le service collaborateur lors de la récupération de la liste des collaborateurs du référent {idReferent}", idReferent); From 051b2fb731003bbee45863e76f5674793045ea14 Mon Sep 17 00:00:00 2001 From: jboinembalome Date: Mon, 21 Sep 2020 18:22:06 +0200 Subject: [PATCH 16/16] Modification des exceptions --- Controllers/FormationsApi.cs | 32 +++++++++++++++++++ .../FormationIncompatibleIdException.cs | 2 +- Exceptions/FormationInvalidException.cs | 2 +- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index 6c58dde..4ed3f3a 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -162,6 +162,10 @@ namespace IO.Swagger.Controllers { formations = await formationService.GetFormationAnnuleesAsync(asc, numPage, parPAge, idAgence, texte, tri); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations annulées est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations annulées."); @@ -270,6 +274,10 @@ namespace IO.Swagger.Controllers { formations = await formationService.GetFormationRealiseeAsync(asc, numPage, parPAge, idAgence, texte, tri); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations réalisées est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations réalisées."); @@ -322,6 +330,10 @@ namespace IO.Swagger.Controllers { formations = await formationService.GetFormationsAsync(asc, numPage, parPAge, idAgence, statutFormation, texte, tri); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations."); @@ -366,6 +378,10 @@ namespace IO.Swagger.Controllers { modeFormations = await formationService.GetModesFormationAsync(); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des modes de formation est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des modes de formation."); @@ -410,6 +426,10 @@ namespace IO.Swagger.Controllers { origineFormations = await formationService.GetOriginesFormationAsync(); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des origines de formation est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des origines de formation."); @@ -461,6 +481,10 @@ namespace IO.Swagger.Controllers { formations = await formationService.GetProchainesFormationAsync(asc, numPage, parPAge, idAgence, texte, tri); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des prochaines formations est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des prochaines formations."); @@ -505,6 +529,10 @@ namespace IO.Swagger.Controllers { statutFormations = await formationService.GetStatutsFormationAsync(); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des statuts de formation est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des statuts de formation."); @@ -549,6 +577,10 @@ namespace IO.Swagger.Controllers { typeFormations = await formationService.GetTypesFormationAsync(); } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des types de formation est invalide."); + } catch (Exception) { logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des types de formation."); diff --git a/Exceptions/FormationIncompatibleIdException.cs b/Exceptions/FormationIncompatibleIdException.cs index 2fc7201..99dcaf2 100644 --- a/Exceptions/FormationIncompatibleIdException.cs +++ b/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 à mettre sont différents + /// 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 /// public class FormationIncompatibleIdException : Exception { diff --git a/Exceptions/FormationInvalidException.cs b/Exceptions/FormationInvalidException.cs index 0d5e444..8b72fe2 100644 --- a/Exceptions/FormationInvalidException.cs +++ b/Exceptions/FormationInvalidException.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace EPAServeur.Exceptions { /// - /// Exception à jeter lorsq'une formation est invalide + /// Exception à jeter lorsqu'une formation est invalide /// public class FormationInvalidException : Exception {