diff --git a/ApiCollaborateur/ReferentApi.cs b/ApiCollaborateur/ReferentApi.cs index d36c4f1..c49c8f0 100644 --- a/ApiCollaborateur/ReferentApi.cs +++ b/ApiCollaborateur/ReferentApi.cs @@ -45,7 +45,7 @@ namespace IO.Swagger.ApiCollaborateur /// ApiResponse of Referent ApiResponse ChercherRefActuelCollabIdWithHttpInfo (Guid? collabId); /// - /// rechercher le référent qui a le plus suivi + /// rechercher le référent actuel /// /// /// rechercher le référent actuel du collaborateur à l'aide de son identifiant @@ -56,7 +56,7 @@ namespace IO.Swagger.ApiCollaborateur Referent ChercherRefActuelCollabMail (string mailApside); /// - /// rechercher le référent qui a le plus suivi + /// rechercher le référent actuel /// /// /// rechercher le référent actuel du collaborateur à l'aide de son identifiant diff --git a/Controllers/CollaborateursApi.cs b/Controllers/CollaborateursApi.cs index ead8209..1e2f473 100644 --- a/Controllers/CollaborateursApi.cs +++ b/Controllers/CollaborateursApi.cs @@ -19,6 +19,11 @@ using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; using EPAServeur.IServices; +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 { @@ -29,9 +34,11 @@ namespace IO.Swagger.Controllers public class CollaborateursApiController : ControllerBase { private readonly ICollaborateurService collaborateurService; - public CollaborateursApiController(ICollaborateurService _collaborateurService) + private readonly ILogger logger; + public CollaborateursApiController(ICollaborateurService _collaborateurService, ILogger _logger) { collaborateurService = _collaborateurService; + logger = _logger; } /// /// @@ -49,21 +56,35 @@ 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)); - - CollaborateurDTO collaborateurDTO = collaborateurService.GetCollaborateurById(idCollaborateur); - if( collaborateurDTO == null) + logger.LogInformation("Récupération du collaborateur d'ID {idCollaborateur}", idCollaborateur); + CollaborateurDTO collaborateurDTO = null; + try { + collaborateurDTO = await collaborateurService.GetCollaborateurByIdAsync(idCollaborateur); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le collaborateur par son id {idCollaborateur}", idCollaborateur); + } + catch (CollaborateurNotFoundException) + { + logger.LogError("Le ccollaborateur {id} est introuvable", idCollaborateur); 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 du collaborateur {idCollaborateur}", idCollaborateur); + } + logger.LogInformation("Collaborateur {id} trouvée", idCollaborateur); return Ok(collaborateurDTO); } @@ -83,23 +104,36 @@ 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)); - - CollaborateurDTO collaborateurDTO = collaborateurService.GetCollaborateurByMail(mail); - if (collaborateurDTO == null) + logger.LogInformation("Récupération d'un collaborateur par le mail {mail}", mail); + CollaborateurDTO collaborateurDTO = null; + try { + collaborateurDTO = await collaborateurService.GetCollaborateurByMailAsync(mail); + } + catch (CollaborateurNotFoundException) + { + logger.LogError("Le ccollaborateur {mail} est introuvable", mail); ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", - Message = "Aucun collaborateur n'est lié au mail "+mail, + Message = "Aucun collaborateur n'est lié au mail " + mail, }; return NotFound(erreurDTO); } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le collaborateur par son mail {mail}", mail); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du collaborateur {mail}", mail); + } + logger.LogInformation("Collaborateur {mail} trouvée", mail); return Ok(collaborateurDTO); - } /// @@ -123,12 +157,26 @@ 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)); - - return Ok(collaborateurService.GetCollaborateurs(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri)); + logger.LogInformation("Récupération de la liste des collaborateurs"); + IEnumerable collaborateurs = null; + try + { + collaborateurs = await collaborateurService.GetCollaborateursAsync(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri); + } + catch(ApiException) + { + logger.LogError("Une erreur est survenue lors de la discussion avec le service Collaborateur pour récupérer la liste des collaborateurs"); + } + catch(Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des collaborateurs"); + } + logger.LogInformation("Liste des collaborateurs récupérée"); + return Ok(collaborateurs); } @@ -153,12 +201,21 @@ 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)); - IEnumerable collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); - if(collaborateurs == null) + 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); + try + { + collaborateurs = collaborateurService.GetCollaborateursByReferent(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); + } + catch (ReferentNotFoundException) { ErreurDTO erreurDTO = new ErreurDTO() { @@ -167,6 +224,11 @@ namespace IO.Swagger.Controllers }; return NotFound(erreurDTO); } + catch (Exception) + { + logger.LogError("Uner erreur inconnue est survenue lors de la récupération des collaborateurs du référent {idReferent}", idReferent); + } + logger.LogInformation("Liste des collaborateurs du référent {idReferent} récupérée", idReferent); return Ok(collaborateurs); } @@ -186,14 +248,23 @@ 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)); - - ProfilDTO collaborateurDTO = collaborateurService.GetProfilByMail(mail); - if (collaborateurDTO == null) + logger.LogInformation("Récupération du profil par la mail {mail}", mail); + ProfilDTO collaborateurDTO = null; + try + { + collaborateurDTO = await collaborateurService.GetProfilByMailAsync(mail); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service collaborateur lors de la récupération du profil par le mail {mail}", mail); + } + catch (CollaborateurNotFoundException) { + logger.LogError("Aucun collaborateur n'est lié au mail {mail}", mail); ErreurDTO erreurDTO = new ErreurDTO() { Code = "404", @@ -201,6 +272,11 @@ namespace IO.Swagger.Controllers }; return NotFound(erreurDTO); } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du profil d'un collaborateur par le mail {mail}", mail); + } + logger.LogInformation("Profil du mail {mail} récupéré", mail); return Ok(collaborateurDTO); } } diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index ba84147..6c58dde 100644 --- a/Controllers/FormationsApi.cs +++ b/Controllers/FormationsApi.cs @@ -11,16 +11,16 @@ 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; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using EPAServeur.Exceptions; +using Microsoft.EntityFrameworkCore; namespace IO.Swagger.Controllers { @@ -31,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; } /// @@ -50,19 +52,32 @@ 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); + 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); - //if (body.Id != null && body.Id > 0) - //{ - // return StatusCode(201, body); - //} - //else - //{ - // return NotFound(); - //} } /// @@ -78,17 +93,41 @@ 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)) + 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(); } @@ -113,10 +152,21 @@ 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); + 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() @@ -124,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); } @@ -146,18 +199,43 @@ 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)); - 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); } @@ -182,10 +260,21 @@ 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); + 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() @@ -193,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); } @@ -220,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 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); + 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() @@ -231,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); } @@ -250,10 +356,21 @@ 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(); + 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() @@ -261,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); } @@ -280,10 +400,21 @@ 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(); + 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() @@ -294,6 +425,8 @@ namespace IO.Swagger.Controllers return NotFound(erreur); } + logger.LogInformation("Liste des origines de formation récupérée."); + return Ok(origineFormations); } @@ -318,10 +451,21 @@ 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); + 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() @@ -329,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); } @@ -348,10 +495,21 @@ 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(); + 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() @@ -359,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); } @@ -378,10 +539,21 @@ 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(); + 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() @@ -389,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); } @@ -410,29 +585,64 @@ 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(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); } - return Ok(formation); + logger.LogInformation("Update effectué avec succès"); - //switch (formationService.UpdateFormation(body)) - //{ - // case 0: - // return Ok(); - // case 1: - // return StatusCode(201); - // case 2: - // return Forbid(); - // default: - // return NotFound(); - //} - + return Ok(formation); } } } diff --git a/Controllers/NotesApi.cs b/Controllers/NotesApi.cs index 1422250..75d4f17 100644 --- a/Controllers/NotesApi.cs +++ b/Controllers/NotesApi.cs @@ -18,9 +18,13 @@ using IO.Swagger.Attributes; using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; -using EPAServeur.Services; using EPAServeur.IServices; using EPAServeur.Models.Notes; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; +using EPAServeur.Exceptions; +using Microsoft.OpenApi.Expressions; +using IO.Swagger.ClientCollaborateur; namespace IO.Swagger.Controllers { @@ -31,10 +35,12 @@ namespace IO.Swagger.Controllers public class NotesApiController : ControllerBase { private readonly INoteService noteService; + private readonly ILogger logger; - public NotesApiController(INoteService _noteService) + public NotesApiController(INoteService _noteService, ILogger _logger) { noteService = _noteService; + logger = _logger; } /// @@ -54,17 +60,36 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual IActionResult DeleteNote([FromRoute][Required]long? idNote) { - //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)); - if(!noteService.SupprimerNote(idNote)) + //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... + // return StatusCode(403, default(ErreurDTO)); + try + { + logger.LogInformation("Suppresion de la note {idNote}", idNote); + noteService.SupprimerNote(idNote); + + } + catch(NoteNotFoundException) { + logger.LogError("Impossible de supprimer la note d'id {idNote} car elle n'existe pas", idNote); ErreurDTO erreur = new ErreurDTO() { Code = "404", Message = "Aucune note trouvé" }; return NotFound(erreur); - }; + } + catch(DbUpdateConcurrencyException) { + logger.LogWarning("La note {idNote} n'a pas pu être supprimé car elle était prise par une autre ressource.", idNote); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur a eu lieu, la note {idNote} n'a pas pu être supprimée.", idNote); + } + catch(Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la suppression de la note {idNote}",idNote); + } + logger.LogInformation("Note {idNote} supprimée avec sucès", idNote); return NoContent(); } @@ -88,16 +113,36 @@ 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)); - DetailsNoteDTO note = noteService.GetNoteById(idNote); - if(note == null) + logger.LogInformation("Récupération de la note {idNote}", idNote); + DetailsNoteDTO note = null; + try + { + note = noteService.GetNoteById(idNote); + } + catch(NoteNotFoundException) { + logger.LogError("Aucune note ne correspond à l'id {idNote} recherchée", idNote); ErreurDTO erreur = new ErreurDTO() { Code = "404", Message = "Aucune note n'a été trouvée" }; return NotFound(erreur); + } + catch (DbUpdateConcurrencyException) + { + logger.LogWarning("La note {idNote} n'a pas pu être récupérée car elle était prise par une autre ressource.", idNote); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur a eu lieu, la note {idNote} n'a pas pu être récupérée.", idNote); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la note {idNote}", idNote); + } + logger.LogInformation("Note d'id {idNote} trouvée",idNote); return Ok(note); } @@ -121,18 +166,12 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] public virtual IActionResult GetNotes([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); + //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 \"idCollaborateur\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"dateMiseAjour\" : \"2000-01-23T04:56:07.000+00:00\",\n \"titre\" : \"titre\",\n \"id\" : 0,\n \"collaborateur\" : \"collaborateur\"\n}, {\n \"idCollaborateur\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"dateMiseAjour\" : \"2000-01-23T04:56:07.000+00:00\",\n \"titre\" : \"titre\",\n \"id\" : 0,\n \"collaborateur\" : \"collaborateur\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + //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(); } /// @@ -158,18 +197,41 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] public virtual IActionResult GetNotesByAuteur([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)); - IEnumerable notes = noteService.GetNotesByAuteur(idReferent, asc, numPage, parPAge, texte, tri); - if(notes == null) + //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 des notes de l'auteur d'id {idReferent}", idReferent); + IEnumerable notes = null; + try + { + notes = noteService.GetNotesByAuteur(idReferent, asc, numPage, parPAge, texte, tri); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la discussion avec le service Collaborateur"); + } + catch (ReferentNotFoundException) { + logger.LogError("Le référent {idReferent} n'a pas été trouvé", idReferent); ErreurDTO erreur = new ErreurDTO() { Code = "404", Message = "Aucun id ne correspond au référent" }; return NotFound(erreur); - } + } + catch (DbUpdateConcurrencyException) + { + logger.LogWarning("Les notes du référents {idReferent} n'ont pas pu être récupérées car une ou plusieurs notes sont prises par une autre ressource.", idReferent); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur dans la base de données est survenue lors de la récupération des notes du référent {idRefrent}", idReferent); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération des notes du référebt {idReferent}", idReferent); + } + logger.LogInformation("Liste des notes de l'auteur {idReferent} récupérée", idReferent); return Ok(notes); } @@ -199,16 +261,50 @@ 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)); - IEnumerable notes = noteService.GetNotesByCollaborateur(idReferent, idCollaborateur, asc, numPage, parPAge, texte, tri); - if (notes == null) + logger.LogInformation("Récupération des notes de l'auteur {idReferent} sur un collaborateur {idCollaborateur}", idReferent, idCollaborateur); + IEnumerable notes = null; + try + { + notes = noteService.GetNotesByCollaborateur(idReferent, idCollaborateur, asc, numPage, parPAge, texte, tri); + + } + catch (ApiException) { + logger.LogError("Une erreur est survenue lors de la discussion avec le service Collaborateur"); + } + catch (CollaborateurNotFoundException) + { + logger.LogError("Le référent {idReferent} n'a pas été trouvé", idReferent); + ErreurDTO erreur = new ErreurDTO() + { + Code = "404", + Message = "Aucun id ne correspond au référent" + }; + return NotFound(erreur); + } + catch(ReferentNotFoundException) + { + logger.LogError("Le collaborateur {idCollaborateur} n'a pas été trouvé", idCollaborateur); ErreurDTO erreur = new ErreurDTO() { Code = "404", - Message = "Aucun id ne correspond au référent et/ou au collaborateur" + Message = "Aucun id ne correspond au collaborateur" }; return NotFound(erreur); } + catch (DbUpdateConcurrencyException) + { + logger.LogWarning("Les notes du référents {idReferent} n'ont pas pu être récupérées pour le collaborateur {idCollaborateur} car une ou plusieurs notes sont prises par une autre ressource", idReferent, idCollaborateur); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur a eu lieu dans la base de données lors de la récupération des notes du référent {idReferent} pour le collaborateur {idCollaborateur}.", idReferent, idCollaborateur); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue a eu lieu lors de la récupération des notes du référent { idReferent} pour le collaborateur { idCollaborateur}.", idReferent, idCollaborateur); + } + logger.LogInformation("Liste des notes de l'auteur {idReferent} sur un collaborateur {idCollaborateur} trouvée", idReferent, idCollaborateur); return Ok(notes); } @@ -229,7 +325,16 @@ 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)); - Note nouvelleNote = noteService.AjouterNote(body); + logger.LogInformation("Ajout d'une nouvelle note"); + DetailsNoteDTO nouvelleNote = null; + try + { + nouvelleNote = noteService.AjouterNote(body); + } + catch (NoteInvalideException) { logger.LogWarning("Des données sont manquants, la nouvelle note 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 note"); } + catch(Exception) { logger.LogError("Une erreur inconnue est survenue lors de l'ajout de la nouvelle note"); } + logger.LogInformation("Nouvelle note ajoutée"); return Created("",nouvelleNote); } @@ -248,17 +353,47 @@ namespace IO.Swagger.Controllers [ValidateModelState] [SwaggerOperation("UpdateNote")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult UpdateNote([FromBody]DetailsNoteDTO body, [FromRoute][Required]long? idNote) + public virtual IActionResult UpdateNote([FromBody] DetailsNoteDTO body, [FromRoute][Required] long? idNote) { //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)); - - Note note = noteService.UpdateNote(idNote, body); - if (note == null) - note = noteService.AjouterNote(body); + logger.LogInformation("Mise à jour de la note d'id {idNote}", idNote); + DetailsNoteDTO note = null; + try + { + note = noteService.UpdateNote(idNote, body); + } + catch(ApiException) + { + logger.LogError("Une erreur est survenue lors de la discussion avec le service Collaborateur"); + } + catch(NoteIdImcompatibleException) + { + logger.LogError("L'id de la note à mettre à jour {body.Id} et l'id de la note avec les nouvelels information {idNote} sont différents", body.Id, idNote); + } + catch(NoteNotFoundException) + { + logger.LogError("La note {idNote} n'a pas pu être mise à jour car elle n'existe pas", idNote); + } + catch (NoteInvalideException) + { + logger.LogWarning("Des données sont manquants, la note {idNote} ne peut pas être mise à jour", idNote); + } + catch (DbUpdateConcurrencyException) + { + logger.LogError("La note {idNote} n'a pas pu être mise à jour car elle été prise par une autre ressource", idNote); + } + catch(DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données lors de la mise à jour de la note {idNote}", idNote); + } + catch(Exception) { + logger.LogError("Une erreur inconnue est survenue lors de la mise à jour de la note {idNote}", idNote); + } + logger.LogInformation("Update effectué avec succès"); return Ok(note); //TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(201); } } -} +} \ No newline at end of file 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/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/EPAServeur.csproj b/EPAServeur.csproj index c4915ce..5900bca 100644 --- a/EPAServeur.csproj +++ b/EPAServeur.csproj @@ -10,6 +10,7 @@ + diff --git a/Exceptions/CollaborateurNotFoundException.cs b/Exceptions/CollaborateurNotFoundException.cs new file mode 100644 index 0000000..a753e13 --- /dev/null +++ b/Exceptions/CollaborateurNotFoundException.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter quand le collaborateur n'est pas trouvé + /// + public class CollaborateurNotFoundException : Exception + { + } +} 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/NoteIdImcompatibleException.cs b/Exceptions/NoteIdImcompatibleException.cs new file mode 100644 index 0000000..8a3e5f3 --- /dev/null +++ b/Exceptions/NoteIdImcompatibleException.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsque l'id de la note avec les données à mettre à jour et l'id de la note à mettre sont différents + /// + public class NoteIdImcompatibleException : Exception + { + } +} diff --git a/Exceptions/NoteInvalideException.cs b/Exceptions/NoteInvalideException.cs new file mode 100644 index 0000000..e85526e --- /dev/null +++ b/Exceptions/NoteInvalideException.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter quand l'objet détails note contient des valeurs null + /// + public class NoteInvalideException : Exception + { + } +} diff --git a/Exceptions/NoteNotFoundException.cs b/Exceptions/NoteNotFoundException.cs new file mode 100644 index 0000000..4244e57 --- /dev/null +++ b/Exceptions/NoteNotFoundException.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter quand la note n'a pas été trouvée + /// + public class NoteNotFoundException : Exception + { + + } +} 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/ReferentNotFoundException.cs b/Exceptions/ReferentNotFoundException.cs new file mode 100644 index 0000000..3559ada --- /dev/null +++ b/Exceptions/ReferentNotFoundException.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter quand le référent n'a pas été trouvée + /// + public class ReferentNotFoundException : Exception + { + } +} 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/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/IServices/IFormationService.cs b/IServices/IFormationService.cs index dbe8278..6b455c8 100644 --- a/IServices/IFormationService.cs +++ b/IServices/IFormationService.cs @@ -10,19 +10,31 @@ namespace EPAServeur.IServices { public interface IFormationService { - FormationDTO GetFormationById(long? id); - - IEnumerable GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); + FormationDTO GetFormationById(long? idFormation); + Task GetFormationByIdAsync(long? idFormation); + 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); + 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); - FormationDTO UpdateFormation(FormationDTO formationDTO); - bool DeleteFormationById(long? id); + Task AddFormationAsync(FormationDTO formationDTO); + FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO); + Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO); + FormationDTO DeleteFormationById(long? idFormation); + Task DeleteFormationByIdAsync(long? idFormation); + } } diff --git a/IServices/INoteService.cs b/IServices/INoteService.cs index ee1c5ce..6b69c12 100644 --- a/IServices/INoteService.cs +++ b/IServices/INoteService.cs @@ -15,8 +15,8 @@ namespace EPAServeur.IServices public IEnumerable GetNotesByAuteur(Guid? idAuteur, bool? asc, int? numPage, int? parPAge, string texte, string tri); public DetailsNoteDTO GetNoteById(long? idNote); public IEnumerable GetNotesByCollaborateur(Guid? idAuteur, Guid? idCollaborateur, bool? asc, int? numPage, int? parPAge, string texte, string tri); - public Note AjouterNote(DetailsNoteDTO nouvelleNote); - public bool SupprimerNote(long? idNote); - public Note UpdateNote(long? idNote, DetailsNoteDTO note); + public DetailsNoteDTO AjouterNote(DetailsNoteDTO nouvelleNote); + public void SupprimerNote(long? idNote); + public DetailsNoteDTO UpdateNote(long? idNote, DetailsNoteDTO note); } } diff --git a/Program.cs b/Program.cs index dda309a..65abc7a 100644 --- a/Program.cs +++ b/Program.cs @@ -21,6 +21,10 @@ namespace EPAServeur public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureLogging(logging => + { + //logging.ClearProviders(); + }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json index 9790dad..0c92275 100644 --- a/Properties/launchSettings.json +++ b/Properties/launchSettings.json @@ -12,7 +12,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "api/notes/1", + "launchUrl": "api/", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/Services/CollaborateurService.cs b/Services/CollaborateurService.cs index f098c48..37137b6 100644 --- a/Services/CollaborateurService.cs +++ b/Services/CollaborateurService.cs @@ -1,4 +1,5 @@ using EPAServeur.Context; +using EPAServeur.Exceptions; using EPAServeur.IServices; using IO.Swagger.ApiCollaborateur; using IO.Swagger.DTO; @@ -6,39 +7,103 @@ using IO.Swagger.ModelCollaborateur; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Threading.Tasks; namespace EPAServeur.Services { + /// + /// Service permettant de récupérer les informations collaborateurs. + /// public class CollaborateurService : ICollaborateurService { + #region Variables + /// + /// API pour accéder aux données collaborateur en passant par le service collaborateur + /// private readonly ICollaborateurApi collaborateurApi; + #endregion + #region Constructeurs public CollaborateurService(ICollaborateurApi _collaborateurApi) { collaborateurApi = _collaborateurApi; } + #endregion - + #region Services + /// + /// Récupérer un collaborateur en fonction d'un id + /// + /// Identifiant du collaborateur à renvoyer + /// Le collaborateur corresponant à l'id en paramètre public CollaborateurDTO GetCollaborateurById(Guid? id) { Collaborateur collaborateur = collaborateurApi.ChercherCollabId(id); if (collaborateur == null) - return null; + throw new CollaborateurNotFoundException(); + 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 + /// + /// Mail du collaborateur à renvoyer + /// Le collaborateur correspondant au mail en paramètre public CollaborateurDTO GetCollaborateurByMail(string mail) { Collaborateur collaborateur = collaborateurApi.ChercherCollabMail(mail); if (collaborateur == null) - return null; + throw new CollaborateurNotFoundException(); 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 + /// + /// + /// 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 IEnumerable GetCollaborateurs(bool? asc, int? numPage, int? parPage, List fonctions, long? idAgence, long? idBU, string texte, string tri) { if (texte == null) @@ -64,15 +129,78 @@ namespace EPAServeur.Services return collaborateursDTO; } - public IEnumerable GetCollaborateursByReferent(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri) + /// + /// 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 + /// + /// 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 IEnumerable GetCollaborateursByReferent(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 = collaborateurApi.ChercherCollabId(idReferent); if (referent == null) - return null; + throw new ReferentNotFoundException(); + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); IEnumerable collaborateurs = collaborateurApi.ChercherCollabRef(idReferent); int skip = (numPage.Value - 1) * parPage.Value; int take = parPage.Value; @@ -82,23 +210,120 @@ 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 + /// + /// mail du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant au mail passé en paramètre public ProfilDTO GetProfilByMail(string mail) { Collaborateur collaborateur = collaborateurApi.ChercherCollabMail(mail); if (collaborateur == null) - return null; + throw new CollaborateurNotFoundException(); 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 + /// + /// id du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant à l'id passé en paramètre public ProfilDTO GetProfilById(Guid? idCollaborateur) { + //Stopwatch stopwatch = new Stopwatch(); + //stopwatch.Start(); Collaborateur collaborateur = collaborateurApi.ChercherCollabId(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) - return null; + throw new CollaborateurNotFoundException(); return GetProfilDTO(collaborateur); } - //Object to DTO + /// + /// 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 + + /// + /// Transformer un objet collaborateur en ProfilDTO + /// + /// collaborateur a transformé en profilDTO + /// Renvoie le profil associé au collaborateur passé en paramètre private ProfilDTO GetProfilDTO(Collaborateur collaborateur) { ProfilDTO profilDTO = new ProfilDTO() @@ -113,7 +338,11 @@ namespace EPAServeur.Services return profilDTO; } - + /// + /// Transformer une agence en agenceDTO + /// + /// agence à transformer en agenceDTO + /// Retourne la transformation DTO de l'agence private AgenceDTO GetAgenceDTO(Agence agence) { if (agence == null) @@ -132,6 +361,11 @@ namespace EPAServeur.Services return agenceDTO; } + /// + /// Transforme une businessUnit en businessUnitDTO + /// + /// businessUnit à transformer en businessUnitDTO + /// Retourne la transformation DTO de la businessUnit private BusinessUnitDTO GetBusinessUnitDTO(BU businessUnit) { if (businessUnit == null) @@ -145,6 +379,11 @@ namespace EPAServeur.Services return businessUnitDTO; } + /// + /// Transforme un collaborateur en collaborateurDTO + /// + /// collaborateur à transformer en collaborateurDTO + /// Renvoie la transformation DTO du collaborateur private CollaborateurDTO GetCollaborateurDTO(Collaborateur collaborateur) { CollaborateurDTO collaborateurDTO = new CollaborateurDTO() @@ -161,6 +400,11 @@ namespace EPAServeur.Services return collaborateurDTO; } + /// + /// Transforme un referent en referentDTO + /// + /// referent à transformer en referentDTO + /// Renvoie la transformation DTO du referent private ReferentDTO GetReferentDTO(Referent referent) { if (referent == null) @@ -174,5 +418,6 @@ namespace EPAServeur.Services }; return referentDTO; } + #endregion } } diff --git a/Services/FormationService.cs b/Services/FormationService.cs index 775bf3d..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; @@ -6,6 +7,7 @@ using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; namespace EPAServeur.Services { @@ -35,18 +37,37 @@ 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; + throw new FormationNotFoundException(); + + 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) + throw new FormationNotFoundException(); return GetFormationDTO(formation); } @@ -61,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; @@ -74,39 +95,113 @@ 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) + 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 + { + formations = epContext.Formation.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation) .Include(formation => formation.Origine) .Include(formation => formation.TypeFormation); - } - 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 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, int? statutFormation, string texte, string tri) + { + IEnumerable formations; + IEnumerable formationDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (statutFormation != null && idAgence != null) + { + formations = await epContext.Formation + .Include(formation => formation.Statut) + .Include(formation => formation.ModeFormation) + .Include(formation => formation.Origine) + .Include(formation => formation.TypeFormation) + .Where(formation => formation.Statut.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 = epContext.Formation.Include(formation => formation.Statut) - .Include(formation => formation.ModeFormation) - .Include(formation => formation.Origine) - .Include(formation => formation.TypeFormation); - } - 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(); + } if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -150,7 +245,51 @@ 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)); + + 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)); @@ -182,39 +321,80 @@ 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 + { + + 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); + + } + + + 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 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) + { + + 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 = 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 = 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(); } if (formations == null) - return new List(); + return null; formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); @@ -245,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)) @@ -268,7 +443,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)); @@ -276,22 +451,87 @@ namespace EPAServeur.Services } /// - /// Récupérer les modes de formation + /// 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 IEnumerable GetModesFormation() + public async Task> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri) { - IEnumerable modeFormations; - IEnumerable modeFormationDTOs; - try + 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) { - modeFormations = epContext.ModeFormation; + 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) + + else { - throw; + 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 + /// + /// + public IEnumerable GetModesFormation() + { + IEnumerable modeFormations; + IEnumerable modeFormationDTOs; + + modeFormations = epContext.ModeFormation; + + if (modeFormations == null) + return null; + + modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); + + return modeFormationDTOs; + } + + /// + /// Récupérer les modes de formation de manière asynchrone + /// + /// + public async Task> GetModesFormationAsync() + { + IEnumerable modeFormations; + IEnumerable modeFormationDTOs; + modeFormations = await epContext.ModeFormation.ToListAsync(); + + if (modeFormations == null) + return null; + modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); return modeFormationDTOs; @@ -306,14 +546,29 @@ namespace EPAServeur.Services IEnumerable origineFormations; IEnumerable origineFormationDTOs; - try - { - origineFormations = epContext.OrigineFormation; - } - catch (Exception ex) - { - throw; - } + origineFormations = epContext.OrigineFormation; + + if (origineFormations == null) + return null; + + origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); + + return origineFormationDTOs; + } + + /// + /// Récupérer les origines de formation de manière asynchrone + /// + /// + public async Task> GetOriginesFormationAsync() + { + IEnumerable origineFormations; + IEnumerable origineFormationDTOs; + + origineFormations = await epContext.OrigineFormation.ToListAsync(); + + if (origineFormations == null) + return null; origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); @@ -329,15 +584,29 @@ namespace EPAServeur.Services IEnumerable statutFormations; IEnumerable statutFormationDTOs; - try - { - statutFormations = epContext.StatutFormation; - } - catch (Exception ex) - { + statutFormations = epContext.StatutFormation; - throw; - } + if (statutFormations == null) + return null; + + statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); + + return statutFormationDTOs; + } + + /// + /// Récupérer les statuts de formation de manière asynchrone + /// + /// + public async Task> GetStatutsFormationAsync() + { + IEnumerable statutFormations; + IEnumerable statutFormationDTOs; + + statutFormations = await epContext.StatutFormation.ToListAsync(); + + if (statutFormations == null) + return null; statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); @@ -353,14 +622,29 @@ namespace EPAServeur.Services IEnumerable typeFormations; IEnumerable typeFormationDTOs; - try - { - typeFormations = epContext.TypeFormation; - } - catch (Exception ex) - { - throw; - } + typeFormations = epContext.TypeFormation; + + if (typeFormations == null) + return null; + + typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); + + return typeFormationDTOs; + } + + /// + /// Récupérer les types de formation de manière asynchrone + /// + /// + public async Task> GetTypesFormationAsync() + { + IEnumerable typeFormations; + IEnumerable typeFormationDTOs; + + typeFormations = await epContext.TypeFormation.ToListAsync(); + + if (typeFormations == null) + return null; typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); @@ -374,27 +658,47 @@ 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); + } + + /// + /// Ajouter une formation de manière asynchrone + /// + /// + /// + 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); + + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } @@ -402,26 +706,50 @@ namespace EPAServeur.Services /// /// Modifier une formation /// + /// /// /// - public FormationDTO UpdateFormation(FormationDTO formationDTO) + public FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO) { - Formation formation = epContext.Formation.FirstOrDefault(formation => formation.Id == formationDTO.Id); + 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); + } + + /// + /// Modifier une formation de manière asynchrone + /// + /// + /// + /// + public async Task UpdateFormationAsync(long? idFormation, FormationDTO formationDTO) + { + if (!IsFormationValide(formationDTO)) + throw new FormationInvalidException(); + + if (formationDTO == null && !formationDTO.Id.HasValue && formationDTO.Id.Value != idFormation) + throw new FormationIncompatibleIdException(); + + Formation formation = await epContext.Formation.FindAsync(idFormation); + + if (formation == null) + return null; + + formation = SetFormation(formation, formationDTO); + await epContext.SaveChangesAsync(); return GetFormationDTO(formation); } @@ -429,32 +757,54 @@ namespace EPAServeur.Services /// /// Supprimer une formation /// - /// + /// /// - public bool DeleteFormationById(long? id) + public FormationDTO DeleteFormationById(long? idFormation) { - Formation formation = epContext.Formation.FirstOrDefault(formation => formation.Id == id); + 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); } + /// + /// Supprimer une formation de manière asynchrone + /// + /// + /// + public async Task DeleteFormationByIdAsync(long? idFormation) + { + Formation formation = await epContext.Formation.FindAsync(idFormation); + + if (formation == null) + throw new FormationNotFoundException(); + + epContext.Remove(formation); + + await epContext.SaveChangesAsync(); + + 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 /// diff --git a/Services/NoteService.cs b/Services/NoteService.cs index 8399e86..64a59f7 100644 --- a/Services/NoteService.cs +++ b/Services/NoteService.cs @@ -1,4 +1,5 @@ using EPAServeur.Context; +using EPAServeur.Exceptions; using EPAServeur.IServices; using EPAServeur.Models.Notes; using IO.Swagger.DTO; @@ -11,31 +12,70 @@ using System.Threading.Tasks; namespace EPAServeur.Services { + /// + /// Service permettant de gérer les notes (ajout, récupération, mise à jour, suppression) + /// public class NoteService : INoteService { + #region Variables + /// + /// API pour accéder aux données collaborateur en passant par le service collaborateur + /// private readonly ICollaborateurService collaborateurService; + /// + /// Contexte pour interagir avec la base de données MySQL du serveur EP + /// private readonly EpContext context; - + #endregion + #region Constructeurs public NoteService(ICollaborateurService _collaborateurService, EpContext _context) { collaborateurService = _collaborateurService; context = _context; } + #endregion - public Note AjouterNote(DetailsNoteDTO nouvelleNote) + /// + /// Ajouter une nouvelle note dans la base de données + /// + /// La nouvelle note a ajouté en base + /// + public DetailsNoteDTO AjouterNote(DetailsNoteDTO nouvelleNote) { if (!IsDetailsNoteValide(nouvelleNote)) - return null; + throw new NoteInvalideException(); Note note = DetailsNoteDTOToNouvelleNote(nouvelleNote); context.Note.Add(note); context.SaveChanges(); - return note; + return NoteToDetailSDTO(note); } + #region Services + /// + /// Récupérer la liste des notes qu'un auteur a écrit sur un collaborateur + /// + /// Id de l'auteur des notes à récupérer + /// Id du collaborateur pour lesquelles les notes ont été écrites + /// 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 notes à renvoyer + /// permet de récupérer les notes les informations du collaborateur ou le titre de la note contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// Retour la liste des notes à afficher public IEnumerable GetNotesByCollaborateur(Guid? idAuteur, Guid? idCollaborateur, bool? asc, int? numPage, int? parPage, string texte, string tri) { + //Stopwatch stopwatch = new Stopwatch(); + //stopwatch.Start(); + if (collaborateurService.GetProfilById(idAuteur) == null) + throw new ReferentNotFoundException(); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution GetProfil 1: {0}", stopwatch.Elapsed.TotalSeconds); + //stopwatch.Restart(); if (collaborateurService.GetProfilById(idAuteur) == null || collaborateurService.GetProfilById(idCollaborateur) == null) - return null; + throw new CollaborateurNotFoundException(); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution GetProfil 2: {0}", stopwatch.Elapsed.TotalSeconds); + if (texte == null) texte = ""; else @@ -46,20 +86,22 @@ namespace EPAServeur.Services where n.IdAuteur == idAuteur && n.IdCollaborateur == idCollaborateur select NoteToAffichageDTO(n, collaborateurService)); AffichageNoteDTO = (from a in AffichageNoteDTO - where a.Collaborateur.ToLower().Contains(texte) || a.Titre.ToLower().Contains(texte) + where a.Titre.ToLower().Contains(texte) select a).Skip(skip).Take(take); return AffichageNoteDTO; } + /// + /// Récupérer une note en fonction de son id + /// + /// Id de la note à récupérer + /// L'objet DTO de la note correspondant à l'id passé en paramètre public DetailsNoteDTO GetNoteById(long? idNote) { Note note = context.Note.Find(idNote); if (note == null) - return null; + throw new NoteNotFoundException(); return NoteToDetailSDTO(note); - /*return (from n in context.Note - where n.Id == idNote - select NoteToDetailSDTO(n)).ToList().FirstOrDefault();*/ } public IEnumerable GetNotes(bool? asc, int? numPage, int? parPage, string texte, string tri) @@ -67,10 +109,20 @@ namespace EPAServeur.Services throw new NotImplementedException(); } + /// + /// Récupérer la liste des notes qu'un auteur a écrit sur un collaborateur + /// + /// Id de l'auteur des notes à 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 notes à renvoyer + /// permet de récupérer les notes les informations du collaborateur ou le titre de la note contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// Retour la liste des notes à afficher public IEnumerable GetNotesByAuteur(Guid? idAuteur, bool? asc, int? numPage, int? parPage, string texte, string tri) { if (collaborateurService.GetCollaborateurById(idAuteur) == null) - return null; + throw new CollaborateurNotFoundException(); if (texte == null) texte = ""; else @@ -93,37 +145,60 @@ namespace EPAServeur.Services return AffichageNoteDTO; } - public bool SupprimerNote(long? idNote) + /// + /// Supprimer une note en fonction de son Id + /// + /// Id de la note à supprimer + /// Si oui ou non la notea bien été supprimé + public void SupprimerNote(long? idNote) { Note note = context.Note.Find(idNote); if (note == null) - return false; + throw new NoteNotFoundException(); context.Remove(note); context.SaveChanges(); - return true; } - public Note UpdateNote(long? idNote, DetailsNoteDTO note) + /// + /// Mettre à jour une note + /// + /// Id de la note à modifier + /// + /// + public DetailsNoteDTO UpdateNote(long? idNote, DetailsNoteDTO note) { + if (idNote != note.Id) + throw new NoteIdImcompatibleException(); if (!IsDetailsNoteValide(note)) - return null; + throw new NoteInvalideException(); Note noteToUpdate = context.Note.Find(idNote); - if (noteToUpdate == null) - return AjouterNote(note); noteToUpdate.Titre = note.Titre; noteToUpdate.Texte = note.Texte; noteToUpdate.DateUpdate = DateTime.Now; context.SaveChanges(); - return noteToUpdate; + return NoteToDetailSDTO(noteToUpdate); } - + /// + /// Vérifier si un objet DetailsNoteDTO possède est valide pour ajout ou mise à jour + /// + /// Un objet DetailsNoteDTO est valide si aucune de ses propriétés n'est à null + /// + /// true si l'objet est valide, false sinon private bool IsDetailsNoteValide(DetailsNoteDTO note) { return !(note == null || note.IdAuteur == null || note.Collaborateur == null || note.Collaborateur.Id == null || note.Titre == null || note.Texte == null) ; } + #endregion + - //Object to DTO + #region ObjectToDTO + /// + /// Transformer un objet note en objet pour afficher un note dans dans un tableau + /// + /// Note à transformer + /// Service collaborateur pour récupérer les informations des collaborateurs + /// La note transformée pour être affichée private static AffichageNoteDTO NoteToAffichageDTO(Note note, ICollaborateurService collaborateurService) { CollaborateurDTO collaborateur = collaborateurService.GetCollaborateurById(note.IdCollaborateur); @@ -138,6 +213,11 @@ namespace EPAServeur.Services return affichage; } + /// + /// Transformatino d'une note en DetailsNoteDTO + /// + /// Note à transformer + /// Note transformer en DetailsNoteDTO private DetailsNoteDTO NoteToDetailSDTO(Note note) { DetailsNoteDTO details = new DetailsNoteDTO() @@ -152,8 +232,15 @@ namespace EPAServeur.Services }; return details; } + #endregion - //DTO to Object + #region DTOToObject + /// + /// Transformer l'objet DTO d'une note en note + /// + /// En général, de base, cette méthode est prévue pour être utilisée qu'à la création d'une nouvelle note, dateCreation et dateUpdate sont donc initialisée à ce moment là + /// Objet DTO à transformer en note + /// L'objet DTO transformé en note private Note DetailsNoteDTOToNouvelleNote(DetailsNoteDTO detailsNoteDTO) { Note note = new Note() @@ -167,5 +254,6 @@ namespace EPAServeur.Services }; return note; } + #endregion } } diff --git a/Startup.cs b/Startup.cs index 28e0eea..9cd8555 100644 --- a/Startup.cs +++ b/Startup.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using EPAServeur.Context; using EPAServeur.IServices; using EPAServeur.Services; @@ -10,12 +6,11 @@ using IO.Swagger.Security; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using System.IO; namespace EPAServeur { @@ -63,8 +58,10 @@ namespace EPAServeur } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory logger) { + string path = Directory.GetCurrentDirectory(); + logger.AddFile(path+"Log/loggerfile-{Date}.txt"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();