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;
            }
        }
        public ActionResult EnvoyerConventionAuClient(string id)
        {
            string error = string.Empty;
            bool isCustomer = true;

            try
            {
                // Id Customer = id in parameter                
                if (string.IsNullOrEmpty(id))
                {
                    error = _languageData.GetContent("client_identité_non_reconnue");
                }
                else
                {
                    using (var context = new UpsilabEntities())
                    {
                        Guid idCustomer = Guid.Parse(id);
                        var customer = (from cust in context.CustomerProspect.Include("ConventionRTO").Include("ConventionRTO.User").Include("User").Include("User1").Include("FirmInstitution")
                                                                        where cust.idCustomer == idCustomer
                                                                        select cust).FirstOrDefault();

                        if (customer == null)
                        {
                            error = _languageData.GetContent("client_identité_non_reconnue");
                        }
                        else
                        {
                            isCustomer = customer.IsCustomer;

                            //TODO : Create pdf to sign
                            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);

                            if (!System.IO.File.Exists(filePath))
                            {
                                EngagementPdfGenerationBL.GeneratePDF(customer, customer.FirmInstitution, filePath, false);
                            }

                            if (System.IO.File.Exists(filePath))
                            {
                               // SignatureDocumentBL.SendConventionMailToClient(customer, true);

                                //Update date send email (invite client to sign CRTO)
                                ConventionRTO convention = customer.ConventionRTO;

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

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

                                    customer.idConventionRTO = convention.idConventionRTO;
                                }

                                //Dates in DB are separeted by ";"
                                var lstDates = new List<string>();
                                if (!string.IsNullOrEmpty(convention.DatesSendMailToCustomer))
                                {
                                    lstDates = convention.DatesSendMailToCustomer.Split(new char[] { ';' }).ToList();
                                }

                                lstDates.Insert(0, DateTime.Now.ToString("dd/MM/yyyy"));
                                string remindDates = string.Join(";", lstDates.ToArray());

                                convention.DatesSendMailToCustomer = remindDates;

                                //Save
                                context.SaveChanges();
                            }
                            else
                            {
                                error = _languageData.GetContent("fic_convetion_rto_n_existe_pas");
                            }
                        }
                    }//End using

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

            //TODO : popup ok
            string message = (!string.IsNullOrEmpty(error)) ? error : _languageData.GetContent("email_invitant_a_signer_convention_rto_envoyé");

            SessionManager.Set<string>("RTO_RETOUR_ENVOI_CONVETION", message); //Clear session in engagement - index

            return RedirectToAction("Index", "ConventionRTO", new { _isCustomer = isCustomer });
        }
        public bool EnvoyerConventionAuClient(Guid id)
        {
            using (var context = new UpsilabEntities())
            {
                Guid idCustomer = id;
                var customer = (from cust in context.CustomerProspect.Include("ConventionRTO").Include("ConventionRTO.User").Include("User").Include("User1").Include("FirmInstitution")
                                                                where cust.idCustomer == idCustomer
                                                                select cust).FirstOrDefault();

                if (customer == null)
                {
                    return false;
                }
                else
                {
                    string docType = ElectronicSafeDocumentBL.DocumentType.CRTO.ToString();
                    string destFullPath = ElectronicSafeDocumentBL.BuildClientUploadDocumentPath(docType, customer);
                    string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType, customer.idCustomer, false);
                    string filePath = System.IO.Path.Combine(destFullPath, filename);

                    if (!System.IO.File.Exists(filePath))
                    {
                        EngagementPdfGenerationBL.GeneratePDF(customer, customer.FirmInstitution, filePath, false);
                    }

                    if (System.IO.File.Exists(filePath))
                    {
                        SignatureDocumentBL.SendCRTOMailToClient(customer, true);

                        //Update date send email (invite client to sign CRTO)
                        ConventionRTO convention = customer.ConventionRTO;

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

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

                            customer.idConventionRTO = convention.idConventionRTO;
                        }

                        //Dates in DB are separeted by ";"
                        var lstDates = new List<string>();
                        if (!string.IsNullOrEmpty(convention.DatesSendMailToCustomer))
                        {
                            lstDates = convention.DatesSendMailToCustomer.Split(new char[] { ';' }).ToList();
                        }

                        lstDates.Insert(0, DateTime.Now.ToString("dd/MM/yyyy"));
                        string remindDates = string.Join(";", lstDates.ToArray());

                        convention.DatesSendMailToCustomer = remindDates;

                        //Save
                        context.SaveChanges();

                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
        }
        //---------------------------POPULATE RELANCE DATE----------------------------------
        public string PopulateDateEC()
        {
            string error = string.Empty;

            try
            {
                using (var context = new UpsilabEntities())
                {
                    Guid idUser;

                    //Get IDCustomer from EmailLog
                    var lstEmailLogEC = (from el in context.EmailLog
                                         where el.EmailType == "SendAgreementMailToClient"
                                         select el).ToList();

                    foreach (var eLog in lstEmailLogEC)
                    {
                        idUser = eLog.IDRecipient.Value;

                        CustomerProspect customer = (from cust in context.CustomerProspect.Include("ConventionRTO").Include("User").Include("User1").Include("FirmInstitution")
                                                                        where cust.User.idUser == idUser
                                                                        select cust).FirstOrDefault();

                        if (customer == null)
                        {
                            error += LanguageData.GetContent("client_identité_non_reconnue");
                        }
                        else
                        {
                            //Update date send email (invite client to sign EC)
                            var convention = customer.ConventionRTO;

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

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

                                customer.idConventionRTO = convention.idConventionRTO;
                            }

                            if (string.IsNullOrEmpty(convention.DatesSendMailToCustomer))
                            {
                                convention.DatesSendMailToCustomer = eLog.DateCreated.ToString("dd/MM/yyyy");
                            }

                            //Save
                            context.SaveChanges();
                        }
                    }
                }//End using

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


            if (!string.IsNullOrEmpty(error))
            {
                return error;
            }
            else
            {
                return "OK";
            }

        }
        public ActionResult DocFileUpload(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;
            bool isCustomer = true;

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    var customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                    isCustomer = customer.IsCustomer;

                    if (uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), customer);
                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string sFilename = ElectronicSafeDocumentBL.BuildDocumentName(objDoctype.DocumentNamePrefix, customer.idCustomer, uploadFile.FileName);

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

                        // 2- Upload file to DICTAO server
                        var 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_MANUELLE_ENGAGEMENT_CONFIDENTIALITE"
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            using (var db = new UpsilabEntities())
                            {
                                //var firmInstitution = SessionManager.GetFirmInstitutionSession();
                                //Guid idFirmInstitution = (firmInstitution != null) ? firmInstitution.idFirmInstitution : customer.idFirmInstitution;

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

                                // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                                ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), objESDoc.DocumentLabel, documentPath, customer.idCustomer, dictaoId, clientD3S);

                                // 5- Sauvegarde dans la base (table ConfidentialityAgreement)
                                string dateSignatureConseiller = Request.Form["DateSignatureConseiller"];
                                string dateSignatureClient = Request.Form["DateSignatureClient"];

                                var dDateSignatureConseiller = new DateTime();
                                var dDateSignatureClient = new DateTime();

                                if (!string.IsNullOrEmpty(dateSignatureConseiller)) DateTime.TryParse(dateSignatureConseiller, out dDateSignatureConseiller);
                                if (!string.IsNullOrEmpty(dateSignatureClient)) DateTime.TryParse(dateSignatureClient, out dDateSignatureClient);

                                var objConvRto = new ConventionRTO()
                                {
                                    idConventionRTO = GuidHelper.GenerateGuid(),
                                    Status = Business.Report.ReportBL.Status.Completed.ToString(),
                                    DateCreated = DateTime.Now,
                                    //DateUpdated = ,
                                    idDictao = dictaoId,
                                    SignedByCustomer = true,
                                    DateSignatureCustomer = dDateSignatureClient,
                                    SignedByAdviser = true,
                                    DateAdviserSignature = dDateSignatureConseiller,
                                    Archived = true,
                                };


                                db.ConventionRTO.Attach(objConvRto);
                                db.ObjectStateManager.ChangeObjectState(objConvRto, System.Data.EntityState.Added);
                                db.SaveChanges();

                                customer.idConventionRTO = objConvRto.idConventionRTO;
                                CustomerProspectBL.Update(customer);
                            }


                        }
                        else
                        {
                            error = LanguageData.GetContent("conv_rto_doc_impossible_a_envoyer_au_cfe");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.AppendException(ex);
                error = ex.Message;
            }

            //----
            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, error); // Remove session value in "index"
            }

            return RedirectToAction("Index", "ConventionRTO", new { _isCustomer = isCustomer });
            //----            
        }