public ActionResult InsertNewClient(CustomerProspect _customer)
        {
            Guid idClientAgreg = Guid.Empty;
            try
            {
                //create client agregateur
                Guid idCgpAgreg = SessionManager.GetUserSession().idAgregCGP.Value;
                ag_upsideo_client clientagreg = new ag_upsideo_client
                {
                    idclient = Guid.NewGuid(),
                    idcgp = idCgpAgreg,
                    nomclient = _customer.User.UserName,
                    prenomclient = _customer.User.UserFirstName,
                    adr = _customer.Adress,
                    cp = _customer.ZipCode,
                    ville = _customer.City,
                    ddn = _customer.DateOfBirth,
                    deleted = "n"
                };
                AgUpsideoClientBL.CreateClient(clientagreg);
                idClientAgreg = clientagreg.idclient;
                //end client agregateur
                //liason client agreg - recueil
                _customer.idAgregClient = idClientAgreg;

                if (string.IsNullOrEmpty(_customer.User.UserEmail))
                {
                    _customer.User.UserLogin = string.Empty;
                }
                else
                {
                    _customer.User.UserLogin = _customer.User.UserEmail;
                }
                
                // create user and prospect/customer
                _customer.User.idUser = Business.Utility.GuidHelper.GenerateGuid();
                _customer.User.idUserProfile = UserProfileBL.GetAllUserProfiles().Where(up => up.UserProfileName.ToLower().Equals("end-user")).FirstOrDefault().idUserProfile;
                _customer.User.DateCreated = DateTime.Now;
                _customer.User.IsActive = true;
                if (!string.IsNullOrEmpty(_customer.DateOfBirthStr))
                {
                    string[] splittedDate = _customer.DateOfBirthStr.Split('/');
                    try { _customer.DateOfBirth = new DateTime(Convert.ToInt32(splittedDate[2]), Convert.ToInt32(splittedDate[1]), Convert.ToInt32(splittedDate[0])); }
                    catch { }
                }

                //Check if mail exists and set the same password 
                string password = "";
                if (!string.IsNullOrEmpty(_customer.User.UserEmail))
                {
                    var user = UserBL.GetUserByEmail(_customer.User.UserEmail);
                    if (user != null)
                        password = user.UserPassword;
                }
                _customer.User.UserPassword = ""; //Temporary set
                _customer.User = UserBL.CreateUser(_customer.User, password);

                _customer.IdUser = _customer.User.idUser;
                _customer.idCustomer = Business.Utility.GuidHelper.GenerateGuid();
                _customer.IsCustomer = true;
                //_customer.idFirmInstitution = idSelectedFirm;
                _customer.User1 = SessionManager.GetUserSession(); //User created

                CustomerProspectBL.CreateCustomer(_customer);
                string outputMsg = string.Empty;
            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
            }

            if (idClientAgreg != Guid.Empty)
            {
                return RedirectToAction("Index", "AgregCompte", new { id = idClientAgreg });
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        //
        // GET: /AgregInitialiseRevenus/

        public string Index()
        {
            try
            {

                using (UpsilabEntities context = new UpsilabEntities())
                {

                    // liste CustomerProspect
                    List<CustomerProspect> customers = CustomerProspectBL.GetCustomerProspectList(context);

                    Report report = null;
                    Report reportValues = null;
                    Guid idClient = Guid.Empty;
                    List<ReportOptionAttributeValue> listeReportImmoJouissance = null;
                    List<ReportOptionAttributeValue> listeReportImmoRapport = null;
                    List<ReportOptionAttributeValue> listeReportProfessionnel = null;

                    //boucle sur les clients
                    Guid currentAgregClientId = Guid.Empty;
                    foreach (CustomerProspect cp in customers)
                    {
                        //teste si client existe dans agreg si non on ajoute et maj customer -- ou ne rien faire
                        currentAgregClientId = cp.idAgregClient.HasValue ? cp.idAgregClient.Value : Guid.Empty;

                        if (!cp.idAgregClient.HasValue)
                        {
                            ag_upsideo_client agregClientToAdd = new ag_upsideo_client()
                            {
                                idclient = Guid.NewGuid(),
                                idcgp = cp.User1.idAgregCGP.Value,
                                nomclient = cp.User.UserName,
                                prenomclient = cp.User.UserFirstName,
                                adr = cp.Adress,
                                cp = cp.ZipCode,
                                ville = cp.City,
                                titre = cp.Title,
                                ddn = DateTime.Now,
                                deleted = "n"
                            };
                            context.ag_upsideo_client.AddObject(agregClientToAdd);

                            cp.idAgregClient = agregClientToAdd.idclient;
                            currentAgregClientId = agregClientToAdd.idclient;
                        }

                        //------------------
                        //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //Get fournisseur
                        Guid idAgregCabinet = cp.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        ag_upsideo_fournisseur agregFournisseur = context.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == cp.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                                                                                                  && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        if (agregFournisseur == null)
                        {
                            agregFournisseur = new ag_upsideo_fournisseur()
                            {
                                idcrmcabinet = idAgregCabinet,
                                nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                                cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                                deleted = "n",
                            };

                            //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                            //Insertion fournisseur avec un autre contexte
                            using (UpsilabEntities dbTemp = new UpsilabEntities())
                            {
                                dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                                dbTemp.SaveChanges();
                            }
                        }

                        //------------------

                        // obtenir le dernier repport pour chaque client (customerprospect)
                        report = new Report();
                        report = ReportBL.GetLatestReportByIdCustomerProspect(cp.idCustomer);

                        if (report != null)
                        {

                            //obtenir les donnés de report
                            reportValues = new Report();
                            reportValues = ReportBL.GetReportWithValues(report.idReport);

                            //obtenir ReportOptionAttributeValue
                            // idOptionAttribute = 204 (1. Immobilier de jouissance (résidence principale, résidence secondaire, terrain à bâtir ou non, etc.)
                            // idOptionAttribute = 205 (2. Immobilier de rapport (location, SICAFI, SIR, certificats immobiliers, sociétés immobilières, etc.)
                            // idOptionAttribute = 206 (c) Patrimoine professionnel (parts sociales, clientèle, fonds de commerce), compte courant, compte d’associé)
                            listeReportImmoJouissance = new List<ReportOptionAttributeValue>();
                            listeReportImmoRapport = new List<ReportOptionAttributeValue>();
                            listeReportProfessionnel = new List<ReportOptionAttributeValue>();

                            if (reportValues.ReportOptionAttributeValue != null && reportValues.ReportOptionAttributeValue.Count > 0)
                            {
                                listeReportImmoJouissance = reportValues.ReportOptionAttributeValue.Where(r => r.idOptionAttribute == 204).ToList();
                                listeReportImmoRapport = reportValues.ReportOptionAttributeValue.Where(r => r.idOptionAttribute == 205).ToList();
                                listeReportProfessionnel = reportValues.ReportOptionAttributeValue.Where(r => r.idOptionAttribute == 206).ToList();

                                dynamic customData = null;
                                string numcompteFictif = string.Empty;
                                int ligneImmoJ = 0;
                                int ligneImmoR = 0;
                                int lignePro = 0;

                                foreach (ReportOptionAttributeValue roav in listeReportImmoJouissance)
                                {
                                    //les valeur dans receuil lab
                                    customData = roav.CustomObjectValue;
                                    //clé de maj pour les revenus dans la table ag_upsideo_compte
                                    numcompteFictif = string.Format("{0}_{1}", roav.idOptionAttribute.ToString(), ligneImmoJ.ToString());
                                    //pour tester les revenus
                                    if (customData.Values["Description"] != null && customData.Values["Description"] != "")
                                    {
                                        //teste si existe déjà (maj) si no new
                                        ag_upsideo_compte currentCompte = context.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numcompteFictif).FirstOrDefault();
                                        //update
                                        if (currentCompte != null)
                                        {
                                            currentCompte.designation = customData.Values["Description"];
                                            currentCompte.dateacquisition = customData.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(customData.Values["AcquisitionDate"]) : null;
                                            currentCompte.valeuracquisition = customData.Values["AcquisitionValue"] != "" ? Convert.ToDouble(customData.Values["AcquisitionValue"]) : null;
                                            currentCompte.totalcompte = customData.Values["CurrentValue"] != "" ? Convert.ToDouble(customData.Values["CurrentValue"]) : null;
                                            currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                            currentCompte.type = "n"; //non gere


                                        }
                                        //new
                                        else
                                        {
                                            currentCompte = new ag_upsideo_compte()
                                            {
                                                idclient = currentAgregClientId,
                                                idcgp = cp.User1.idAgregCGP.Value,
                                                idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                                numcompte = numcompteFictif,
                                                typecontrat = "bien immobilier",
                                                deleted = "n",

                                                designation = customData.Values["Description"],
                                                dateacquisition = customData.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(customData.Values["AcquisitionDate"]) : null,
                                                valeuracquisition = customData.Values["AcquisitionValue"] != "" ? Convert.ToDouble(customData.Values["AcquisitionValue"]) : null,
                                                totalcompte = customData.Values["CurrentValue"] != "" ? Convert.ToDouble(customData.Values["CurrentValue"]) : null,

                                                type = "n", //non gere

                                            };
                                            context.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    ligneImmoJ = ligneImmoJ + 1;
                                }

                                foreach (ReportOptionAttributeValue roav in listeReportImmoRapport)
                                {
                                    customData = roav.CustomObjectValue;
                                    numcompteFictif = string.Format("{0}_{1}", roav.idOptionAttribute.ToString(), ligneImmoR.ToString());
                                    //pour tester les revenus
                                    if (customData.Values["Description"] != null && customData.Values["Description"] != "")
                                    {
                                        //teste si existe déjà (maj) si no new
                                        ag_upsideo_compte currentCompte = context.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numcompteFictif).FirstOrDefault();
                                        if (currentCompte != null)
                                        {
                                            currentCompte.designation = customData.Values["Description"];
                                            currentCompte.dateacquisition = customData.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(customData.Values["AcquisitionDate"]) : null;
                                            currentCompte.valeuracquisition = customData.Values["AcquisitionValue"] != "" ? Convert.ToDouble(customData.Values["AcquisitionValue"]) : null;
                                            currentCompte.totalcompte = customData.Values["CurrentValue"] != "" ? Convert.ToDouble(customData.Values["CurrentValue"]) : null;
                                            currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                            currentCompte.type = "n"; //non gere
                                        }
                                        else
                                        {
                                            currentCompte = new ag_upsideo_compte()
                                            {
                                                idclient = currentAgregClientId,
                                                idcgp = cp.User1.idAgregCGP.Value,
                                                idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                                numcompte = numcompteFictif,
                                                typecontrat = "bien immobilier",
                                                deleted = "n",

                                                designation = customData.Values["Description"],
                                                dateacquisition = customData.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(customData.Values["AcquisitionDate"]) : null,
                                                valeuracquisition = customData.Values["AcquisitionValue"] != "" ? Convert.ToDouble(customData.Values["AcquisitionValue"]) : null,
                                                totalcompte = customData.Values["CurrentValue"] != "" ? Convert.ToDouble(customData.Values["CurrentValue"]) : null,

                                                type = "n", //non gere
                                            };
                                            context.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    ligneImmoR = ligneImmoR + 1;
                                }

                                foreach (ReportOptionAttributeValue roav in listeReportProfessionnel)
                                {
                                    customData = roav.CustomObjectValue;
                                    numcompteFictif = string.Format("{0}_{1}", roav.idOptionAttribute.ToString(), lignePro.ToString());
                                    //pour tester les revenus
                                    if (customData.Values["Description"] != null && customData.Values["Description"] != "")
                                    {
                                        double capital = 0;
                                        double.TryParse(customData.Values["OwnedCapital"], out capital);

                                        //teste si existe déjà (maj) si no new
                                        ag_upsideo_compte currentCompte = context.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numcompteFictif).FirstOrDefault();

                                        if (currentCompte != null)
                                        {
                                            currentCompte.designation = customData.Values["Description"];
                                            currentCompte.totalcompte = customData.Values["OwnedCapital"] != "" ? capital : (double?)null;
                                            currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                            currentCompte.type = "n"; //non gere
                                        }
                                        else
                                        {
                                            currentCompte = new ag_upsideo_compte()
                                            {
                                                idclient = currentAgregClientId,
                                                idcgp = cp.User1.idAgregCGP.Value,
                                                idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                                numcompte = numcompteFictif,
                                                typecontrat = "professionels",
                                                deleted = "n",

                                                designation = customData.Values["Description"],
                                                totalcompte = customData.Values["OwnedCapital"] != "" ? capital : (double?)null,

                                                type = "n", //non gere
                                            };
                                            context.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    lignePro = lignePro + 1;
                                }

                            }

                        }


                    }

                    context.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                Upsilab.Business.Log.Log.AppendException(ex);
                return "Erreur : " + ex.Message;
            }
            
            return "OK";
        }
        public static ag_upsideo_client CreateClient(ag_upsideo_client client)
        {
            using (UpsilabEntities db = new UpsilabEntities())
            {


                db.ag_upsideo_client.Attach(client);
                db.ObjectStateManager.ChangeObjectState(client, System.Data.EntityState.Added);
                db.SaveChanges();
            }

            return client;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportIdDest"></param>
        /// <param name="lstReportOptionValuesSource"></param>
        public static int SaveReportOptionValue(Guid idReport, Upsilab.Data.Model.Option option, int idOptionAttribute, string value, string fieldType, string colomnName, int? lineNumber)
        {
            ReportOptionAttributeValue optionAttributeValue2 = null;
            int idOption = option.idOption;
            bool updateDateUpdated = false;
            string completedStatus = Report.ReportBL.Status.Completed.ToString();
            string waitingForClientUpdateStatus = Report.ReportBL.Status.WaitingForClientUpdate.ToString();

            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                //Get current report
                Data.Model.Report report = (from rep in db.Report
                                            where rep.idReport == idReport
                                            select rep).FirstOrDefault();

                //Check if customer has completed report
                var checkCompletedReport = (from rep in db.Report
                                            where rep.CustomerProspect.idCustomer == report.CustomerProspect.idCustomer
                                                  && rep.Status == completedStatus
                                            select rep).FirstOrDefault();

                if (checkCompletedReport != null)
                {
                    updateDateUpdated = true;
                }

                //#9262 : Check if customer changes the info after Adviser request
                if (!updateDateUpdated)
                {
                    if (report.Status == waitingForClientUpdateStatus && SessionManager.GetUserSession().IsEndUser())
                    {
                        updateDateUpdated = true;
                    }
                }

                #region TEXTBOX, DROPDOWN : txt, dt, enum
                //1- Save option attribute value (simple textbox / textarea)
                if (fieldType == "txt" || fieldType == "dt" || fieldType == "enum")
                {
                    ReportOptionAttributeValue optionAttributeValue = (from roav in db.ReportOptionAttributeValue.Include("ReportOptionValue")
                                                                       where roav.idReport == idReport && roav.idOptionAttribute == idOptionAttribute
                                                                       select roav).FirstOrDefault();

                    if (optionAttributeValue != null)
                    {
                        if (optionAttributeValue.Value != value) //update if not equal
                        {
                            optionAttributeValue.Value = value;
                            optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                            optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                        }
                        else
                        {
                            //Do nothing if equal
                        }
                        optionAttributeValue2 = optionAttributeValue;
                    }
                    else if (!string.IsNullOrEmpty(value)) //Insert if value is not empty
                    {
                        //Check if reportOptionValue exists
                        ReportOptionValue optionValue = (from rov in db.ReportOptionValue
                                                         where rov.idReport == idReport && rov.idOption == idOption
                                                         select rov).FirstOrDefault();

                        if (optionValue == null) //insert option value
                        {
                            optionValue = new ReportOptionValue()
                            {
                                idReport = idReport,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                            };

                            //Add ReportOptionValue to DB : don't save yet
                            db.ReportOptionValue.AddObject(optionValue);

                            //Insert parent
                            while (option.idParent.HasValue)
                            {
                                ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                       where rov.idReport == idReport && rov.idOption == option.idParent
                                                                       select rov).FirstOrDefault();

                                if (optionParentValue == null)
                                {
                                    optionParentValue = new ReportOptionValue()
                                    {
                                        idReport = idReport,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add ReportOptionValue to DB : don't save yet
                                    db.ReportOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                    break;
                                }
                            }
                        }

                        //Insert optionattrubutevalue
                        ReportOptionAttributeValue newReportOptionAttributeValue = new ReportOptionAttributeValue()
                        {
                            idReport = idReport,
                            idOptionAttribute = idOptionAttribute,
                            idReportOptionValue = optionValue.idReportOptionValue,
                            Value = value,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionAttributeValue to DB : don't save yet
                        optionValue.ReportOptionAttributeValue.Add(newReportOptionAttributeValue);
                        optionAttributeValue2 = newReportOptionAttributeValue;
                    }
                }
                #endregion

                #region RADIO BUTTON : rb
                //2- Save option attribute value (Radio button)
                else if (fieldType == "rb")
                {
                    //Delete old rb
                    IList<ReportOptionValue> optionValues = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                             where rov.idReport == idReport && rov.Option.idParent == option.idParent
                                                             select rov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var optionValue in optionValues)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    if (!string.IsNullOrEmpty(value) && value.ToLower() == "true")
                    {
                        //Insert new rb
                        ReportOptionValue newOptionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(newOptionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }


                    
                    }
                }
                #endregion

                #region CHECKBOX : chk
                //3- Save option attribute value (Checkbox)
                else if (fieldType == "chk")
                {
                    ReportOptionValue optionValue;

                    if (value == "false")
                    {
                        //Delete old chk
                        optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                       where rov.idReport == idReport && rov.idOption == idOption
                                       select rov).FirstOrDefault();

                        //Delete option attribute values attached to option value
                        if (optionValue != null)
                        {
                            IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.ReportOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<ReportOptionValue> lstOptionValuesChild = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                                             where rov.idReport == idReport && rov.Option.idParent == optionValue.idOption
                                                                             select rov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValueChild.ReportOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.ReportOptionAttributeValue.Where(oa => oa.idReportOptionAttributeValue == item.idReportOptionAttributeValue).FirstOrDefault();
                                        db.ReportOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.ReportOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }
                    }
                    else if (value == "true")
                    {
                        //Insert new chk
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region CUSTOM DATATYPE
                //4- Custom datatype
                else
                {
                    //pour agreg
                    ReportOptionAttributeValue agregOptionAttributeValue = null;
                    //

                    ReportOptionValue optionValue = (from rov in db.ReportOptionValue.Include("ReportOptionAttributeValue")
                                                     where rov.idReport == idReport && rov.idOption == idOption
                                                     select rov).FirstOrDefault();

                    IList<ReportOptionAttributeValue> lstOptionAttributeValues = new List<ReportOptionAttributeValue>();

                    //Option value ?
                    if (optionValue != null)
                    {
                        lstOptionAttributeValues = new List<ReportOptionAttributeValue>(optionValue.ReportOptionAttributeValue);
                        lstOptionAttributeValues = lstOptionAttributeValues.Where(oav => oav.idOptionAttribute == idOptionAttribute).ToList();
                    }
                    else if (!string.IsNullOrEmpty(value))
                    {
                        optionValue = new ReportOptionValue()
                        {
                            idReport = idReport,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                        };

                        //Add ReportOptionValue to DB : don't save yet
                        db.ReportOptionValue.AddObject(optionValue);

                        //Insert parent
                        while (option.idParent.HasValue)
                        {
                            ReportOptionValue optionParentValue = (from rov in db.ReportOptionValue.Include("Option")
                                                                   where rov.idReport == idReport && rov.idOption == option.idParent
                                                                   select rov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new ReportOptionValue()
                                {
                                    idReport = idReport,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                //Add ReportOptionValue to DB : don't save yet
                                db.ReportOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                optionParentValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                break;
                            }
                        }
                    }

                    //Get target option attribute
                    if (lineNumber.HasValue && lineNumber.Value < lstOptionAttributeValues.Count)
                    {
                        //Line already in database
                        ReportOptionAttributeValue reportOptionAttrValue = lstOptionAttributeValues[lineNumber.Value];
                        dynamic customData = reportOptionAttrValue.CustomObjectValue;

                        if (customData != null)
                        {
                            bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                            if (!isTheSameValue)
                            {
                                CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                reportOptionAttrValue.CustomObjectValue = customData;
                                reportOptionAttrValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                reportOptionAttrValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                //pour agreg
                                agregOptionAttributeValue = reportOptionAttrValue;
                                //
                            }
                        }
                        optionAttributeValue2 = reportOptionAttrValue;

                    }
                    else
                    {
                        //Get Custom datatype columns
                        List<string> customAttribute = OptionBL.GetCustomAttributeNames(fieldType);

                        if (customAttribute.Count > 0)
                        {
                            dynamic customData = new Upsilab.Data.Model.CustomObject();
                            dynamic customDataEmpty = new Upsilab.Data.Model.CustomObject();

                            foreach (string itemColumnName in customAttribute)
                            {
                                string _strVal = string.Empty;

                                if (itemColumnName == colomnName)
                                {
                                    _strVal = value;
                                }
                                CustomObject.SetValueByPropertyName(customData, itemColumnName, _strVal);
                                CustomObject.SetValueByPropertyName(customDataEmpty, itemColumnName, string.Empty);
                            }

                            ReportOptionAttributeValue optionAttributeValue = null;
                            bool createOptionAttr = true;
                            if (!lineNumber.HasValue && lstOptionAttributeValues.Count > 0)
                            {
                                createOptionAttr = false;
                                optionAttributeValue = optionValue.ReportOptionAttributeValue.Where(oav => oav.idOptionAttribute == idOptionAttribute).FirstOrDefault();
                                optionAttributeValue2 = optionAttributeValue;
                            }
                            else if (lineNumber.HasValue)
                            {
                                //Create empty lines
                               // while (lstOptionAttributeValues.Count < lineNumber.Value)
                                {
                                    optionAttributeValue = new ReportOptionAttributeValue()
                                    {
                                        idReport = idReport,
                                        idOptionAttribute = idOptionAttribute,
                                        idReportOptionValue = optionValue.idReportOptionValue,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                    };

                                    optionAttributeValue.CustomObjectValue = customDataEmpty;

                                    lstOptionAttributeValues.Add(optionAttributeValue);
                                    optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                                }
                            }

                            //if (optionAttributeValue == null)
                            if (createOptionAttr)
                            {
                                //Add new line
                                //Insert optionattrubutevalue
                                optionAttributeValue = new ReportOptionAttributeValue()
                                {
                                    idReport = idReport,
                                    idOptionAttribute = idOptionAttribute,
                                    idReportOptionValue = optionValue.idReportOptionValue,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null
                                };

                                optionAttributeValue.CustomObjectValue = customData;

                                //pour agreg
                                agregOptionAttributeValue = optionAttributeValue;
                                optionAttributeValue2 = agregOptionAttributeValue;
                                //
                            }
                            else
                            {
                                customData = optionAttributeValue.CustomObjectValue;

                                if (customData != null)
                                {
                                    bool isTheSameValue = CustomObject.IsTheSameValue(customData, colomnName, value);

                                    if (!isTheSameValue)
                                    {
                                        CustomObject.SetValueByPropertyName(customData, colomnName, value);
                                        optionAttributeValue.CustomObjectValue = customData;
                                        optionAttributeValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;

                                        optionAttributeValue.ReportOptionValue.DateUpdated = (updateDateUpdated) ? DateTime.Now : (DateTime?)null;
                                        //pour agreg
                                        agregOptionAttributeValue = optionAttributeValue;
                                        //
                                    }
                                }
                            }

                            //Add ReportOptionAttributeValue to DB : don't save yet
                            optionValue.ReportOptionAttributeValue.Add(optionAttributeValue);
                            optionAttributeValue2 = optionAttributeValue;
                        }
                    }

                    #region Save patrimoine from Recueil/lab to Agregateur
                    //update/add ag_upsideo_compte
                    //if (report.CustomerProspect.User1.idLicenseAgreg.HasValue && report.CustomerProspect.User1.idAgregCGP.HasValue
                    //    && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                    //    && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    if (report.CustomerProspect.User1.HasAggregatorLicense() && report.CustomerProspect.User1.idAgregCGP.HasValue
                        && (idOptionAttribute == 204 || idOptionAttribute == 205 || idOptionAttribute == 206)
                        && report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet != null)
                    {
                        //Les ids en cours : agregCabinet, agregCGP et agregClient
                        Guid idAgregCGP = report.CustomerProspect.User1.idAgregCGP.Value;
                        Guid idAgregCabinet = report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet;
                        Guid currentAgregClientId = Guid.Empty;

                        if (report.CustomerProspect.idAgregClient.HasValue)
                        {
                            currentAgregClientId = report.CustomerProspect.idAgregClient.Value;
                        }
                        else
                        {
                            ag_upsideo_client clientAgregToAdd = new ag_upsideo_client()
                            {
                                idclient = Guid.NewGuid(),
                                idcgp = idAgregCGP,
                                nomclient = report.CustomerProspect.User.UserName,
                                prenomclient = report.CustomerProspect.User.UserFirstName,
                                adr = report.CustomerProspect.Adress,
                                cp = report.CustomerProspect.ZipCode,
                                ville = report.CustomerProspect.City,
                                titre = report.CustomerProspect.Title,
                                ddn = DateTime.Now,
                                deleted = "n"
                            };

                            db.ag_upsideo_client.AddObject(clientAgregToAdd);

                            report.CustomerProspect.idAgregClient = clientAgregToAdd.idclient;
                            currentAgregClientId = clientAgregToAdd.idclient;
                        }

                        //Fournisseur de l'actif : comme il s'agit de données provenant du "Recueil/LAB", mettre "UPSIDEO" comme fournisseur fictif (pour chaque cabinet / etablissement)
                        //Get fournisseur
                        ag_upsideo_fournisseur agregFournisseur = db.ag_upsideo_fournisseur.Where(f => f.idcrmcabinet == report.CustomerProspect.FirmInstitution.ag_upsideo_cabinet.idcrmcabinet
                                                                                                  && f.nomfournisseur == Business.Agreg.agupsideocompteBL.FournisseurUpsideo).FirstOrDefault();

                        if (agregFournisseur == null)
                        {
                            agregFournisseur = new ag_upsideo_fournisseur()
                            {
                                idcrmcabinet = idAgregCabinet,
                                nomfournisseur = Business.Agreg.agupsideocompteBL.FournisseurUpsideo,
                                cleAgreg = Business.Agreg.agupsideocompteBL.FournisseurUpsideo.ToLower(),
                                deleted = "n",
                            };

                            //TODO : to delete : normalement à faire lors de la souscription mais garder ce code pour test
                            //Insertion fournisseur avec un autre contexte
                            using (UpsilabEntities dbTemp = new UpsilabEntities())
                            {
                                dbTemp.ag_upsideo_fournisseur.AddObject(agregFournisseur);
                                dbTemp.SaveChanges();
                            }
                        }

                        //num compte fictif dans table compte Agreg
                        string numCompteFictif = string.Empty;
                        numCompteFictif = string.Format("{0}_{1}", idOptionAttribute.ToString(), lineNumber.Value.ToString());

                        //teste si existe déjà (maj) si no new
                        ag_upsideo_compte currentCompte = db.ag_upsideo_compte.Where(c => c.idclient == currentAgregClientId && c.numcompte == numCompteFictif).FirstOrDefault();

                        //maj
                        if (currentCompte != null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                        currentCompte.dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null;
                                        currentCompte.valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null;
                                        currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null;
                                        currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                        currentCompte.type = "n"; //pour l'instant : non géré
                                    }
                                    break;
                                case 206:
                                    currentCompte.designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"];
                                    currentCompte.totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null;
                                    currentCompte.idfrontfournisseur = agregFournisseur.idfrontfournisseur;
                                    currentCompte.type = "n"; //pour l'instant : non géré
                                    break;
                                default:
                                    break;

                            }
                        }
                        //new
                        else if (currentCompte == null && agregOptionAttributeValue != null)
                        {
                            switch (idOptionAttribute)
                            {
                                case 204:
                                case 205:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "bien immobilier",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            dateacquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"] != "" ? Convert.ToDateTime(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionDate"]) : null,
                                            valeuracquisition = agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["AcquisitionValue"]) : null,
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["CurrentValue"]) : null
                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }

                                    }
                                    break;

                                case 206:
                                    {
                                        currentCompte = new ag_upsideo_compte()
                                        {
                                            idclient = currentAgregClientId,
                                            idcgp = report.CustomerProspect.User1.idAgregCGP.Value,
                                            idfrontfournisseur = agregFournisseur.idfrontfournisseur,
                                            numcompte = numCompteFictif,
                                            typecontrat = "professionels",
                                            deleted = "n",

                                            designation = agregOptionAttributeValue.CustomObjectValue.Values["Description"],
                                            totalcompte = agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"] != "" ? Convert.ToDouble(agregOptionAttributeValue.CustomObjectValue.Values["OwnedCapital"]) : null

                                        };
                                        if (!string.IsNullOrEmpty(agregOptionAttributeValue.CustomObjectValue.Values["Description"]))
                                        {
                                            db.ag_upsideo_compte.AddObject(currentCompte);
                                        }
                                    }
                                    break;
                                default:
                                    break;

                            }
                        }
                    }
                    #endregion


                }
                #endregion

                #region Report
                //5- Update dateupdated report               
                report.DateUpdated = DateTime.Now;
                #endregion

                //6- Commit all changes here
                db.SaveChanges();
                return optionAttributeValue2!=null ? optionAttributeValue2.idReportOptionAttributeValue : 0;
            }
        }