public ActionResult GetCompteContratAgrege(string idclient)
 {
     AgregCompteDetail agregcomptedetail = new AgregCompteDetail();
     var guidclient = Guid.Parse(idclient);            
     Guid idCgpAgreg = Guid.Empty;
     User currentUser = SessionManager.GetUserSession();
     if (currentUser.IsEndUser())
     {
         CustomerProspect currentCustomer = SessionManager.GetCustomerProspectSession();
         User currenttUserCreated = currentCustomer.User1;
         idCgpAgreg = currenttUserCreated.idAgregCGP.Value;
         bool existclient = true;
         existclient = (currentCustomer.idAgregClient.HasValue && currentCustomer.idAgregClient.Value.Equals(guidclient)) ? true : false;
         if (!existclient)
         {
             var LanguageData = PageLanguageHelper.GetLanguageContent("User", "agregcompte");
             throw new Exception(LanguageData.GetContent("incorrect_client"));
             //throw new Exception("Ce client n'est pas un client de l'utilisateur en cours.");
         }
     }
     else
     {
         idCgpAgreg = currentUser.idAgregCGP.Value;
     }
     //
     if (!AgUpsideoClientBL.IsClientCgp(idCgpAgreg, guidclient))
     {
         var LanguageData = PageLanguageHelper.GetLanguageContent("User", "agregcompte");
         throw new Exception(LanguageData.GetContent("incorrect_client"));
     }
     try
     {
         agregcomptedetail.AgregCompteDetailList = agupsideocompteBL.GetCompteDetailContratAgrege(guidclient);
         agregcomptedetail.SoldeEspece = agupsideocompteBL.SoldeEspeceClient(guidclient);
         ViewBag.Title = AgUpsideoClientBL.GetClientTitleNameFirstNameByidClient(guidclient);
         ViewBag.IdClient = string.Format("{0}", idclient);
     }
     catch (Exception ex)
     {
         Upsilab.Business.Log.Log.AppendException(ex);
     }
     return View("CompteContratAgrege", agregcomptedetail);
 }
        public ActionResult CompteDetail(string id = null)
        {
            AgregCompteDetail agregcomptedetail = new AgregCompteDetail();
            int idCompte = 0;
            if (!string.IsNullOrEmpty(id))
            {
                idCompte = Convert.ToInt32(id);
                SessionManager.Set<int>(agupsideocompteBL.AgregCompteIdSessionKey, idCompte);

            }
            else
            {
                SessionManager.Get<int>(agupsideocompteBL.AgregCompteIdSessionKey, out idCompte);
            }
            //
            //
            //
            Guid idClient;
            SessionManager.Get<Guid>(agupsideocompteBL.AgregClientIdSessionKey, out idClient);

            var correctcompte = agupsideocompteBL.IsClientCompte(idClient, idCompte);
            if (!correctcompte)
            {
                var LanguageData = PageLanguageHelper.GetLanguageContent("User", "agregcompte");
                throw new Exception(LanguageData.GetContent("incorrect_compte"));
            }
            //
            //
            //
            try
            {                                
                agregcomptedetail.AgregCompteDetailList = agupsideocompteBL.GetCompteDetail(idCompte);
                agregcomptedetail.AgregCompte = agupsideocompteBL.GetComptesByIdCompte(idCompte);
                agregcomptedetail.SoldeEspece = agupsideocompteBL.SoldeEspece(idCompte);
            }
            catch (Exception ex)
            {
                Upsilab.Business.Log.Log.AppendException(ex);
            }
            return View(agregcomptedetail);
        }
        public ActionResult UpdateSupport(ag_upsideo_cptrelsupports _cpt)
        {
            int idCompte = 0;
            SessionManager.Get<int>(agupsideocompteBL.AgregCompteIdSessionKey, out idCompte);
            Guid idCgpAgreg = Guid.Empty;
            User currentUser = SessionManager.GetUserSession();
            if (currentUser.IsEndUser())
            {
                CustomerProspect currentCustomer = SessionManager.GetCustomerProspectSession();
                User currenttUserCreated = currentCustomer.User1;
                idCgpAgreg = currenttUserCreated.idAgregCGP.Value;
            }
            else
            {
                idCgpAgreg = currentUser.idAgregCGP.Value;
            }
            ag_upsideo_cgp cgpagreg = AgregCgpBL.GetCgpById(idCgpAgreg);
            try
            {
                int IdFrontsupport = 0;
                double qte = 0;
                double pam = 0;
                int idrefsupport = 0;
                if (Request.Form["idsupport"] != null && !string.IsNullOrEmpty(Request.Form["idsupport"]))
                {
                    IdFrontsupport = Convert.ToInt32(Request.Form["idsupport"]);
                }
                if (Request.Form["quantite"] != null && !string.IsNullOrEmpty(Request.Form["quantite"]))
                {
                    qte = Convert.ToDouble(Request.Form["quantite"]);
                }
                if (Request.Form["pam"] != null && !string.IsNullOrEmpty(Request.Form["pam"]))
                {
                    pam = Convert.ToDouble(Request.Form["pam"]);
                }
                if (Request.Form["idrefsupport"] != null && !string.IsNullOrEmpty(Request.Form["idrefsupport"]))
                {
                    idrefsupport = Convert.ToInt32(Request.Form["idrefsupport"]);
                }

                //il faut en 1er créer le support selectionné depuis le réferentiel dans la table support
                //ensuite prendre le support depuis la table support                
                if (IdFrontsupport == 0 && idrefsupport > 0)
                {
                    using (UpsilabEntities db = new UpsilabEntities())
                    {
                        ag_upsideo_referentiel refer = db.ag_upsideo_referentiel.Where(r => r.idrefsupport == idrefsupport).FirstOrDefault();
                        if (refer != null)
                        {                            
                            ag_upsideo_support newsup = new ag_upsideo_support()
                            {
                                idrefsupport = refer.idrefsupport,
                                idcrmcabinet = cgpagreg.idcrmcabinet,
                                idsg = 0,
                                idtypesupport = refer.idtypesupport,
                                nomsupport = refer.nomsupport,
                                datevl = refer.datevl,
                                vl = refer.vl,
                                codeisin = refer.codeisin,
                                devise = refer.devise,
                                niveaurisque = refer.niveaurisque,
                                categorisation = refer.categorisation,
                                Vleuro = refer.Vleuro,
                                actions = refer.actions,
                                obligations = refer.obligations,
                                monetaire = refer.monetaire,
                                immobilier = refer.immobilier,
                                autres = refer.autres,
                                Performance12mois = refer.Performance12mois,
                                Performance3112 = refer.Performance3112,
                                Performance60mois = refer.Performance60mois,
                                Volatilite12mois = refer.Volatilite12mois,
                                Volatilite60mois = refer.Volatilite60mois,
                                deleted = "n",
                                fiche_prospectus = refer.fiche_prospectus,
                                fiche_dici = refer.fiche_dici
                            };
                            db.ag_upsideo_support.AddObject(newsup);
                            db.SaveChanges();
                            //set new support
                            IdFrontsupport = newsup.idfrontsupport;
                        }
                    }
                }
                using (UpsilabEntities db = new UpsilabEntities())
                {                  
                    //regarder si la table relation existe
                    ag_upsideo_cptrelsupports cptsupport = db.ag_upsideo_cptrelsupports.Include("ag_upsideo_support").Where(c => c.Idfrontcompte == idCompte && c.idfrontsupport == IdFrontsupport).FirstOrDefault();
                    ag_upsideo_cptrelsupports_histo cpthisto = db.ag_upsideo_cptrelsupports_histo.Where(c => c.idfrontcompte == idCompte && c.idfrontsupport == IdFrontsupport).FirstOrDefault();
                    //update
                    double qtedepart = 0;
                    bool isRachat = false;
                    bool isNewRelation = false;
                    if (cptsupport != null)
                    {
                        qtedepart = cptsupport.qte.HasValue ? cptsupport.qte.Value : 0;
                         isRachat =(qte < qtedepart) ? true : false;

                        if (qte == qtedepart)
                        {
                            ViewBag.Message = "Le pru n'a pas pu être calculé";
                            AgregCompteDetail agregcomptedetail = new AgregCompteDetail();
                            agregcomptedetail.AgregCompteDetailList = agupsideocompteBL.GetCompteDetail(idCompte);
                            agregcomptedetail.AgregCompte = agupsideocompteBL.GetComptesByIdCompte(idCompte);
                            agregcomptedetail.SoldeEspece = agupsideocompteBL.SoldeEspece(idCompte);
                            return View("CompteDetail",agregcomptedetail);
                        }
                        else
                        {
                            double vlhisto = 0;
                            if(cpthisto == null)
                            {
                                vlhisto = cptsupport.ag_upsideo_support.vl.HasValue ? cptsupport.ag_upsideo_support.vl.Value : 0;
                            }
                             else
                            {
                                vlhisto = cpthisto.vl.HasValue ? cpthisto.vl.Value : 0; 
                            }                           
                            //calcul pru
                            if (isRachat)
                            {
                                cptsupport.pru = ((qtedepart * vlhisto) - (qte * pam)) / (qtedepart - qte);                                
                            }
                            else
                            {
                                cptsupport.pru = ((qte * pam) - (qtedepart * vlhisto)) / (qte - qtedepart);                               
                            }
                            cptsupport.qte = qte;
                            cptsupport.datemaj = DateTime.Now;
                            
                        }
                    }
                    //ajout
                    else
                    {
                        //ajout pru
                        isNewRelation = true;
                        cptsupport = new ag_upsideo_cptrelsupports()
                        {
                            Idfrontcompte = idCompte,
                            idfrontsupport = IdFrontsupport,
                            qte = qte,
                            pru = pam,
                            datemaj = DateTime.Now
                        };                       
                        db.ag_upsideo_cptrelsupports.AddObject(cptsupport);
                    }

                    //update pru liquidité                    
                    double liquidite = 0;
                    liquidite = isRachat ? (qtedepart - qte) * pam : -(qte - qtedepart) * pam;
                    //voir si le cabinet a un fond fictif (nomsupport = Liquidités)                        
                    ag_upsideo_support supportfictif = db.ag_upsideo_support.Where(s => s.idcrmcabinet == cgpagreg.idcrmcabinet && s.nomsupport == "Liquidités" && (s.deleted == null || (s.deleted != null && s.deleted == "n"))).FirstOrDefault();
                    //si support fictif existe 
                    if (supportfictif != null)
                    {
                        ag_upsideo_cptrelsupports relationfictif = db.ag_upsideo_cptrelsupports.Where(s => s.Idfrontcompte == idCompte && s.idfrontsupport == supportfictif.idfrontsupport).FirstOrDefault();
                        if (relationfictif != null)
                        {
                            relationfictif.pru = relationfictif.pru + liquidite;
                            relationfictif.qte = 1;
                        }
                    }
                    //fin maj pru fictif

                    //add histo ag_upsideo_cptrelsupports_histo
                    double mtfondeuro = 0;
                    List<ag_upsideo_cptrelsupports> cptsupportListe = new List<ag_upsideo_cptrelsupports>();
                    cptsupportListe = db.ag_upsideo_cptrelsupports.Include("ag_upsideo_support").Where(c => c.Idfrontcompte == idCompte).ToList();
                    foreach (ag_upsideo_cptrelsupports cptsupportnow in cptsupportListe)
                    {
                        if (cptsupportnow.ag_upsideo_support.vl.HasValue
                        && cptsupportnow.ag_upsideo_support.vl.Value > 0
                        && cptsupportnow.qte.HasValue
                        && cptsupportnow.qte.Value > 1)
                        {
                            mtfondeuro = cptsupportnow.qte.Value * cptsupportnow.ag_upsideo_support.vl.Value;
                        }
                        else
                        {
                            mtfondeuro = cptsupportnow.pru.HasValue ? cptsupportnow.pru.Value : 0;
                        }
                        //regarde si déjà dans l'histo pour la date du jour
                        ag_upsideo_cptrelsupports_histo cptsupporthistonow = db.ag_upsideo_cptrelsupports_histo.Where(h => h.idfrontcompte == idCompte
                                                                                        && h.idfrontsupport == cptsupportnow.idfrontsupport
                                                                                        && h.datehisto.Value.Year == DateTime.Now.Year
                                                                                        && h.datehisto.Value.Month == DateTime.Now.Month
                                                                                        && h.datehisto.Value.Day == DateTime.Now.Day).FirstOrDefault();
                        if (cptsupporthistonow != null)
                        {
                            cptsupporthistonow.datemaj = DateTime.Now;
                            cptsupporthistonow.qte = cptsupportnow.qte;
                            cptsupporthistonow.pru = cptsupportnow.pru;
                            cptsupporthistonow.vl = cptsupportnow.ag_upsideo_support.vl;
                            cptsupporthistonow.mtfondeuro = mtfondeuro;
                        }
                        else
                        {
                            cptsupporthistonow = new ag_upsideo_cptrelsupports_histo()
                            {
                                datehisto = DateTime.Now,
                                datemaj = DateTime.Now,
                                idfrontcompte = cptsupportnow.Idfrontcompte,
                                idfrontsupport = cptsupportnow.idfrontsupport,
                                qte = cptsupportnow.qte,
                                pru = cptsupportnow.pru,
                                vl = cptsupportnow.ag_upsideo_support.vl,
                                mtfondeuro = mtfondeuro
                            };
                            db.ag_upsideo_cptrelsupports_histo.AddObject(cptsupporthistonow);
                        }

                    }
                    //si un nouveau relation (pas encore dans la table relation)
                    if (isNewRelation)
                    {
                        if (cptsupport.ag_upsideo_support != null
                        && cptsupport.ag_upsideo_support.vl.HasValue
                        && cptsupport.ag_upsideo_support.vl.Value > 0
                        && cptsupport.qte.HasValue
                        && cptsupport.qte.Value > 1)
                        {
                            mtfondeuro = cptsupport.qte.Value * cptsupport.ag_upsideo_support.vl.Value;
                        }
                        else
                        {
                            mtfondeuro = cptsupport.pru.HasValue ? cptsupport.pru.Value : 0;
                        }

                        ag_upsideo_cptrelsupports_histo cptsupporthistofornewrelation = new ag_upsideo_cptrelsupports_histo()
                        {
                            datehisto = DateTime.Now,
                            datemaj = DateTime.Now,
                            idfrontcompte = cptsupport.Idfrontcompte,
                            idfrontsupport = cptsupport.idfrontsupport,
                            qte = cptsupport.qte,
                            pru = cptsupport.pru,
                            vl = cptsupport.ag_upsideo_support.vl.Value,
                            mtfondeuro = mtfondeuro
                        };
                        db.ag_upsideo_cptrelsupports_histo.AddObject(cptsupporthistofornewrelation);
                    }
                    //fin histo ag_upsideo_cptrelsupports_histo  
                    //save
                    db.SaveChanges();
                    //après chaque opération , lancer la proc frontalweb_majtotalcomptecpts                   
                    db.CommandTimeout = 180;
                    db.ExecuteStoreCommand("exec agreg.frontalweb_majtotalcompte @idcrmcabinet,@idfrontcompte", new SqlParameter("@idcrmcabinet", cgpagreg.idcrmcabinet), new SqlParameter("@idfrontcompte", idCompte));

                }

                using (UpsilabEntities db = new UpsilabEntities())
                {
                    //compte aprés maj
                    ag_upsideo_compte compteahistoriser = db.ag_upsideo_compte.Where(c => c.Idfrontcompte == idCompte && (c.deleted == null || (c.deleted != null && c.deleted == "n"))).FirstOrDefault();

                    //historisé dans ag_upsideo_compte_histo
                    ag_upsideo_compte_histo cpthisto = db.ag_upsideo_compte_histo.Where(h => h.idfrontcompte == idCompte
                                                                                        && h.datehisto.Year == DateTime.Now.Year
                                                                                        && h.datehisto.Month == DateTime.Now.Month
                                                                                        && h.datehisto.Day == DateTime.Now.Day).FirstOrDefault();
                    if (cpthisto != null)
                    {
                        cpthisto.datehisto = DateTime.Now;
                        cpthisto.totalcompte = compteahistoriser.totalcompte.Value;
                    }
                    else
                    {
                        ag_upsideo_compte_histo cpthistonew = new ag_upsideo_compte_histo()
                        {
                            datehisto = DateTime.Now,
                            idfrontcompte = compteahistoriser.Idfrontcompte,
                            devise = string.IsNullOrEmpty(compteahistoriser.devise) ? "EUR" : compteahistoriser.devise,
                            totalcompte = compteahistoriser.totalcompte.HasValue ? compteahistoriser.totalcompte.Value : 0
                        };
                        //insert
                        db.ag_upsideo_compte_histo.AddObject(cpthistonew);
                    }
                    //save
                    db.SaveChanges();
                    //fin historisation
                }

            }
            catch (Exception ex)
            {
                Upsilab.Business.Log.Log.AppendException(ex);                
                ViewBag.Message = "Erreur: " + ex.Message;
                AgregCompteDetail agregcomptedetail = new AgregCompteDetail();
                agregcomptedetail.AgregCompteDetailList = agupsideocompteBL.GetCompteDetail(idCompte);
                agregcomptedetail.AgregCompte = agupsideocompteBL.GetComptesByIdCompte(idCompte);
                agregcomptedetail.SoldeEspece = agupsideocompteBL.SoldeEspece(idCompte);
                return View("CompteDetail", agregcomptedetail);
            }

            return RedirectToAction("CompteDetail", new { id = idCompte });
        }