Yanaël GRETTE 4 years ago
commit d7a9e83a8e
  1. 4
      ApiCollaborateur/ReferentApi.cs
  2. 98
      Context/EpContext.cs
  3. 25
      Controllers/CollaborateursApi.cs
  4. 177
      Controllers/EngagementsApi.cs
  5. 364
      Controllers/FormationsApi.cs
  6. 244
      Controllers/ReferentsApi.cs
  7. 6
      DTO/EpInformationDTO.cs
  8. 7
      DTO/FormationDetailsDTO.cs
  9. 40
      Exceptions/EngagementIncompatibleIdException.cs
  10. 40
      Exceptions/EngagementInvalidException.cs
  11. 40
      Exceptions/EngagementNotFoundException.cs
  12. 40
      Exceptions/FormationIncompatibleIdException.cs
  13. 40
      Exceptions/FormationInvalidException.cs
  14. 40
      Exceptions/FormationNotFoundException.cs
  15. 40
      Exceptions/ModeFormationNotFoundException.cs
  16. 40
      Exceptions/OrigineFormationNotFoundException.cs
  17. 40
      Exceptions/StatutFormationNotFoundException.cs
  18. 40
      Exceptions/TypeFormationNotFoundException.cs
  19. 7
      IServices/ICollaborateurService.cs
  20. 25
      IServices/IEngagementService.cs
  21. 22
      IServices/IFormationService.cs
  22. 24
      IServices/IReferentService.cs
  23. 4
      Models/EP/Ep.cs
  24. 141
      Services/CollaborateurService.cs
  25. 457
      Services/EngagementService.cs
  26. 616
      Services/FormationService.cs
  27. 431
      Services/ReferentService.cs
  28. 3
      Startup.cs

@ -986,7 +986,7 @@ namespace IO.Swagger.ApiCollaborateur
if (refId == null) if (refId == null)
throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId");
var localVarPath = "/referent/{refId}"; var localVarPath = "/referents/{refId}";
var localVarPathParams = new Dictionary<String, String>(); var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
@ -1052,7 +1052,7 @@ namespace IO.Swagger.ApiCollaborateur
if (refId == null) if (refId == null)
throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId"); throw new ApiException(400, "Missing required parameter 'refId' when calling ReferentApi->ChercherRefId");
var localVarPath = "/referent/{refId}"; var localVarPath = "/referents/{refId}";
var localVarPathParams = new Dictionary<String, String>(); var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);

