public ActionResult ProspectPartial_Create([ModelBinder(typeof(DevExpressEditorsBinder))] CustomerProspectViewModel _prospectData)
        {
            CustomerProspect prospect = new CustomerProspect() { User = new User() };

            var LanguageData = Upsilab.Business.Utility.PageLanguageHelper.GetLanguageContent("User", "Client/Index");

            if (string.IsNullOrEmpty(_prospectData.UserEmail))
            {
                prospect.User.UserLogin = string.Empty;
            }
            else
            {
                prospect.User.UserLogin = _prospectData.UserEmail;
                prospect.User.UserEmail = _prospectData.UserEmail;
            }

            if (ModelState.IsValid)
            {
                //NB : Up to know : many clients can use the same email
                Guid idSelectedFirm = SessionManager.GetFirmInstitutionSession().idFirmInstitution;
                if (!string.IsNullOrEmpty(Request.Params["TxtSelectedFirmeGUIDPartial"].ToString()))
                {
                    Guid.TryParse(Request.Params["TxtSelectedFirmeGUIDPartial"].ToString(), out idSelectedFirm);
                }

                // create user and prospect/customer
                // create user and prospect/customer
                prospect.User.idUser = Business.Utility.GuidHelper.GenerateGuid();
                prospect.User.idUserProfile = UserProfileBL.GetAllUserProfiles().Where(up => up.UserProfileName.ToLower().Equals("end-user")).FirstOrDefault().idUserProfile;
                prospect.User.DateCreated = DateTime.Now;
                prospect.User.IsActive = true;

                prospect.User.UserMobilePhone = _prospectData.UserMobilePhone;
                prospect.User.UserName = _prospectData.UserName;
                prospect.User.UserFirstName = _prospectData.UserFirstName;

                prospect.Adress = _prospectData.Adress;
                prospect.City = _prospectData.City;
                prospect.ZipCode = _prospectData.ZipCode;
                prospect.IsCorporation = _prospectData.IsCorporation;
                prospect.CompanyName = _prospectData.CompanyName;
                prospect.PlaceOfBirth = _prospectData.PlaceOfBirth;
                prospect.Nationality = _prospectData.Nationality;

                if (!string.IsNullOrEmpty(_prospectData.DateOfBirthStr))
                {
                    string[] splittedDate = _prospectData.DateOfBirthStr.Split('/');
                    try { prospect.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(_prospectData.UserEmail))
                {
                    var user = UserBL.GetUserByEmail(_prospectData.UserEmail);
                    if (user != null)
                        password = user.UserPassword;
                }
                prospect.User.UserPassword = ""; //Temporary set
                prospect.User = UserBL.CreateUser(prospect.User, password);

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

                CustomerProspectBL.CreateProspect(prospect);

                string outputMsg = string.Empty;
            }
            else
            {
                ViewData["EditError"] = LanguageData.GetContent("Client_Index_please_fill_input");
            }

            //Get prospects
            List<FirmInstitution> lstFirmInstitutions = new List<FirmInstitution>();
            List<User> lstUserAdvisers = new List<User>();

            GetDataToPopulateDropDowns(null, out lstUserAdvisers, out lstFirmInstitutions);
            List<CustomerProspectViewModel> lstProspects = GetProspects(null, lstFirmInstitutions);

            return PartialView("ProspectPartial", lstProspects);
        }
        public string MajIsAlertClient()
        {
            if (Request.Form["customerId"] != null && Request.Form["IsAlertClient"] != null)
            {
                Guid id;
                Guid.TryParse(Request.Form["customerId"].ToString(), out id);

                CustomerProspect customer = new CustomerProspect()
                {
                    idCustomer = id,
                    IsAlertRecipientClient = (Request.Form["IsAlertClient"].ToString() == "1") ? true : false
                };
                CustomerProspectBL.UpdateIsAlertRecipientClient(customer);
            }
            return "Ok";
        }
        public string MajNextDate()
        {
            if (Request.Form["customerId"] != null && Request.Form["Date"] != null && Request.Form["Type"] != null)
            {
                Guid id;
                Guid.TryParse(Request.Form["customerId"].ToString(), out id);
                string pType = Request.Form["Type"].ToString();
                DateTime date;
                DateTime.TryParse(Request.Form["Date"].ToString(), out date);
                CustomerProspect customer = new CustomerProspect()
                {
                    idCustomer = id
                };
                if (pType == "REC")
                    customer.DateUpdatedNext = date;
                else if (pType == "LAB")
                    customer.DateShiftLABNext = date;
                else if (pType == "CNI")
                    customer.CNIDateExpired = date;
                else if (pType == "PAS") //PASSEPORT
                    customer.PasseportDateExpired = date;

                CustomerProspectBL.UpdateDateMaj(customer, pType);
            }
            return "Ok";
        }
        private string GenerateRTODocument(CustomerProspect customer)
        {
            using (var context = new UpsilabEntities())
            {
                #region 1- Convention RTO Document

                var crto = customer.ConventionRTO;

                if (crto == null)
                {
                    crto = new ConventionRTO()
                    {
                        idConventionRTO = GuidHelper.GenerateGuid(),
                        Status = Business.Report.ReportBL.Status.InProgress.ToString(),
                        DateCreated = DateTime.Now,
                        SignedByCustomer = false,
                        SignedByAdviser = false,
                        Archived = false,
                        DatesSendMailToCustomer = DateTime.Now.ToShortDateString()
                    };

                    context.ConventionRTO.Attach(crto);
                    context.ObjectStateManager.ChangeObjectState(crto, System.Data.EntityState.Added);

                    customer.idConventionRTO = crto.idConventionRTO;
                    context.SaveChanges();
                }

                Business.CustomerProspect.CustomerProspectBL.Update(customer,false,true);

                DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeByCode("CRTO");
                

                string documentPath =
                    ElectronicSafeDocumentBL.BuildClientDocumentPath(
                        ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), customer);
                string documentFullPath = Server.MapPath(string.Format("~/uploads/{0}", documentPath));
                string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix,
                                                                              customer.idCustomer, "CRTO.pdf");
                if (!System.IO.Directory.Exists(documentFullPath))
                {
                    System.IO.Directory.CreateDirectory(documentFullPath);
                }
                string crtoFilePath = System.IO.Path.Combine(documentFullPath, sFilename);

                MissionDocumentPdfGenerationBL.GenerateRTO(crto.idConventionRTO, SessionManager.GetUserSession(),
                                                           customer, crtoFilePath, false);


                if (System.IO.File.Exists(crtoFilePath))
                {
                    return crtoFilePath;
                }


                #endregion

                return string.Empty;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        private void InsertProcess(DataRow row, ImportO2SModel model, bool isUsedByManymore = false, Dictionary<string, Guid> fieldsMatching = null)
        {
            string nom = this.GetNomClient(row, model.Nom);
            string prenom = this.GetPrenomClient(row, model.Prenom);
            string email = this.GetEmailClient(row, model.Email);
            string mobilePhone = this.GetPhoneClient(row, model.TelephoneMobile); //TODO: Verifier format du numero phone
            string privatePhone = this.GetPhoneClient(row, model.Telephone); //TODO: Verifier format du numero phone
            string professionalPhone = this.GetPhoneClient(row, model.TelephoneProfessionnel); //TODO: Verifier format du numero phone
            string fax = !string.IsNullOrEmpty(model.Fax) ? this.CleanString(row[model.Fax].ToString()) : string.Empty;
            bool isPersonnePhysique = this.IsPersonnePhysique(row, model.TypePersonne);
            bool isCustomer = Convert.ToBoolean(model.IsCustomer);// this.IsCustomer(row, model.IsCustomer);
            string dateNaissance = this.GetDate(row, model.DateNaissance);
            string weddingDate = this.GetDate(row, model.WeddingDate);

            if (string.IsNullOrEmpty(email))
                email = string.Empty; // string.Format("{0}@{1}", (nom + prenom).Replace(" ", ""), User.DEFAULT_MAIL_DOMAIN);

            if (string.IsNullOrEmpty(mobilePhone))
                mobilePhone = User.DEFAULT_MOBILEPHONE;


            CustomerProspect pCustomerProspect = new CustomerProspect();

            pCustomerProspect.User = new User();

            pCustomerProspect.User.idUser = Business.Utility.GuidHelper.GenerateGuid();
            pCustomerProspect.User.idUserProfile = model.idUserProfile;
            pCustomerProspect.User.DateCreated = DateTime.Now;
            pCustomerProspect.User.IsActive = true;
            pCustomerProspect.idFirmInstitution = !model.idFirmInstitution.HasValue ? SessionManager.GetFirmInstitutionSession().idFirmInstitution : model.idFirmInstitution.Value;// model.idFirmInstitution.Value;//SessionManager.GetFirmInstitutionSession().idFirmInstitution;
            pCustomerProspect.User.UserPassword = ""; //Temporary set


            pCustomerProspect.idCustomer = Business.Utility.GuidHelper.GenerateGuid();


            //common parts from import
            pCustomerProspect.User.UserName = nom;
            pCustomerProspect.User.UserFirstName = prenom;
            pCustomerProspect.User.UserEmail = email;
            pCustomerProspect.User.UserLogin = email;
            pCustomerProspect.User.UserMobilePhone = mobilePhone;


            //default value personne physique if model.TypePersonne is Empty or Null
            pCustomerProspect.IsCorporation = false;

            if (!string.IsNullOrEmpty(model.TypePersonne))
            {
                pCustomerProspect.IsCorporation = !isPersonnePhysique;
                //IF PM, set companyName = UserName
                if (!isPersonnePhysique)
                    pCustomerProspect.CompanyName = nom;
            }

            if (!string.IsNullOrEmpty(dateNaissance))
            {
                pCustomerProspect.DateOfBirth = Convert.ToDateTime(dateNaissance);
                pCustomerProspect.User.DateOfBirth = Convert.ToDateTime(dateNaissance);
            }
            
            pCustomerProspect.User = UserBL.CreateUser(pCustomerProspect.User, pCustomerProspect.User.UserPassword);

            pCustomerProspect.IdUser = pCustomerProspect.User.idUser;
            pCustomerProspect.IsCustomer = isCustomer;
            pCustomerProspect.MobilePhone = mobilePhone;
            pCustomerProspect.ProfessionalPhone = professionalPhone;
            pCustomerProspect.PrivatePhone = privatePhone;
            pCustomerProspect.Fax = fax;



            //Conseiller principal for Admin User
            if (fieldsMatching != null && fieldsMatching.Count > 0)
            {
                string conseiller = this.CleanString(row[CONSEILLER_PRINCIPAL].ToString());
                if (!string.IsNullOrEmpty(conseiller) && fieldsMatching.ContainsKey(conseiller))
                    pCustomerProspect.idUserCreated = fieldsMatching[conseiller];
            }
            //Conseiller principal for Not Manymore
            //markage
            else if (/*isUsedByManymore &&*/ !string.IsNullOrEmpty(model.ColumnConseillerPrincipal) && !String.IsNullOrEmpty(row[model.ColumnConseillerPrincipal].ToString()))
            {
                string conseiller = row[model.ColumnConseillerPrincipal].ToString().Trim();
                User CustomerProspectCreator = this.GetAdviser(conseiller, model.FirmInstitution);
                if (CustomerProspectCreator != null)
                    pCustomerProspect.idUserCreated = CustomerProspectCreator.idUser;
            }
            //Conseiller principal Manymore simple User or Not Manymore with non specified Adviser
            //Or Take current User as Default Adviser if userCreated is empty
            if (pCustomerProspect.idUserCreated == Guid.Empty)
                pCustomerProspect.idUserCreated = SessionManager.GetUserSession().idUser;

            try
            {
                string title = this.CleanString(row[model.Title].ToString());

                if (title == "M")
                {
                    title = "Monsieur";
                }
                else if (title == "F")
                {
                    title = "Madame";
                }

                pCustomerProspect.Title = title;
            }
            catch { }

            try
            {
                pCustomerProspect.PlaceOfBirth = this.CleanString(row[model.LieuNaissance].ToString());
            }
            catch { }
            try
            {
                string adress2 = !string.IsNullOrEmpty(model.Adresse2) ? this.CleanString(row[model.Adresse2].ToString()) : string.Empty;
                pCustomerProspect.Adress = this.CleanString(row[model.Adresse].ToString());
                if (!string.IsNullOrEmpty(adress2))
                {
                    pCustomerProspect.Adress += Environment.NewLine + adress2;
                }
            }
            catch { }
            try
            {
                string resident = this.CleanString(row[model.Resident].ToString()).ToLower().Replace("é", "e").Replace("ç", "c");
                if (resident == "francais" || resident == "resident" || resident == "r")
                {
                    pCustomerProspect.IsResident = true;
                }

                if (resident == "non resident" || resident.ToLower() == "non r")
                {
                    pCustomerProspect.IsResident = false;
                }
            }
            catch { }
            try
            {
                pCustomerProspect.RefExtConjoint = this.CleanString(row[model.RefExtConjoint].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.MarriageSettlement = this.CleanString(row[model.MarriageSettlement].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.Liberality = this.CleanString(row[model.Liberalites].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.MaidenName = this.CleanString(row[model.MaidenName].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.City = this.CleanString(row[model.Ville].ToString());

            }
            catch { }
            try
            {
                string country = this.CleanString(row[model.Pays].ToString());
                if (country.ToUpper() == "FR")
                    country = "France";
                pCustomerProspect.Country = country;
            }
            catch { }
            try
            {
                pCustomerProspect.ZipCode = this.CleanString(row[model.CodePostal].ToString());
            }
            catch { }

            try
            {
                string maritalStatus = this.CleanString(row[model.MaritalStatus].ToString());
                if (maritalStatus.ToLower().StartsWith("c"))
                {
                    maritalStatus = "Célibataire";
                }
                else if (maritalStatus.ToLower().StartsWith("d"))
                {
                    maritalStatus = "Divorcé";
                }
                else if (maritalStatus.ToLower().StartsWith("m"))
                {
                    maritalStatus = "Marié";
                }
                else if (maritalStatus.ToLower().StartsWith("v"))
                {
                    maritalStatus = "Veuf";
                }
                else if (maritalStatus.ToLower().StartsWith("p"))
                {
                    maritalStatus = "Pacsé";
                }

                if (!maritalStatus.ToLower().Contains("non défini"))
                    pCustomerProspect.MaritalStatus = maritalStatus;
            }
            catch { }

            try
            {
                pCustomerProspect.Nationality = this.CleanString(row[model.Nationality].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.NumSIREN = this.CleanString(row[model.NumSIREN].ToString());
            }
            catch { }
            try
            {
                if (pCustomerProspect.IsCorporation == true)
                {
                    //Cabinet
                    //SC - Société civile
                    //Non définie
                    //SAS - Société anonyme par actions simplifiée
                    //SC - Société civile
                    //SARL - Société à responsabilité limitée

                    string legalForm = this.CleanString(row[model.LegalForm].ToString()).ToUpper();
                    string fiscalPlan = model.FiscalPlan == null ? string.Empty : this.CleanString(row[model.FiscalPlan].ToString()).ToUpper();

                    if (legalForm.Contains("EURL"))
                        pCustomerProspect.LegalForm = "EURL";

                    else if (legalForm.Contains("SARL") || legalForm.Contains("S.A.R.L."))
                        pCustomerProspect.LegalForm = "SARL";

                    else if (legalForm.Contains("SAS") || legalForm.Contains("S.A.S."))
                        pCustomerProspect.LegalForm = "SAS";

                    else if (legalForm.Contains("SA") || legalForm.Contains("S.A."))
                        pCustomerProspect.LegalForm = "SA";

                    else if (legalForm.Contains("ASSOCIATION"))
                    {
                        if (fiscalPlan.Contains("IR"))
                            pCustomerProspect.LegalForm = "Association_IR"; //Association - IR
                        else if (fiscalPlan.Contains("IS"))
                            pCustomerProspect.LegalForm = "Association_IS";//Association - IS
                        else
                            pCustomerProspect.LegalForm = "Association";
                    }

                    else if ((legalForm.Contains("SC") || legalForm.Contains("S.C.")) && !legalForm.Contains("S.C.I."))
                    {
                        //#4303
                        if (fiscalPlan.Contains("IR"))
                            pCustomerProspect.LegalForm = "SC_IR"; //societe civile - impot sur le revenu
                        else if (fiscalPlan.Contains("IS"))
                            pCustomerProspect.LegalForm = "SC_IS";//societe civile - IS
                        else
                            pCustomerProspect.LegalForm = "SC";

                    }
                    //Autre
                    else
                    {
                        if (fiscalPlan.Contains("IR"))
                            pCustomerProspect.LegalForm = "Autre_IR"; //Autre - IR
                        else if (fiscalPlan.Contains("IS"))
                            pCustomerProspect.LegalForm = "Autre_IS";//Autre - IS
                        else
                            pCustomerProspect.LegalForm = "Autre";

                        pCustomerProspect.LegalForm_Autre = legalForm;
                    }
                }
            }
            catch { }
            try
            {
                string date = this.GetDate(row, model.RelationshipBeginingDate);
                if (!string.IsNullOrEmpty(date))
                    pCustomerProspect.RelationshipBeginingDate = Convert.ToDateTime(date);
            }
            catch { }
            try
            {
                pCustomerProspect.RiskProfile = this.CleanString(row[model.RiskProfile].ToString());
            }
            catch { }
            try
            {
                string legalCapacity = this.CleanString(row[model.LegalCapacity].ToString());
                pCustomerProspect.LegalCapacity = legalCapacity;
            }
            catch { }
            try
            {
                pCustomerProspect.Profession = this.CleanString(row[model.Profession].ToString());
            }
            catch { }
            try
            {
                pCustomerProspect.RefExt = this.CleanString(row[model.RefExt].ToString());
            }
            catch { }
            /*new*/
            try
            {
                string numerorcs = this.CleanString(row[model.NumeroRCS].ToString());
                pCustomerProspect.NumRCS = numerorcs;
            }
            catch { }
            try
            {
                string lieurcs = this.CleanString(row[model.LieuRCS].ToString());
                pCustomerProspect.NumRCS = lieurcs;
            }
            catch { }
            try
            {
                string originerelation = this.CleanString(row[model.Originerelation].ToString());
                if (originerelation.ToLower().Trim().Equals("recommandation")
                    || originerelation.ToLower().Trim().Equals("prescription")
                    || originerelation.ToLower().Trim().Equals("lien familial"))
                {
                    originerelation = "contactparrecommandation";
                }
                else if (originerelation.ToLower().Trim().Equals("client historique"))
                {
                    originerelation = "clientdepuis";
                }
                else
                {
                    originerelation = "autre";
                }

                pCustomerProspect.RelationshipType = originerelation;
            }
            catch { }
            try
            {
                string clientdepuis = this.GetDate(row, model.Clientdepuis);
                if (!string.IsNullOrEmpty(clientdepuis))
                {
                    pCustomerProspect.RelationshipBeginingDate = Convert.ToDateTime(clientdepuis);
                    pCustomerProspect.RelationshipType = "clientdepuis";
                }
            }
            catch { }

            string maritalStatusTest = string.Empty;
            try
            {
                maritalStatusTest = this.CleanString(row[model.MaritalStatus].ToString());
            }
            catch { }
            string datepacs = string.Empty;
            try
            {
                datepacs = this.GetDate(row, model.Datepacs);
            }
            catch { }
            string datedivorce = string.Empty;
            try
            {
                datedivorce = this.GetDate(row, model.Datedivorce);
            }
            catch { }
            try
            {                
                if (!string.IsNullOrEmpty(datepacs) && string.IsNullOrEmpty(maritalStatusTest))
                {
                    pCustomerProspect.WeddingDate = Convert.ToDateTime(datepacs);
                    pCustomerProspect.MaritalStatus = "Pacsé";
                }

            }
            catch { }
            try
            {
                if (!string.IsNullOrEmpty(datedivorce) && string.IsNullOrEmpty(maritalStatusTest) && string.IsNullOrEmpty(datepacs))
                {
                    pCustomerProspect.WeddingDate = Convert.ToDateTime(datedivorce);
                    pCustomerProspect.MaritalStatus = "Divorcé";
                }
            }
            catch { }
            try
            {
                if (!string.IsNullOrEmpty(weddingDate) && string.IsNullOrEmpty(maritalStatusTest)
                    && string.IsNullOrEmpty(datepacs) && string.IsNullOrEmpty(datedivorce))
                {
                    pCustomerProspect.WeddingDate = Convert.ToDateTime(weddingDate);
                    pCustomerProspect.MaritalStatus = "Marié";
                }
            }
            catch { }
            try
            {
                string residencefiscal = this.CleanString(row[model.Residencefiscale].ToString());
                pCustomerProspect.FiscalAddrress = residencefiscal;
            }
            catch { }
            /*end new*/
            CustomerProspectBL.CreateCustomerForImport(pCustomerProspect);

        }
        public PartialViewResult CreateNewClient(string client)
        {
            CustomerProspect newCust = new CustomerProspect(){};
            newCust.idCustomer = GuidHelper.GenerateGuid();

            return PartialView("PopupNewClient", newCust);
        }
        public ActionResult StartLABUpdate()
        {
            Guid idCustomer = Guid.NewGuid();
            CustomerProspect customerProspect = new CustomerProspect();

            try
            {
                SessionManager.Get<Guid>(LABStudyBL.IdCustomerSessionKey, out idCustomer);
                LABStudy labStudy = LABStudyBL.GetLatestLABStudyByIdCustomerProspect(idCustomer);

                //Duplicate latest LAB if status "SentToCoffreFort" : start new LAB study
                labStudy = this.CopyLatestLABStudy(labStudy);

                //update customer
                customerProspect = CustomerProspectBL.GetById(idCustomer);
                customerProspect.CurrentLabStatus = Data.Model.LABStudy.StatusEnum.Completed.ToString();
                customerProspect.NbVigilanceMeasure = 0; //Do new measure if vigi = 4 or vigi = 5
                CustomerProspectBL.Update(customerProspect);
            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                return RedirectToAction("Index", "Client");
            }

            return RedirectToAction("QuestionClient", "LABStudy");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="docType"></param>
        /// <param name="idDocumentCategory"></param>
        /// <returns></returns>
        public Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument> GetCustomerDocuments(CustomerProspect customer, DocumentType docType, int idDocumentCategory = 0)
        {
            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument() { CustomerProspect = customer, DocumentType = docType });
            var LanguageData = PageLanguageHelper.GetLanguageContent("User", "CoffreFortController");

            try
            {
                // Get list of documents
                IList<ElectronicSafeDocument> lstElectronicSafeDocs = ElectronicSafeDocumentBL.GetDocuments(customer.idCustomer, docType.DocumentNamePrefix);
                ElectronicSafeDocument newElecSafeDoc = new ElectronicSafeDocument() { CustomerProspect = customer, DocumentType = docType };

                // Si filtrage par rapport à DocumentCategory
                if (docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.DOC.ToString())
                {
                    // avec idDocumentCategory différent de null (Appartenant à une rubrique(DocumentCategory))
                    if (idDocumentCategory != 0)
                    {
                        //lstElectronicSafeDocs = lstElectronicSafeDocs.Where(e => e.idDocumentCategory == idDocumentCategory || e.DocumentCategory.IdDocumentCategoryParent == idDocumentCategory).ToList();
                        //
                        var tmpList = lstElectronicSafeDocs.Where(e => e.idDocumentCategory == idDocumentCategory).ToList();
                        lstElectronicSafeDocs = (tmpList.Count == 0) ?
                            lstElectronicSafeDocs.Where(e => e.idDocumentCategory.HasValue && e.DocumentCategory.IdDocumentCategoryParent.HasValue && e.DocumentCategory.IdDocumentCategoryParent.Value == idDocumentCategory).ToList() :
                            tmpList;

                        newElecSafeDoc.idDocumentCategory = idDocumentCategory;
                    }
                    else
                    {
                        lstElectronicSafeDocs = lstElectronicSafeDocs.Where(e => e.idDocumentCategory == null).ToList();
                    }
                }

                tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(lstElectronicSafeDocs, newElecSafeDoc);

                // Check if Firm has sufficient credit to send doc to coffre fort
                if (docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.DOC.ToString())
                {
                    if (!CreditOperationBL.HasFirmInstitutionSufficientCredit(customer.FirmInstitution.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS.ToString()))

                    // if (!CreditOperationBL.HasFirmInstitutionSufficientCredit(SessionManager.GetFirmInstitutionSession().idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS.ToString()))
                    {
                        ViewBag.CanUploadDoc = false;
                        ViewBag.ErrorBeforeUpload = LanguageData.GetContent("CoffreFort_envoi_doc_impossible");
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                Business.Log.Log.AppendException(ex);
            }
            return tuple;
        }
        public Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument> GetDossierDocumentsWithLab(List<int> idSubscriptionFiles, CustomerProspect customer, DocumentType docType)
        {
            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument() { SubscriptionFile = new SubscriptionFile() });
            var newElecSafeDoc = new ElectronicSafeDocument() { CustomerProspect = customer, DocumentType = docType };
            try
            {
                /* subscriptions list for customer lab*/
                if (customer!=null)
                {
                    var firmInstitutionForProduct = FrDossierBL.GetInfoLiteByCustomerLab(customer.idCustomer);
                    SessionManager.Set<List<FirmInstitutionViewModel>>(SUBSCRIPTION_FILE_OBJECT_LIST_SESSION, firmInstitutionForProduct); 
                }
                // Get list of documents
                var lstElectronicSafeDocs = new List<ElectronicSafeDocument>();
                idSubscriptionFiles.ForEachESD(lstElectronicSafeDocs.AddRange);
                tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(lstElectronicSafeDocs, newElecSafeDoc);

            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                Business.Log.Log.AppendException(ex);
            }
            return tuple;
        }
        public ActionResult StartReportUpdate()
        {
            Guid? idCustomer = null;
            CustomerProspect customerProspect = new CustomerProspect();

            try
            {
                User currentUser = SessionManager.GetUserSession();
                idCustomer = GetCPID();
                Report currentReport = ReportBL.GetLatestReportByIdCustomerProspect(idCustomer.Value);

                //Duplicate latest report values if status "COMPLETED" : start new report
                if (!currentUser.IsEndUser())
                {
                    if (currentReport.Status.ToLower().Equals(ReportBL.Status.Completed.ToString().ToLower()))
                    {
                        currentReport = this.CopyLatestReport(currentReport);

                        //update customer status (since optimization)
                        customerProspect = CustomerProspectBL.GetById(idCustomer.Value);
                        customerProspect.CurrentReportStatus = ReportBL.Status.InProgress.ToString();
                        CustomerProspectBL.Update(customerProspect);
                    }
                }
            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                return RedirectToAction("Index", (customerProspect.IsCustomer) ? "Client" : "Prospect");
            }

            return RedirectToAction("Index");
        }
        private void SetGeneratedRTOPathFileName(CustomerProspect customer)
        {
            if (customer.ConventionRTO != null && customer.ConventionRTO.SignedByCustomer)
            {
                customer.GeneratedECPathFileName = string.Empty;
            }
            else
            {
                string docType = ElectronicSafeDocumentBL.DocumentType.CRTO.ToString();
                string userPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType, customer, true);
                string destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, customer.idCustomer, false);
                string filePath = System.IO.Path.Combine(destFullPath, filename);

                //Generate EC
                EngagementPdfGenerationBL.GeneratePDF(customer, customer.FirmInstitution, filePath, false);

                customer.GeneratedCRTOPathFileName = Url.Content(string.Format("~/uploads/{0}/{1}", userPath, filename).Replace("\\", "/"));
            }
        }
        private void SetCreditsMessage(CustomerProspect pCustomer)
        {
            CustomerProspect customer = null;

            var currentUser = SessionManager.GetUserSession();

            if (currentUser.IsEndUser())
            {
                customer = SessionManager.GetCustomerProspectSession();
            }
            else
            {
                customer = pCustomer;
            }
            if (customer != null)
            {
                if (!CreditOperationBL.HasFirmInstitutionSufficientCredit(customer.FirmInstitution.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_ETUDE_LAB.ToString()))
                    ViewBag.CanSendToFce = LanguageData.GetContent("sendtoCF_credit_error");
            }

        }
        public ActionResult IndexPartial(CustomerProspect _customer)
        {
            CustomerProspect Customer = CustomerProspectBL.GetCustomerProspectById(_customer.idCustomer);
            TempData["Target_idCustomer"] = _customer.idCustomer;
            if (!string.IsNullOrEmpty(Request.Params["rb_PP"])
                && Request.Params["rb_PP"].ToLower().Equals("c"))
            {
                Customer.IsCorporation = false;
                CustomerProspectBL.UpdateProspect(Customer);
                return RedirectToAction("QuestionClient");
            }
            else if (!string.IsNullOrEmpty(Request.Params["rb_PM"])
                && Request.Params["rb_PM"].ToLower().Equals("c"))
            {
                Customer.IsCorporation = true;
                CustomerProspectBL.UpdateProspect(Customer);
                return RedirectToAction("QuestionClient");
            }

            return PartialView("IndexPartial", Customer);
        }
        public int? GetRootOptionID(CustomerProspect _customer, int _questionParentID)
        {
            int? retVal = null;

            if (_customer.IsCorporation.HasValue)
            {
                if (_customer.IsCorporation.Value)
                {
                    switch (_questionParentID)
                    {
                        case 1: retVal = 717; break;
                        default: break;
                    }
                }
                else
                {
                    switch (_questionParentID)
                    {
                        case 1: retVal = 759; break;
                        default: break;
                    }
                }
            }

            return retVal;
        }
 public void DeleteProspects()
 {
     if (!string.IsNullOrEmpty(Request.Params["_toDeleteID"]))
     {
         var qParamValues = Request.Params["_toDeleteID"].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
         foreach (string param in qParamValues)
         {
             CustomerProspect cust = new CustomerProspect() { idCustomer = Guid.Parse(param) };
             CustomerProspectBL.DeleteCustomerProspect(cust);
         }
     }
 }
        public Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument> GetDossierDocumentsWithPJ(string idDocument,CustomerProspect customer)
        {
            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument() { SubscriptionFile = new SubscriptionFile() });
            var newElecSafeDoc = new ElectronicSafeDocument() { CustomerProspect = customer };
            try
            {
                Guid idDocGuid = Guid.Empty;
                Guid.TryParse(idDocument, out idDocGuid);
                Document doc = null;
                /* subscriptions list for customer lab*/
                if (idDocGuid != Guid.Empty)
                {
                    List<Document> listdoc = new List<Document>();
                    doc = DocumentBL.GetDocumentById(idDocGuid);
                    listdoc.Add(doc);
                    newElecSafeDoc.DocumentType = DocumentTypeBL.GetDocumentTypeByCode(doc.DocumentType);
                    SessionManager.Set<List<Document>>(SUBSCRIPTION_FILE_DOCUMENT_SESSION, listdoc);
                }
                
                // Get list of documents
                var lstElectronicSafeDocs = new List<ElectronicSafeDocument>();
                tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(lstElectronicSafeDocs, newElecSafeDoc);

            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
                Business.Log.Log.AppendException(ex);
            }
            return tuple;
        }
        private string SendCGVToCoffreFort(CustomerProspect customer)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeByCode(ElectronicSafeDocumentBL.DocumentType.CG.ToString());
            string error = string.Empty;

            try
            {
                //TODO : mise au coffre pour le conseiller ?
                if (customer.User.IsEndUser())
                {
                    string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.CG.ToString(), customer);
                    string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                    string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, "CG_client_final.pdf");

                    // 1- File to save to coffre fort
                    string filenameCGS = "CG_client_final.pdf"; //by default FR ?                    
                    
                    if (ConfigurationManager.ExtranetHostCode == PageLanguageHelper.HostCode.BE.ToString())
                    {
                        filenameCGS = "BE_CG_client_final.pdf";
                    }

                    string pathOriginalFileName = Server.MapPath(string.Format("~/Documents/{0}", filenameCGS));
                    byte[] fileBin = System.IO.File.ReadAllBytes(pathOriginalFileName);

                    string pathFilename = System.IO.Path.Combine(documentFullPath, sFilename);
                    System.IO.File.WriteAllBytes(pathFilename, fileBin);

                    // 2- Upload file to DICTAO server
                    D3SClient clientD3S = new D3SClient();
                    string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                    // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_CONDITION_GENERALE"
                    if (!string.IsNullOrEmpty(dictaoId))
                    {
                        //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                        //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

                        CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_CONDITION_GENERALE.ToString(), customer.idUserCreated, customer.idCustomer);

                        // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                        ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.CG.ToString(), LanguageDataPage.GetContent("conditions_generales"), documentPath, customer.idCustomer, dictaoId, clientD3S);
                    }
                    else
                    {
                        error = LanguageDataPage.GetContent("doc_non_envoye_au_cfe");
                    }
                }

            }
            catch (Exception ex)
            {
                Business.Log.Log.AppendException(ex);
                error = ex.Message;
            }

            return error;
        }
        public ActionResult ImportClientAgregateur(ImportClientAgregateur model)
        {
            try
            {
                int clientimporte = 0;
                int clientAimporte = 0;
                model.IsEndImport = true;
                Guid idCgpAgreg = SessionManager.GetUserSession().idAgregCGP.Value;
                if (Request.Form["chkClient"] != null)
                {
                    string[] clientIdList = Request.Form["chkClient"].ToString().Split(',');
                    clientAimporte = clientIdList.Count();
                    string ImportMode = Request.Form["ImportMode"].ToString();
                    List<ImportErrorModel> lsterror = new List<ImportErrorModel>();
                    using (UpsilabEntities context = new UpsilabEntities())
                    {
                        //cas d'initialisation
                        if (ImportMode == "0")
                        {
                            List<CustomerProspect> listecustomer = context.CustomerProspect.Where(c => c.User1.idAgregCGP == idCgpAgreg).ToList();
                            if (listecustomer.Count > 0)
                            {
                                foreach (CustomerProspect customer in listecustomer)
                                {
                                    var user = customer.User;
                                    user.IsDeleted = true;
                                    user.IsActive = false;
                                    user.DateDeleted = DateTime.Now;
                                    user.DateExpired = DateTime.Now;
                                    customer.isDeleted = true;
                                }
                            }
                        }
                        //fin

                        foreach (string sId in clientIdList)
                        {
                            Guid clientId = new Guid(sId);
                            //get client agreg
                            ag_upsideo_client currentClientAgreg = context.ag_upsideo_client.Where(c => c.idclient == clientId && c.deleted != "o").FirstOrDefault();
                            //get client recueil/lab si existe
                            if (currentClientAgreg != null)
                            {
                                string nomclient = string.IsNullOrEmpty(currentClientAgreg.nomclient) ? "" : currentClientAgreg.nomclient.ToLower();
                                string prenomclient = string.IsNullOrEmpty(currentClientAgreg.prenomclient) ? "" : currentClientAgreg.prenomclient.ToLower();
                                CustomerProspect currentcustomer = context.CustomerProspect.Where(c => c.User1.idAgregCGP == idCgpAgreg && c.User.UserName.ToLower() == nomclient && c.User.UserFirstName.ToLower() == prenomclient && (!c.isDeleted.HasValue || (c.isDeleted.HasValue && !c.isDeleted.Value))).FirstOrDefault();
                                switch (ImportMode)
                                {
                                    case "0":
                                        try
                                        {
                                            /*if (currentcustomer != null )
                                            {
                                                //supprimer
                                                currentcustomer.isDeleted = true;
                                                currentcustomer.User.IsDeleted = true;                                            
                                            }*/
                                            User usernow = new User()
                                            {
                                                idUser = Guid.NewGuid(),
                                                idUserProfile = 8,
                                                UserPassword = "",
                                                UserName = currentClientAgreg.nomclient,
                                                UserFirstName = currentClientAgreg.prenomclient,
                                                IsActive = true,
                                                DateCreated = DateTime.Now,
                                                IsDeleted = false,
                                                CGVOk = true,
                                                HasReadMessage = false,
                                                ReceiveLicenseRemind = false,
                                            };

                                            context.User.AddObject(usernow);

                                            CustomerProspect customernow = new CustomerProspect()
                                            {
                                                idCustomer = Guid.NewGuid(),
                                                idFirmInstitution = model.idFirmInstitution.Value,
                                                DateCreated = DateTime.Now,
                                                IdUser = usernow.idUser,
                                                IsCustomer = model.IsCustomer,
                                                idUserCreated = SessionManager.GetUserSession().idUser,
                                                IsAlertRecipientClient = false,
                                                Adress = currentClientAgreg.adr,
                                                ZipCode = currentClientAgreg.cp,
                                                City = currentClientAgreg.ville,
                                                DateOfBirth = currentClientAgreg.ddn,
                                                FiscalAddrress = currentClientAgreg.adr2,
                                                Title = currentClientAgreg.titre,
                                                idAgregClient = currentClientAgreg.idclient,
                                                IsCorporation = false,
                                                isDeleted = false,
                                            };

                                            context.CustomerProspect.AddObject(customernow);

                                            clientimporte = clientimporte + 1;
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    case "1":
                                        try
                                        {
                                            if (currentcustomer != null)
                                            {
                                                currentcustomer.idAgregClient = currentClientAgreg.idclient;
                                                /*currentcustomer.Adress = currentClientAgreg.adr;
                                                currentcustomer.ZipCode = currentClientAgreg.cp;
                                                currentcustomer.City = currentClientAgreg.ville;                                           
                                                currentcustomer.FiscalAddrress = currentClientAgreg.adr2;*/

                                            }
                                            else
                                            {
                                                User usernow1 = new User()
                                                {
                                                    idUser = Guid.NewGuid(),
                                                    idUserProfile = 8,
                                                    UserPassword = "",
                                                    UserName = currentClientAgreg.nomclient,
                                                    UserFirstName = currentClientAgreg.prenomclient,
                                                    IsActive = true,
                                                    DateCreated = DateTime.Now,
                                                    IsDeleted = false,
                                                    CGVOk = true,
                                                    HasReadMessage = false,
                                                    ReceiveLicenseRemind = false
                                                };

                                                context.User.AddObject(usernow1);

                                                CustomerProspect customernow1 = new CustomerProspect()
                                                {
                                                    idCustomer = Guid.NewGuid(),
                                                    idFirmInstitution = model.idFirmInstitution.Value,
                                                    DateCreated = DateTime.Now,
                                                    IdUser = usernow1.idUser,
                                                    IsCustomer = model.IsCustomer,
                                                    idUserCreated = SessionManager.GetUserSession().idUser,
                                                    IsAlertRecipientClient = false,
                                                    Adress = currentClientAgreg.adr,
                                                    ZipCode = currentClientAgreg.cp,
                                                    City = currentClientAgreg.ville,
                                                    DateOfBirth = currentClientAgreg.ddn,
                                                    FiscalAddrress = currentClientAgreg.adr2,
                                                    Title = currentClientAgreg.titre,
                                                    idAgregClient = currentClientAgreg.idclient,
                                                    isDeleted = false

                                                };
                                                context.CustomerProspect.AddObject(customernow1);
                                            }
                                            clientimporte = clientimporte + 1;
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    case "2":
                                        try
                                        {
                                            if (currentcustomer == null)
                                            {
                                                User usernow2 = new User()
                                                {
                                                    idUser = Guid.NewGuid(),
                                                    idUserProfile = 8,
                                                    UserPassword = "",
                                                    UserName = currentClientAgreg.nomclient,
                                                    UserFirstName = currentClientAgreg.prenomclient,
                                                    IsActive = true,
                                                    DateCreated = DateTime.Now,
                                                    IsDeleted = false,
                                                    CGVOk = true,
                                                    HasReadMessage = false,
                                                    ReceiveLicenseRemind = false
                                                };

                                                context.User.AddObject(usernow2);

                                                CustomerProspect customernow2 = new CustomerProspect()
                                                {
                                                    idCustomer = Guid.NewGuid(),
                                                    idFirmInstitution = model.idFirmInstitution.Value,
                                                    DateCreated = DateTime.Now,
                                                    IdUser = usernow2.idUser,
                                                    IsCustomer = model.IsCustomer,
                                                    idUserCreated = SessionManager.GetUserSession().idUser,
                                                    IsAlertRecipientClient = false,
                                                    Adress = currentClientAgreg.adr,
                                                    ZipCode = currentClientAgreg.cp,
                                                    City = currentClientAgreg.ville,
                                                    DateOfBirth = currentClientAgreg.ddn,
                                                    FiscalAddrress = currentClientAgreg.adr2,
                                                    Title = currentClientAgreg.titre,
                                                    idAgregClient = currentClientAgreg.idclient,
                                                    isDeleted = false

                                                };
                                                context.CustomerProspect.AddObject(customernow2);

                                                clientimporte = clientimporte + 1;
                                            }
                                            else
                                            {
                                                ImportErrorModel err = new ImportErrorModel()
                                                {
                                                    Name = currentClientAgreg.nomclient,
                                                    FirstName = currentClientAgreg.prenomclient,
                                                    Error = "Le client existe déjà"
                                                };
                                                lsterror.Add(err);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            ImportErrorModel err = new ImportErrorModel()
                                            {
                                                Name = currentClientAgreg.nomclient,
                                                FirstName = currentClientAgreg.prenomclient,
                                                Error = ex.Message
                                            };
                                            lsterror.Add(err);
                                        }
                                        break;
                                    default:
                                        break;
                                }

                            }
                        }
                        context.SaveChanges();
                        model.Message = string.Format("{0} client(s) importé(s) sur {1}", clientimporte.ToString(), clientAimporte.ToString());
                        model.ListeErreur = lsterror;
                    }

                }
                else
                {
                    model.Message = "Pas de client importé.";
                }

                return View("Agregateur", model);

            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
                model.Message = ex.Message;
            }
            return View("Agregateur", model);
        }
        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");
            }
        }
        public LABStudyModel GetLABStudyModel(CustomerProspect _customer, int _questionParentID)
        {
            //1- Initialize
            LABStudyModel labStudyModel = new LABStudyModel();
            labStudyModel.idParent = _questionParentID;
            labStudyModel.idCustomer = _customer.idCustomer;
            labStudyModel.Customer = _customer;

            //2- Get latest LABStudy : if null, create
            LABStudy labStudy = LABStudyBL.GetLatestLABStudyByIdCustomerProspect(labStudyModel.idCustomer);

            if (labStudy == null)
            {
                labStudy = CreateEmptyLABStudy(_customer.idCustomer);
                //update customer
                labStudyModel.Customer.CurrentLabStatus = Data.Model.LABStudy.StatusEnum.InProgress.ToString();
                CustomerProspectBL.Update(labStudyModel.Customer);
            }

            labStudyModel.LABStudy = labStudy;
            labStudyModel.idLABStudy = labStudy.idLABStudy;

            //3- Get LAB Questions
            labStudyModel.LABQuestions = LABQuestionBL.GetLABQuestionListWithIdParent(_questionParentID, labStudyModel.Customer).ToList();

            //4- Get LAB Answers
            var answers = LABAnswerBL.GetAnswersByIdParentQuestionAndIdCustomerProspect(labStudyModel);
            if (answers != null)
            {
                labStudyModel.LABAnswers = answers;
            }

            //5- Check if all questions have been answered
            this.CheckIfAllQuestionsAnswered(labStudyModel);

            //Is readonly ?
            bool needsMesuresVigilance = false;
            Upsilab.Business.Utility.SessionManager.Get<bool>(Upsilab.Business.LAB.LABStudyBL.NeedMesureVigilanceSessionKey, out needsMesuresVigilance);
            labStudyModel.IsReadOnly = needsMesuresVigilance;

            //Create new LAB if status is ("SentToCoffreFort" or "Canceled") and it's not for vigilance measure
            if ((labStudy.Status.Equals(Data.Model.LABStudy.StatusEnum.SentToCoffreFort.ToString())
                || labStudy.Status.Equals(Data.Model.LABStudy.StatusEnum.Canceled.ToString()))

                && !labStudyModel.IsReadOnly)
            {
                labStudy = this.CopyLatestLABStudy(labStudyModel.LABStudy);
                labStudyModel.LABStudy = labStudy;
                labStudyModel.idLABStudy = labStudy.idLABStudy;

                //update customer
                labStudyModel.Customer.CurrentLabStatus = Data.Model.LABStudy.StatusEnum.Completed.ToString();
                labStudyModel.Customer.NbVigilanceMeasure = 0; //Do new measure if vigi = 4 or vigi = 5
                CustomerProspectBL.Update(labStudyModel.Customer);
            }

            //Set session ?
            SessionManager.Set<Guid>(LABStudyBL.IdLABStudySessionKey, labStudy.idLABStudy);

            //Save data from customerprospect to laboptionvalues (this replaces the override)
            if (_questionParentID == CLIENT_ROOT_ID)
            {
                LABStudyOptionBL.SaveCustomerProspectDataToLABStudyOptionValues(labStudyModel.idLABStudy, labStudyModel.Customer);
            }

            //6- Get options and options'value
            labStudyModel.OptionData = GetLABStudyOptionModel(labStudyModel);

            //7- Get Question assessments
            labStudyModel.QuestionAssessment = QuestionAssessmentBL.Get();

            return labStudyModel;
        }