diff --git a/ApiCollaborateur/ReferentApi.cs b/ApiCollaborateur/ReferentApi.cs index c49c8f0..753673e 100644 --- a/ApiCollaborateur/ReferentApi.cs +++ b/ApiCollaborateur/ReferentApi.cs @@ -986,7 +986,7 @@ namespace IO.Swagger.ApiCollaborateur if (refId == null) throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); - var localVarPath = "/referent/{refId}"; + var localVarPath = "/referents/{refId}"; var localVarPathParams = new Dictionary(); var localVarQueryParams = new List>(); var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); @@ -1052,7 +1052,7 @@ namespace IO.Swagger.ApiCollaborateur if (refId == null) throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); - var localVarPath = "/referent/{refId}"; + var localVarPath = "/referents/{refId}"; var localVarPathParams = new Dictionary(); var localVarQueryParams = new List>(); var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); diff --git a/Context/EpContext.cs b/Context/EpContext.cs index 9221c12..3ca5964 100644 --- a/Context/EpContext.cs +++ b/Context/EpContext.cs @@ -506,14 +506,14 @@ namespace EPAServeur.Context //COM --> Commercial //DEL --> Delivery // 10 EP - /* + Ep ep; - DemandeFormation df; - ParticipationFormation pf; + //DemandeFormation df; + //ParticipationFormation pf; ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "COM1", + IdCollaborateur = Guid.Parse("1ec99fde-f756-11ea-adc1-0242ac120002"), + IdReferent = Guid.Parse("1ec9a204-f756-11ea-adc1-0242ac120002"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -526,20 +526,20 @@ namespace EPAServeur.Context CV = "CV.pdf", DateSaisie = new DateTime(2018, 6, 20) }; - df = new DemandeFormation - { - Description = "Description formation", - DemandeRH = false, - DateDemande = new DateTime(2018, 7, 8), - }; + //df = new DemandeFormation + //{ + // Description = "Description formation", + // DemandeRH = false, + // DateDemande = new DateTime(2018, 7, 8), + //}; Ep.Add(ep); ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("779bf1cf-4d38-48fb-8550-3d583384523b"), + IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -556,8 +556,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("006226f6-51b2-4a02-a302-7447f7fccc04"), + IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -574,8 +574,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("f960f851-16b6-4631-952e-d05f38d8d80f"), + IdReferent = Guid.Parse("6aa62dcb-f7c9-4c0c-af40-e934a4d6a7eb"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -592,8 +592,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), + IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -610,8 +610,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), + IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -627,8 +627,8 @@ namespace EPAServeur.Context Ep.Add(ep); ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("9e1ee839-4477-4d64-9b4d-80654c97c39f"), + IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -645,8 +645,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("3f532f4c-a5c9-466c-b7c1-fdc6bc48780e"), + IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -663,8 +663,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("59a8becb-bc0a-4d3d-adb1-8a8bd13c48c9"), + IdReferent = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -681,8 +681,8 @@ namespace EPAServeur.Context ep = new Ep { - IdCollaborateur = "C1", - IdReferent = "C6", + IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"), + IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"), IdAgence = 1, IdBu = 2, Fonction = "Dev", @@ -696,9 +696,47 @@ namespace EPAServeur.Context DateSaisie = new DateTime(2018, 6, 20) }; Ep.Add(ep); - */ + Engagement engagement; + engagement = new Engagement + { + Action = "Je m'engage à...", + Disposition = "interne", + Modalite = "Modalite", + DateLimite = new DateTime(2017, 7, 7), + Realise = false, + Realisable = true, + RaisonNonRealisable = null, + Ep = ep + }; + Engagement.Add(engagement); + + engagement = new Engagement + { + Action = "Je m'engage à faire...", + Disposition = "externe", + Modalite = "Modalite 2", + DateLimite = new DateTime(2017, 7, 8), + Realise = true, + Realisable = true, + RaisonNonRealisable = null, + Ep = ep + }; + Engagement.Add(engagement); + + engagement = new Engagement + { + Action = "Je m'engage à faire...", + Disposition = "externe", + Modalite = "Modalite 3", + DateLimite = new DateTime(2017, 7, 8), + Realise = null, + Realisable = null, + RaisonNonRealisable = "Aucune formation disponible", + Ep = ep + }; + Engagement.Add(engagement); //AVoir un tableau pour dire combien de demande de formations seront faites pour chaque EP //Avoir un tableau pour dire combien de demande de Participation seront faites et accepter (max : 11) //La formation associée sera choisie de manière aléatoire parmi celles créées (pas grave si la cohérence niveau date est foireuse....) diff --git a/Controllers/CollaborateursApi.cs b/Controllers/CollaborateursApi.cs index 53f2158..29a4dbe 100644 --- a/Controllers/CollaborateursApi.cs +++ b/Controllers/CollaborateursApi.cs @@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging; using EPAServeur.Exceptions; using IO.Swagger.ClientCollaborateur; using Microsoft.AspNetCore.Server.Kestrel.Core; +using System.Threading.Tasks; namespace IO.Swagger.Controllers { @@ -55,7 +56,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateurById([FromRoute][Required]Guid? idCollaborateur) + public virtual async Task GetCollaborateurById([FromRoute][Required]Guid? idCollaborateur) { //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(403, default(ErreurDTO)); @@ -63,7 +64,7 @@ namespace IO.Swagger.Controllers CollaborateurDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetCollaborateurById(idCollaborateur); + collaborateurDTO = await collaborateurService.GetCollaborateurByIdAsync(idCollaborateur); } catch (ApiException) { @@ -103,7 +104,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateurByMail([FromRoute][Required]string mail) + public virtual async Task GetCollaborateurByMail([FromRoute][Required]string mail) { //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(403, default(ErreurDTO)); @@ -111,7 +112,7 @@ namespace IO.Swagger.Controllers CollaborateurDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetCollaborateurByMail(mail); + collaborateurDTO = await collaborateurService.GetCollaborateurByMailAsync(mail); } catch (CollaborateurNotFoundException) { @@ -156,7 +157,7 @@ namespace IO.Swagger.Controllers [SwaggerOperation("GetCollaborateurs")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetCollaborateurs([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetCollaborateurs([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) { //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(403, default(ErreurDTO)); @@ -164,7 +165,7 @@ namespace IO.Swagger.Controllers IEnumerable collaborateurs = null; try { - collaborateurs = collaborateurService.GetCollaborateurs(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri); + collaborateurs = await collaborateurService.GetCollaborateursAsync(asc, numPage, parPAge, fonctions, idAgence, idBU, texte, tri); } catch(ApiException) { @@ -200,16 +201,16 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetCollaborateursByReferent([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idReferent, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) + public virtual async Task GetCollaborateursByReferent([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idReferent, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) { //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(403, default(ErreurDTO)); logger.LogInformation("Récupération de la liste des collaborateurs du référent {idReferent}",idReferent); - IEnumerable collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); + IEnumerable collaborateurs = null; try { - collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); - } + collaborateurs = await collaborateurService.GetCollaborateursByReferentAsync(idReferent, asc, numPage, parPAge, texte, tri); + } catch (ApiException) { logger.LogError("Une erreur est survenue lors de la communication avec le service collaborateur lors de la récupération de la liste des collaborateurs du référent {idReferent}", idReferent); @@ -247,7 +248,7 @@ namespace IO.Swagger.Controllers [SwaggerResponse(statusCode: 200, type: typeof(ProfilDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetProfilCollaborateurByMail([FromRoute][Required]string mail) + public virtual async Task GetProfilCollaborateurByMailAsync([FromRoute][Required]string mail) { //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... // return StatusCode(403, default(ErreurDTO)); @@ -255,7 +256,7 @@ namespace IO.Swagger.Controllers ProfilDTO collaborateurDTO = null; try { - collaborateurDTO = collaborateurService.GetProfilByMail(mail); + collaborateurDTO = await collaborateurService.GetProfilByMailAsync(mail); } catch (ApiException) { diff --git a/Controllers/EngagementsApi.cs b/Controllers/EngagementsApi.cs index d72dadb..30814e3 100644 --- a/Controllers/EngagementsApi.cs +++ b/Controllers/EngagementsApi.cs @@ -18,6 +18,11 @@ using IO.Swagger.Attributes; using IO.Swagger.Security; using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; +using EPAServeur.IServices; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using EPAServeur.Exceptions; +using Microsoft.EntityFrameworkCore; namespace IO.Swagger.Controllers { @@ -26,7 +31,16 @@ namespace IO.Swagger.Controllers /// [ApiController] public class EngagementsApiController : ControllerBase - { + { + private readonly IEngagementService engagementService; + private readonly ILogger logger; + + + public EngagementsApiController(IEngagementService _engagementService, ILogger _logger) + { + engagementService = _engagementService; + logger = _logger; + } /// /// /// @@ -41,25 +55,33 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagements")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + { + logger.LogInformation("Récupération de la liste des engagements."); + + IEnumerable engagements = null; + + try + { + engagements = await engagementService.GetEngagementsAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements."); + } + + logger.LogInformation("Liste des engagements récupérée."); + + return Ok(engagements); } /// @@ -76,25 +98,33 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements/enattente")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagementsEnAttente")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + { + logger.LogInformation("Récupération de la liste des engagements en attente."); + + IEnumerable engagements = null; + + try + { + engagements = await engagementService.GetEngagementsEnAttenteAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements en attente est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements en attente."); + } + + logger.LogInformation("Liste des engagements en attente récupérée."); + + return Ok(engagements); } /// @@ -111,25 +141,33 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpGet] [Route("/api/engagements/repondus")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("GetEngagementsRepondus")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n}, {\n \"realisable\" : true,\n \"realise\" : true,\n \"action\" : \"action\",\n \"id\" : 2,\n \"datePrevisionnelle\" : \"2000-01-23T04:56:07.000+00:00\",\n \"dispositif\" : \"dispositif\",\n \"modalite\" : \"modalite\",\n \"raisonNonRealisable\" : \"raisonNonRealisable\"\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) + { + logger.LogInformation("Récupération de la liste des engagements répondus."); + + IEnumerable engagements = null; + + try + { + engagements = await engagementService.GetEngagementsRepondusAsync(asc, numPage, parPAge, idAgence, texte, tri); + } + catch (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements répondus est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des engagements répondus."); + } + + logger.LogInformation("Liste des engagements répondus récupérée."); + + return Ok(engagements); } /// @@ -142,19 +180,50 @@ namespace IO.Swagger.Controllers /// Acces interdit [HttpPut] [Route("/api/engagements/{idEngagement}/repondre")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] [SwaggerOperation("RepondreEngagement")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200); + public virtual async Task RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) + { + logger.LogInformation("Tentative de mise à jour de l'engagement {idEngagement}.", idEngagement); + + EngagementDTO engagement = null; + + try + { + engagement = await engagementService.RepondreEngagementAsync(body, idEngagement); + } + catch (EngagementInvalidException ex) + { + logger.LogWarning("Des données sont manquants, l'engagement {idEngagement} ne peut pas être mise à jour.", idEngagement); + ErreurDTO erreur = new ErreurDTO() + { + Code = "400", + Message = ex.Message + }; + return BadRequest(erreur); + } + catch (EngagementIncompatibleIdException) + { + logger.LogError("L'id de l'engagement à mettre à jour {body.Id} et l'id de l'engagement avec les nouvelles informations {idEngagement} sont différents.", body.Id, idEngagement); + } + catch (DbUpdateConcurrencyException) + { + logger.LogError("L'engagement {idEngagement} n'a pas pu être mise à jour car il est pris par une autre ressource.", idEngagement); + } + catch (DbUpdateException) + { + logger.LogError("Une erreur est survenue dans la base de données lors de la mise à jour de l'engagement {idEngagement}.", idEngagement); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la mise à jour de l'engagement {idEngagement}.", idEngagement); + } - //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("Mise à jour de l'engagement {idEngagement} réussie."); - throw new NotImplementedException(); + return Ok(engagement); } } } diff --git a/Controllers/FormationsApi.cs b/Controllers/FormationsApi.cs index ba84147..4ed3f3a 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,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations annulées est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations annulées."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -124,9 +178,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 +203,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 +264,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations réalisées est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations réalisées."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -193,9 +290,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 +320,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des formations est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des formations."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -231,9 +346,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 +368,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des modes de formation est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des modes de formation."); + } + if (modeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -261,9 +394,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 +416,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des origines de formation est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des origines de formation."); + } + if (origineFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -294,6 +445,8 @@ namespace IO.Swagger.Controllers return NotFound(erreur); } + logger.LogInformation("Liste des origines de formation récupérée."); + return Ok(origineFormations); } @@ -318,10 +471,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des prochaines formations est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des prochaines formations."); + } + if (formations == null) { ErreurDTO erreur = new ErreurDTO() @@ -329,9 +497,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 +519,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des statuts de formation est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des statuts de formation."); + } + if (statutFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -359,9 +545,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 +567,25 @@ 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 (ArgumentNullException) + { + logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des types de formation est invalide."); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération de la liste des types de formation."); + } + if (typeFormations == null) { ErreurDTO erreur = new ErreurDTO() @@ -389,9 +593,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 +617,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/ReferentsApi.cs b/Controllers/ReferentsApi.cs index f4adbb0..cf5c6ad 100644 --- a/Controllers/ReferentsApi.cs +++ b/Controllers/ReferentsApi.cs @@ -11,132 +11,232 @@ using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -using Swashbuckle.AspNetCore.SwaggerGen; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using IO.Swagger.Attributes; -using IO.Swagger.Security; -using Microsoft.AspNetCore.Authorization; using IO.Swagger.DTO; +using EPAServeur.IServices; +using System.Net; +using Microsoft.AspNetCore.Authorization; +using IO.Swagger.Security; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using IO.Swagger.ClientCollaborateur; +using EPAServeur.Exceptions; namespace IO.Swagger.Controllers -{ +{ /// /// /// [ApiController] public class ReferentsApiController : ControllerBase - { + { + private readonly IReferentService referentService; + private readonly ILogger logger; + + public ReferentsApiController(IReferentService _referentService, ILogger _logger) + { + referentService = _referentService; + logger = _logger; + } + /// /// /// - /// Récupérer la liste des référents d'un collaborateur + /// Récupérer un referent par son id + /// id referent + /// OK + /// Acces interdit + /// Ressource n'a pas été trouvée + [HttpGet] + [Route("/api/referents/{idReferent}")] + ////[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [ValidateModelState] + [SwaggerOperation("GetReferentById")] + [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] + [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] + [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] + public virtual async Task GetReferentById([FromRoute][Required]Guid? idReferent) + { + logger.LogInformation("Récupération du référent {idReferent}.", idReferent); + + ReferentDTO referentDTO = null; + + try + { + referentDTO = await referentService.GetReferentByIdAsync(idReferent); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le référent par son id {idReferent}.", idReferent); + } + catch (ReferentNotFoundException) + { + logger.LogError("Le référent {idReferent} est introuvable.", idReferent); + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Le référent n'existe pas", + }; + + return NotFound(erreurDTO); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du référent {idReferent}.", idReferent); + } + + logger.LogInformation("Référent {idReferent} récupéré.", idReferent); + + return Ok(referentDTO); + } + + /// + /// + /// + /// Récupérer la liste de tous les referents /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) - /// id collaborateur /// Numéro de la page du tableau qui affiche les données /// Nombre d'éléments affiché sur chaque page du tableau + /// Liste des fonctions des collaborateurs que l'on veut récupérer + /// id de l'agence à laquelle sont rattachées les données à récupérer + /// id de la business unit à laquelle sont rattachées les données à récupérer /// Texte permettant d'identifier l'objet rechercher /// Colonne du tableau sur lequel le tri s'effectue /// OK /// Acces interdit - /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents/collaborateur/{idCollaborateur}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferentByCollaborateur")] + [SwaggerOperation("GetReferents")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentByCollaborateur([FromQuery][Required()]bool? asc, [FromRoute][Required]Guid? idCollaborateur, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]string texte, [FromQuery]string tri) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(404, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}, {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) + { + //IEnumerable referentDTOs = referentService.GetReferents(asc,numPage,parPAge,fonctions,idAgence,idBU,texte,tri); + return NoContent(); } /// /// /// - /// Récupérer un referent par son id - /// id referent + /// Récupérer le référent actuel d'un collaborateur + /// id collaborateur /// OK /// Acces interdit /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents/{idReferent}")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents/actuel/collaborateur/{idCollaborateur}")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferentById")] + [SwaggerOperation("GetReferentActuelCollaborateur")] [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] - public virtual IActionResult GetReferentById([FromRoute][Required]Guid? idReferent) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(ReferentDTO)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - - //TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(404, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "{\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject(exampleJson) - : default(ReferentDTO); //TODO: Change the data returned - return new ObjectResult(example); + public virtual async Task GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur) + { + logger.LogInformation("Récupération du référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + + ReferentDTO referentDTO = null; + + try + { + referentDTO = await referentService.GetReferentActuelCollaborateurAsync(idCollaborateur); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service Collaborateur pour récupérer le référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + } + catch (ReferentNotFoundException) + { + logger.LogError("Le référent actuel du collaborateur {idCollaborateur} est introuvable.", idCollaborateur); + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Aucun référent actuel pour le collaborateur", + }; + + return NotFound(erreurDTO); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération du référent actuel du collaborateur {idCollaborateur}.", idCollaborateur); + } + + logger.LogInformation("Référent actuel du collaborateur {idCollaborateur} récupéré.", idCollaborateur); + + return Ok(referentDTO); } /// /// /// - /// Récupérer la liste de tous les referents + /// Récupérer la liste des référents d'un collaborateur /// Préciser si les données sont dans l'ordre (true) ou dans l'ordre inverse (false) + /// id collaborateur /// Numéro de la page du tableau qui affiche les données /// Nombre d'éléments affiché sur chaque page du tableau - /// Liste des fonctions des collaborateurs que l'on veut récupérer - /// id de l'agence à laquelle sont rattachées les données à récupérer - /// id de la business unit à laquelle sont rattachées les données à récupérer /// Texte permettant d'identifier l'objet rechercher /// Colonne du tableau sur lequel le tri s'effectue /// OK /// Acces interdit + /// Ressource n'a pas été trouvée [HttpGet] - [Route("/api/referents")] - [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] + [Route("/api/referents/collaborateur/{idCollaborateur}")] + //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [ValidateModelState] - [SwaggerOperation("GetReferents")] + [SwaggerOperation("GetReferentByCollaborateur")] [SwaggerResponse(statusCode: 200, type: typeof(List), description: "OK")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] - public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) - { - //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(200, default(List)); - - //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... - // return StatusCode(403, default(ErreurDTO)); - string exampleJson = null; - exampleJson = "[ {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}, {\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n} ]"; - - var example = exampleJson != null - ? JsonConvert.DeserializeObject>(exampleJson) - : default(List); //TODO: Change the data returned - return new ObjectResult(example); + [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n'a pas été trouvée")] + public virtual async Task GetReferentsByCollaborateur([FromQuery][Required()] bool? asc, [FromRoute][Required] Guid? idCollaborateur, [FromQuery][Required()] int? numPage, [FromQuery][Required()] int? parPAge, [FromQuery] string texte, [FromQuery] string tri) + { + logger.LogInformation("Récupération de la liste des référents du collaborateur {idCollaborateur}.", idCollaborateur); + + IEnumerable referentDTOs = null; + + try + { + referentDTOs = await referentService.GetReferentsByCollaborateurAsync(asc, idCollaborateur, numPage, parPAge, texte, tri); + } + catch (ApiException) + { + logger.LogError("Une erreur est survenue lors de la communication avec le service collaborateur lors de la récupération de la liste des référents du collaborateur {idReferent}.", idCollaborateur); + } + catch (CollaborateurNotFoundException) + { + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Le collaborateur n'existe pas", + }; + + return NotFound(erreurDTO); + } + catch (Exception) + { + logger.LogError("Une erreur inconnue est survenue lors de la récupération des référents du collaborateur {idCollaborateur}.", idCollaborateur); + } + + if (referentDTOs.Count() == 0) + { + logger.LogInformation("Aucun référent pour le collaborateur {idCollaborateur}.", idCollaborateur); + + ErreurDTO erreurDTO = new ErreurDTO() + { + Code = "404", + Message = "Aucun référent pour le collaborateur", + }; + + return NotFound(erreurDTO); + } + + logger.LogInformation("Liste des référents du collaborateur {idCollaborateur} récupérée", idCollaborateur); + + return Ok(referentDTOs); } } } diff --git a/DTO/EpInformationDTO.cs b/DTO/EpInformationDTO.cs index 9188543..77f9432 100644 --- a/DTO/EpInformationDTO.cs +++ b/DTO/EpInformationDTO.cs @@ -38,14 +38,14 @@ namespace IO.Swagger.DTO /// [Required] [DataMember(Name="type")] - public int? Type { get; set; } + public string Type { get; set; } /// /// Gets or Sets Statut /// [Required] [DataMember(Name="statut")] - public int? Statut { get; set; } + public string Statut { get; set; } /// /// Gets or Sets DateDisponibilite @@ -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/Exceptions/EngagementIncompatibleIdException.cs b/Exceptions/EngagementIncompatibleIdException.cs new file mode 100644 index 0000000..d11a25b --- /dev/null +++ b/Exceptions/EngagementIncompatibleIdException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsque l'id de l'engagement avec les données à mettre à jour et l'id de l'engagement à mettre sont différents + /// + public class EngagementIncompatibleIdException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementIncompatibleIdException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementIncompatibleIdException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementIncompatibleIdException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/EngagementInvalidException.cs b/Exceptions/EngagementInvalidException.cs new file mode 100644 index 0000000..15e974a --- /dev/null +++ b/Exceptions/EngagementInvalidException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un engagement est invalide + /// + public class EngagementInvalidException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementInvalidException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementInvalidException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementInvalidException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/EngagementNotFoundException.cs b/Exceptions/EngagementNotFoundException.cs new file mode 100644 index 0000000..365f553 --- /dev/null +++ b/Exceptions/EngagementNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un engagement n'a pas été trouvé + /// + public class EngagementNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public EngagementNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public EngagementNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public EngagementNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/FormationIncompatibleIdException.cs b/Exceptions/FormationIncompatibleIdException.cs new file mode 100644 index 0000000..99dcaf2 --- /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 dans la base de données 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..8b72fe2 --- /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 lorsqu'une formation est invalide + /// + public class FormationInvalidException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public FormationInvalidException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public FormationInvalidException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public FormationInvalidException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/FormationNotFoundException.cs b/Exceptions/FormationNotFoundException.cs new file mode 100644 index 0000000..93fdcc9 --- /dev/null +++ b/Exceptions/FormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'une formation n'a pas été trouvée + /// + public class FormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public FormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public FormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public FormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/ModeFormationNotFoundException.cs b/Exceptions/ModeFormationNotFoundException.cs new file mode 100644 index 0000000..c3c1f4a --- /dev/null +++ b/Exceptions/ModeFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un mode de formation n'a pas été trouvé + /// + public class ModeFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public ModeFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public ModeFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public ModeFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/OrigineFormationNotFoundException.cs b/Exceptions/OrigineFormationNotFoundException.cs new file mode 100644 index 0000000..26438b6 --- /dev/null +++ b/Exceptions/OrigineFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'une origine de formation n'a pas été trouvée + /// + public class OrigineFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public OrigineFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public OrigineFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public OrigineFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/StatutFormationNotFoundException.cs b/Exceptions/StatutFormationNotFoundException.cs new file mode 100644 index 0000000..66c7167 --- /dev/null +++ b/Exceptions/StatutFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un statut de formation n'a pas été trouvé + /// + public class StatutFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public StatutFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public StatutFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public StatutFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/Exceptions/TypeFormationNotFoundException.cs b/Exceptions/TypeFormationNotFoundException.cs new file mode 100644 index 0000000..54f1de8 --- /dev/null +++ b/Exceptions/TypeFormationNotFoundException.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Exceptions +{ + /// + /// Exception à jeter lorsqu'un type de formation n'a pas été trouvé + /// + public class TypeFormationNotFoundException : Exception + { + /// + /// Initialise une nouvelle instance de la classe class. + /// + public TypeFormationNotFoundException() + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + public TypeFormationNotFoundException(string message) : base(message) + { + + } + + /// + /// Initialise une nouvelle instance de la classe class. + /// + /// + /// + public TypeFormationNotFoundException(string message, Exception inner) : base(message, inner) + { + + } + } +} diff --git a/IServices/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/IEngagementService.cs b/IServices/IEngagementService.cs new file mode 100644 index 0000000..cbf5d6c --- /dev/null +++ b/IServices/IEngagementService.cs @@ -0,0 +1,25 @@ +using EPAServeur.Context; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.IServices +{ + public interface IEngagementService + { + + IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + Task> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri); + + EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement); + Task RepondreEngagementAsync(EngagementDTO engagement, long? idEngagement); + + } +} diff --git a/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/IReferentService.cs b/IServices/IReferentService.cs new file mode 100644 index 0000000..8cb68cb --- /dev/null +++ b/IServices/IReferentService.cs @@ -0,0 +1,24 @@ +using EPAServeur.Context; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.IServices +{ + public interface IReferentService + { + ReferentDTO GetReferentById(Guid? idReferent); + Task GetReferentByIdAsync(Guid? idReferent); + ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur); + Task GetReferentActuelCollaborateurAsync(Guid? idCollaborateur); + IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); + Task> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri); + + IEnumerable GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri); + Task> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri); + + } +} diff --git a/Models/EP/Ep.cs b/Models/EP/Ep.cs index feb31a1..7423451 100644 --- a/Models/EP/Ep.cs +++ b/Models/EP/Ep.cs @@ -24,8 +24,8 @@ namespace EPAServeur.Models.EP public class Ep { public long Id { get; set; } - public string IdCollaborateur { get; set; } - public string IdReferent { get; set; } + public Guid IdCollaborateur { get; set; } + public Guid IdReferent { get; set; } public long IdAgence { get; set; } public long IdBu { get; set; } public string Fonction { get; set; } diff --git a/Services/CollaborateurService.cs b/Services/CollaborateurService.cs index 55d58b1..37137b6 100644 --- a/Services/CollaborateurService.cs +++ b/Services/CollaborateurService.cs @@ -47,6 +47,19 @@ namespace EPAServeur.Services return GetCollaborateurDTO(collaborateur); } + /// + /// Récupérer un collaborateur en fonction d'un id de manière asynchrone + /// + /// Identifiant du collaborateur à renvoyer + /// Le collaborateur corresponant à l'id en paramètre + public async Task GetCollaborateurByIdAsync(Guid? id) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(id); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetCollaborateurDTO(collaborateur); + } + /// /// Récupérer un collaborateur en fonction d'un mail /// @@ -60,6 +73,19 @@ namespace EPAServeur.Services return GetCollaborateurDTO(collaborateur); } + /// + /// Récupérer un collaborateur en fonction d'un mail de manière asynchrone + /// + /// Mail du collaborateur à renvoyer + /// Le collaborateur correspondant au mail en paramètre + public async Task GetCollaborateurByMailAsync(string mail) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetCollaborateurDTO(collaborateur); + } + /// /// Récupérer la liste de tous les collaborateurs /// @@ -103,6 +129,49 @@ namespace EPAServeur.Services return collaborateursDTO; } + /// + /// Récupérer la liste de tous les collaborateurs de manière asynchrone + /// + /// + /// Précise si la liste est trié dans l'ordre croissant ou décroissant + /// Numéro de la page qui est affiché du côté front + /// Nombre de collaborateurs à renvoyer + /// Liste des fonctions + /// id de l'agence à laquelle appartient les collaborateurs à récupérer + /// + /// permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// + /// idBU est à prendre en compte avant l'idAgence + /// idAgence n'est à prendre en compte que si idBU est nul + /// + /// + /// Renvoie la liste des collaborateurs en fonction des paramètres + public async Task> GetCollaborateursAsync(bool? asc, int? numPage, int? parPage, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + IEnumerable collaborateurs; + IEnumerable collaborateursDTO; + if (idBU != null) + collaborateurs = await collaborateurApi.ChercherCollabBUAsync(idBU); + else if (idAgence != null) + collaborateurs = await collaborateurApi.ChercherCollabAgenceAsync(idAgence); + else + collaborateurs = await collaborateurApi.ChercherCollabAsync(); + if (collaborateurs == null) + return new List(); + int skip = (numPage.Value - 1) * parPage.Value; + int take = parPage.Value; + collaborateursDTO = (from c in collaborateurs + where (c.Nom + " " + c.Prenom).ToLower().Contains(texte) || (c.Prenom + " " + c.Nom).ToLower().Contains(texte) + select GetCollaborateurDTO(c)).Skip(skip).Take(take); + + return collaborateursDTO; + } + /// /// Récupérer les collaborateurs d'un référent /// @@ -141,6 +210,44 @@ namespace EPAServeur.Services return collaborateursDTO; } + /// + /// Récupérer les collaborateurs d'un référent de manière asynchrone + /// + /// id du référent des collaborateurs à récupérer + /// Précise si la liste est trié dans l'ordre croissant ou décroissant + /// Numéro de la page qui est affiché du côté front + /// Nombre de collaborateurs à renvoyer + /// permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte + /// Choisir l'attribut par lequel est trié la liste + /// Renvoyer les collaborateurs du référent dont l'id est passé en paramètre + public async Task> GetCollaborateursByReferentAsync(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri) + { + /* + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + stopwatch.Stop(); + Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + stopwatch.Restart(); + stopwatch.Stop(); + Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + */ + Collaborateur referent = await collaborateurApi.ChercherCollabIdAsync(idReferent); + if (referent == null) + throw new ReferentNotFoundException(); + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + IEnumerable collaborateurs = await collaborateurApi.ChercherCollabRefAsync(idReferent); + int skip = (numPage.Value - 1) * parPage.Value; + int take = parPage.Value; + IEnumerable collaborateursDTO = (from c in collaborateurs + where (c.Nom + " " + c.Prenom).ToLower().Contains(texte) || (c.Prenom + " " + c.Nom).ToLower().Contains(texte) + select GetCollaborateurDTO(c)).Skip(skip).Take(take); + return collaborateursDTO; + } + /// /// Récupérer le profil d'un collaborateur par mail /// @@ -154,6 +261,19 @@ namespace EPAServeur.Services return GetProfilDTO(collaborateur); } + /// + /// Récupérer le profil d'un collaborateur par mail de manière asynchrone + /// + /// mail du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant au mail passé en paramètre + public async Task GetProfilByMailAsync(string mail) + { + Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail); + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetProfilDTO(collaborateur); + } + /// /// Récupérer un profil d'un collaborateur par l'id /// @@ -174,6 +294,27 @@ namespace EPAServeur.Services throw new CollaborateurNotFoundException(); return GetProfilDTO(collaborateur); } + + /// + /// Récupérer un profil d'un collaborateur par l'id de manière asynchrone + /// + /// id du collaborateur dont on cherche le profil + /// Renvoie le profil correspondant à l'id passé en paramètre + public async Task GetProfilByIdAsync(Guid? idCollaborateur) + { + //Stopwatch stopwatch = new Stopwatch(); + //stopwatch.Start(); + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(idCollaborateur); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution GetProfil: {0}", stopwatch.Elapsed.TotalSeconds); + //stopwatch.Restart(); + //stopwatch.Stop(); + //Console.WriteLine("Durée d'exécution numéro 1: {0}", stopwatch.Elapsed.TotalSeconds); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + return GetProfilDTO(collaborateur); + } #endregion #region DTO To Object diff --git a/Services/EngagementService.cs b/Services/EngagementService.cs new file mode 100644 index 0000000..cab7c58 --- /dev/null +++ b/Services/EngagementService.cs @@ -0,0 +1,457 @@ +using EPAServeur.Context; +using EPAServeur.Exceptions; +using EPAServeur.IServices; +using EPAServeur.Models.EP; +using EPAServeur.Models.Formation; +using EPAServeur.Models.SaisieChamp; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Services +{ + public class EngagementService : IEngagementService + { + #region Variables + + private readonly EpContext epContext; + private readonly ICollaborateurService collaborateurService; + private readonly IReferentService referentService; + #endregion + + #region Contructeurs + + /// + /// Constructeur de la classe EngagementService + /// + /// + public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService, IReferentService _referentService) + { + epContext = _epContext; + collaborateurService = _collaborateurService; + referentService = _referentService; + } + + #endregion + + #region Méthodes Service + + public IEnumerable GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence); + else + engagements = epContext.Engagement.Include(engagement => engagement.Ep); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).ToListAsync(); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); + + return results; + } + + public IEnumerable GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToList(); + else + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToList(); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Realise == null).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise == null).ToListAsync(); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); + + return results; + } + + public IEnumerable GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Modalite.ToLower().Contains(texte)); + else + engagements = epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement)); + + return engagementDTOs; + } + + public async Task> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri) + { + IEnumerable engagements; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idAgence != null) + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Ep.IdAgence == idAgence && engagement.Modalite.ToLower().Contains(texte)).ToListAsync(); + else + engagements = await epContext.Engagement.Include(engagement => engagement.Ep).Where(engagement => engagement.Realise != null && engagement.Modalite.ToLower().Contains(texte)).ToListAsync(); + + if (engagements == null || engagements.Count() == 0) + return new List(); + + var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement)); + var results = await Task.WhenAll(engagementDTOs); + + return results; + } + + /// + /// Donner une réponse à un engagement + /// + /// + /// + /// + public EngagementDTO RepondreEngagement(EngagementDTO engagementDTO, long? idEngagement) + { + + if (!IsEngagementValide(engagementDTO)) + throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); + + if (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) + throw new EngagementInvalidException("Impossible de répondre à l'engagement, une raison doit être rensignée lorsqu'un engagement n'est pas réalisé."); + + if (engagementDTO == null && !engagementDTO.Id.HasValue && engagementDTO.Id.Value != idEngagement) + throw new EngagementIncompatibleIdException(); + + + Engagement engagement = epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefault(engagement => engagement.Id == idEngagement); + + if (engagement == null) + throw new EngagementNotFoundException(); + + engagement.Realise = engagementDTO.Realise; + + switch (engagement.Realise) + { + case true: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = null; + break; + case false: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + break; + default: + engagement.Realisable = null; + engagement.RaisonNonRealisable = null; + break; + } + + epContext.SaveChanges(); + + return GetEngagementDTO(engagement); + } + + + /// + /// Donner une réponse à un engagement de manière asynchrone + /// + /// + /// + /// + public async Task RepondreEngagementAsync(EngagementDTO engagementDTO, long? idEngagement) + { + + if (!IsEngagementValide(engagementDTO)) + throw new EngagementInvalidException("Impossible de répondre à l'engagement, des données sont manquants."); + + if (engagementDTO.Realise == false && string.IsNullOrWhiteSpace(engagementDTO.RaisonNonRealisable)) + throw new EngagementInvalidException("Impossible de répondre à l'engagement, une raison doit être rensignée lorsqu'un engagement n'est pas réalisé."); + + + Engagement engagement = await epContext.Engagement.Include(engagement => engagement.Ep).FirstOrDefaultAsync(engagement => engagement.Id == idEngagement); + + if (engagement == null) + throw new EngagementNotFoundException(); + + engagement.Realise = engagementDTO.Realise; + + switch (engagement.Realise) + { + case true: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = null; + break; + case false: + engagement.Realisable = engagementDTO.Realisable; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + break; + default: + engagement.Realisable = null; + engagement.RaisonNonRealisable = null; + break; + } + + await epContext.SaveChangesAsync(); + + return await GetEngagementDTOAsync(engagement); + } + + + #endregion + + #region Méthodes Privée + private bool IsEngagementValide(EngagementDTO engagementDTO) + { + return !(engagementDTO == null || engagementDTO.Id == null || engagementDTO.Action == null || engagementDTO.DatePrevisionnelle == null || engagementDTO.Dispositif == null || engagementDTO.Modalite == null); + } + + #region Object to DTO + + /// + /// Récupère un objet EngagementDTO en fonction d'un objet Engagement + /// + /// + /// + private EngagementDTO GetEngagementDTO(Engagement engagement) + { + EngagementDTO engagementDTO = new EngagementDTO() + { + Id = engagement.Id, + Action = engagement.Action, + DatePrevisionnelle = engagement.DateLimite, + Dispositif = engagement.Disposition, + Modalite = engagement.Modalite, + RaisonNonRealisable = engagement.RaisonNonRealisable, + Realisable = engagement.Realisable, + Realise = engagement.Realise, + Ep = GetEpInformationDTO(engagement.Ep) + }; + + return engagementDTO; + } + + /// + /// Récupère un objet EngagementDTO en fonction d'un objet Engagement + /// + /// + /// + private async Task GetEngagementDTOAsync(Engagement engagement) + { + EngagementDTO engagementDTO = new EngagementDTO() + { + Id = engagement.Id, + Action = engagement.Action, + DatePrevisionnelle = engagement.DateLimite, + Dispositif = engagement.Disposition, + Modalite = engagement.Modalite, + RaisonNonRealisable = engagement.RaisonNonRealisable, + Realisable = engagement.Realisable, + Realise = engagement.Realise, + Ep = await GetEpInformationDTOAsync(engagement.Ep) + }; + + return engagementDTO; + } + + /// + /// Récupère un objet EpInformationDTO en fonction d'un objet Ep + /// + /// + /// + private EpInformationDTO GetEpInformationDTO(Ep ep) + { + EpInformationDTO epInformationDTO = new EpInformationDTO() + { + Id = ep.Id, + Type = ep.TypeEP.ToString(), + Statut = ep.Statut.ToString(), + DatePrevisionnelle = ep.DatePrevisionnelle, + Obligatoire = ep.Obligatoire, + Collaborateur = collaborateurService.GetCollaborateurById(ep.IdCollaborateur), + Referent = referentService.GetReferentById(ep.IdReferent) + //Ajouter la date de disponibilité + }; + + return epInformationDTO; + } + + /// + /// Récupère un objet EpInformationDTO en fonction d'un objet Ep + /// + /// + /// + private async Task GetEpInformationDTOAsync(Ep ep) + { + EpInformationDTO epInformationDTO = new EpInformationDTO() + { + Id = ep.Id, + Type = ep.TypeEP.ToString(), + Statut = ep.Statut.ToString(), + DatePrevisionnelle = ep.DatePrevisionnelle, + Obligatoire = ep.Obligatoire + //Ajouter la date de disponibilité + }; + var collaborateur = collaborateurService.GetCollaborateurByIdAsync(ep.IdCollaborateur); + var referent = referentService.GetReferentByIdAsync(ep.IdReferent); + + await Task.WhenAll(collaborateur, referent); + + epInformationDTO.Collaborateur = collaborateur.Result; + epInformationDTO.Referent = referent.Result; + + + return epInformationDTO; + } + + #endregion + + #region DTO to Object + + /// + /// Modifie un objet Engagement en fonction d'un objet FormationDTO + /// + /// + /// + /// + private Engagement SetEngagement(Engagement engagement, EngagementDTO engagementDTO) + { + engagement.Action = engagementDTO.Action; + engagement.DateLimite = engagementDTO.DatePrevisionnelle.Value; + engagement.Disposition = engagementDTO.Dispositif; + engagement.Modalite = engagementDTO.Modalite; + engagement.RaisonNonRealisable = engagementDTO.RaisonNonRealisable; + engagement.Realisable = engagementDTO.Realisable; + engagement.Realise = engagementDTO.Realise; + engagement.Ep = GetEp(engagementDTO.Ep); + + + return engagement; + } + + /// + /// Récupère un objet Ep en fonction d'un objet EpDTO + /// + /// + /// + private Ep GetEp(EpInformationDTO epInformationDTO) + { + if (epInformationDTO == null) + return null; + + // Traiter + Enum.TryParse(epInformationDTO.Type, out TypeChamp typeChamp); + + Enum.TryParse(epInformationDTO.Statut, out StatutEP statutEP); + + Ep ep = new Ep() + { + Id = epInformationDTO.Id.Value, + TypeEP = typeChamp, + Statut = statutEP, + DatePrevisionnelle = epInformationDTO.DatePrevisionnelle.Value, + Obligatoire = epInformationDTO.Obligatoire.Value, + IdReferent = epInformationDTO.Referent.Id.Value, + IdCollaborateur = epInformationDTO.Collaborateur.Id.Value, + // Ajouter la date de disponibilité + }; + + return ep; + } + + + #endregion + + #endregion + + } +} diff --git a/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/ReferentService.cs b/Services/ReferentService.cs new file mode 100644 index 0000000..dcabe51 --- /dev/null +++ b/Services/ReferentService.cs @@ -0,0 +1,431 @@ +using EPAServeur.Exceptions; +using EPAServeur.IServices; +using IO.Swagger.ApiCollaborateur; +using IO.Swagger.DTO; +using IO.Swagger.ModelCollaborateur; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace EPAServeur.Services +{ + public class ReferentService : IReferentService + { + #region Variables + private readonly IReferentApi referentApi; + private readonly ICollaborateurApi collaborateurApi; + #endregion + + #region Contructeurs + public ReferentService(IReferentApi _referentApi, ICollaborateurApi _collaborateurApi) + { + referentApi = _referentApi; + collaborateurApi = _collaborateurApi; + } + + #endregion + + #region Méthodes Service + + /// + /// Récupère un référent par son id + /// + /// + /// + public ReferentDTO GetReferentById(Guid? idReferent) + { + Referent referent = referentApi.ChercherRefId(idReferent); + + if (referent == null) + throw new ReferentNotFoundException(); + + return GetReferentDTO(referent); + } + + /// + /// Récupère un référent par son id de manière asynchrone + /// + /// + /// + public async Task GetReferentByIdAsync(Guid? idReferent) + { + Referent referent = await referentApi.ChercherRefIdAsync(idReferent); + + if (referent == null) + throw new ReferentNotFoundException(); + + return GetReferentDTO(referent); + } + + /// + /// Récupère un référent en fonction d'un collaborateur + /// + /// + /// + public ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur) + { + Referent referent = referentApi.ChercherRefActuelCollabId(idCollaborateur); + + if (referent == null) + throw new ReferentNotFoundException(); + + return GetReferentDTO(referent); + } + + /// + /// Récupère un référent en fonction d'un collaborateur de manière asynchrone + /// + /// + /// + public async Task GetReferentActuelCollaborateurAsync(Guid? idCollaborateur) + { + Referent referent = await referentApi.ChercherRefActuelCollabIdAsync(idCollaborateur); + + if (referent == null) + throw new ReferentNotFoundException(); + + return GetReferentDTO(referent); + } + + /// + /// Récupère la liste des référents pour une agence + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public IEnumerable GetReferents(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + throw new NotImplementedException(); + + ////IEnumerable collaborateurs; // A changer (Sera utilisé pour récupérer la liste des référents par fonction + //IEnumerable referents = null; // A changer + //IEnumerable referentDTOs = null; // A changer + ////List ids = fonctions.Select(guid => (Guid?)Guid.Parse(guid)).ToList(); + + ////collaborateurs = collaborateurApi.ChercherCollab(ids); + //if (texte == null) + // texte = ""; + //else + // texte = texte.ToLower(); + + //int skip = (numPage.Value - 1) * parPAge.Value; + //int take = parPAge.Value; + + //if (idBU != null) + //{ + + //} + //else + //{ + + //} + + //if (idAgence != null) + //{ + // try + // { + + // } + // catch (Exception ex) + // { + // throw; + // } + //} + //else + //{ + // try + // { + + // } + // catch (Exception ex) + // { + // throw; + // } + //} + + + //if (referents == null) + // return new List(); + + //referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + //return referentDTOs; + } + + /// + /// Récupère la liste des référents pour une agence de manière asynchrone + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + + public async Task> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List fonctions, long? idAgence, long? idBU, string texte, string tri) + { + throw new NotImplementedException(); + + //IEnumerable referents = null ; // A changer + //IEnumerable referentDTOs = null; // A changer + + //if (texte == null) + // texte = ""; + //else + // texte = texte.ToLower(); + + //int skip = (numPage.Value - 1) * parPAge.Value; + //int take = parPAge.Value; + + //if (idBU != null) + //{ + + //} + //else + //{ + + //} + + //if (idAgence != null) + //{ + // try + // { + + // } + // catch (Exception ex) + // { + // throw; + // } + //} + //else + //{ + // try + // { + + // } + // catch (Exception ex) + // { + // throw; + // } + //} + + + //if (referents == null) + // return new List(); + + //referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + //return referentDTOs; + } + + + /// + /// Récupère la liste des référents pour un collaborateur + /// + /// + /// + /// + /// + /// + /// + /// + public IEnumerable GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri) + { + IEnumerable referents; + IEnumerable referentDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idCollaborateur == null) + return new List(); + + Collaborateur collaborateur = collaborateurApi.ChercherCollabId(idCollaborateur); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + + referents = referentApi.ChercherRefCollabId(idCollaborateur); + + if (referents == null) + return new List(); + + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + + /// + /// Récupère la liste des référents pour un collaborateur de manère asynchrone + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri) + { + IEnumerable referents; + IEnumerable referentDTOs; + + if (texte == null) + texte = ""; + else + texte = texte.ToLower(); + + int skip = (numPage.Value - 1) * parPAge.Value; + int take = parPAge.Value; + + if (idCollaborateur == null) + return new List(); + + Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(idCollaborateur); + + if (collaborateur == null) + throw new CollaborateurNotFoundException(); + + referents = await referentApi.ChercherRefCollabIdAsync(idCollaborateur); + + if (referents == null) + return new List(); + + referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent)); + + return referentDTOs; + } + + #endregion + + #region Méthodes Privées + + #region Object to DTO + + /// + /// Récupère un objet AgenceDTO en fonction d'un objet Agence + /// + /// + /// + private AgenceDTO GetAgenceDTO(Agence agence) + { + if (agence == null) + return null; + AgenceDTO agenceDTO = new AgenceDTO() + { + Id = agence.Id, + Nom = agence.Nom, + Bu = new List() + }; + agenceDTO.Bu = agence.Bus.Select(bu => new BusinessUnitDTO() + { + Id = bu.Id, + Nom = bu.Nom + }).ToList(); + return agenceDTO; + } + + /// + /// Récupère un objet BusinessUnitDTO en fonction d'un objet BU + /// + /// + /// + private BusinessUnitDTO GetBusinessUnitDTO(BU businessUnit) + { + if (businessUnit == null) + return null; + BusinessUnitDTO businessUnitDTO = new BusinessUnitDTO() + { + Id = businessUnit.Id, + Nom = businessUnit.Nom, + Agence = GetAgenceDTO(businessUnit.Agence) + }; + return businessUnitDTO; + } + + /// + /// Récupère un objet CollaborateurDTO en fonction d'un objet Collaborateur + /// + /// + /// + private CollaborateurDTO GetCollaborateurDTO(Collaborateur collaborateur) + { + CollaborateurDTO collaborateurDTO = new CollaborateurDTO() + { + Id = collaborateur.Id, + Prenom = collaborateur.Prenom, + Nom = collaborateur.Nom, + MailApside = collaborateur.MailApside, + DateArrivee = collaborateur.DateArrivee, + + }; + collaborateurDTO.BusinessUnit = GetBusinessUnitDTO(collaborateur.BusinessUnit); + collaborateurDTO.Referent = GetReferentDTO(collaborateur.Referent); + return collaborateurDTO; + } + + /// + /// Récupère un objet ReferentDTO en fonction d'un objet Referent + /// + /// + /// + private ReferentDTO GetReferentDTO(Referent referent) + { + if (referent == null) + return null; + ReferentDTO referentDTO = new ReferentDTO() + { + Id = referent.Id, + Prenom = referent.Prenom, + Nom = referent.Nom, + MailApside = referent.MailApside + }; + return referentDTO; + } + + /// + /// Récupère un objet ReferentDTO en fonction d'un objet Collaborateur + /// + /// + /// + private ReferentDTO GetReferentDTO(Collaborateur collaborateur) + { + if (collaborateur == null) + return null; + ReferentDTO referentDTO = new ReferentDTO() + { + Id = collaborateur.Id, + Prenom = collaborateur.Prenom, + Nom = collaborateur.Nom, + MailApside = collaborateur.MailApside + }; + return referentDTO; + } + #endregion + + #region DTO to Object + + #endregion + + #endregion + + + + + } +} diff --git a/Startup.cs b/Startup.cs index 9a566b1..8d79041 100644 --- a/Startup.cs +++ b/Startup.cs @@ -64,7 +64,8 @@ namespace EPAServeur services.AddScoped(); services.AddScoped(); services.AddScoped(); - + services.AddScoped(); + services.AddScoped(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.