@ -506,14 +506,14 @@ namespace EPAServeur.Context
//COM --> Commercial //COM --> Commercial
//DEL --> Delivery //DEL --> Delivery
// 10 EP // 10 EP
/*
Ep ep; Ep ep;
DemandeFormation df; //DemandeFormation df;
ParticipationFormation pf; //ParticipationFormation pf;
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("1ec99fde-f756-11ea-adc1-0242ac120002"),
IdReferent = "COM1", IdReferent = Guid.Parse("1ec9a204-f756-11ea-adc1-0242ac120002"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -526,20 +526,20 @@ namespace EPAServeur.Context
CV = "CV.pdf", CV = "CV.pdf",
DateSaisie = new DateTime(2018, 6, 20) DateSaisie = new DateTime(2018, 6, 20)
}; };
df = new DemandeFormation //df = new DemandeFormation
{ //{
Description = "Description formation", // Description = "Description formation",
DemandeRH = false, // DemandeRH = false,
DateDemande = new DateTime(2018, 7, 8), // DateDemande = new DateTime(2018, 7, 8),
}; //};
Ep.Add(ep); Ep.Add(ep);
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("779bf1cf-4d38-48fb-8550-3d583384523b"),
IdReferent = "C6", IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -556,8 +556,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("006226f6-51b2-4a02-a302-7447f7fccc04"),
IdReferent = "C6", IdReferent = Guid.Parse("ecf528c3-e509-402f-87bb-c8821467e350"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -574,8 +574,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("f960f851-16b6-4631-952e-d05f38d8d80f"),
IdReferent = "C6", IdReferent = Guid.Parse("6aa62dcb-f7c9-4c0c-af40-e934a4d6a7eb"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -592,8 +592,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"),
IdReferent = "C6", IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -610,8 +610,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"),
IdReferent = "C6", IdReferent = Guid.Parse("3fa56dc6-8597-4030-a0b2-1619b98c428d"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -627,8 +627,8 @@ namespace EPAServeur.Context
Ep.Add(ep); Ep.Add(ep);
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("9e1ee839-4477-4d64-9b4d-80654c97c39f"),
IdReferent = "C6", IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -645,8 +645,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("3f532f4c-a5c9-466c-b7c1-fdc6bc48780e"),
IdReferent = "C6", IdReferent = Guid.Parse("efb063b2-ce1e-4d19-8340-d4b0b022d0d0"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -663,8 +663,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("59a8becb-bc0a-4d3d-adb1-8a8bd13c48c9"),
IdReferent = "C6", IdReferent = Guid.Parse("e5d36da4-df16-4d19-8a11-1ba2f6efc80c"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -681,8 +681,8 @@ namespace EPAServeur.Context
ep = new Ep ep = new Ep
{ {
IdCollaborateur = "C1", IdCollaborateur = Guid.Parse("a00eb610-d735-4a83-ac5a-7b89cbd4b42d"),
IdReferent = "C6", IdReferent = Guid.Parse("d3f69a83-8a29-4971-8d3c-2d0cf320dad2"),
IdAgence = 1, IdAgence = 1,
IdBu = 2, IdBu = 2,
Fonction = "Dev", Fonction = "Dev",
@ -696,9 +696,47 @@ namespace EPAServeur.Context
DateSaisie = new DateTime(2018, 6, 20) DateSaisie = new DateTime(2018, 6, 20)
}; };
Ep.Add(ep); 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 formations seront faites pour chaque EP
//Avoir un tableau pour dire combien de demande de Participation seront faites et accepter (max : 11) //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....) //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....)

@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging;
using EPAServeur.Exceptions; using EPAServeur.Exceptions;
using IO.Swagger.ClientCollaborateur; using IO.Swagger.ClientCollaborateur;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using System.Threading.Tasks;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
@ -55,7 +56,7 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
public virtual IActionResult GetCollaborateurById([FromRoute][Required]Guid? idCollaborateur) public virtual async Task<IActionResult> 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(..), ... //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); // return StatusCode(403, default(ErreurDTO));
@ -63,7 +64,7 @@ namespace IO.Swagger.Controllers
CollaborateurDTO collaborateurDTO = null; CollaborateurDTO collaborateurDTO = null;
try try
{ {
collaborateurDTO = collaborateurService.GetCollaborateurById(idCollaborateur); collaborateurDTO = await collaborateurService.GetCollaborateurByIdAsync(idCollaborateur);
} }
catch (ApiException) catch (ApiException)
{ {
@ -103,7 +104,7 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(CollaborateurDTO), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
public virtual IActionResult GetCollaborateurByMail([FromRoute][Required]string mail) public virtual async Task<IActionResult> 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(..), ... //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); // return StatusCode(403, default(ErreurDTO));
@ -111,7 +112,7 @@ namespace IO.Swagger.Controllers
CollaborateurDTO collaborateurDTO = null; CollaborateurDTO collaborateurDTO = null;
try try
{ {
collaborateurDTO = collaborateurService.GetCollaborateurByMail(mail); collaborateurDTO = await collaborateurService.GetCollaborateurByMailAsync(mail);
} }
catch (CollaborateurNotFoundException) catch (CollaborateurNotFoundException)
{ {
@ -156,7 +157,7 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetCollaborateurs")] [SwaggerOperation("GetCollaborateurs")]
[SwaggerResponse(statusCode: 200, type: typeof(List<CollaborateurDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<CollaborateurDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [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<string> fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<IActionResult> GetCollaborateurs([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List<string> 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(..), ... //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); // return StatusCode(403, default(ErreurDTO));
@ -164,7 +165,7 @@ namespace IO.Swagger.Controllers
IEnumerable<CollaborateurDTO> collaborateurs = null; IEnumerable<CollaborateurDTO> collaborateurs = null;
try 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) catch(ApiException)
{ {
@ -200,16 +201,16 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(List<CollaborateurDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<CollaborateurDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;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<IActionResult> 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(..), ... //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); // return StatusCode(403, default(ErreurDTO));
logger.LogInformation("Récupération de la liste des collaborateurs du référent {idReferent}",idReferent); logger.LogInformation("Récupération de la liste des collaborateurs du référent {idReferent}",idReferent);
IEnumerable<CollaborateurDTO> collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); IEnumerable<CollaborateurDTO> collaborateurs = null;
try try
{ {
collaborateurs = collaborateurService.GetCollaborateursByReferent(idReferent, asc, numPage, parPAge, texte, tri); collaborateurs = await collaborateurService.GetCollaborateursByReferentAsync(idReferent, asc, numPage, parPAge, texte, tri);
} }
catch (ApiException) 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); 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: 200, type: typeof(ProfilDTO), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
public virtual IActionResult GetProfilCollaborateurByMail([FromRoute][Required]string mail) public virtual async Task<IActionResult> 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(..), ... //TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); // return StatusCode(403, default(ErreurDTO));
@ -255,7 +256,7 @@ namespace IO.Swagger.Controllers
ProfilDTO collaborateurDTO = null; ProfilDTO collaborateurDTO = null;
try try
{ {
collaborateurDTO = collaborateurService.GetProfilByMail(mail); collaborateurDTO = await collaborateurService.GetProfilByMailAsync(mail);
} }
catch (ApiException) catch (ApiException)
{ {

@ -18,6 +18,11 @@ using IO.Swagger.Attributes;
using IO.Swagger.Security; using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using IO.Swagger.DTO; 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 namespace IO.Swagger.Controllers
{ {
@ -26,7 +31,16 @@ namespace IO.Swagger.Controllers
/// </summary> /// </summary>
[ApiController] [ApiController]
public class EngagementsApiController : ControllerBase public class EngagementsApiController : ControllerBase
{ {
private readonly IEngagementService engagementService;
private readonly ILogger<EngagementsApiController> logger;
public EngagementsApiController(IEngagementService _engagementService, ILogger<EngagementsApiController> _logger)
{
engagementService = _engagementService;
logger = _logger;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
@ -41,25 +55,33 @@ namespace IO.Swagger.Controllers
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
[HttpGet] [HttpGet]
[Route("/api/engagements")] [Route("/api/engagements")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetEngagements")] [SwaggerOperation("GetEngagements")]
[SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetEngagements([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<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(..), ... logger.LogInformation("Récupération de la liste des engagements.");
// return StatusCode(200, default(List<EngagementDTO>));
IEnumerable<EngagementDTO> engagements = null;
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); try
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} ]"; engagements = await engagementService.GetEngagementsAsync(asc, numPage, parPAge, idAgence, texte, tri);
}
var example = exampleJson != null catch (ArgumentNullException)
? JsonConvert.DeserializeObject<List<EngagementDTO>>(exampleJson) {
: default(List<EngagementDTO>); //TODO: Change the data returned logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements est invalide.");
return new ObjectResult(example); }
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);
} }
/// <summary> /// <summary>
@ -76,25 +98,33 @@ namespace IO.Swagger.Controllers
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
[HttpGet] [HttpGet]
[Route("/api/engagements/enattente")] [Route("/api/engagements/enattente")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetEngagementsEnAttente")] [SwaggerOperation("GetEngagementsEnAttente")]
[SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetEngagementsEnAttente([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<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(..), ... logger.LogInformation("Récupération de la liste des engagements en attente.");
// return StatusCode(200, default(List<EngagementDTO>));
IEnumerable<EngagementDTO> engagements = null;
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); try
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} ]"; engagements = await engagementService.GetEngagementsEnAttenteAsync(asc, numPage, parPAge, idAgence, texte, tri);
}
var example = exampleJson != null catch (ArgumentNullException)
? JsonConvert.DeserializeObject<List<EngagementDTO>>(exampleJson) {
: default(List<EngagementDTO>); //TODO: Change the data returned logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements en attente est invalide.");
return new ObjectResult(example); }
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);
} }
/// <summary> /// <summary>
@ -111,25 +141,33 @@ namespace IO.Swagger.Controllers
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
[HttpGet] [HttpGet]
[Route("/api/engagements/repondus")] [Route("/api/engagements/repondus")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetEngagementsRepondus")] [SwaggerOperation("GetEngagementsRepondus")]
[SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<EngagementDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetEngagementsRepondus([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]long? idAgence, [FromQuery]string texte, [FromQuery]string tri) public virtual async Task<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(..), ... logger.LogInformation("Récupération de la liste des engagements répondus.");
// return StatusCode(200, default(List<EngagementDTO>));
IEnumerable<EngagementDTO> engagements = null;
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); try
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} ]"; engagements = await engagementService.GetEngagementsRepondusAsync(asc, numPage, parPAge, idAgence, texte, tri);
}
var example = exampleJson != null catch (ArgumentNullException)
? JsonConvert.DeserializeObject<List<EngagementDTO>>(exampleJson) {
: default(List<EngagementDTO>); //TODO: Change the data returned logger.LogError("Un des arguments passés dans la requête pour récupérer la liste des engagements répondus est invalide.");
return new ObjectResult(example); }
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);
} }
/// <summary> /// <summary>
@ -142,19 +180,50 @@ namespace IO.Swagger.Controllers
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
[HttpPut] [HttpPut]
[Route("/api/engagements/{idEngagement}/repondre")] [Route("/api/engagements/{idEngagement}/repondre")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("RepondreEngagement")] [SwaggerOperation("RepondreEngagement")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult RepondreEngagement([FromBody]EngagementDTO body, [FromRoute][Required]long? idEngagement) public virtual async Task<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(..), ... logger.LogInformation("Tentative de mise à jour de l'engagement {idEngagement}.", idEngagement);
// return StatusCode(200);
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(..), ... logger.LogInformation("Mise à jour de l'engagement {idEngagement} réussie.");
// return StatusCode(403, default(ErreurDTO));
throw new NotImplementedException(); return Ok(engagement);
} }
} }
} }

@ -11,16 +11,16 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes; using IO.Swagger.Attributes;
using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization;
using IO.Swagger.DTO; using IO.Swagger.DTO;
using EPAServeur.IServices; using EPAServeur.IServices;
using System.Reflection.Metadata.Ecma335; using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using EPAServeur.Exceptions;
using Microsoft.EntityFrameworkCore;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
@ -31,10 +31,12 @@ namespace IO.Swagger.Controllers
public class FormationsApiController : ControllerBase public class FormationsApiController : ControllerBase
{ {
private readonly IFormationService formationService; private readonly IFormationService formationService;
private readonly ILogger<FormationsApiController> logger;
public FormationsApiController(IFormationService _formationService) public FormationsApiController(IFormationService _formationService, ILogger<FormationsApiController> _logger)
{ {
formationService = _formationService; formationService = _formationService;
logger = _logger;
} }
/// <summary> /// <summary>
@ -50,19 +52,32 @@ namespace IO.Swagger.Controllers
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("AjouterFormation")] [SwaggerOperation("AjouterFormation")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult AjouterFormation([FromBody] FormationDTO body) public virtual async Task<IActionResult> 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); return Created("", nouvelleFormation);
//if (body.Id != null && body.Id > 0)
//{
// return StatusCode(201, body);
//}
//else
//{
// return NotFound();
//}
} }
/// <summary> /// <summary>
@ -78,17 +93,41 @@ namespace IO.Swagger.Controllers
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("DeleteFormation")] [SwaggerOperation("DeleteFormation")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult DeleteFormation([FromRoute][Required] long? idFormation) public virtual async Task<IActionResult> 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() ErreurDTO erreur = new ErreurDTO()
{ {
Code = "404", Code = "404",
Message = "Aucune formation trouvée" Message = "Aucune formation trouvée"
}; };
return NotFound(erreur); 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(); return NoContent();
} }
@ -113,10 +152,25 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;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<IActionResult> 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(..), ... logger.LogInformation("Récupération de la liste des formations annulées.");
IEnumerable<FormationDTO> formations = formationService.GetFormationAnnulees(asc, numPage, parPAge, idAgence, texte, tri);
IEnumerable<FormationDTO> 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) if (formations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -124,9 +178,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucune formation annulée" Message = "Aucune formation annulée"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des formations annulées récupérée.");
return Ok(formations); return Ok(formations);
} }
@ -146,18 +203,43 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(FormationDTO), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
public virtual IActionResult GetFormationById([FromRoute][Required] long? idFormation) public virtual async Task<IActionResult> GetFormationById([FromRoute][Required] long? idFormation)
{ {
FormationDTO formationDTO = formationService.GetFormationById(Convert.ToInt32(idFormation)); logger.LogInformation("Récupération de la formation {idFormation}.", idFormation);
if (formationDTO == null)
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() ErreurDTO erreurDTO = new ErreurDTO()
{ {
Code = "404", Code = "404",
Message = "La formation n'existe pas", Message = "La formation n'existe pas",
}; };
return NotFound(erreurDTO); 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); return Ok(formationDTO);
} }
@ -182,10 +264,25 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;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<IActionResult> 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(..), ... logger.LogInformation("Récupération de la liste des formations réalisées.");
IEnumerable<FormationDTO> formations = formationService.GetFormationRealisee(asc, numPage, parPAge, idAgence, texte, tri);
IEnumerable<FormationDTO> 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) if (formations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -193,9 +290,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucune formation réalisée" Message = "Aucune formation réalisée"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des formations réalisées récupérée.");
return Ok(formations); return Ok(formations);
} }
@ -220,10 +320,25 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetFormations")] [SwaggerOperation("GetFormations")]
[SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [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<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)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération de la liste des formations.");
IEnumerable<FormationDTO> formations = formationService.GetFormations(asc, numPage, parPAge, idAgence, texte, tri);
IEnumerable<FormationDTO> 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) if (formations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -231,9 +346,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucune formation" Message = "Aucune formation"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des formations récupérée.");
return Ok(formations); return Ok(formations);
} }
@ -250,10 +368,25 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetModesFormation")] [SwaggerOperation("GetModesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<ModeFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<ModeFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetModesFormation() public virtual async Task<IActionResult> GetModesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération de la liste des modes de formation.");
IEnumerable<ModeFormationDTO> modeFormations = formationService.GetModesFormation();
IEnumerable<ModeFormationDTO> 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) if (modeFormations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -261,9 +394,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucun mode de formation" Message = "Aucun mode de formation"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des modes de formation récupérée.");
return Ok(modeFormations); return Ok(modeFormations);
} }
@ -280,10 +416,25 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetOriginesFormation")] [SwaggerOperation("GetOriginesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<OrigineFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<OrigineFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetOriginesFormation() public virtual async Task<IActionResult> GetOriginesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération de la liste des origines de formation.");
IEnumerable<OrigineFormationDTO> origineFormations = formationService.GetOriginesFormation();
IEnumerable<OrigineFormationDTO> 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) if (origineFormations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -294,6 +445,8 @@ namespace IO.Swagger.Controllers
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des origines de formation récupérée.");
return Ok(origineFormations); return Ok(origineFormations);
} }
@ -318,10 +471,25 @@ namespace IO.Swagger.Controllers
[SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<FormationDetailsDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;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<IActionResult> 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(..), ... logger.LogInformation("Récupération de la liste des prochaines formations.");
IEnumerable<FormationDTO> formations = formationService.GetProchainesFormation(asc, numPage, parPAge, idAgence, texte, tri);
IEnumerable<FormationDTO> 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) if (formations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -329,9 +497,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucune prochaine formation" Message = "Aucune prochaine formation"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des prochaines formations récupérée.");
return Ok(formations); return Ok(formations);
} }
@ -348,10 +519,25 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetStatutsFormation")] [SwaggerOperation("GetStatutsFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<StatutFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<StatutFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetStatutsFormation() public virtual async Task<IActionResult> GetStatutsFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération de la liste des statuts de formation.");
IEnumerable<StatutFormationDTO> statutFormations = formationService.GetStatutsFormation();
IEnumerable<StatutFormationDTO> 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) if (statutFormations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -359,9 +545,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucun statut de formation" Message = "Aucun statut de formation"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des statuts de formation récupérée.");
return Ok(statutFormations); return Ok(statutFormations);
} }
@ -378,10 +567,25 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("GetTypesFormation")] [SwaggerOperation("GetTypesFormation")]
[SwaggerResponse(statusCode: 200, type: typeof(List<TypeFormationDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<TypeFormationDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult GetTypesFormation() public virtual async Task<IActionResult> GetTypesFormation()
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération de la liste des types de formation.");
IEnumerable<TypeFormationDTO> typeFormations = formationService.GetTypesFormation();
IEnumerable<TypeFormationDTO> 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) if (typeFormations == null)
{ {
ErreurDTO erreur = new ErreurDTO() ErreurDTO erreur = new ErreurDTO()
@ -389,9 +593,12 @@ namespace IO.Swagger.Controllers
Code = "404", Code = "404",
Message = "Aucun type de formation" Message = "Aucun type de formation"
}; };
return NotFound(erreur); return NotFound(erreur);
} }
logger.LogInformation("Liste des types de formation récupérée.");
return Ok(typeFormations); return Ok(typeFormations);
} }
@ -410,29 +617,64 @@ namespace IO.Swagger.Controllers
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("UpdateFormation")] [SwaggerOperation("UpdateFormation")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
public virtual IActionResult UpdateFormation([FromBody] FormationDTO body, [FromRoute][Required] long? idFormation) public virtual async Task<IActionResult> 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) 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 Created("", formation);
} }
return Ok(formation);
logger.LogInformation("Update effectué avec succès");
//switch (formationService.UpdateFormation(body)) return Ok(formation);
//{
// case 0:
// return Ok();
// case 1:
// return StatusCode(201);
// case 2:
// return Forbid();
// default:
// return NotFound();
//}
} }
} }
} }

@ -11,132 +11,232 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes; using IO.Swagger.Attributes;
using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization;
using IO.Swagger.DTO; 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 namespace IO.Swagger.Controllers
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
[ApiController] [ApiController]
public class ReferentsApiController : ControllerBase public class ReferentsApiController : ControllerBase
{ {
private readonly IReferentService referentService;
private readonly ILogger<ReferentsApiController> logger;
public ReferentsApiController(IReferentService _referentService, ILogger<ReferentsApiController> _logger)
{
referentService = _referentService;
logger = _logger;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <remarks>Récupérer la liste des référents d&#x27;un collaborateur</remarks> /// <remarks>Récupérer un referent par son id</remarks>
/// <param name="idReferent">id referent</param>
/// <response code="200">OK</response>
/// <response code="403">Acces interdit</response>
/// <response code="404">Ressource n&#x27;a pas été trouvée</response>
[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&#x27;a pas été trouvée")]
public virtual async Task<IActionResult> 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);
}
/// <summary>
///
/// </summary>
/// <remarks>Récupérer la liste de tous les referents</remarks>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param> /// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="idCollaborateur">id collaborateur</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param> /// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param> /// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="fonctions">Liste des fonctions des collaborateurs que l&#x27;on veut récupérer</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="idBU">id de la business unit à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param> /// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param> /// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <response code="200">OK</response> /// <response code="200">OK</response>
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
/// <response code="404">Ressource n&#x27;a pas été trouvée</response>
[HttpGet] [HttpGet]
[Route("/api/referents/collaborateur/{idCollaborateur}")] [Route("/api/referents")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetReferentByCollaborateur")] [SwaggerOperation("GetReferents")]
[SwaggerResponse(statusCode: 200, type: typeof(List<ReferentDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<ReferentDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] public virtual IActionResult GetReferents([FromQuery][Required()]bool? asc, [FromQuery][Required()]int? numPage, [FromQuery][Required()]int? parPAge, [FromQuery]List<string> fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri)
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) {
{ //IEnumerable<ReferentDTO> referentDTOs = referentService.GetReferents(asc,numPage,parPAge,fonctions,idAgence,idBU,texte,tri);
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... return NoContent();
// return StatusCode(200, default(List<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}, {\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<List<ReferentDTO>>(exampleJson)
: default(List<ReferentDTO>); //TODO: Change the data returned
return new ObjectResult(example);
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <remarks>Récupérer un referent par son id</remarks> /// <remarks>Récupérer le référent actuel d&#x27;un collaborateur</remarks>
/// <param name="idReferent">id referent</param> /// <param name="idCollaborateur">id collaborateur</param>
/// <response code="200">OK</response> /// <response code="200">OK</response>
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
/// <response code="404">Ressource n&#x27;a pas été trouvée</response> /// <response code="404">Ressource n&#x27;a pas été trouvée</response>
[HttpGet] [HttpGet]
[Route("/api/referents/{idReferent}")] [Route("/api/referents/actuel/collaborateur/{idCollaborateur}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetReferentById")] [SwaggerOperation("GetReferentActuelCollaborateur")]
[SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(ReferentDTO), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")]
[SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")] [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
public virtual IActionResult GetReferentById([FromRoute][Required]Guid? idReferent) public virtual async Task<IActionResult> GetReferentActuelCollaborateur([FromRoute][Required] Guid? idCollaborateur)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... logger.LogInformation("Récupération du référent actuel du collaborateur {idCollaborateur}.", idCollaborateur);
// return StatusCode(200, default(ReferentDTO));
ReferentDTO referentDTO = null;
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(403, default(ErreurDTO)); try
{
//TODO: Uncomment the next line to return response 404 or use other options such as return this.NotFound(), return this.BadRequest(..), ... referentDTO = await referentService.GetReferentActuelCollaborateurAsync(idCollaborateur);
// return StatusCode(404, default(ErreurDTO)); }
string exampleJson = null; catch (ApiException)
exampleJson = "{\n \"mailApside\" : \"\",\n \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n \"nom\" : \"nom\",\n \"prenom\" : \"prenom\",\n \"collaborateurs\" : [ null, null ]\n}"; {
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);
var example = exampleJson != null }
? JsonConvert.DeserializeObject<ReferentDTO>(exampleJson) catch (ReferentNotFoundException)
: default(ReferentDTO); //TODO: Change the data returned {
return new ObjectResult(example); 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);
} }
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <remarks>Récupérer la liste de tous les referents</remarks> /// <remarks>Récupérer la liste des référents d&#x27;un collaborateur</remarks>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param> /// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="idCollaborateur">id collaborateur</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param> /// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param> /// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="fonctions">Liste des fonctions des collaborateurs que l&#x27;on veut récupérer</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="idBU">id de la business unit à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param> /// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param> /// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <response code="200">OK</response> /// <response code="200">OK</response>
/// <response code="403">Acces interdit</response> /// <response code="403">Acces interdit</response>
/// <response code="404">Ressource n&#x27;a pas été trouvée</response>
[HttpGet] [HttpGet]
[Route("/api/referents")] [Route("/api/referents/collaborateur/{idCollaborateur}")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] //[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("GetReferents")] [SwaggerOperation("GetReferentByCollaborateur")]
[SwaggerResponse(statusCode: 200, type: typeof(List<ReferentDTO>), description: "OK")] [SwaggerResponse(statusCode: 200, type: typeof(List<ReferentDTO>), description: "OK")]
[SwaggerResponse(statusCode: 403, type: typeof(ErreurDTO), description: "Acces interdit")] [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<string> fonctions, [FromQuery]long? idAgence, [FromQuery]long? idBU, [FromQuery]string texte, [FromQuery]string tri) [SwaggerResponse(statusCode: 404, type: typeof(ErreurDTO), description: "Ressource n&#x27;a pas été trouvée")]
{ public virtual async Task<IActionResult> GetReferentsByCollaborateur([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<ReferentDTO>)); logger.LogInformation("Récupération de la liste des référents du collaborateur {idCollaborateur}.", idCollaborateur);
//TODO: Uncomment the next line to return response 403 or use other options such as return this.NotFound(), return this.BadRequest(..), ... IEnumerable<ReferentDTO> referentDTOs = null;
// return StatusCode(403, default(ErreurDTO));
string exampleJson = null; try
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} ]"; {
referentDTOs = await referentService.GetReferentsByCollaborateurAsync(asc, idCollaborateur, numPage, parPAge, texte, tri);
var example = exampleJson != null }
? JsonConvert.DeserializeObject<List<ReferentDTO>>(exampleJson) catch (ApiException)
: default(List<ReferentDTO>); //TODO: Change the data returned {
return new ObjectResult(example); 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);
} }
} }
} }

@ -38,14 +38,14 @@ namespace IO.Swagger.DTO
/// </summary> /// </summary>
[Required] [Required]
[DataMember(Name="type")] [DataMember(Name="type")]
public int? Type { get; set; } public string Type { get; set; }
/// <summary> /// <summary>
/// Gets or Sets Statut /// Gets or Sets Statut
/// </summary> /// </summary>
[Required] [Required]
[DataMember(Name="statut")] [DataMember(Name="statut")]
public int? Statut { get; set; } public string Statut { get; set; }
/// <summary> /// <summary>
/// Gets or Sets DateDisponibilite /// Gets or Sets DateDisponibilite
@ -80,7 +80,7 @@ namespace IO.Swagger.DTO
/// </summary> /// </summary>
[Required] [Required]
[DataMember(Name="referent")] [DataMember(Name="referent")]
public CollaborateurDTO Referent { get; set; } public ReferentDTO Referent { get; set; }
/// <summary> /// <summary>
/// Returns the string presentation of the object /// Returns the string presentation of the object

@ -66,6 +66,13 @@ namespace IO.Swagger.DTO
[DataMember(Name="nbPartitipants")] [DataMember(Name="nbPartitipants")]
public int? NbPartitipants { get; set; } public int? NbPartitipants { get; set; }
/// <summary>
/// Gets or Sets Origine
/// </summary>
[Required]
[DataMember(Name = "origine")]
public OrigineFormationDTO Origine { get; set; }
/// <summary> /// <summary>
/// Gets or Sets Mode /// Gets or Sets Mode
/// </summary> /// </summary>

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsque l'id de l'engagement avec les données à mettre à jour et l'id de l'engagement à mettre sont différents
/// </summary>
public class EngagementIncompatibleIdException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementIncompatibleIdException"/> class.
/// </summary>
public EngagementIncompatibleIdException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementIncompatibleIdException"/> class.
/// </summary>
/// <param name="message"></param>
public EngagementIncompatibleIdException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementIncompatibleIdException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public EngagementIncompatibleIdException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'un engagement est invalide
/// </summary>
public class EngagementInvalidException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementInvalidException"/> class.
/// </summary>
public EngagementInvalidException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementInvalidException"/> class.
/// </summary>
/// <param name="message"></param>
public EngagementInvalidException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementInvalidException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public EngagementInvalidException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'un engagement n'a pas été trouvé
/// </summary>
public class EngagementNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementNotFoundException"/> class.
/// </summary>
public EngagementNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public EngagementNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="EngagementNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public EngagementNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// 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
/// </summary>
public class FormationIncompatibleIdException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationIncompatibleIdException"/> class.
/// </summary>
public FormationIncompatibleIdException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationIncompatibleIdException"/> class.
/// </summary>
/// <param name="message"></param>
public FormationIncompatibleIdException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationIncompatibleIdException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public FormationIncompatibleIdException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'une formation est invalide
/// </summary>
public class FormationInvalidException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationInvalidException"/> class.
/// </summary>
public FormationInvalidException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationInvalidException"/> class.
/// </summary>
/// <param name="message"></param>
public FormationInvalidException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationInvalidException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public FormationInvalidException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'une formation n'a pas été trouvée
/// </summary>
public class FormationNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationNotFoundException"/> class.
/// </summary>
public FormationNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public FormationNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="FormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public FormationNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'un mode de formation n'a pas été trouvé
/// </summary>
public class ModeFormationNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="ModeFormationNotFoundException"/> class.
/// </summary>
public ModeFormationNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="ModeFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public ModeFormationNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="ModeFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public ModeFormationNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'une origine de formation n'a pas été trouvée
/// </summary>
public class OrigineFormationNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="OrigineFormationNotFoundException"/> class.
/// </summary>
public OrigineFormationNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="OrigineFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public OrigineFormationNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="OrigineFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public OrigineFormationNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'un statut de formation n'a pas été trouvé
/// </summary>
public class StatutFormationNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="StatutFormationNotFoundException"/> class.
/// </summary>
public StatutFormationNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="StatutFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public StatutFormationNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="StatutFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public StatutFormationNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Exceptions
{
/// <summary>
/// Exception à jeter lorsqu'un type de formation n'a pas été trouvé
/// </summary>
public class TypeFormationNotFoundException : Exception
{
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="TypeFormationNotFoundException"/> class.
/// </summary>
public TypeFormationNotFoundException()
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="TypeFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
public TypeFormationNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="TypeFormationNotFoundException"/> class.
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public TypeFormationNotFoundException(string message, Exception inner) : base(message, inner)
{
}
}
}

@ -12,10 +12,17 @@ namespace EPAServeur.IServices
public interface ICollaborateurService public interface ICollaborateurService
{ {
CollaborateurDTO GetCollaborateurById(Guid? id); CollaborateurDTO GetCollaborateurById(Guid? id);
Task<CollaborateurDTO> GetCollaborateurByIdAsync(Guid? id);
CollaborateurDTO GetCollaborateurByMail(string mail); CollaborateurDTO GetCollaborateurByMail(string mail);
Task<CollaborateurDTO> GetCollaborateurByMailAsync(string mail);
ProfilDTO GetProfilById(Guid? idCollaborateur); ProfilDTO GetProfilById(Guid? idCollaborateur);
Task<ProfilDTO> GetProfilByIdAsync(Guid? idCollaborateur);
ProfilDTO GetProfilByMail(string mail); ProfilDTO GetProfilByMail(string mail);
Task<ProfilDTO> GetProfilByMailAsync(string mail);
IEnumerable<CollaborateurDTO> GetCollaborateurs(bool? asc, int? numPage, int? parPage, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri); IEnumerable<CollaborateurDTO> GetCollaborateurs(bool? asc, int? numPage, int? parPage, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri);
Task<IEnumerable<CollaborateurDTO>> GetCollaborateursAsync(bool? asc, int? numPage, int? parPage, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri);
IEnumerable<CollaborateurDTO> GetCollaborateursByReferent(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri); IEnumerable<CollaborateurDTO> GetCollaborateursByReferent(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri);
Task<IEnumerable<CollaborateurDTO>> GetCollaborateursByReferentAsync(Guid? idReferent, bool? asc, int? numPage, int? parPage, string texte, string tri);
} }
} }

@ -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<EngagementDTO> GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
IEnumerable<EngagementDTO> GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
IEnumerable<EngagementDTO> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
Task<IEnumerable<EngagementDTO>> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri);
EngagementDTO RepondreEngagement(EngagementDTO engagement, long? idEngagement);
Task<EngagementDTO> RepondreEngagementAsync(EngagementDTO engagement, long? idEngagement);
}
}

@ -10,19 +10,31 @@ namespace EPAServeur.IServices
{ {
public interface IFormationService public interface IFormationService
{ {
FormationDTO GetFormationById(long? id); FormationDTO GetFormationById(long? idFormation);
Task<FormationDTO> GetFormationByIdAsync(long? idFormation);
IEnumerable<FormationDTO> GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable<FormationDTO> GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri);
IEnumerable<FormationDTO> GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable<FormationDTO> GetFormationAnnulees(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
IEnumerable<FormationDTO> GetFormationRealisee(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable<FormationDTO> GetFormationRealisee(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetFormationRealiseeAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
IEnumerable<FormationDTO> GetProchainesFormation(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri); IEnumerable<FormationDTO> GetProchainesFormation(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
Task<IEnumerable<FormationDTO>> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri);
IEnumerable<ModeFormationDTO> GetModesFormation(); IEnumerable<ModeFormationDTO> GetModesFormation();
Task<IEnumerable<ModeFormationDTO>> GetModesFormationAsync();
IEnumerable<OrigineFormationDTO> GetOriginesFormation(); IEnumerable<OrigineFormationDTO> GetOriginesFormation();
Task<IEnumerable<OrigineFormationDTO>> GetOriginesFormationAsync();
IEnumerable<StatutFormationDTO> GetStatutsFormation(); IEnumerable<StatutFormationDTO> GetStatutsFormation();
Task<IEnumerable<StatutFormationDTO>> GetStatutsFormationAsync();
IEnumerable<TypeFormationDTO> GetTypesFormation(); IEnumerable<TypeFormationDTO> GetTypesFormation();
Task<IEnumerable<TypeFormationDTO>> GetTypesFormationAsync();
FormationDTO AddFormation(FormationDTO formationDTO); FormationDTO AddFormation(FormationDTO formationDTO);
FormationDTO UpdateFormation(FormationDTO formationDTO); Task<FormationDTO> AddFormationAsync(FormationDTO formationDTO);
bool DeleteFormationById(long? id); FormationDTO UpdateFormation(long? idFormation, FormationDTO formationDTO);
Task<FormationDTO> UpdateFormationAsync(long? idFormation, FormationDTO formationDTO);
FormationDTO DeleteFormationById(long? idFormation);
Task<FormationDTO> DeleteFormationByIdAsync(long? idFormation);
} }
} }

@ -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<ReferentDTO> GetReferentByIdAsync(Guid? idReferent);
ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur);
Task<ReferentDTO> GetReferentActuelCollaborateurAsync(Guid? idCollaborateur);
IEnumerable<ReferentDTO> GetReferents(bool? asc, int? numPage, int? parPAge, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri);
Task<IEnumerable<ReferentDTO>> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri);
IEnumerable<ReferentDTO> GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri);
Task<IEnumerable<ReferentDTO>> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri);
}
}

@ -24,8 +24,8 @@ namespace EPAServeur.Models.EP
public class Ep public class Ep
{ {
public long Id { get; set; } public long Id { get; set; }
public string IdCollaborateur { get; set; } public Guid IdCollaborateur { get; set; }
public string IdReferent { get; set; } public Guid IdReferent { get; set; }
public long IdAgence { get; set; } public long IdAgence { get; set; }
public long IdBu { get; set; } public long IdBu { get; set; }
public string Fonction { get; set; } public string Fonction { get; set; }

@ -47,6 +47,19 @@ namespace EPAServeur.Services
return GetCollaborateurDTO(collaborateur); return GetCollaborateurDTO(collaborateur);
} }
/// <summary>
/// Récupérer un collaborateur en fonction d'un id de manière asynchrone
/// </summary>
/// <param name="id">Identifiant du collaborateur à renvoyer</param>
/// <returns>Le collaborateur corresponant à l'id en paramètre</returns>
public async Task<CollaborateurDTO> GetCollaborateurByIdAsync(Guid? id)
{
Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(id);
if (collaborateur == null)
throw new CollaborateurNotFoundException();
return GetCollaborateurDTO(collaborateur);
}
/// <summary> /// <summary>
/// Récupérer un collaborateur en fonction d'un mail /// Récupérer un collaborateur en fonction d'un mail
/// </summary> /// </summary>
@ -60,6 +73,19 @@ namespace EPAServeur.Services
return GetCollaborateurDTO(collaborateur); return GetCollaborateurDTO(collaborateur);
} }
/// <summary>
/// Récupérer un collaborateur en fonction d'un mail de manière asynchrone
/// </summary>
/// <param name="mail">Mail du collaborateur à renvoyer</param>
/// <returns>Le collaborateur correspondant au mail en paramètre</returns>
public async Task<CollaborateurDTO> GetCollaborateurByMailAsync(string mail)
{
Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail);
if (collaborateur == null)
throw new CollaborateurNotFoundException();
return GetCollaborateurDTO(collaborateur);
}
/// <summary> /// <summary>
/// Récupérer la liste de tous les collaborateurs /// Récupérer la liste de tous les collaborateurs
/// </summary> /// </summary>
@ -103,6 +129,49 @@ namespace EPAServeur.Services
return collaborateursDTO; return collaborateursDTO;
} }
/// <summary>
/// Récupérer la liste de tous les collaborateurs de manière asynchrone
/// </summary>
///
/// <param name="asc">Précise si la liste est trié dans l'ordre croissant ou décroissant</param>
/// <param name="numPage">Numéro de la page qui est affiché du côté front</param>
/// <param name="parPage">Nombre de collaborateurs à renvoyer</param>
/// <param name="fonctions">Liste des fonctions</param>
/// <param name="idAgence">id de l'agence à laquelle appartient les collaborateurs à récupérer</param>
/// <param name="idBU"></param>
/// <param name="texte">permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte</param>
/// <param name="tri">Choisir l'attribut par lequel est trié la liste</param>
/// <remarks>
/// <para> idBU est à prendre en compte avant l'idAgence</para>
/// <para> idAgence n'est à prendre en compte que si idBU est nul </para>
/// </remarks>
///
/// <returns>Renvoie la liste des collaborateurs en fonction des paramètres</returns>
public async Task<IEnumerable<CollaborateurDTO>> GetCollaborateursAsync(bool? asc, int? numPage, int? parPage, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri)
{
if (texte == null)
texte = "";
else
texte = texte.ToLower();
IEnumerable<Collaborateur> collaborateurs;
IEnumerable<CollaborateurDTO> 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<CollaborateurDTO>();
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;
}
/// <summary> /// <summary>
/// Récupérer les collaborateurs d'un référent /// Récupérer les collaborateurs d'un référent
/// </summary> /// </summary>
@ -141,6 +210,44 @@ namespace EPAServeur.Services
return collaborateursDTO; return collaborateursDTO;
} }
/// <summary>
/// Récupérer les collaborateurs d'un référent de manière asynchrone
/// </summary>
/// <param name="idReferent">id du référent des collaborateurs à récupérer</param>
/// <param name="asc">Précise si la liste est trié dans l'ordre croissant ou décroissant</param>
/// <param name="numPage">Numéro de la page qui est affiché du côté front</param>
/// <param name="parPage">Nombre de collaborateurs à renvoyer</param>
/// <param name="texte">permet de récupérer les collaborateurs dont le nom + prénom ou le prénom + nom contient le texte</param>
/// <param name="tri">Choisir l'attribut par lequel est trié la liste</param>
/// <returns>Renvoyer les collaborateurs du référent dont l'id est passé en paramètre</returns>
public async Task<IEnumerable<CollaborateurDTO>> 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<Collaborateur> collaborateurs = await collaborateurApi.ChercherCollabRefAsync(idReferent);
int skip = (numPage.Value - 1) * parPage.Value;
int take = parPage.Value;
IEnumerable<CollaborateurDTO> 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;
}
/// <summary> /// <summary>
/// Récupérer le profil d'un collaborateur par mail /// Récupérer le profil d'un collaborateur par mail
/// </summary> /// </summary>
@ -154,6 +261,19 @@ namespace EPAServeur.Services
return GetProfilDTO(collaborateur); return GetProfilDTO(collaborateur);
} }
/// <summary>
/// Récupérer le profil d'un collaborateur par mail de manière asynchrone
/// </summary>
/// <param name="mail">mail du collaborateur dont on cherche le profil</param>
/// <returns>Renvoie le profil correspondant au mail passé en paramètre</returns>
public async Task<ProfilDTO> GetProfilByMailAsync(string mail)
{
Collaborateur collaborateur = await collaborateurApi.ChercherCollabMailAsync(mail);
if (collaborateur == null)
throw new CollaborateurNotFoundException();
return GetProfilDTO(collaborateur);
}
/// <summary> /// <summary>
/// Récupérer un profil d'un collaborateur par l'id /// Récupérer un profil d'un collaborateur par l'id
/// </summary> /// </summary>
@ -174,6 +294,27 @@ namespace EPAServeur.Services
throw new CollaborateurNotFoundException(); throw new CollaborateurNotFoundException();
return GetProfilDTO(collaborateur); return GetProfilDTO(collaborateur);
} }
/// <summary>
/// Récupérer un profil d'un collaborateur par l'id de manière asynchrone
/// </summary>
/// <param name="idCollaborateur">id du collaborateur dont on cherche le profil</param>
/// <returns>Renvoie le profil correspondant à l'id passé en paramètre</returns>
public async Task<ProfilDTO> 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 #endregion
#region DTO To Object #region DTO To Object

@ -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
/// <summary>
/// Constructeur de la classe EngagementService
/// </summary>
/// <param name="_epContext"></param>
public EngagementService(EpContext _epContext, ICollaborateurService _collaborateurService, IReferentService _referentService)
{
epContext = _epContext;
collaborateurService = _collaborateurService;
referentService = _referentService;
}
#endregion
#region Méthodes Service
public IEnumerable<EngagementDTO> GetEngagements(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement));
return engagementDTOs;
}
public async Task<IEnumerable<EngagementDTO>> GetEngagementsAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement));
var results = await Task.WhenAll(engagementDTOs);
return results;
}
public IEnumerable<EngagementDTO> GetEngagementsEnAttente(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement));
return engagementDTOs;
}
public async Task<IEnumerable<EngagementDTO>> GetEngagementsEnAttenteAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement));
var results = await Task.WhenAll(engagementDTOs);
return results;
}
public IEnumerable<EngagementDTO> GetEngagementsRepondus(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTO(engagement));
return engagementDTOs;
}
public async Task<IEnumerable<EngagementDTO>> GetEngagementsRepondusAsync(bool? asc, int? numPage, int? parPAge, long? idAgence, string texte, string tri)
{
IEnumerable<Engagement> 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<EngagementDTO>();
var engagementDTOs = engagements.Where(engagement => engagement.Modalite.ToLower().Contains(texte)).Select(engagement => GetEngagementDTOAsync(engagement));
var results = await Task.WhenAll(engagementDTOs);
return results;
}
/// <summary>
/// Donner une réponse à un engagement
/// </summary>
/// <param name="engagementDTO"></param>
/// <param name="idEngagement"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Donner une réponse à un engagement de manière asynchrone
/// </summary>
/// <param name="engagementDTO"></param>
/// <param name="idEngagement"></param>
/// <returns></returns>
public async Task<EngagementDTO> 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
/// <summary>
/// Récupère un objet EngagementDTO en fonction d'un objet Engagement
/// </summary>
/// <param name="engagement"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet EngagementDTO en fonction d'un objet Engagement
/// </summary>
/// <param name="engagement"></param>
/// <returns></returns>
private async Task<EngagementDTO> 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;
}
/// <summary>
/// Récupère un objet EpInformationDTO en fonction d'un objet Ep
/// </summary>
/// <param name="ep"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet EpInformationDTO en fonction d'un objet Ep
/// </summary>
/// <param name="ep"></param>
/// <returns></returns>
private async Task<EpInformationDTO> 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
/// <summary>
/// Modifie un objet Engagement en fonction d'un objet FormationDTO
/// </summary>
/// <param name="engagement"></param>
/// <param name="engagementDTO"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet Ep en fonction d'un objet EpDTO
/// </summary>
/// <param name="origineFormationDTO"></param>
/// <returns></returns>
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
}
}

@ -1,4 +1,5 @@
using EPAServeur.Context; using EPAServeur.Context;
using EPAServeur.Exceptions;
using EPAServeur.IServices; using EPAServeur.IServices;
using EPAServeur.Models.Formation; using EPAServeur.Models.Formation;
using IO.Swagger.DTO; using IO.Swagger.DTO;
@ -6,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace EPAServeur.Services namespace EPAServeur.Services
{ {
@ -35,18 +37,37 @@ namespace EPAServeur.Services
/// <summary> /// <summary>
/// Récupérer une formation par son id /// Récupérer une formation par son id
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="idFormation"></param>
/// <returns></returns> /// <returns></returns>
public FormationDTO GetFormationById(long? id) public FormationDTO GetFormationById(long? idFormation)
{ {
Formation formation = epContext.Formation.Include(formation => formation.Statut) Formation formation = epContext.Formation.Include(formation => formation.Statut)
.Include(formation => formation.ModeFormation) .Include(formation => formation.ModeFormation)
.Include(formation => formation.Origine) .Include(formation => formation.Origine)
.Include(formation => formation.TypeFormation) .Include(formation => formation.TypeFormation)
.FirstOrDefault(formation => formation.Id == id); .FirstOrDefault(formation => formation.Id == idFormation);
if (formation == null) if (formation == null)
return null; throw new FormationNotFoundException();
return GetFormationDTO(formation);
}
/// <summary>
/// Récupérer une formation par son id de manière asynchrone
/// </summary>
/// <param name="idFormation"></param>
/// <returns></returns>
public async Task<FormationDTO> 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); return GetFormationDTO(formation);
} }
@ -61,7 +82,7 @@ namespace EPAServeur.Services
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param> /// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param> /// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<FormationDTO> GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri) public IEnumerable<FormationDTO> GetFormations(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri)
{ {
IEnumerable<Formation> formations; IEnumerable<Formation> formations;
IEnumerable<FormationDTO> formationDTOs; IEnumerable<FormationDTO> formationDTOs;
@ -74,39 +95,113 @@ namespace EPAServeur.Services
int skip = (numPage.Value - 1) * parPAge.Value; int skip = (numPage.Value - 1) * parPAge.Value;
int take = parPAge.Value; int take = parPAge.Value;
if (idAgence != null) if (statutFormation != null && idAgence != null)
{ {
try formations = epContext.Formation
{ .Include(formation => formation.Statut)
formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence) .Include(formation => formation.ModeFormation)
.Include(formation => formation.Statut) .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.ModeFormation)
.Include(formation => formation.Origine) .Include(formation => formation.Origine)
.Include(formation => formation.TypeFormation); .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;
}
/// <summary>
/// Récupérer la liste des formations de manière asynchrone
/// </summary>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <returns></returns>
public async Task<IEnumerable<FormationDTO>> GetFormationsAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, int? statutFormation, string texte, string tri)
{
IEnumerable<Formation> formations;
IEnumerable<FormationDTO> 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 else
{ {
try
{ formations = await epContext.Formation.Include(formation => formation.Statut)
formations = epContext.Formation.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation)
.Include(formation => formation.ModeFormation) .Include(formation => formation.Origine)
.Include(formation => formation.Origine) .Include(formation => formation.TypeFormation).ToListAsync();
.Include(formation => formation.TypeFormation);
}
catch (Exception ex)
{
throw;
}
} }
if (formations == null) if (formations == null)
return new List<FormationDTO>(); return null;
formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
@ -150,7 +245,51 @@ namespace EPAServeur.Services
.Include(formation => formation.TypeFormation); .Include(formation => formation.TypeFormation);
if (formations == null) if (formations == null)
return new List<FormationDTO>(); return null;
formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
return formationDTOs;
}
/// <summary>
/// Récupérer les formations annulées de manière asynchrone
/// </summary>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <returns></returns>
public async Task<IEnumerable<FormationDTO>> GetFormationAnnuleesAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri)
{
IEnumerable<Formation> formations;
IEnumerable<FormationDTO> 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)); formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
@ -182,39 +321,80 @@ namespace EPAServeur.Services
if (idAgence != null) if (idAgence != null)
{ {
try
{ formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3)
formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && formation.Statut.Id == 3) .Include(formation => formation.Statut)
.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation)
.Include(formation => formation.ModeFormation) .Include(formation => formation.Origine)
.Include(formation => formation.Origine) .Include(formation => formation.TypeFormation);
.Include(formation => formation.TypeFormation); }
}
catch (Exception ex) else
{ {
throw;
} formations = epContext.Formation.Where(formation => formation.Statut.Id == 3)
.Include(formation => formation.Statut)
.Include(formation => formation.ModeFormation)
.Include(formation => formation.Origine)
.Include(formation => formation.TypeFormation);
}
if (formations == null)
return null;
formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
return formationDTOs;
}
/// <summary>
/// Récupérer les formations réalisées de manière asynchrone
/// </summary>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <returns></returns>
public async Task<IEnumerable<FormationDTO>> GetFormationRealiseeAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri)
{
IEnumerable<Formation> formations;
IEnumerable<FormationDTO> 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 else
{ {
try
{ formations = await epContext.Formation.Where(formation => formation.Statut.Id == 3)
formations = epContext.Formation.Where(formation => formation.Statut.Id == 3) .Include(formation => formation.Statut)
.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation)
.Include(formation => formation.ModeFormation) .Include(formation => formation.Origine)
.Include(formation => formation.Origine) .Include(formation => formation.TypeFormation).ToListAsync();
.Include(formation => formation.TypeFormation);
}
catch (Exception ex)
{
throw;
}
} }
if (formations == null) if (formations == null)
return new List<FormationDTO>(); return null;
formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
@ -245,19 +425,14 @@ namespace EPAServeur.Services
int take = parPAge.Value; int take = parPAge.Value;
if (idAgence != null) if (idAgence != null)
try {
{ formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2))
formations = epContext.Formation.Where(formation => formation.IdAgence == idAgence && (formation.Statut.Id == 1 || formation.Statut.Id == 2)) .Include(formation => formation.Statut)
.Include(formation => formation.Statut) .Include(formation => formation.ModeFormation)
.Include(formation => formation.ModeFormation) .Include(formation => formation.Origine)
.Include(formation => formation.Origine) .Include(formation => formation.TypeFormation);
.Include(formation => formation.TypeFormation);
}
catch (Exception ex)
{
throw;
}
}
else else
{ {
formations = epContext.Formation.Where(formation => (formation.Statut.Id == 1 || formation.Statut.Id == 2)) formations = epContext.Formation.Where(formation => (formation.Statut.Id == 1 || formation.Statut.Id == 2))
@ -268,7 +443,7 @@ namespace EPAServeur.Services
} }
if (formations == null) if (formations == null)
return new List<FormationDTO>(); return null;
formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation)); formationDTOs = formations.Where(formation => formation.Intitule.ToLower().Contains(texte)).Select(formation => GetFormationDTO(formation));
@ -276,22 +451,87 @@ namespace EPAServeur.Services
} }
/// <summary> /// <summary>
/// Récupérer les modes de formation /// Récupérer les formations plannifiées et replannifiées de manère asynchrone
/// </summary> /// </summary>
/// <param name="asc">Préciser si les données sont dans l&#x27;ordre (true) ou dans l&#x27;ordre inverse (false)</param>
/// <param name="numPage">Numéro de la page du tableau qui affiche les données</param>
/// <param name="parPAge">Nombre d&#x27;éléments affiché sur chaque page du tableau</param>
/// <param name="idAgence">id de l&#x27;agence à laquelle sont rattachées les données à récupérer</param>
/// <param name="texte">Texte permettant d&#x27;identifier l&#x27;objet rechercher</param>
/// <param name="tri">Colonne du tableau sur lequel le tri s&#x27;effectue</param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<ModeFormationDTO> GetModesFormation() public async Task<IEnumerable<FormationDTO>> GetProchainesFormationAsync(bool? asc, int? numPage, int? parPAge, int? idAgence, string texte, string tri)
{ {
IEnumerable<ModeFormation> modeFormations; IEnumerable<Formation> formations;
IEnumerable<ModeFormationDTO> modeFormationDTOs; IEnumerable<FormationDTO> formationDTOs;
try
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;
}
/// <summary>
/// Récupérer les modes de formation
/// </summary>
/// <returns></returns>
public IEnumerable<ModeFormationDTO> GetModesFormation()
{
IEnumerable<ModeFormation> modeFormations;
IEnumerable<ModeFormationDTO> modeFormationDTOs;
modeFormations = epContext.ModeFormation;
if (modeFormations == null)
return null;
modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation));
return modeFormationDTOs;
}
/// <summary>
/// Récupérer les modes de formation de manière asynchrone
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<ModeFormationDTO>> GetModesFormationAsync()
{
IEnumerable<ModeFormation> modeFormations;
IEnumerable<ModeFormationDTO> modeFormationDTOs;
modeFormations = await epContext.ModeFormation.ToListAsync();
if (modeFormations == null)
return null;
modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation)); modeFormationDTOs = modeFormations.Select(modeFormation => GetModeFormationDTO(modeFormation));
return modeFormationDTOs; return modeFormationDTOs;
@ -306,14 +546,29 @@ namespace EPAServeur.Services
IEnumerable<OrigineFormation> origineFormations; IEnumerable<OrigineFormation> origineFormations;
IEnumerable<OrigineFormationDTO> origineFormationDTOs; IEnumerable<OrigineFormationDTO> origineFormationDTOs;
try origineFormations = epContext.OrigineFormation;
{
origineFormations = epContext.OrigineFormation; if (origineFormations == null)
} return null;
catch (Exception ex)
{ origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation));
throw;
} return origineFormationDTOs;
}
/// <summary>
/// Récupérer les origines de formation de manière asynchrone
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<OrigineFormationDTO>> GetOriginesFormationAsync()
{
IEnumerable<OrigineFormation> origineFormations;
IEnumerable<OrigineFormationDTO> origineFormationDTOs;
origineFormations = await epContext.OrigineFormation.ToListAsync();
if (origineFormations == null)
return null;
origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation)); origineFormationDTOs = origineFormations.Select(origineFormation => GetOrigineFormationDTO(origineFormation));
@ -329,15 +584,29 @@ namespace EPAServeur.Services
IEnumerable<StatutFormation> statutFormations; IEnumerable<StatutFormation> statutFormations;
IEnumerable<StatutFormationDTO> statutFormationDTOs; IEnumerable<StatutFormationDTO> statutFormationDTOs;
try statutFormations = epContext.StatutFormation;
{
statutFormations = epContext.StatutFormation;
}
catch (Exception ex)
{
throw; if (statutFormations == null)
} return null;
statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation));
return statutFormationDTOs;
}
/// <summary>
/// Récupérer les statuts de formation de manière asynchrone
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<StatutFormationDTO>> GetStatutsFormationAsync()
{
IEnumerable<StatutFormation> statutFormations;
IEnumerable<StatutFormationDTO> statutFormationDTOs;
statutFormations = await epContext.StatutFormation.ToListAsync();
if (statutFormations == null)
return null;
statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation)); statutFormationDTOs = statutFormations.Select(statutFormation => GetStatutFormationDTO(statutFormation));
@ -353,14 +622,29 @@ namespace EPAServeur.Services
IEnumerable<TypeFormation> typeFormations; IEnumerable<TypeFormation> typeFormations;
IEnumerable<TypeFormationDTO> typeFormationDTOs; IEnumerable<TypeFormationDTO> typeFormationDTOs;
try typeFormations = epContext.TypeFormation;
{
typeFormations = epContext.TypeFormation; if (typeFormations == null)
} return null;
catch (Exception ex)
{ typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation));
throw;
} return typeFormationDTOs;
}
/// <summary>
/// Récupérer les types de formation de manière asynchrone
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<TypeFormationDTO>> GetTypesFormationAsync()
{
IEnumerable<TypeFormation> typeFormations;
IEnumerable<TypeFormationDTO> typeFormationDTOs;
typeFormations = await epContext.TypeFormation.ToListAsync();
if (typeFormations == null)
return null;
typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation)); typeFormationDTOs = typeFormations.Select(typeFormation => GetTypeFormationDTO(typeFormation));
@ -374,27 +658,47 @@ namespace EPAServeur.Services
/// <returns></returns> /// <returns></returns>
public FormationDTO AddFormation(FormationDTO formationDTO) public FormationDTO AddFormation(FormationDTO formationDTO)
{ {
if (!IsFormationValide(formationDTO))
throw new FormationInvalidException();
Formation formation = new Formation(); Formation formation = new Formation();
formation = SetFormation(formation, formationDTO); formation = SetFormation(formation, formationDTO);
if (formation.Statut != null) if (formation.Statut != null)
{
epContext.StatutFormation.Attach(formation.Statut); epContext.StatutFormation.Attach(formation.Statut);
}
epContext.OrigineFormation.Attach(formation.Origine); epContext.OrigineFormation.Attach(formation.Origine);
epContext.ModeFormation.Attach(formation.ModeFormation); epContext.ModeFormation.Attach(formation.ModeFormation);
epContext.TypeFormation.Attach(formation.TypeFormation); epContext.TypeFormation.Attach(formation.TypeFormation);
epContext.Add(formation); epContext.Add(formation);
try epContext.SaveChanges();
{
epContext.SaveChanges(); return GetFormationDTO(formation);
} }
catch (Exception ex)
{ /// <summary>
throw; /// Ajouter une formation de manière asynchrone
} /// </summary>
/// <param name="formationDTO"></param>
/// <returns></returns>
public async Task<FormationDTO> 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); return GetFormationDTO(formation);
} }
@ -402,26 +706,50 @@ namespace EPAServeur.Services
/// <summary> /// <summary>
/// Modifier une formation /// Modifier une formation
/// </summary> /// </summary>
/// <param name="idFormation"></param>
/// <param name="formationDTO"></param> /// <param name="formationDTO"></param>
/// <returns></returns> /// <returns></returns>
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) if (formation == null)
{
return null; return null;
}
formation = SetFormation(formation, formationDTO); formation = SetFormation(formation, formationDTO);
try
{ epContext.SaveChanges();
epContext.SaveChanges();
} return GetFormationDTO(formation);
catch (Exception ex) }
{
throw; /// <summary>
} /// Modifier une formation de manière asynchrone
/// </summary>
/// <param name="idFormation"></param>
/// <param name="formationDTO"></param>
/// <returns></returns>
public async Task<FormationDTO> 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); return GetFormationDTO(formation);
} }
@ -429,32 +757,54 @@ namespace EPAServeur.Services
/// <summary> /// <summary>
/// Supprimer une formation /// Supprimer une formation
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="idFormation"></param>
/// <returns></returns> /// <returns></returns>
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) if (formation == null)
return false; throw new FormationNotFoundException();
epContext.Remove(formation); epContext.Remove(formation);
try
{
epContext.SaveChanges();
}
catch (Exception)
{
throw;
}
return true; epContext.SaveChanges();
return GetFormationDTO(formation);
} }
/// <summary>
/// Supprimer une formation de manière asynchrone
/// </summary>
/// <param name="idFormation"></param>
/// <returns></returns>
public async Task<FormationDTO> 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 #endregion
#region Méthodes Privée #region Méthodes Privée
/// <summary>
/// Vérifier si un objet FormationDTO est valide pour ajout ou mise à jour
/// </summary>
/// <remarks> Un objet FormationDTO est valide si aucune de ses propriétés n'est à null</remarks>
/// <param name="formation"></param>
/// <returns>true si l'objet est valide, false sinon</returns>
private bool IsFormationValide(FormationDTO formation)
{
return !(formation == null || formation.IdAgence == null || formation.Intitule == null || formation.Organisme == null);
}
#region Object to DTO #region Object to DTO
/// <summary> /// <summary>

@ -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
/// <summary>
/// Récupère un référent par son id
/// </summary>
/// <param name="idReferent"></param>
/// <returns></returns>
public ReferentDTO GetReferentById(Guid? idReferent)
{
Referent referent = referentApi.ChercherRefId(idReferent);
if (referent == null)
throw new ReferentNotFoundException();
return GetReferentDTO(referent);
}
/// <summary>
/// Récupère un référent par son id de manière asynchrone
/// </summary>
/// <param name="idReferent"></param>
/// <returns></returns>
public async Task<ReferentDTO> GetReferentByIdAsync(Guid? idReferent)
{
Referent referent = await referentApi.ChercherRefIdAsync(idReferent);
if (referent == null)
throw new ReferentNotFoundException();
return GetReferentDTO(referent);
}
/// <summary>
/// Récupère un référent en fonction d'un collaborateur
/// </summary>
/// <param name="idCollaborateur"></param>
/// <returns></returns>
public ReferentDTO GetReferentActuelCollaborateur(Guid? idCollaborateur)
{
Referent referent = referentApi.ChercherRefActuelCollabId(idCollaborateur);
if (referent == null)
throw new ReferentNotFoundException();
return GetReferentDTO(referent);
}
/// <summary>
/// Récupère un référent en fonction d'un collaborateur de manière asynchrone
/// </summary>
/// <param name="idCollaborateur"></param>
/// <returns></returns>
public async Task<ReferentDTO> GetReferentActuelCollaborateurAsync(Guid? idCollaborateur)
{
Referent referent = await referentApi.ChercherRefActuelCollabIdAsync(idCollaborateur);
if (referent == null)
throw new ReferentNotFoundException();
return GetReferentDTO(referent);
}
/// <summary>
/// Récupère la liste des référents pour une agence
/// </summary>
/// <param name="asc"></param>
/// <param name="numPage"></param>
/// <param name="parPAge"></param>
/// <param name="fonctions"></param>
/// <param name="idAgence"></param>
/// <param name="idBU"></param>
/// <param name="texte"></param>
/// <param name="tri"></param>
/// <returns></returns>
public IEnumerable<ReferentDTO> GetReferents(bool? asc, int? numPage, int? parPAge, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri)
{
throw new NotImplementedException();
////IEnumerable<Collaborateur> collaborateurs; // A changer (Sera utilisé pour récupérer la liste des référents par fonction
//IEnumerable<Referent> referents = null; // A changer
//IEnumerable<ReferentDTO> referentDTOs = null; // A changer
////List<Guid?> 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<ReferentDTO>();
//referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent));
//return referentDTOs;
}
/// <summary>
/// Récupère la liste des référents pour une agence de manière asynchrone
/// </summary>
/// <param name="asc"></param>
/// <param name="numPage"></param>
/// <param name="parPAge"></param>
/// <param name="fonctions"></param>
/// <param name="idAgence"></param>
/// <param name="idBU"></param>
/// <param name="texte"></param>
/// <param name="tri"></param>
/// <returns></returns>
public async Task<IEnumerable<ReferentDTO>> GetReferentsAsync(bool? asc, int? numPage, int? parPAge, List<string> fonctions, long? idAgence, long? idBU, string texte, string tri)
{
throw new NotImplementedException();
//IEnumerable<Referent> referents = null ; // A changer
//IEnumerable<ReferentDTO> 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<ReferentDTO>();
//referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent));
//return referentDTOs;
}
/// <summary>
/// Récupère la liste des référents pour un collaborateur
/// </summary>
/// <param name="asc"></param>
/// <param name="idCollaborateur"></param>
/// <param name="numPage"></param>
/// <param name="parPAge"></param>
/// <param name="texte"></param>
/// <param name="tri"></param>
/// <returns></returns>
public IEnumerable<ReferentDTO> GetReferentsByCollaborateur(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri)
{
IEnumerable<Referent> referents;
IEnumerable<ReferentDTO> 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<ReferentDTO>();
Collaborateur collaborateur = collaborateurApi.ChercherCollabId(idCollaborateur);
if (collaborateur == null)
throw new CollaborateurNotFoundException();
referents = referentApi.ChercherRefCollabId(idCollaborateur);
if (referents == null)
return new List<ReferentDTO>();
referentDTOs = referents.Where(referent => (referent.Nom + " " + referent.Prenom).ToLower().Contains(texte) || (referent.Prenom + " " + referent.Nom).ToLower().Contains(texte)).Select(referent => GetReferentDTO(referent));
return referentDTOs;
}
/// <summary>
/// Récupère la liste des référents pour un collaborateur de manère asynchrone
/// </summary>
/// <param name="asc"></param>
/// <param name="idCollaborateur"></param>
/// <param name="numPage"></param>
/// <param name="parPAge"></param>
/// <param name="texte"></param>
/// <param name="tri"></param>
/// <returns></returns>
public async Task<IEnumerable<ReferentDTO>> GetReferentsByCollaborateurAsync(bool? asc, Guid? idCollaborateur, int? numPage, int? parPAge, string texte, string tri)
{
IEnumerable<Referent> referents;
IEnumerable<ReferentDTO> 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<ReferentDTO>();
Collaborateur collaborateur = await collaborateurApi.ChercherCollabIdAsync(idCollaborateur);
if (collaborateur == null)
throw new CollaborateurNotFoundException();
referents = await referentApi.ChercherRefCollabIdAsync(idCollaborateur);
if (referents == null)
return new List<ReferentDTO>();
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
/// <summary>
/// Récupère un objet AgenceDTO en fonction d'un objet Agence
/// </summary>
/// <param name="agence"></param>
/// <returns></returns>
private AgenceDTO GetAgenceDTO(Agence agence)
{
if (agence == null)
return null;
AgenceDTO agenceDTO = new AgenceDTO()
{
Id = agence.Id,
Nom = agence.Nom,
Bu = new List<BusinessUnitDTO>()
};
agenceDTO.Bu = agence.Bus.Select(bu => new BusinessUnitDTO()
{
Id = bu.Id,
Nom = bu.Nom
}).ToList();
return agenceDTO;
}
/// <summary>
/// Récupère un objet BusinessUnitDTO en fonction d'un objet BU
/// </summary>
/// <param name="businessUnit"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet CollaborateurDTO en fonction d'un objet Collaborateur
/// </summary>
/// <param name="collaborateur"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet ReferentDTO en fonction d'un objet Referent
/// </summary>
/// <param name="referent"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Récupère un objet ReferentDTO en fonction d'un objet Collaborateur
/// </summary>
/// <param name="referent"></param>
/// <returns></returns>
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
}
}

@ -64,7 +64,8 @@ namespace EPAServeur
services.AddScoped<ICollaborateurService, CollaborateurService>(); services.AddScoped<ICollaborateurService, CollaborateurService>();
services.AddScoped<IFormationService, FormationService>(); services.AddScoped<IFormationService, FormationService>();
services.AddScoped<INoteService, NoteService>(); services.AddScoped<INoteService, NoteService>();
services.AddScoped<IReferentService, ReferentService>();
services.AddScoped<IEngagementService, EngagementService>();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

Loading…
Cancel
Save