using System; using System.Collections.Generic; using…
- User
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Objects; using System.Data.Objects.SqlClient; using System.Linq; using System.Net; using System.Reflection; using ServicesApiOcaPeek.Data; using ServicesApiOcaPeek.ExceptionPersonnalisees; using ServicesApiOcaPeek.Extensions; using ServicesApiOcaPeek.Models;
namespace ServicesApiOcaPeek.Helpers { /// /// Gestion de l'accès à la couche de données /// public class ServicesApiOcaPeekDataHelper : IDisposable { OCAPEEKEntities ent;
public virtual void Dispose() { ent.Dispose(); ent = null; } /// <summary> /// /// </summary> public ServicesApiOcaPeekDataHelper() { try { ent = new OCAPEEKEntities(); } catch (Exception exc) { Utils.ElmahLogException(exc); throw exc; } } #region Check connection base /// <summary> /// Permet de test si la base de données est disponible /// </summary> /// <returns></returns> internal bool CheckConnectionBase() { return ent.DatabaseExists(); } internal bool CheckAccessTable() { return ent.OP_VISITE.Any(); } #endregion public PAR_GEN_SERV GetParcGenServDansBdd(string environnement) { return ent.PAR_GEN_SERV.Where(w => w.PGS_ENV.Equals(environnement, StringComparison.OrdinalIgnoreCase)) .SingleOrDefault(); } /// <summary> /// recuperer les visites /// </summary> /// <param name="site">site</param> /// <param name="username">nom d'utilisateur</param> /// <param name="startDate">date de debut</param> /// <param name="endDate">date de fin</param> /// <param name="sortindex">nom propiete </param> /// <param name="sortdir">sans de l'ordre (exemple : 'ASC' pour croissant)</param> /// <param name="page">numéro de page</param> /// <param name="count">nombre element dans une page</param> /// <param name="archive"></param> /// <returns></returns> public ListePaginee<Visite> ListeVisites(string site = null, string username = null, DateTime? startDate = null, DateTime? endDate = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10, bool archive = false) { var req = ent.OP_VISITE .Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh }) .Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv }) .Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ov, joined.odh, joined.ovv, ovvs }) .Where(joined => (string.IsNullOrEmpty(site) || joined.ov.OPV_SITE.StartsWith(site)) && (string.IsNullOrEmpty(username) || joined.ov.OPV_COLLAB_USERNAME.StartsWith(username)) && (startDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) >= EntityFunctions.TruncateTime(startDate)) && (endDate == null || EntityFunctions.TruncateTime(joined.odh.OPDH_DATE_DEBUT) <= EntityFunctions.TruncateTime(endDate)) && (joined.ov.OPV_ARCHIVE == archive)) .Select(result => new Visite { id = result.ov.OPV_ID, archive = result.ov.OPV_ARCHIVE, description = result.ov.OPV_DESCRIPTION, site = result.ov.OPV_SITE, status = result.ov.OPV_STATUS, sujet = result.ov.OPV_SUJET, titre = result.ov.OPV_TITRE, type = result.ov.OPV_TYPE_VISITE, dateDebut = result.odh.OPDH_DATE_DEBUT, dateFin = result.odh.OPDH_DATE_FIN, duree = result.odh.OPDH_DUREE, heureArrivee = result.odh.OPDH_HEURE_ARRIVEE, heureDepart = result.odh.OPDH_HEURE_DEPART, badge = result.ovv.OPVVS_BADGE, overtime = result.ovv.OPVVS_OVERTIME, plaqueImmatriculation = result.ovv.OPVVS_PLAQUE_IMMATRICUL, parking = result.ovv.OPVVS_PARKING, nomCollaborateur = result.ov.OPV_COLLAB_USERNAME, contact = new VisiteContact { nom = result.ov.OPV_NOM_CONTACT, telephone = result.ov.OPV_TELEPHONE_CONTACT } }).OrderBy(x => EntityFunctions.DiffDays(x.dateDebut, DateTime.Now)).AsEnumerable(); req = req.Distinct(); var visiteListe = req.ToList(); List<Visite> listeVisite = new List<Visite>(); #region système de pagination int total = req.Count(); IEnumerable<Visite> elems = Enumerable.Empty<Visite>(); if (string.IsNullOrEmpty(sortindex)) { elems = req.AsEnumerable(); } else { var nomPropriete = typeof(Visite).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase)) { elems = req.OrderBy(x => nomPropriete.GetValue(x, null)); } else { elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null)); } } var res = elems.Skip((page - 1) * count).Take(count); #endregion return new ListePaginee<Visite> { count = count, elements = res.ToList(), page = page, total = total }; } public Visite GetVisite(int visiteId) { var listeVisiteur = GetListeVisiteurFromVisite(visiteId); var req = (from ov in ent.OP_VISITE join odh in ent.OP_DATE_HORAIRE on ov.OPV_ID equals odh.OPDH_OPV_ID join ovv in ent.OP_VISITE_VISITEUR on ov.OPV_ID equals ovv.OPVVS_OPV_ID join ovvs in ent.OP_VISITEUR on ovv.OPVVS_OPVS_ID equals ovvs.OPVS_ID where ( ov.OPV_ID.Equals(visiteId) ) select new Visite { archive = ov.OPV_ARCHIVE, badge = ovv.OPVVS_BADGE, dateDebut = odh.OPDH_DATE_DEBUT, dateFin = odh.OPDH_DATE_FIN, overtime = ovv.OPVVS_OVERTIME, titre = ov.OPV_TITRE, description = ov.OPV_DESCRIPTION, site = ov.OPV_SITE, type = ov.OPV_TYPE_VISITE, status = ov.OPV_STATUS, id = ov.OPV_ID, duree = odh.OPDH_DUREE, heureArrivee = odh.OPDH_HEURE_ARRIVEE, heureDepart = odh.OPDH_HEURE_DEPART, nomCollaborateur = ov.OPV_COLLAB_USERNAME, reponse = new VisiteReponse { refus = (bool)ovv.OPVVS_REFUS ? ovv.OPVVS_REFUS : false, raisonRefus = ovv.OPVVS_RAISON_REFUS }, contact = new VisiteContact { nom = ov.OPV_NOM_CONTACT, telephone = ov.OPV_TELEPHONE_CONTACT } }).AsEnumerable(); if (listeVisiteur.Count == 0) { throw new Exception("Aucun visiteur pour cette visite"); } var visiteWithVisiteurs = req.ToArray(); var visiteToReturn = req.FirstOrDefault(); visiteToReturn.reponse = null; for (var i = 0; i < visiteWithVisiteurs.Length; i++) { var visiteur = listeVisiteur.ElementAt(i); var visite = visiteWithVisiteurs.ElementAt(i); visiteur.reponse = visite.reponse; } if (visiteToReturn != null) { visiteToReturn.visiteurs = listeVisiteur; } //return visiteWithVisiteurs; return visiteToReturn; } public VisiteCourante GetVisiteByKey(string key) { var vvs = ent.OP_VISITE_VISITEUR.SingleOrDefault(v => v.OPVVS_CLE_LIEN == key); if (vvs == null) { throw new ExceptionNotFoundApi("Clé invalide"); } var visiteur = vvs.OP_VISITEUR; var visite = vvs.OP_VISITE; var odh = visite.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID); if (odh == null || vvs == null) { throw new ExceptionNotFoundApi("Erreur: Cette visite n'existe pas"); } return new VisiteCourante { archive = vvs.OP_VISITE.OPV_ARCHIVE, collabUsername = visite.OPV_COLLAB_USERNAME, confirmee = vvs.OPVVS_CONFIRMEE, overtime = vvs.OPVVS_OVERTIME, badge = vvs.OPVVS_BADGE, parking = vvs.OPVVS_PARKING, dateDebut = odh.OPDH_DATE_DEBUT, heureDebut = odh.OPDH_HEURE_ARRIVEE, heureDebutPrev = odh.OPDH_HEURE_DEBUT_PREV, dateDebutPrev = odh.OPDH_DATE_DEBUT_PREV, dateFinPrev = odh.OPDH_DATE_FIN_PREV, heureFinPrev = odh.OPDH_HEURE_FIN_PREV, description = visite.OPV_DESCRIPTION, donneeReponse = vvs.OPVVS_DONNEE_REPONSE, horaireId = odh.OPDH_ID, idVvs = vvs.OPVVS_ID, idVisite = visite.OPV_ID, idVisiteur = visiteur.OPVS_ID, email = visiteur.OPVS_EMAIL, nom = visiteur.OPVS_NOM, prenom = visiteur.OPVS_PRENOM, telephone = visiteur.OPVS_TELEPHONE, site = visite.OPV_SITE, status = visite.OPV_STATUS, titre = visite.OPV_TITRE, typeVisite = visite.OPV_TYPE_VISITE, duree = odh.OPDH_DUREE.HasValue ? odh.OPDH_DUREE.Value : 0, }; } /// <summary> /// Crée une visite /// </summary> /// <param name="valeur"></param> /// <returns>Identifiant de la visite crée</returns> public VisiteVisiteur CreerVisite(VisiteVisiteur valeur) { if (valeur.visiteurs.Count <= 0) { throw new Exception("Au moins un visiteur est requis"); } var visite = new OP_VISITE { OPV_ARCHIVE = false, OPV_DESCRIPTION = valeur.visite.description, OPV_SITE = valeur.visite.site, OPV_STATUS = valeur.visite.status, OPV_SUJET = valeur.visite.sujet, OPV_TITRE = valeur.visite.titre, OPV_TYPE_VISITE = valeur.visite.type, OPV_COLLAB_USERNAME = valeur.visite.initiateur, OPV_NOM_CONTACT = valeur.visite.contact.nom, OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone }; var dateHoraire = new OP_DATE_HORAIRE { OPDH_DATE_DEBUT = valeur.visite.dateDebut, OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee, OPDH_DUREE = valeur.visite.duree, OPDH_SITE = valeur.visite.site, OP_VISITE = visite, }; var index = 0; Random rnd = new Random(); valeur.visiteurs.ForEach((payloadVisiteur) => { OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR { // données globales OPVVS_BADGE = valeur.badge, OPVVS_OVERTIME = valeur.overtime, OP_VISITE = visite, OPVVS_PARKING = payloadVisiteur.parking, OPVVS_PLAQUE_IMMATRICUL = payloadVisiteur.plaqueImmatriculation, }; var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == payloadVisiteur.id); if (visiteurExistant != null) { visiteCourrante.OP_VISITEUR = visiteurExistant; } else { visiteCourrante.OP_VISITEUR = new OP_VISITEUR { OPVS_EMAIL = payloadVisiteur.email, OPVS_NOM = payloadVisiteur.nom, OPVS_PRENOM = payloadVisiteur.prenom, OPVS_TELEPHONE = payloadVisiteur.telephone, }; } string hash = UtilHelpers.GenSHA512($"{rnd.Next()}{visiteCourrante.OP_VISITEUR.OPVS_EMAIL}"); visiteCourrante.OPVVS_CLE_LIEN = hash; valeur.visiteurs[index].hashKey = hash; ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); index++; }); ent.OP_DATE_HORAIRE.AddObject(dateHoraire); ent.SaveChanges(); return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs }; } /// <summary> /// Modifier une visite /// </summary> /// <param name="id"></param> /// <param name="valeur"></param> /// <returns></returns> /// public VisiteVisiteur ModifierVisite(int id, VisiteVisiteur valeur) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { throw new ExceptionDataConstraint("La visite n'existe pas"); } visite.OPV_ARCHIVE = valeur.visite.archive; visite.OPV_DESCRIPTION = valeur.visite.description; visite.OPV_SITE = valeur.visite.site; visite.OPV_STATUS = valeur.visite.status; visite.OPV_SUJET = valeur.visite.sujet; visite.OPV_TITRE = valeur.visite.titre; visite.OPV_TYPE_VISITE = valeur.visite.type; visite.OPV_COLLAB_USERNAME = valeur.visite.initiateur; visite.OPV_NOM_CONTACT = valeur.visite.contact.nom; visite.OPV_TELEPHONE_CONTACT = valeur.visite.contact.telephone; var dateHoraire = ent.OP_DATE_HORAIRE.SingleOrDefault(dh => dh.OPDH_OPV_ID == visite.OPV_ID); if (dateHoraire == null) { throw new ExceptionDataConstraint("La date de la visite n'existe pas"); } dateHoraire.OPDH_DATE_DEBUT = valeur.visite.dateDebut; dateHoraire.OPDH_HEURE_ARRIVEE = valeur.visite.heureArrivee; dateHoraire.OPDH_DUREE = valeur.visite.duree; ent.SaveChanges(); AddVisitorsToVisit(id, valeur.visiteurs); return new VisiteVisiteur() { id = visite.OPV_ID, visite = valeur.visite, visiteurs = valeur.visiteurs }; } //AddVisitorsToVisit public void AddVisitorsToVisit(int id, List<Visiteur> visiteurs) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { throw new ExceptionDataConstraint("La visite n'existe pas"); } visite.OP_VISITE_VISITEUR.ToList().ForEach(v => ent.OP_VISITE_VISITEUR.DeleteObject(v)); visiteurs.ForEach((visiteur) => { OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR { // données globales OP_VISITE = visite, OPVVS_PARKING = visiteurs[0].parking, OPVVS_PLAQUE_IMMATRICUL = visiteurs[0].plaqueImmatriculation, }; var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == visiteur.id); if (visiteurExistant != null) { visiteCourrante.OP_VISITEUR = visiteurExistant; } else { visiteCourrante.OP_VISITEUR = new OP_VISITEUR { OPVS_EMAIL = visiteur.email, OPVS_NOM = visiteur.nom, OPVS_PRENOM = visiteur.prenom, OPVS_TELEPHONE = visiteur.telephone, }; } ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); }); ent.SaveChanges(); } /// <summary> /// /// </summary> /// <param name="nom"></param> /// <param name="prenom"></param> /// <param name="username"></param> /// <param name="sortindex"></param> /// <param name="sortdir"></param> /// <param name="page"></param> /// <param name="count"></param> /// <returns></returns> public ListePaginee<Visiteur> ListeVisiteur(string nom = null, string prenom = null, string username = null, string sortindex = null, string sortdir = "ASC", int page = 1, int count = 10) { var req = ent.OP_VISITEUR .Join(ent.OP_VISITE_VISITEUR, ov => ov.OPVS_ID, ovv => ovv.OPVVS_OPVS_ID, (ov, ovv) => new Visiteur { nom = ov.OPVS_NOM, prenom = ov.OPVS_PRENOM, email = ov.OPVS_EMAIL, telephone = ov.OPVS_TELEPHONE, id = ov.OPVS_ID }) .Where(ov => (string.IsNullOrEmpty(nom) || ov.nom.StartsWith(nom)) && (string.IsNullOrEmpty(prenom) || ov.prenom.StartsWith(prenom))) .Distinct() .AsEnumerable(); #region système de pagination int total = req.Count(); IEnumerable<Visiteur> elems = Enumerable.Empty<Visiteur>(); if (string.IsNullOrEmpty(sortindex)) { elems = req; } else { var nomPropriete = typeof(Visiteur).GetProperty(sortindex, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (sortdir.Equals("ASC", StringComparison.InvariantCultureIgnoreCase)) { elems = req.OrderBy(x => nomPropriete.GetValue(x, null)); } else { elems = req.OrderByDescending(x => nomPropriete.GetValue(x, null)); } } var res = elems.Skip((page - 1) * count).Take(count); #endregion return new ListePaginee<Visiteur> { count = count, elements = res.ToList(), page = 0, total = total }; } /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="valeur"></param> /// <returns></returns> public VisiteVisiteur ModifierVisiteur(int id, VisiteVisiteur valeur) { var visiteur = ent.OP_VISITEUR.SingleOrDefault(v => v.OPVS_ID == id); if (visiteur == null) { throw new ExceptionDataConstraint("Le visiteur n'existe pas"); } visiteur.OPVS_NOM = valeur.visiteurs[0].nom; visiteur.OPVS_PRENOM = valeur.visiteurs[0].prenom; visiteur.OPVS_EMAIL = valeur.visiteurs[0].email; visiteur.OPVS_TELEPHONE = valeur.visiteurs[0].telephone; ent.SaveChanges(); return new VisiteVisiteur() { id = visiteur.OPVS_ID, visite = valeur.visite, visiteurs = valeur.visiteurs }; } public VisiteVisiteur EnvoieReponseVisite(int visiteId, int visiteurId, VisiteReponse valeur) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; if (visiteCourante.OPVVS_DONNEE_REPONSE == true) { throw new ExceptionDataConstraint("Le visiteur à déja repondu à la visite"); } visiteCourante.OPVVS_DONNEE_REPONSE = true; if ((bool)valeur.refus) { visiteCourante.OPVVS_REFUS = valeur.refus; visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus; } visiteCourante.OPVVS_PLAQUE_IMMATRICUL = valeur.plaqueImmat; visiteCourante.OPVVS_PARKING = valeur.parking; var estCurrVisiteRefusee = estVisiteRefusee(result.Item2); var estVisiteInitie = !estCurrVisiteRefusee && estVisiteInitiee(result.Item2); if (estCurrVisiteRefusee) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (estVisiteInitie) // si tous les visiteurs ont repondu { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.CONFIRMATION_INITIATEUR; } ent.SaveChanges(); return new VisiteVisiteur(); } public VisiteVisiteur EnvoieRefusVisiteur(int visiteId, int visiteurId, VisiteReponse valeur) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; if (!visiteCourante.OPVVS_DONNEE_REPONSE) { throw new ExceptionDataConstraint("Le visiteur n'a pas encore donnée sa réponse"); } if (valeur.refus.HasValue && valeur.refus.Value) { visiteCourante.OPVVS_REFUS = valeur.refus; visiteCourante.OPVVS_RAISON_REFUS = valeur.raisonRefus; } visiteCourante.OPVVS_CONFIRMEE = true; bool isVisitRefusee = estVisiteRefusee(result.Item2); bool isVisitProgramme = !isVisitRefusee && estVisiteProgramme(result.Item2); if (estVisiteRefusee(result.Item2)) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (isVisitProgramme) // si tous les visiteurs ont repondu { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE; } ent.SaveChanges(); return new VisiteVisiteur { }; } public HttpResponseExtension SignalerPresenceVisiteur(int visiteId, int visiteurId) { var result = GetVisiteCourante(visiteId, visiteurId); HttpResponseExtension reponse = new HttpResponseExtension(); var visiteCourante = result.Item1; if (!visiteCourante.OPVVS_DONNEE_REPONSE || !visiteCourante.OPVVS_CONFIRMEE || (visiteCourante.OPVVS_REFUS.HasValue && visiteCourante.OPVVS_REFUS.Value)) { throw new ExceptionDataConstraint("Erreur: L'Etat du visiteur n'est pas valide"); } visiteCourante.OPVVS_PRESENT = true; var estCurrVisiteEnCours = estVisiteEnCours(result.Item2); if (estCurrVisiteEnCours) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.EN_COURS; reponse.statusUpdated = true; } ent.SaveChanges(); reponse.message = "Le visiteur à été signalé comme entré"; return reponse; } public Tuple<OP_VISITE_VISITEUR, List<OP_VISITE_VISITEUR>> GetVisiteCourante(int visiteId, int visiteurId) { var visiteVisiteurs = ent.OP_VISITE_VISITEUR.Where(vvs => vvs.OP_VISITE.OPV_ID == visiteId).ToList(); var dataVisiteCourante = visiteVisiteurs.Where(visiteur => visiteur.OP_VISITEUR.OPVS_ID == visiteurId).SingleOrDefault(); if (dataVisiteCourante == null || dataVisiteCourante == null) { throw new ExceptionDataConstraint("Aucun visiteur ou aucune visite existante"); } return Tuple.Create(dataVisiteCourante, visiteVisiteurs); } public bool estVisiteRefusee(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_REFUS == true).Count() == ovvs.Count(); } public bool estVisiteProgramme(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_CONFIRMEE == true).Count() == ovvs.Count(); } public bool estVisiteInitiee(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_DONNEE_REPONSE == true).Count() == ovvs.Count(); } public bool estVisiteEnCours(List<OP_VISITE_VISITEUR> ovvs) { return ovvs.Where(v => v.OPVVS_PRESENT == true).Count() == ovvs.Count(); } public bool ConfirmationVisiteur(int visiteId, int visiteurId) { var result = GetVisiteCourante(visiteId, visiteurId); var visiteCourante = result.Item1; visiteCourante.OPVVS_CONFIRMEE = true; bool estCurrVisiteRefuse = estVisiteRefusee(result.Item2); bool estCurrVisiteProgramme = estVisiteProgramme(result.Item2); if (estCurrVisiteRefuse) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.REFUSEE; } if (estCurrVisiteProgramme) { visiteCourante.OP_VISITE.OPV_STATUS = VisiteStatus.PROGRAMMEE; } ent.SaveChanges(); return true; } public List<Visiteur> GetListeVisiteurFromVisite(int visiteId) { var visiteurQuery = ent.OP_VISITE .Join(ent.OP_DATE_HORAIRE, ov => ov.OPV_ID, odh => odh.OPDH_OPV_ID, (ov, odh) => new { ov, odh }) .Join(ent.OP_VISITE_VISITEUR, joined => joined.ov.OPV_ID, ovv => ovv.OPVVS_OPV_ID, (joined, ovv) => new { joined.ov, joined.odh, ovv }) .Join(ent.OP_VISITEUR, joined => joined.ovv.OPVVS_OPVS_ID, ovvs => ovvs.OPVS_ID, (joined, ovvs) => new { joined.ovv, ovvs }) .Where(joined => joined.ovv.OPVVS_OPV_ID == visiteId) .Select(result => new { result.ovvs.OPVS_NOM, result.ovvs.OPVS_PRENOM, result.ovvs.OPVS_EMAIL, result.ovvs.OPVS_TELEPHONE, result.ovvs.OPVS_ID, result.ovv.OPVVS_PLAQUE_IMMATRICUL, result.ovv.OPVVS_PARKING, result.ovv.OPVVS_DONNEE_REPONSE, result.ovv.OPVVS_CONFIRMEE, result.ovv.OPVVS_RAISON_REFUS, result.ovv.OPVVS_REFUS, result.ovv.OPVVS_PRESENT }); var visiteurListe = visiteurQuery.ToList(); if (visiteurListe.Count == 0) throw new DataNotFoundException("Les données demandées n'existent pas"); List<Visiteur> listeVisiteur = new List<Visiteur>(); visiteurListe.ForEach((OP_VISITEUR) => { listeVisiteur.Add(new Visiteur { nom = OP_VISITEUR.OPVS_NOM, prenom = OP_VISITEUR.OPVS_PRENOM, telephone = OP_VISITEUR.OPVS_TELEPHONE, email = OP_VISITEUR.OPVS_EMAIL, plaqueImmatriculation = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL, id = OP_VISITEUR.OPVS_ID, parking = OP_VISITEUR.OPVVS_PARKING, donneeReponse = OP_VISITEUR.OPVVS_DONNEE_REPONSE, confirmer = OP_VISITEUR.OPVVS_CONFIRMEE, present = OP_VISITEUR.OPVVS_PRESENT, reponse = new VisiteReponse { raisonRefus = OP_VISITEUR.OPVVS_RAISON_REFUS, refus = OP_VISITEUR.OPVVS_REFUS, plaqueImmat = OP_VISITEUR.OPVVS_PLAQUE_IMMATRICUL } }); }); return listeVisiteur; } /// <summary> /// Créer une date horaire /// </summary> /// <param name="valeur"></param> /// <returns></returns> public DateHoraire CreeHoraire(DateHoraire valeur) { return new DateHoraire() { }; } /// <summary> /// Création d'un visiteur /// </summary> /// <param name="value"></param> /// <returns></returns> public Visiteur CreerVisiteur(Visiteur value) { return new Visiteur { }; } public Visite ArchiveVisite(int id) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { return null; } visite.OPV_ARCHIVE = true; ent.SaveChanges(); return new Visite { id = id }; } }}
- Assistant
The provided code represents a data access helper class,
ServicesApiOcaPeekDataHelper, within a fictional application, presumably for managing visits (visites) and visitors (visiteurs) for a facility or an organization. The class is designed to interact with an Entity Framework model,OCAPEEKEntities, and provides various methods to perform CRUD operations and queries against the database.Here's a high-level breakdown of its functionalities:
-
Construction and Disposal: The constructor initializes an
OCAPEEKEntitiescontext which is then disposed of when the data helper itself is disposed of, following the Dispose pattern for managing unmanaged resources. -
Database Connection Check: Methods like
CheckConnectionBaseandCheckAccessTableare designed to test the availability and accessibility of the database and specific tables within it. -
Query Methods: Several methods, such as
GetParcGenServDansBdd,ListeVisites,GetVisite,ListeVisiteur, etc., are intended for fetching and parsing data from the database. These methods facilitate the retrieval of lists of visits and visitors with filtering, sorting, and paging capabilities. Each method translates LINQ queries into SQL queries that the Entity Framework executes against the database, returning projected objects (Visite,Visiteur, etc.) according to the operations defined (e.g., joining tables, applying conditions). -
Modification and Creation: The class also offers functionalities to create or modify entities in the database, such as
CreerVisite,ModifierVisite,CreerVisiteur, etc. These methods involve adding or updating records in the relevant tables. The modifications are then persisted to the database via the Entity Framework'sSaveChangesmethod. -
Specialized Actions: Other methods, like
EnvoieReponseVisite,SignalerPresenceVisiteur, etc., are designed for more specialized operations, such as recording a visitor's response to a visit invitation or signaling a visitor's presence. -
Utility Functions: The class also includes utility methods like
GetVisiteCourante,estVisiteRefusee,estVisiteProgramme, etc., which support conditional checks, data aggregation, or auxiliary operations required by other key functionalities.
The overall design demonstrates an integration of business logic within data access operations, which are tightly coupled with the
OCAPEEKEntitiesEntity Framework model. Each operation reflects specific business requirements, manipulating and querying data as needed for the application's functionality.The coding style adheres to clean coding practices, with clear separation of concerns within each method and careful handling of database contexts to avoid resource leaks. The naming convention and structure suggest a focus on maintaining readability and manageability of the code. However, a best practice would be to further separate concerns by abstracting business logic from direct data access operations, potentially using a repository pattern or similar architectural approaches for better modularity and testability.
-
- User
[SwaggerResponse(HttpStatusCode.NotFound, Description = "Aucun visiteur ou visite")] [SwaggerResponse(HttpStatusCode.OK, "Le visiteur à été ajouté")] [ActionName("AddVisitorToVisit")] [HttpPatch] public HttpResponseMessage AjouterVisiteurAVisite([FromUri] int visiteId, [FromUri] int visiteurId) { using (var dbcontext = new ServicesApiOcaPeekDataHelper()) { HttpResponseMessage retour = null; try { var resultat = dbcontext.AddVisitorsToVisit(visiteId, new List(visiteurId)); if (resultat == null) retour = Request.CreateResponse(HttpStatusCode.NotFound, "Aucun visiteur pour la visite " + visiteId + " ."); else retour = Request.CreateResponse(HttpStatusCode.OK, ""); } catch (Exception exc) { Utils.ElmahLogException(exc); throw exc; }
return retour; } } fix this AjouterVisiteurAVisite method corresponding with AddVisitorsToVisit method - Assistant
To fix the
AjouterVisiteurAVisitemethod so that it correctly corresponds and integrates with theAddVisitorsToVisitmethod from theServicesApiOcaPeekDataHelper, we need to address a few issues and misalignments in the initial code snippet:- Conversion Issue: Directly creating a
List<Visiteur>withvisiteurIdas an argument will cause a compilation error becausevisiteurIdis anintand cannot be directly converted into a list ofVisiteurobjects. - Response Content: On successful addition of a visitor to a visit, it could be more informative to return a success message or details about the operation instead of an empty string.
- Exception Handling: Rethrowing the exception as
throw exc;can disrupt the stack trace; usually, it's better to use simplythrow;to rethrow the current exception. - Method Return Type: The method is currently expected to return
HttpResponseMessage, which aligns with older Web API patterns. If using ASP.NET Core, you might consider usingIActionResultinstead.
Given these issues, here's an updated and corrected version of the method, assuming the method
AddVisitorsToVisithas been correctly implemented and designed to accept one or moreVisiteurobjects to add to a specific visit. Also, assuming you are using theServicesApiOcaPeekDataHelperin an older Web API context due to the return type:[SwaggerResponse(HttpStatusCode.NotFound, Description = "Aucun visiteur ou visite")] [SwaggerResponse(HttpStatusCode.OK, "Le visiteur a été ajouté")] [ActionName("AddVisitorToVisit")] [HttpPatch] public HttpResponseMessage AjouterVisiteurAVisite([FromUri] int visiteId, [FromUri] int visiteurId) { using (var dbcontext = new ServicesApiOcaPeekDataHelper()) { HttpResponseMessage retour = null; try { // Assuming there's a way to fetch a visitor by their ID var visiteur = dbcontext.GetVisiteurById(visiteurId); // This method needs to be implemented in the data helper if (visiteur == null) { retour = Request.CreateResponse(HttpStatusCode.NotFound, "Visiteur " + visiteurId + " introuvable."); return retour; } // We have the visiteur object now and can wrap it in a list to pass to AddVisitorsToVisit var resultat = dbcontext.AddVisitorsToVisit(visiteId, new List<Visiteur> { visiteur }); // Deciding on the response based on the outcome, assuming AddVisitorsToVisit returns a boolean or similar. if (resultat) retour = Request.CreateResponse(HttpStatusCode.OK, "Visiteur ajouté à la visite " + visiteId + "."); else retour = Request.CreateResponse(HttpStatusCode.NotFound, "Aucun visiteur pour la visite " + visiteId + "."); } catch (Exception exc) { Utils.ElmahLogException(exc); // Logging the exception retour = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Une erreur est survenue."); } return retour; } }This code still assumes you have a method
GetVisiteurById(int visiteurId)within yourServicesApiOcaPeekDataHelperclass or an equivalent way to retrieve aVisiteurobject by its ID. The exact implementation may vary depending on your data model and business logic. - Conversion Issue: Directly creating a
- User
décris-moi ce code : public VisiteVisiteur AddVisitorsToVisit(int id, List visiteurs) { var visite = ent.OP_VISITE.SingleOrDefault(v => v.OPV_ID == id); if (visite == null) { throw new ExceptionDataConstraint("La visite n'existe pas"); }
visite.OP_VISITE_VISITEUR.ToList().ForEach(v => ent.OP_VISITE_VISITEUR.DeleteObject(v)); visiteurs.ForEach((visiteur) => { OP_VISITE_VISITEUR visiteCourrante = new OP_VISITE_VISITEUR { // données globales OP_VISITE = visite, OPVVS_PARKING = visiteurs[0].parking, OPVVS_PLAQUE_IMMATRICUL = visiteurs[0].plaqueImmatriculation, }; var visiteurExistant = ent.OP_VISITEUR.SingleOrDefault(ov => ov.OPVS_ID == visiteur.id); if (visiteurExistant != null) { visiteCourrante.OP_VISITEUR = visiteurExistant; } else { visiteCourrante.OP_VISITEUR = new OP_VISITEUR { OPVS_EMAIL = visiteur.email, OPVS_NOM = visiteur.nom, OPVS_PRENOM = visiteur.prenom, OPVS_TELEPHONE = visiteur.telephone, }; } ent.OP_VISITE_VISITEUR.AddObject(visiteCourrante); }); ent.SaveChanges(); return null; } - Assistant
This method,
AddVisitorsToVisit, appears to belong to a backend service responsible for managing visits and visitors within an application, likely a part of a larger system designed for scheduling or tracking visits, such as a visitor management system for offices, buildings, or facilities.Purpose:
The primary function of this method is to associate a list of visitors (
List<Visiteur> visiteurs) with a specific visit (int id) within a database. It adds records to the junction (association or linking) table that connects visitors with visits, effectively documenting which visitors are part of which visit.Process:
-
Locate the Visit: The method starts by attempting to find a visit in the database with the matching
id. This is accomplished via theSingleOrDefaultLINQ method onent.OP_VISITE, whereentis presumably an Entity Framework database context. If no such visit exists, an exception is thrown, indicating a data constraint violation. -
Remove Existing Associations: It then clears any existing records in the junction table (
OP_VISITE_VISITEUR) related to this visit. This step indicates that any time visitors are added to a visit, it resets the list of visitors for that visit entirely. -
Process Each Visitor:
- For each visitor in the provided list, it creates a new junction table entity (
OP_VISITE_VISITEUR visiteCourrante) to hold the association between the visit and the visitor. - It checks if the visitor already exists in the database (
ent.OP_VISITEUR) by matchingvisiteur.id. If the visitor exists, it links the existing visitor entity to the new junction entity; if not, it creates a new visitor entity with the provided details (email,nom,prenom,telephone) and links this new entity. - Importantly, the first visitor's
parkingandplaqueImmatriculationare used for all visitors in the method as it's hardcoded to usevisiteurs[0]for setting these properties. This could be a logical error unless all visitors are assumed to share the same parking and vehicle information, which seems unlikely.
- For each visitor in the provided list, it creates a new junction table entity (
-
Save Changes: After setting up all the new association entities, it saves these changes to the database by calling
ent.SaveChanges(). -
Return Value: Interestingly, the method returns
null, which is unconventional. Typically, methods that create or modify data return some indicator of the operation's success, such as a boolean flag, a reference to the newly created/modified entities, or a specific result object. Returningnullprovides no feedback to the caller about the operation's success or failure, except through the side effect of the database update itself.
Potential Issues and Improvements:
- Return Value: The method should likely return a meaningful result, possibly the updated
VisiteVisiteurobject or at least a success status. - Error Handling: Better error handling could be implemented to provide more detailed feedback on why an operation might fail, such as when database constraints are violated.
- Hardcoded Properties: The use of
visiteurs[0].parkingandvisiteurs[0].plaqueImmatriculationfor all visitors suggests either a copy-paste error or an incorrect assumption about visitors sharing properties. - Performance Considerations: Deleting and re-adding records, instead of updating existing ones, might not be the most efficient approach, especially for a large number of visitors or frequent operations.
Overall, this method represents an essential functionality within a visitor management system, allowing the dynamic association of visitors with specific site visits.
-
- User
je mets dans mon front : }; addVisitor = (visitor: UiVisitor, visitId: number): Observable => { return this.http.patch( apiUrl.buildUrl(apiUrl.visitEndpoint, 'AddVisitorToVisit'), { nom: visitor.surname, prenom: visitor.name, email: visitor.email, telephone: visitor.phone, parking: visitor.parking, }, { params: { visiteId: visitId } } ); };
- Assistant
Your snippet showcases a method designed to integrate frontend functionality with a backend service, specifically for adding a visitor to a visit by making an HTTP PATCH request. Let's break down this method:
Understanding the Method:
-
Method Purpose:
addVisitoraims to add a visitor object to a specific visit identified byvisitId. This is achieved by sending data to the backend service endpoint responsible for processing such requests. -
Parameters:
visitor: UiVisitor- An object representing the visitor's information. It must match theUiVisitorinterface (not shown in the snippet but presumably defined elsewhere in your codebase).visitId: number- The unique identifier of the visit to which the visitor will be added.
-
HTTP Request:
- Type:
PATCH- This method is chosen to partially update or modify an existing resource, in this case, to add a visitor to an existing visit. - URL: Constructed using a utility/function
apiUrl.buildUrl(apiUrl.visitEndpoint, 'AddVisitorToVisit'), presumably designed to dynamically construct URL paths pointing to various API endpoints.apiUrl.visitEndpointwould be the base path or endpoint for visit-related operations.'AddVisitorToVisit'is the specific action or method name appended to the endpoint, likely mapped on the backend to handle visitor additions.
- Body: An object literal that includes several properties (
nom,prenom,email,telephone,parking), populated using thevisitorobject. The property names are sent in French, suggesting the backend expects these specific keys.- Note: The mapping from
UiVisitorproperties to the body object requires attention to naming consistency (surnamemapped tonom,nametoprenom, etc.).
- Note: The mapping from
- Params: A query parameter object specifying
visiteId. This indicates which visit the visitor is being added to.
- Type:
-
Return Type:
Observable<UiVisitor>- This suggests that the method returns an Observable wrapping aUiVisitorobject, implying the frontend uses RxJS observables to handle asynchronous operations, such as HTTP requests. This pattern is common in Angular applications.
Potential Improvements and Considerations:
- Error Handling: Consider implementing error handling for the HTTP request. Angular's HttpClient allows for handling responses and errors gracefully with RxJS operators such as
catchError. - Refactoring: Ensure property naming consistency between the front and backend. If
surnameandnameare used in the frontend, the backend should ideally use the same naming convention or vice versa. - Type Mismatch: The return type is an
Observable<UiVisitor>, but the HTTP request specifies<ApiVisitor>as the generic parameter. Ensure these types are correctly mapped or converted as necessary. It might require additional transformation if the objectsUiVisitorandApiVisitorhave different structures or properties. - Success Feedback: Depending on your UI/UX design, you may want to provide feedback to the user upon successful addition of a visitor. This might involve updating the UI or displaying a success message.
This method is a good example of how modern single-page application (SPA) frameworks interact with backend services, leveraging RxJS and Angular's HttpClient for asynchronous data operations.
-
- User
addVisitor = (visitor: UiVisitor, visitId: number): Observable => { return this.http.patch( apiUrl.buildUrl(apiUrl.visitEndpoint, 'AddVisitorToVisit'), { nom: visitor.surname, prenom: visitor.name, email: visitor.email, telephone: visitor.phone, parking: visitor.parking, }, { params: { visitId: visitId } } ); };
- Assistant
In the revised code snippet, you're defining a TypeScript method named
addVisitorwithin a service class. This method is intended to send an HTTP PATCH request to add a visitor's details to a specific visit by its identifier (visitId). The method leverages Angular'sHttpClientfor the request, indicating use within an Angular application framework. The function uses generic parameterization to expect a response in the shape ofApiVisitorfrom the server but returns anObservable<UiVisitor>to the caller. Here’s a breakdown and some insights into the operation and structure of this method:Method Breakdown:
-
Method Purpose: The
addVisitormethod is designed for adding or updating visitor information associated with a specific visit. The method takes in a visitor object and a visit ID, constructing an HTTP PATCH request to the backend. -
Parameters:
visitor: UiVisitor- A complex object conforming to theUiVisitorinterface. This object contains details about the visitor that are necessary for the addition or update.visitId: number- A numeric identifier for the visit to which the visitor is being added.
-
HTTP PATCH Request:
- Executes an HTTP PATCH request using Angular's HttpClient, indicating a partial update or modification to an existing resource on the server.
- The request URL is dynamically built using a helper or service (
apiUrl.buildUrl), appending the specific action or method name 'AddVisitorToVisit' to the visit-related endpoint base path. - The request body includes the visitor's details extracted from the
visitorobject. These details are structured according to the backend's expected format.
-
Return Type:
Observable<UiVisitor>suggests the method asynchronously returns data conforming to theUiVisitorinterface, packaged within an RxJS Observable. This choice perfectly aligns with Angular's reactive programming paradigm and its use of Observables for handling asynchronous operations.
Points of Attention:
-
Endpoint Construction: The dynamic URL construction implies a modular and scalable approach to handling API endpoints, which is good practice for maintainable code.
-
Error Handling: While not explicitly shown, it’s essential to handle potential errors in HTTP requests. This is typically done using RxJS operators like
.pipe()combined withcatchError()when working within the Angular framework. -
Data Transformation: The method converts from
ApiVisitorin the response toUiVisitoras the return type. Ensure proper transformation or mapping exists, possibly within a.pipe(map())operation after the PATCH request, if the structures ofApiVisitorandUiVisitordiffer. -
Consistency in Naming: The method shows a consistent mapping from the frontend model property names to the expected backend format. This consistency is crucial for the seamless flow of data between client and server.
-
Usage of PATCH: Using HTTP PATCH signifies that the intent is to partially update the visit resource with visitor details. This is semantically appropriate if the visit exists and only needs modification or addition of visitor information.
-
Parameterization: The use of
{ params: { visitId: visitId } }correctly applies query parameters to the request, showcasing familiarity with Angular's HttpClient API.
Conclusion:
The
addVisitormethod is a succinct and effective way to communicate visitor addition or updates from an Angular frontend to a backend service. It emphasizes modern web development practices like reactive programming, RESTful API communication, and type safety, making it a robust part of a service class in an Angular application. -
- User
addVisitor = (visitId: number) => { this.visitorService.addVisitor(this.visitor, visitId).subscribe(visitor => { this.dialogRef.close(visitor); }); }; }
- Assistant
The provided code snippet appears to be a TypeScript method likely situated within an Angular component. This method,
addVisitor, encapsulates the process of adding a visitor to a visit by utilizing a service, presumablyvisitorService, and then closing a dialog upon successful completion of the operation. Here's a breakdown and explanation of the functionality:Method Overview:
- Purpose: The primary goal of the
addVisitormethod is to send visitor information, along with a specific visit identifier (visitId), to a backend service for processing (such as creating or updating a visitor's record associated with a visit). Upon successful completion of this operation, it closes an open dialog, potentially a modal dialog displaying a form for entering or editing visitor information.
Key Components:
-
Method Signature:
addVisitor: The method name.(visitId: number): The method accepts a single parameter,visitId, which is a number. This parameter is expected to uniquely identify a visit to which the visitor will be added.
-
Service Invocation:
this.visitorService.addVisitor(this.visitor, visitId): This line calls theaddVisitormethod on an injected service namedvisitorService. The method on the service also namedaddVisitorsuggests an operation that involves server communication to add a visitor to a visit.this.visitor: Presumably,this.visitorrefers to a visitor object maintained within the component's state. This object contains the data to be sent to the backend, such as the visitor's name, contact information, etc.
-
Reactive Programming:
.subscribe(visitor => { ... }): Following Angular's reactive programming pattern, the operation is asynchronous and returns an Observable. Thesubscribemethod is used to handle the response once the asynchronous operation completes. The response, in this context referred to byvisitor, is the updated or newly created visitor object returned by the backend.
-
Dialog Closure:
this.dialogRef.close(visitor): This line executes within the subscription's callback function, indicating it runs after successfully adding the visitor.dialogRefis a reference to the dialog instance, and itsclosemethod is called with thevisitorobject, which implies that the dialog might be showing visitor-related information and needs to pass back the updated or new visitor data upon closing.
Operation Flow:
- A visit identified by
visitIdis selected as the target for adding a visitor. - The visitor information stored in
this.visitoris submitted to a service for processing. - Upon successful completion, the backend service likely adds the visitor to the specified visit and returns the updated visitor information.
- The dialog displaying the form or visitor information is closed, and the updated/new visitor information is passed back as an argument to the
closemethod for potential further use by the component that opened the dialog.
Considerations:
- Error Handling: It's good practice to handle potential errors in subscriptions. Consider adding error handling logic to manage scenarios where the operation fails (e.g., due to network issues or validation errors from the backend).
- Unsubscription: To avoid memory leaks, especially in more complex applications or when the operation might take longer, ensure you manage subscriptions properly, either by unsubscribing when the component is destroyed or using patterns like
takeUntil()with a subject that completes on component destruction. - User Feedback: Providing user feedback, such as loading indicators while the operation is in progress or success/error messages upon completion, can significantly improve user experience.
This method nicely encapsulates a specific function within your component, demonstrating a clear and straightforward example of Angular's capabilities for building interactive and reactive web applications.
- Purpose: The primary goal of the
- User
ERROR Error: Http failure response for http://localhost:53134/api/Visite/AddVisitorToVisit?visitId=undefined: 400 Bad Request
- Assistant
The error message you're encountering indicates a couple of issues that are occurring when you attempt to add a visitor to a visit via an HTTP request:
1. Bad Request (400 Error)
A
400 Bad Requesterror generally means that the server (your backend) cannot or will not process the request due to something that is perceived by the server as a client error. This could be due to various reasons such as invalid request format, invalid request message parameters, or other client-side input errors.2.
visitId=undefinedin the Request URLOne specific issue highlighted by the error message is that the
visitIdquery parameter in your request URL isundefined. This means that when your front-end code constructs the request to the backend, thevisitIdvalue is not being correctly passed or is missing entirely.How to Diagnose and Fix:
Verify
visitIdValueFirst, ensure that the
visitIdyou're attempting to pass toaddVisitorfunction/method is correctly obtained and is notundefined. You can add a console log before the request to verify its value:console.log("visitId being sent:", visitId); addVisitor = (visitId: number) => { ... };Check the Method Call
Make sure that when you're calling the
addVisitormethod/function, you're passing thevisitIdcorrectly. It's possible there's a logic error wherevisitIdisn't set or obtained correctly by the time you're making the HTTP request.Check for Asynchronous Issues
If you're fetching
visitIdasynchronously (e.g., from another HTTP request or asynchronous operation), ensure theaddVisitorfunction is called after thevisitIdis successfully fetched and defined.HTTP Request and Parameter Handling
Review how parameters are appended to the HTTP request in your service. Ensure your service method that performs the HTTP request is correctly handling cases where
visitIdmight beundefinedor null.Server-Side Validation
Look at the server-side code handling the
AddVisitorToVisitendpoint. Ensure it robustly handles cases wherevisitIdis not provided or is incorrect. This might also give you clues as to why the request is being rejected.Example of Correct HTTP Request with Parameters:
Double-check that the parameter appending logic to your HTTP request correctly includes the
visitIdwhen it is defined. For instance, in Angular:this.http.patch<ApiVisitor>( apiUrl.buildUrl(apiUrl.visitEndpoint, 'AddVisitorToVisit'), visitor, // Assuming this is the payload { params: new HttpParams().set('visitId', visitId) } // Correctly setting params );Final Thoughts:
After performing the above checks and ensuring
visitIdis passed correctly, your request should no longer result in a400 Bad Requestdue to an undefinedvisitId. If the issue persists, consider other parts of the request or server-side validations that might be causing the bad request.