public ActionResult Index()
 {
     Guid? customerId = GetTargetCustomer();
     RegulatoryDocumentModel retVal = new RegulatoryDocumentModel();
     if (customerId.HasValue)
     {
         retVal.TargetCustomerProspect = CustomerProspectBL.GetCustomerProspectById(customerId.Value);
     }
     else
     {
         return RedirectToAction("Index", "Client");
     }
     return View(retVal);
 }
        private void UploadAndSaveManager(RegulatoryDocumentModel _documentData, IEnumerable<HttpPostedFileBase> files, bool isUpsideoModel)
        {
            ViewBag.Error = null;
            ViewBag.Ok = null;
            Guid? customerId = this.GetTargetCustomer();
            bool isMissionLetter = _documentData.IsMissionLetter;

            MissionDocument missionDoc = MissionDocumentBL.GetLatestMissionDocumentByIdCustomer(customerId.Value, isMissionLetter);

            bool isAttachInformationCard = false;
            if (Request.Params["AttachInformationCardText"] != null)
                isAttachInformationCard = Convert.ToBoolean(Request.Params["AttachInformationCardText"].ToString());
            bool isInformationCardFromFirmModel = false;
            if (Request.Params["IsInformationCardFromModelText"] != null)
                isInformationCardFromFirmModel = Convert.ToBoolean(Request.Params["IsInformationCardFromModelText"].ToString());

            bool isAttachPresentation = false;
            if (Request.Params["AttachPresentationText"] != null)
                isAttachPresentation = Convert.ToBoolean(Request.Params["AttachPresentationText"].ToString());
            bool isPresentationFromFirmModel = false;
            if (Request.Params["IsPresentationInformationCardFromModelText"] != null)
                isPresentationFromFirmModel = Convert.ToBoolean(Request.Params["IsPresentationInformationCardFromModelText"].ToString());

            bool isAttachConventionRTO = Convert.ToBoolean(Request.Params["AttachConventionRTOText"].ToString());
            bool isConventionRTOFromFirmModel = Convert.ToBoolean(Request.Params["IsConventionRTOFromYourModelText"].ToString());

            string sDocTypePrefix = (_documentData.IsMissionLetter) ? ElectronicSafeDocumentBL.DocumentType.LM.ToString() : ElectronicSafeDocumentBL.DocumentType.RM.ToString();

            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeByCode(sDocTypePrefix);
            string error = string.Empty;

            bool inputFile_0 = Convert.ToBoolean(Request.Params["inputFile_0"].ToString());
            bool inputFile_1 = Convert.ToBoolean(Request.Params["inputFile_1"].ToString());
            try
            {
                CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(customerId.Value);

                #region RTO et upload
                int i = 0;
                if (isConventionRTOFromFirmModel)
                {
                    bool hasFile = false;
                    if (files != null)
                    {
                        foreach (var file in files)
                        {
                            if (((files.Count() == 1 && inputFile_1 && i == 0) || (files.Count() == 2 && inputFile_1 && i == 1)) && file != null && file.ContentLength > 0)
                            {
                                hasFile = true;

                                //Check file contenttype
                                //if (FileManager.IsPDF(file.ContentType))
                                if (FileManager.IsPDF(file.FileName))
                                {
                                    sDocTypePrefix = string.Concat(sDocTypePrefix, "_", ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());

                                    string fullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(sDocTypePrefix, customer);
                                    string fileName = ElectronicSafeDocumentBL.BuildDocumentName(sDocTypePrefix, customer.idCustomer, "Mission.pdf");

                                    // 1- Sauvegarde dans le repertoire
                                    string filePath = System.IO.Path.Combine(fullPath, fileName);
                                    file.SaveAs(filePath);
                                    missionDoc.ConventionRTOFirmModelFileName = fileName;

                                    ViewBag.Ok = ViewBag.Ok + LanguageData.GetContent("convention_rto_enregistree");
                                }
                                else
                                {
                                    ViewBag.Error = ViewBag.Error + LanguageData.GetContent("fichier_pdf_requis");
                                }
                            }
                            i++;
                        }
                    }

                    if (!hasFile && string.IsNullOrEmpty(missionDoc.ConventionRTOFirmModelFileName))
                    {
                        // NB : #4608 : ne pas afficher l'erreur si l'utilisateur a décidé de ne pas joindre le fichier
                        if (isAttachConventionRTO)
                        {
                            ViewBag.Error = ViewBag.Error + string.Format(LanguageData.GetContent("aucun_fichier_rto_selectionne"));
                        }
                    }

                }
                #endregion

                #region Upload Lettre de Mission / Report Mission
                //L'upload is mandatory for Firm model
                if (!isUpsideoModel)
                {
                    bool hasFile = false;
                    string documentLabel = (isMissionLetter) ? LanguageData.GetContent("lettre_de_mission") : LanguageData.GetContent("rapport_de_mission");

                    int a = 0;
                    if (files != null)
                    {
                        foreach (var file in files)
                        {
                            if (((files.Count() == 1 && inputFile_0 && a == 0) || (files.Count() == 2 && inputFile_0 && a == 0)))
                            {
                                if (file != null && file.ContentLength > 0)
                                {
                                    hasFile = true;

                                    //Check file content type
                                    //if (FileManager.IsPDF(file.ContentType))
                                    if (FileManager.IsPDF(file.FileName))
                                    {
                                        #region Traitement du formulaire : sauvegarde du fichier
                                        sDocTypePrefix = objDoctype.DocumentNamePrefix;

                                        string fullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(sDocTypePrefix, customer);
                                        string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(sDocTypePrefix, customer.idCustomer, "Mission.pdf");

                                        // 1- Sauvegarde dans le repertoire
                                        string filePath = System.IO.Path.Combine(fullPath, sFilename);
                                        file.SaveAs(filePath);

                                        missionDoc.FileName = sFilename;
                                        #endregion
                                    }
                                    else
                                    {
                                        ViewBag.Error = ViewBag.Error + string.Format(LanguageData.GetContent("telecharger_un_fichier_pdf"), documentLabel);
                                    }
                                }
                            }

                            a++;
                        }
                    }

                    if (!hasFile && string.IsNullOrEmpty(missionDoc.FileName))
                    {
                        ViewBag.Error = ViewBag.Error + string.Format(LanguageData.GetContent("aucun_fichier_selectionne"), documentLabel);
                    }

                }
                #endregion

                #region Traitement Fiche d'information légale (appelé par la suite : "Document d'entree en relation")
                /*
                    * Dans le cas où l'utilisateur choisit "J'utilise mon modèle", cela suppose
                    * que l'administrateur de l'établissement ait préalablement uploadé les
                    * documents
                */
                if (isInformationCardFromFirmModel)
                {
                    // Tester si les documents ont été bien uploadés
                    // on enregistre
                    if (!string.IsNullOrEmpty(customer.FirmInstitution.LegalInformationFile))
                    {
                        missionDoc.IsInformationCardFromModel = true;
                    }
                    else
                    {
                        /* 
                         * "Le document d'entrée en relation de votre établissement n'a pas été renseignée par votre administrateur"
                         *  NB : #4608 : ne pas afficher l'erreur si l'utilisateur a décidé de ne pas joindre le fichier
                          */

                        if (isAttachInformationCard)
                        {
                            missionDoc.IsInformationCardFromModel = false;
                            ViewBag.Error = ViewBag.Error + LanguageData.GetContent("doc_d_entree_en_relation_non_renseigné");
                        }
                    }
                }
                else
                {
                    missionDoc.IsInformationCardFromModel = false;
                }
                #endregion

                #region Traitement de la Présentation de la société
                /*
                    * Dans le cas où l'utilisateur choisit "J'utilise mon modèle", cela suppose
                    * que l'administrateur de l'établissement ait préalablement uploadé les
                    * documents
                */
                if (isPresentationFromFirmModel)
                {
                    // Tester si les documents ont été bien uploadés
                    // on enregistre
                    if (!string.IsNullOrEmpty(customer.FirmInstitution.PresentationFile))
                    {
                        missionDoc.IsPresentationFromModel = true;
                    }
                    else
                    {
                        /* 
                         * "La présentation de votre société n'a pas été renseignée par votre administrateur"
                         * NB : #4608 : ne pas afficher l'erreur si l'utilisateur a décidé de ne pas joindre le fichier
                          */

                        if (isAttachPresentation)
                        {
                            missionDoc.IsPresentationFromModel = false;
                            ViewBag.Error = ViewBag.Error + LanguageData.GetContent("presentation_etab_non_renseigné");
                        }
                    }
                }
                else
                {
                    missionDoc.IsPresentationFromModel = false;
                }
                #endregion

                #region Sauvegarde de MissionDocument
                // 2- update avec le statut InProgress
                if (ViewBag.Error == null)
                {
                    missionDoc.Status = RegulatoryDocumentModel.Status.InProgress.ToString();
                    missionDoc.DateUpdated = DateTime.Now;
                    missionDoc.AttachConventionRTO = isAttachConventionRTO;
                    missionDoc.AttachInformationCard = isAttachInformationCard;
                    missionDoc.AttachPresentation = isAttachPresentation;
                    missionDoc.IsConventionRTOFromYourModel = isConventionRTOFromFirmModel;
                    missionDoc.IsUpsideoModel = isUpsideoModel;

                    MissionDocumentBL.UpdateMissionDocument(missionDoc);

                    string documentLabel = (isMissionLetter) ? LanguageData.GetContent("de_la_lettre_de_mission") : LanguageData.GetContent("du_rapport_de_mission");
                    ViewBag.Ok = string.Format(LanguageData.GetContent("save_success"), documentLabel);
                }
                #endregion
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                Log.AppendException(ex);
            }

            //If there is message, show it
            this.SetMessage();
        }
        public ActionResult FromYourModel(RegulatoryDocumentModel _documentData, IEnumerable<HttpPostedFileBase> files)
        {
            UploadAndSaveManager(_documentData, files, false);

            string docType = (_documentData.IsMissionLetter) ? MissionDocumentBL.DocumentType.LM.ToString() : MissionDocumentBL.DocumentType.RM.ToString();
            
            var firm = SessionManager.GetFirmInstitutionSession();
            IList<DocumentCategory> lstDocumentCategory = new List<DocumentCategory>();
            if (firm != null)
            {
                lstDocumentCategory = DocumentCategoryBL.GetDocumentCategorysByFirmParent(firm.idFirmInstitution);
                ViewBag.LstDocumentCategory = lstDocumentCategory;
            }


            return RedirectToAction("FromYourModel", new { docType = docType });
            //return RenderView("FromYourModel", CustomerProspectBL.NoQuestionId, isMissionLetter); //Lettre de mission
        }
        public List<CustomerProspectOptionAttributeValue> GetAttributValueFromPostData(RegulatoryDocumentModel _dataModel, int idOption)
        {
            List<CustomerProspectOptionAttributeValue> retVal = new List<CustomerProspectOptionAttributeValue>();

            Option targetOption = _dataModel.Option.Where(o => o.idOption.Equals(idOption)).FirstOrDefault();

            if (targetOption.OptionAttribute != null)
            {
                foreach (var optAttr in targetOption.OptionAttribute)
                {
                    string idPrefix = string.Empty;
                    string dataType = optAttr.Datatype.ToLower();

                    if (dataType.Equals("string") || dataType.Equals("multiline")) idPrefix = "txt_{0}_{1}";
                    else if (dataType.Equals("int") || dataType.Equals("float")) idPrefix = "txt_{0}_{1}";
                    else if (dataType.Equals("datetime")) idPrefix = "dt_{0}_{1}";
                    else if (dataType.Equals("paymenttype")) idPrefix = "enum_{0}_{1}";

                    string ParamName = string.Format(idPrefix, optAttr.idOption, optAttr.idOptionAttribute);

                    if (!string.IsNullOrEmpty(Request.Params[ParamName]))
                    {
                        string strVal = Request.Params[ParamName];

                        CustomerProspectOptionAttributeValue newVal = new CustomerProspectOptionAttributeValue();
                        newVal.idOptionAttribute = optAttr.idOptionAttribute;
                        newVal.idCustomerProspect = _dataModel.TargetCustomerProspect.idCustomer;
                        newVal.Value = strVal;
                        retVal.Add(newVal);
                    }
                }
            }

            return retVal;
        }
        public List<CustomerProspectOptionValue> GetSelectedOptionsFromPostData(RegulatoryDocumentModel _dataModel, int idParent)
        {
            List<CustomerProspectOptionValue> retVal = new List<CustomerProspectOptionValue>();

            Option ParentOption = _dataModel.Option.Where(o => o.idOption.Equals(idParent)).FirstOrDefault();

            if (ParentOption != null)
            {
                var ChildOptions = _dataModel.Option.Where(o => o.idParent.HasValue && o.idParent.Value.Equals(ParentOption.idOption));
                foreach (var childOp in ChildOptions)
                {
                    bool isSelected = !ParentOption.SingleOption.HasValue;
                    string idPrefix = string.Empty;
                    if (ParentOption.SingleOption.HasValue)
                    {
                        if (ParentOption.SingleOption.Value) idPrefix = "rb_{0}_{1}";
                        else idPrefix = "chk_{0}_{1}";

                        string postDataName = string.Format(idPrefix, childOp.idParent.Value, childOp.idOption);
                        if (!string.IsNullOrEmpty(Request.Params[postDataName]) && Request.Params[postDataName].ToLower().Equals("c"))
                        {
                            isSelected = true;
                        }
                    }

                    if (isSelected)
                    {
                        CustomerProspectOptionValue newVal = new CustomerProspectOptionValue();
                        newVal.idCustomerProspect = _dataModel.TargetCustomerProspect.idCustomer;
                        newVal.idOption = childOp.idOption;
                        newVal.Option = childOp;
                        retVal.Add(newVal);

                        if (_dataModel.Option.Count(o => o.idParent.HasValue && o.idParent.Value.Equals(childOp.idOption)) > 0)
                        {
                            retVal.AddRange(GetSelectedOptionsFromPostData(_dataModel, childOp.idOption));
                        }
                    }
                }
            }

            return retVal;
        }
        public List<CustomerProspectOptionValue> GetSelectedOptions(RegulatoryDocumentModel _dataModel)
        {
            List<CustomerProspectOptionValue> retVal = new List<CustomerProspectOptionValue>();

            var ParentOptions = _dataModel.Option.Where(o => !o.idParent.HasValue);
            if (ParentOptions != null)
            {
                foreach (var parent in ParentOptions)
                {
                    var selectedChild = GetSelectedOptionsFromPostData(_dataModel, parent.idOption);
                    if (selectedChild.Count > 0)
                    {
                        CustomerProspectOptionValue newVal = new CustomerProspectOptionValue();
                        newVal.idCustomerProspect = _dataModel.TargetCustomerProspect.idCustomer;
                        newVal.idOption = parent.idOption;
                        newVal.Option = parent;
                        retVal.Add(newVal);
                        retVal.AddRange(selectedChild);
                    }
                }
            }

            return retVal;
        }
 public void UpdateData(RegulatoryDocumentModel _dataModel)
 {
     //Retrieve selected Options
     List<CustomerProspectOptionValue> SelectedOptions = GetSelectedOptions(_dataModel);
     //Retrieve Set Attribute Values
     foreach (var optionVal in SelectedOptions)
     {
         foreach (var data in GetAttributValueFromPostData(_dataModel, optionVal.idOption))
         {
             optionVal.CustomerProspectOptionAttributeValue.Add(data);
         }
     }
     //Send Data
     CustomerProspectOptionBL.UpdateCustomerProspectOptions(_dataModel.TargetCustomerProspect.idCustomer, SelectedOptions);
 }
        public List<OptionModel> DeriveDataForView(RegulatoryDocumentModel inputData)
        {
            List<OptionModel> retVal = new List<OptionModel>();

            foreach (Option opt in inputData.Option)
            {
                OptionModel optModel = new OptionModel(opt);
                var optValue = inputData.OptionValue.Where(ov => ov.idOption.Equals(optModel.Option.idOption));
                if (optValue != null)
                {
                    optModel.IsSelected = optValue.Count() > 0;
                }
                retVal.Add(optModel);
            }

            return retVal;
        }
        private RegulatoryDocumentModel AddParentOptionToOptionValue(int idOption, int idOptionParent, RegulatoryDocumentModel regulatoryDocumentModel)
        {
            List<CustomerProspectOptionValue> lstRMValues = regulatoryDocumentModel.OptionValue;

            //exist optionvalue from RM ?
            CustomerProspectOptionValue rmOptValue = lstRMValues.Where(ov => ov.idOption == idOption).FirstOrDefault();
            if (rmOptValue != null)
            {
                //Add optionParent if not exist
                CustomerProspectOptionValue rmOptParentValue = lstRMValues.Where(ov => ov.idOption == idOptionParent).FirstOrDefault();
                if (rmOptParentValue == null)
                {
                    rmOptParentValue = new CustomerProspectOptionValue()
                    {
                        idCustomerProspectOptionValue = 0, //??
                        idOption = idOptionParent,
                        idCustomerProspect = regulatoryDocumentModel.TargetCustomerProspect.idCustomer,
                        Value = string.Empty
                    };
                    lstRMValues.Add(rmOptParentValue);
                }
            }

            return regulatoryDocumentModel;
        }
        public RegulatoryDocumentModel GetViewDataModel(int idParentOption, Guid idTargetCustomer, bool isMissionLetter)
        {
            RegulatoryDocumentModel regulatoryDocumentModel = new RegulatoryDocumentModel();
            regulatoryDocumentModel.IsMissionLetter = isMissionLetter;
            regulatoryDocumentModel.idOptionParent = idParentOption;
            regulatoryDocumentModel.TargetCustomerProspect = CustomerProspectBL.GetCustomerProspectById(idTargetCustomer);

            //1- Get latest mission document for the customer or create if no doc
            MissionDocument missionDoc = MissionDocumentBL.GetLatestMissionDocumentByIdCustomer(idTargetCustomer, isMissionLetter); //Mission letter

            //2- If null, create one
            //If current user is END-USER, don't create new document
            var currentUser = SessionManager.GetUserSession();

            if (!currentUser.IsEndUser())
            {
                if (missionDoc == null)
                {
                    missionDoc = this.CreateMissionDocument(regulatoryDocumentModel, isMissionLetter);
                    //update customer status
                    if (isMissionLetter)
                        regulatoryDocumentModel.TargetCustomerProspect.LetterStatus = RegulatoryDocumentModel.Status.Created.ToString();
                    else
                        regulatoryDocumentModel.TargetCustomerProspect.MissionStatus = RegulatoryDocumentModel.Status.Created.ToString();
                    CustomerProspectBL.Update(regulatoryDocumentModel.TargetCustomerProspect);
                }
                else if (missionDoc.Status == RegulatoryDocumentModel.Status.Canceled.ToString()
                         || missionDoc.Status == RegulatoryDocumentModel.Status.Completed.ToString())
                {
                    //3- Check if canceled or completed : create a new document in progress
                    //missionDoc = this.CreateMissionDocument(regulatoryDocumentModel, isMissionLetter, RegulatoryDocumentModel.Status.InProgress);

                    //Update : #4535 / #4536 : always create an initial mission document => status = Created
                    missionDoc = this.CreateMissionDocument(regulatoryDocumentModel, isMissionLetter);
                    //update customer 
                    if (isMissionLetter)
                        regulatoryDocumentModel.TargetCustomerProspect.LetterStatus = RegulatoryDocumentModel.Status.Created.ToString();
                    else
                        regulatoryDocumentModel.TargetCustomerProspect.MissionStatus = RegulatoryDocumentModel.Status.Created.ToString();
                    CustomerProspectBL.Update(regulatoryDocumentModel.TargetCustomerProspect);
                }
            }
            else
            {
                if (missionDoc == null)
                {
                    missionDoc = new MissionDocument();
                }
            }

            regulatoryDocumentModel.MissionDocument = missionDoc;

            //4- Retrieve Options and Attributes data
            var option = OptionBL.GetOptionsByIdParent(idParentOption);

            // if PP
            bool isPP = (regulatoryDocumentModel.TargetCustomerProspect.IsCorporation.HasValue) ? ((regulatoryDocumentModel.TargetCustomerProspect.IsCorporation.Value) ? false : true) : false;
            if (isPP)
            {
                //Remove some options for PM
                option.RemoveAll(o => o.NameKey.Contains("Client_Letter_PM_"));
            }
            else
            {
                int indexFirstPP = 0; // sert de repère pour l'index d'insertion de List PL
                var optionRepere = option.Where(o => o.NameKey.CompareTo("Client_Letter_029") == 0).FirstOrDefault();
                if (optionRepere != null)
                {
                    indexFirstPP = option.IndexOf(optionRepere);
                }

                var lstOptsPM = option.Where(o => o.NameKey.Contains("Client_Letter_PM_")).ToList(); // à ajouter dans un rang(position) précis un peu plus tard

                //Remove some options for PP
                option.RemoveAll(o => o.idParent == 151);
                option.RemoveAll(o => o.NameKey.CompareTo("Client_Letter_029") == 0);
                option.RemoveAll(o => o.NameKey.Contains("Client_Letter_PM_")); // à supprimer car ne respecte pas le rang (position des éléments)

                option.InsertRange(indexFirstPP, lstOptsPM);
            }

            if (option != null)
            {
                regulatoryDocumentModel.Option = option.ToList();
            }

            //5- Update Data if post ?
            if (Request.RequestType.ToLower() != "get")
            {
                UpdateData(regulatoryDocumentModel);
            }

            //6- Retrieve Option Value and OptionAttribute Value
            regulatoryDocumentModel.OptionValue = CustomerProspectOptionBL.GetOptionValueListWithIdCustomerProspectAndIdParentOption(idTargetCustomer, idParentOption);

            //For new RM : recall Remuneration value from LM
            if (!isMissionLetter && regulatoryDocumentModel.MissionDocument.Status == RegulatoryDocumentModel.Status.Created.ToString())
            {
                regulatoryDocumentModel.LM_RemunerationOptionValues = CustomerProspectOptionBL.GetOptionValueListWithIdCustomerProspectAndIdOptions(idTargetCustomer, new List<Int32>() { 131, 133 }); //131 : remuneration; 133 : honoraire

                regulatoryDocumentModel = GetRemunerationDefaultValueFromLMtoRM(regulatoryDocumentModel);


            }

            //7- Signature log
            regulatoryDocumentModel.SignatureInformation = this.BuildSignatureLog(regulatoryDocumentModel.MissionDocument);

            //8- Map data to View Model
            regulatoryDocumentModel.OptionData = DeriveDataForView(regulatoryDocumentModel);

            //9- Retrieve CustomEnum
            int idCurrentLanguage = SessionManager.GetCurrentLanguage().idLanguageType;
            IDictionary<int, List<DropDownEnumModel>> dicoDropDownEnumModel = CustomEnumBL.GetCustomEnums(idCurrentLanguage);

            regulatoryDocumentModel.EnumPaymentValue = dicoDropDownEnumModel[CustomEnumBL.PaymentType];

            //10- Check credits
            regulatoryDocumentModel.InsufficientCreditMessage = this.CheckInsufficientCredits(regulatoryDocumentModel);

            //11- Signature controller
            regulatoryDocumentModel.SignatureController = SignatureDocumentBL.GetSignatureControllerName(missionDoc.Status, missionDoc.idDTPUserAccess);

            return regulatoryDocumentModel;
        }
        private RegulatoryDocumentModel GetOptionAttributeValueFromLMtoRM(int idOptionLM, int idOptionAttributeLM, int idOptionRM, int idOptionAttributeRM, RegulatoryDocumentModel regulatoryDocumentModel)
        {
            List<CustomerProspectOptionValue> lstRMValues = regulatoryDocumentModel.OptionValue;
            List<CustomerProspectOptionValue> lstLMValues = regulatoryDocumentModel.LM_RemunerationOptionValues;

            //Get from RM
            string RM_AttributeValue = CustomerProspectOptionBL.GetAttributeValue(idOptionRM, idOptionAttributeRM, lstRMValues);

            if (!string.IsNullOrEmpty(RM_AttributeValue))
            {
                //Remove old option and attribute values
                CustomerProspectOptionValue rmOptValue = lstRMValues.Where(ov => ov.idOption == idOptionRM).FirstOrDefault();

                IList<CustomerProspectOptionAttributeValue> lstOptionAttributeValues = new List<CustomerProspectOptionAttributeValue>(rmOptValue.CustomerProspectOptionAttributeValue);
                foreach (var item in lstOptionAttributeValues)
                {
                    var optionAttrValueToBeDel = rmOptValue.CustomerProspectOptionAttributeValue.Where(oa => oa.idCustomerProspectOptionAttributeValue == item.idCustomerProspectOptionAttributeValue).FirstOrDefault();
                    rmOptValue.CustomerProspectOptionAttributeValue.Remove(optionAttrValueToBeDel);
                }

                lstRMValues.Remove(rmOptValue);
            }

            //Get from LM
            string LM_AttributeValue = CustomerProspectOptionBL.GetAttributeValue(idOptionLM, idOptionAttributeLM, lstLMValues);

            if (!string.IsNullOrEmpty(LM_AttributeValue))
            {
                //exist optionvalue from RM ?
                CustomerProspectOptionValue rmOptValue = lstRMValues.Where(ov => ov.idOption == idOptionRM).FirstOrDefault();
                if (rmOptValue == null)
                {
                    rmOptValue = new CustomerProspectOptionValue()
                    {
                        idCustomerProspectOptionValue = 0, //??
                        idOption = idOptionRM,
                        idCustomerProspect = regulatoryDocumentModel.TargetCustomerProspect.idCustomer,
                        Value = string.Empty
                    };
                    lstRMValues.Add(rmOptValue);
                }

                CustomerProspectOptionAttributeValue newOptAttributeValue = new CustomerProspectOptionAttributeValue()
                {
                    idCustomerProspectOptionAttributeValue = 0, //??
                    idOptionAttribute = idOptionAttributeRM,
                    idCustomerProspect = regulatoryDocumentModel.TargetCustomerProspect.idCustomer,
                    Value = LM_AttributeValue,
                };

                //Add optionattribute to optionvalue
                rmOptValue.CustomerProspectOptionAttributeValue.Add(newOptAttributeValue);

            }

            return regulatoryDocumentModel;
        }
        private RegulatoryDocumentModel GetRemunerationDefaultValueFromLMtoRM(RegulatoryDocumentModel regulatoryDocumentModel)
        {
            try
            {
                List<CustomerProspectOptionValue> lstRMValues = regulatoryDocumentModel.OptionValue;
                List<CustomerProspectOptionValue> lstLMValues = regulatoryDocumentModel.LM_RemunerationOptionValues;

                // LM idOption_idOptionAttribute
                List<int[]> lstLMOptionAttributes = new List<int[]>() 
                {
                    //
                    new int[] {131, 105},
                    new int[] {131, 106},
                    new int[] {181, 115},
                    new int[] {181, 116},
                    new int[] {181, 117},
                    new int[] {182, 118},
                    new int[] {183, 119},
                    new int[] {133, 120},
                    new int[] {133, 121},
                    new int[] {1239, 765},
                };

                // RM idOption_idOptionAttribute
                List<int[]> lstRMOptionAttributes = new List<int[]>() 
                { 
                    new int[] {1234, 756},
                    new int[] {1234, 757},
                    new int[] {1236, 760},
                    new int[] {1236, 761},
                    new int[] {1236, 762},
                    new int[] {1237, 763},
                    new int[] {1238, 764},
                    new int[] {1235, 758},
                    new int[] {1235, 759},
                    new int[] {1240, 766},
                };

                // RM idOptionParent_idOption
                List<int[]> lstRMOptionParents = new List<int[]>() 
                { 
                    new int[] {1235, 1236},
                    new int[] {1235, 1237},
                    new int[] {1235, 1238},
                    new int[] {1235, 1240},
                };

                //Get option attribute values from LM
                for (int i = 0; i < lstRMOptionAttributes.Count; i++)
                {
                    int[] optionIdLM = lstLMOptionAttributes[i];
                    int[] optionIdRM = lstRMOptionAttributes[i];

                    regulatoryDocumentModel = GetOptionAttributeValueFromLMtoRM(optionIdLM[0], optionIdLM[1], optionIdRM[0], optionIdRM[1], regulatoryDocumentModel);
                }

                //Add parent options
                for (int i = 0; i < lstRMOptionParents.Count; i++)
                {
                    int[] optionParentIdOptionId = lstRMOptionParents[i];
                    int idOptionParent = optionParentIdOptionId[0];
                    int idOption = optionParentIdOptionId[1];

                    regulatoryDocumentModel = AddParentOptionToOptionValue(idOption, idOptionParent, regulatoryDocumentModel);

                }

            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
            }

            return regulatoryDocumentModel;
        }
        private string CheckInsufficientCredits(RegulatoryDocumentModel pRegulatoryDocumentModel)
        {
            CustomerProspect customer = null;
            string message = string.Empty;

            var currentUser = SessionManager.GetUserSession();

            if (currentUser.IsEndUser())
            {
                customer = SessionManager.GetCustomerProspectSession();
            }
            else
            {
                customer = pRegulatoryDocumentModel.TargetCustomerProspect;
            }

            if (customer != null)
            {
                if (!CreditOperationBL.HasFirmInstitutionSufficientCredit(customer.FirmInstitution.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_DOCUMENT_MISSION.ToString())) //OR  :MISE_AU_COFFRE_MANUELLE_DOCUMENT_MISSION
                {
                    message = LanguageData.GetContent("sign_credit_error");
                }
            }

            return message;

        }
        private MissionDocument CreateMissionDocument(RegulatoryDocumentModel regulatoryDocumentModel, bool isLetter, RegulatoryDocumentModel.Status docStatus = RegulatoryDocumentModel.Status.Created)
        {
            MissionDocument missionDoc = new MissionDocument()
            {
                idMissionDocument = GuidHelper.GenerateGuid(),
                idCustomerProspect = regulatoryDocumentModel.TargetCustomerProspect.idCustomer,
                Status = docStatus.ToString(),
                DateCreated = DateTime.Now,
                DateUpdated = DateTime.Now,
                IsLetter = isLetter,
                AttachInformationCard = true,
                IsInformationCardFromModel = true,
                AttachPresentation = true,
                IsPresentationFromModel = true
            };

            MissionDocumentBL.InsertMissionDocument(missionDoc);

            return missionDoc;
        }
        private DER CreateDer(DerModel derModel, RegulatoryDocumentModel.Status docStatus = RegulatoryDocumentModel.Status.Created)
        {
            DER der = new DER()
            {
                idDer = GuidHelper.GenerateGuid(),
                idCustomerProspect = derModel.TargetCustomerProspect.idCustomer,
                Status = docStatus.ToString(),
                DateCreated = DateTime.Now,
                DateUpdated = DateTime.Now,
                IsDerFromModel = true,
                AttachPresentation = true,
                IsPresentationFromModel = true
            };

            DerBL.InsertDER(der);

            return der;
        }