public PartialViewResult ShowPopupAddDocRM(string CustomerProspectId)
        {
            Guid gCustPid = Guid.Empty;

            if (Guid.TryParse(CustomerProspectId, out gCustPid))
            {
                gCustPid = new Guid(CustomerProspectId);
            }

            DocumentType objDocType = DocumentTypeBL.GetDocumentTypeByCode(ElectronicSafeDocumentBL.DocumentType.RM.ToString());

            int iIdTypeDoc = 0;
            if (objDocType != null)
            {
                iIdTypeDoc = objDocType.idDocumentType;
            }

            CustomerProspect _customer = CustomerProspectBL.GetCustomerProspectByIdUser(gCustPid);
            ElectronicSafeDocument objESD = new ElectronicSafeDocument()
            {
                idCustomer = gCustPid,
                idDocumentType = iIdTypeDoc,
                CustomerProspect = _customer,
                DateCreated = DateTime.Now
            }; // TODO idDocumentType = ??

            return PartialView("RapportDeMission_Popup", objESD);
        }
        public ActionResult DocFileUploadRM(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {

            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;

            if (objESDoc.idCustomer.HasValue)
            {
                CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                MissionDocument missionRapport = MissionDocumentBL.GetLatestMissionDocumentByIdCustomer(objESDoc.idCustomer.Value, false);

                DateTime selectedDate = Convert.ToDateTime(Request.Params["datepicker5"].ToString());
                objESDoc.DocumentLabel = "Rapport_écrit_de_mission_" + customer.User.UserFirstName + "_" + customer.User.UserName + "_" + selectedDate.ToShortDateString();
                if (uploadFile.ContentLength > 0)
                {
                    string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.RM.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
                    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_DIVERS_DOCUMENTS"
                    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_MANUELLE_DOCUMENT_MISSION.ToString(), customer.idUserCreated, customer.idCustomer);

                        //4- Update date/status de la lettre de mission
                        customer.DateLastUpdateMission = selectedDate;
                        customer.MissionStatus = RegulatoryDocumentModel.Status.Completed.ToString();
                        customer.IsMissionOriginal = false;
                        CustomerProspectBL.Update(customer);

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

                        //6-  Update missionDocument table
                        missionRapport.Status = RegulatoryDocumentModel.Status.Completed.ToString();
                        missionRapport.Archived = true;
                        missionRapport.IsOriginal = false;
                        missionRapport.idDictao = dictaoId;
                        missionRapport.DateUpdated = DateTime.Now;
                        MissionDocumentBL.UpdateMissionDocument(missionRapport);
                    }
                    else
                    {
                        throw new Exception(LanguageData.GetContent("doc_non_envoyé_veuillez_reessayer"));
                    }
                }
            }

            return RedirectToAction("Index", "Client");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userAdviser"></param>
        /// <param name="docType"></param>
        /// <returns></returns>
        private Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument> GetAdviserDocuments(Upsilab.Data.Model.User userAdviser, DocumentType docType, int idDocumentCategory = 0)
        {
            var tuple = new Tuple<IEnumerable<ElectronicSafeDocument>, ElectronicSafeDocument>(new List<ElectronicSafeDocument>(), new ElectronicSafeDocument() { DocumentType = docType });
            var LanguageData = PageLanguageHelper.GetLanguageContent("User", "CoffreFortController");

            try
            {
                IList<ElectronicSafeDocument> lstElectronicSafeDocs = ElectronicSafeDocumentBL.GetDocumentsByCustomerUserCreatedId(userAdviser.idUser, docType.DocumentNamePrefix);
                ElectronicSafeDocument newElecSafeDoc = new ElectronicSafeDocument() { DocumentType = docType };

                // Si filtrage par rapport à DocumentCategory
                if (docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.DOC.ToString() && idDocumentCategory != 0)
                {
                    lstElectronicSafeDocs = lstElectronicSafeDocs.Where(e => e.idDocumentCategory == idDocumentCategory).ToList();
                    newElecSafeDoc.idDocumentCategory = idDocumentCategory;
                }

                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()
                    || docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.FIL.ToString()
                    || docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.BS.ToString())
                {
                    if (!CreditOperationBL.HasFirmInstitutionSufficientCredit(SessionManager.GetFirmInstitutionSession().idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS.ToString())) //TODO : BS and FIL
                    {
                        ViewBag.CanUploadDoc = false;
                        ViewBag.ErrorBeforeUpload = LanguageData.GetContent("CoffreFort_envoi_doc_impossible");
                    }
                }
                return tuple;
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return tuple;
        }
        public ActionResult UploadToCoffre(ElectronicSafeDocument electronicSafeDocument, HttpPostedFileBase uploadFile)
        {
            DocumentType docType = DocumentTypeBL.GetDocumentTypeById(electronicSafeDocument.idDocumentType);
            string error = string.Empty;
            Guid idCustomerOrUser = Guid.Empty;
            Upsilab.Data.Model.User currentUser = SessionManager.GetUserSession();
            var LanguageData = PageLanguageHelper.GetLanguageContent("User", "CoffreFortController");
            int? idDocCateg = null;

            try
            {
                if (electronicSafeDocument.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(electronicSafeDocument.idCustomer.Value);
                    if (customer == null && currentUser.IsEndUser())
                    {
                        customer = SessionManager.GetCustomerProspectSession();
                    }

                    idCustomerOrUser = (customer == null) ? currentUser.idUser : customer.idCustomer;

                    if (uploadFile.ContentLength > 0 )
                    {
                        var ext = Path.GetExtension(uploadFile.FileName);
                        if (ext.ToLower() != ".pdf")
                        {
                            error = "Seulement le fichier pdf est valide.";
                            throw new Exception(error);
                            return RedirectToAction("Liste", new { documentTypeCode = docType.DocumentNamePrefix });
                        }

                        if (uploadFile.ContentLength > 5000000)
                        {
                            error = "La taille maximale autorisée pour les fichiers est de 5 MO.";
                            throw new Exception(error);
                            return RedirectToAction("Liste", new { documentTypeCode = docType.DocumentNamePrefix });
                        }

                        string documentPath = string.Empty;
                        if (customer != null)
                        {
                            documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.DocumentNamePrefix, customer);
                        }
                        else
                        {
                            documentPath = ElectronicSafeDocumentBL.BuildUserDocumentPath(docType.DocumentNamePrefix, currentUser); //TODO : to test
                        }

                        string documentFullPath = System.IO.Path.Combine(ConfigurationManager.CoffreFortRootPath, documentPath);
                        string filename = ElectronicSafeDocumentBL.BuildDocumentName(docType.DocumentNamePrefix, idCustomerOrUser, uploadFile.FileName);

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

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

                        // 3- Gestion Crédit : soustraire des points au creditCount de la firme pour avoir fait une operation ayant le creditCode "MISE_AU_COFFRE_DIVERS_DOCUMENTS"
                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            CreditOperationBL.OperationType creditOperationType;

                            switch (docType.DocumentNamePrefix)
                            {
                                case "BS":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break; //TODO
                                case "FIL":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break; //TODO
                                case "DOC":
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break;
                                default:
                                    creditOperationType = CreditOperationBL.OperationType.MISE_AU_COFFRE_DIVERS_DOCUMENTS; break;
                            }

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

                            string sIdDocumentCategory = Request.Params["idDocumentCategory"]; // TODO on n'a pas pu recupérer immediatement avec electronicSafeDocument.idDocumentCategory donc j'ai fait comme ça
                            int iIdDocumentCategory = 0;
                            if (!string.IsNullOrEmpty(sIdDocumentCategory))
                            {
                                Int32.TryParse(sIdDocumentCategory, out iIdDocumentCategory);
                            }

                            if (iIdDocumentCategory != 0)
                            {
                                idDocCateg = iIdDocumentCategory;
                            }

                            // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                            ElectronicSafeDocumentBL.SaveDocumentToDB(filename, docType.DocumentNamePrefix, electronicSafeDocument.DocumentLabel, documentPath, idCustomerOrUser, dictaoId, clientD3S, (customer != null) ? true : false, idDocCateg);

                            // 5- Update date du DER
                            if (docType.DocumentNamePrefix == ElectronicSafeDocumentBL.DocumentType.FIL.ToString())
                            {
                                DateTime selectedDate = DateTime.Now;
                                DateTime.TryParse(Request.Params["documentDate"].ToString(), out selectedDate);

                                if (selectedDate == DateTime.MinValue)
                                {
                                    selectedDate = DateTime.Now;
                                }

                                customer.DateLastUpdateDer = selectedDate;
                                customer.DerStatus = Upsilab.Business.SignatureDocument.DocumentBL.Status.Completed.ToString();
                                customer.IsDerOriginal = false;
                                CustomerProspectBL.Update(customer);
                            }

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

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

            // Redirect to "liste"
            object rootValues = new { documentTypeCode = docType.DocumentNamePrefix };

            if (idDocCateg != 0)
            {
                rootValues = new { documentTypeCode = docType.DocumentNamePrefix, idDocumentCategory = idDocCateg };
            }

            return RedirectToAction("Liste", rootValues);
        }
        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 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;
        }
        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 });
            //----            
        }
        /// <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 ActionResult DocFileUploadPM(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);
                    DateTime selectedDate = Convert.ToDateTime(Request.Params["datepicker5"].ToString());
                    objESDoc.DocumentLabel = "Receuil_" + customer.User.UserFirstName + "_" + customer.User.UserName + "_" + selectedDate.ToShortDateString();
                    if (uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.RC.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
                        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_RECUEIL"
                        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_RECUEIL.ToString(), customer.idUserCreated, customer.idCustomer);

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

                            // 5- Sauvegarde dans la base (table ConfidentialityAgreement)
                            Guid idReport = Guid.Empty;

                            SessionManager.Get<Guid>(ReportBL.IdReportSessionKey, out idReport);
                            Report objCurrentReport = ReportBL.GetReportById(idReport);
                            objCurrentReport.Status = ReportBL.Status.Completed.ToString();
                            objCurrentReport.IsOriginal = false;
                            objCurrentReport.Profile = Request.Params["cbProfil"].ToString();
                            objCurrentReport.DateUpdated = DateTime.Now;
                            objCurrentReport.idDictao = dictaoId;

                            ReportBL.UpdateReport(objCurrentReport);

                            // 6- Sauvegarde dans CustomerProspect
                            customer.DateUpdatedLast = selectedDate;
                            customer.DateUpdatedNext = customer.DateUpdatedLast.Value.AddYears(1);
                            customer.RiskProfile = Request.Params["cbProfil"].ToString();
                            customer.CurrentReportStatus = ReportBL.Status.Completed.ToString();
                            customer.IsReportOriginal = false;
                            customer.HasCompletedReport = true;
                            if (customer.NbElectronicSafeDocument.HasValue)
                                customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                            else
                                customer.NbElectronicSafeDocument = 1;
                            CustomerProspectBL.Update(customer);
                        }
                        else
                        {
                            error = LanguageData.GetContent("doc_non_envoye_au_coffre");
                            Business.Log.Log.AppendException(new Exception(error));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Business.Log.Log.AppendException(ex);
            }

            if (!string.IsNullOrEmpty(error))
            {
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, error); // Remove session value in "liste"
            }
            else
                SessionManager.Set<string>(ERROR_UPLOAD_SESSION, "OK");
            return RedirectToAction("SentToCoffreFort");

            // ViewBag.Error = error;
            //  return RedirectToAction("TitulairePM");

        }
        public PartialViewResult ShowPopupAddDoc(string CustomerProspectId)
        {
            Guid gCustPid = Guid.Empty;

            if (Guid.TryParse(CustomerProspectId, out gCustPid))
            {
                gCustPid = new Guid(CustomerProspectId);
            }

            DocumentType docType = DocumentTypeBL.GetDocumentTypeByCode(ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());

            var _customer = CustomerProspectBL.GetCustomerProspectById(gCustPid);
            var objESD = new ElectronicSafeDocument() { idCustomer = gCustPid, idDocumentType = docType.idDocumentType, CustomerProspect = _customer };

            return PartialView("Convention_AddDoc_Popup", objESD);
        }
        public ActionResult DocFileUpload(ElectronicSafeDocument objESDoc, HttpPostedFileBase uploadFile)
        {
            DocumentType objDoctype = DocumentTypeBL.GetDocumentTypeById(objESDoc.idDocumentType);
            string error = string.Empty;
            bool isCustomer = this.IsClient;
            bool isPasseport = false;

            if (Upsilab.Business.Utility.SessionManager.Exists(ISPASSEPORT))
            {
                Upsilab.Business.Utility.SessionManager.Get<bool>(ISPASSEPORT, out isPasseport);
            }

            try
            {
                if (objESDoc.idCustomer.HasValue)
                {
                    CustomerProspect customer = CustomerProspectBL.GetCustomerProspectById(objESDoc.idCustomer.Value);

                    if (uploadFile!=null && uploadFile.ContentLength > 0)
                    {
                        string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(objDoctype.DocumentNamePrefix, 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
                        D3SClient clientD3S = new D3SClient();
                        string dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(documentFullPath, sFilename, clientD3S);

                        // 3- Mise à jour de customerProspect
                        string dateExpiration = Request.Params["DateExpiration"];
                        string dateEmission = string.Empty;
                        if (!isPasseport)
                            dateEmission = Request.Params["DateEmission"];

                        DateTime dDateExpiration = new DateTime();
                        if (!string.IsNullOrEmpty(dateExpiration))
                        {
                            DateTime.TryParse(dateExpiration, out dDateExpiration);
                        }

                        DateTime dDateEmission = new DateTime();
                        if (!string.IsNullOrEmpty(dateEmission))
                        {
                            DateTime.TryParse(dateEmission, out dDateEmission);
                        }

                        if (isPasseport)
                        {
                            customer.PasseportFileName = sFilename;

                            if (dDateExpiration != null)
                            {
                                customer.PasseportDateExpired = dDateExpiration;
                            }

                            //if (dDateEmission != null)
                            //{
                            //    customer.PasseportEmissionDate = dDateEmission;
                            //}
                        }
                        else
                        {
                            customer.CNIFileName = sFilename;
                            if (dDateExpiration != null)
                            {
                                customer.CNIDateExpired = dDateExpiration;
                            }

                            if (dDateEmission != null && dDateEmission != DateTime.MinValue)
                            {
                                customer.CNIEmissionDate = dDateEmission;
                            }
                        }
                        CustomerProspectBL.Update(customer);

                        // 4- Sauvegarde dans la base (table ElectronicSafeDocument)
                        string docLabel = isPasseport ? "Passeport" : "CNI"; //objESDoc.DocumentLabel
                        ElectronicSafeDocumentBL.SaveDocumentToDB(sFilename, objDoctype.DocumentNamePrefix, docLabel, documentPath, customer.idCustomer, dictaoId, clientD3S);
                    }
                    else // changement des dates uniquement
                    {
                        string dateExpiration = Request.Params["DateExpiration"];
                        string dateEmission = string.Empty;
                        if (!isPasseport)
                            dateEmission = Request.Params["DateEmission"];

                        DateTime dDateExpiration = new DateTime();
                        if (!string.IsNullOrEmpty(dateExpiration))
                        {
                            DateTime.TryParse(dateExpiration, out dDateExpiration);
                        }

                        DateTime dDateEmission = new DateTime();
                        if (!string.IsNullOrEmpty(dateEmission))
                        {
                            DateTime.TryParse(dateEmission, out dDateEmission);
                        }

                        if (isPasseport)
                        {

                            if (dDateExpiration != null)
                            {
                                customer.PasseportDateExpired = dDateExpiration;
                            }
                        }
                        else
                        {
                            if (dDateExpiration != null)
                            {
                                customer.CNIDateExpired = dDateExpiration;
                            }

                            if (dDateEmission != null && dDateEmission != DateTime.MinValue)
                            {
                                customer.CNIEmissionDate = dDateEmission;
                            }
                        }
                        CustomerProspectBL.Update(customer);
                    }
                }
            }
            catch (Exception ex)
            {
                Business.Log.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", "CNIPasseport", new { client = this.IsClient.ToString() });
        }
        public PartialViewResult ShowPopupAddDoc(string CustomerProspectId, string type)
        {
            Guid gCustPid = Guid.Empty;

            if (Guid.TryParse(CustomerProspectId, out gCustPid))
            {
                gCustPid = new Guid(CustomerProspectId);
            }

            // On donne une valeur par défaut CNI
            if (string.IsNullOrEmpty(type) || (type.ToUpper() != ElectronicSafeDocumentBL.DocumentType.CNI.ToString() && type.ToUpper() != ElectronicSafeDocumentBL.DocumentType.PASSEPORT.ToString()))
            {
                type = ElectronicSafeDocumentBL.DocumentType.CNI.ToString();
                SessionManager.Set<bool>(ISPASSEPORT, false);
            }
            else
            {
                if (type.ToUpper() == ElectronicSafeDocumentBL.DocumentType.CNI.ToString())
                {
                    type = ElectronicSafeDocumentBL.DocumentType.CNI.ToString();
                    SessionManager.Set<bool>(ISPASSEPORT, false);
                }
                else
                {
                    type = ElectronicSafeDocumentBL.DocumentType.PASSEPORT.ToString();
                    SessionManager.Set<bool>(ISPASSEPORT, true);
                }
            }
            DocumentType docType = DocumentTypeBL.GetDocumentTypeByCode(type);

            CustomerProspect _customer = CustomerProspectBL.GetCustomerProspectById(gCustPid);
            ElectronicSafeDocument objESD = new ElectronicSafeDocument() { idCustomer = gCustPid, idDocumentType = docType.idDocumentType, CustomerProspect = _customer };

            return PartialView("Popup_AddDoc", objESD);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="documentName"></param>
        /// <param name="documentType"></param>
        /// <param name="documentLabel"></param>
        /// <param name="documentLocation"></param>
        /// <param name="customerOrFirmInstitutionId"></param>
        /// <param name="dictaoId"></param>
        /// <param name="clientD3S">Set if D3S, null if DTP</param>
        /// <returns>ID ElectronicSafeDocuement</returns>
        public static Guid SaveDocumentToDB(string documentName, string documentType, string documentLabel, string documentLocation, Guid? customerOrFirmInstitutionId, string dictaoId, D3SClient clientD3S = null, bool customerDocument = true, int? idDocumentCategory = null, int? idSubscriptionFile = null, Guid? idSignatureTransaction = null)
        {
            //TODO : Gerer idCustomerOrUser
            Upsilab.Data.Model.DocumentType objDocumentType = DocumentTypeBL.GetDocumentTypeByCode(documentType);

            ElectronicSafeDocument electronicSafeDoc = new ElectronicSafeDocument()
            {
                idElectronicSafeDocument = Guid.NewGuid(),
                idDocumentType = objDocumentType.idDocumentType,
                idCustomer = (customerDocument) ? customerOrFirmInstitutionId : (Guid?)null,
                idFirmInstitution = (!customerDocument) ? customerOrFirmInstitutionId : (Guid?)null,
                idDocumentCategory = idDocumentCategory,
                IdSubscriptionFile = idSubscriptionFile,
                IdSignatureTransaction = idSignatureTransaction,
                idDictao = dictaoId,

                DocumentName = documentName,
                DocumentLabel = documentLabel,
                DocumentLocation = documentLocation,
                Signed = (clientD3S == null) ? true : false, //DTP is for signature
                DateCreated = DateTime.Now,

            };

            //Generate "Fichier d'intégrité" before save
            ElectronicSafeDocumentBL.GenerateElectronicBufferPDF(electronicSafeDoc, clientD3S);

            using (UpsilabEntities db = new UpsilabEntities())
            {
                db.ElectronicSafeDocument.AddObject(electronicSafeDoc);
                db.SaveChanges();
            }

            //List<string> excludedType = new List<string>() { "RC", "LAB", "RM", "LM" }; // l'incrementation du NbElectronicSafeDocument pour ces docs se font ailleurs
            // mise à jour des infos sur le client
            //if (customerDocument && !excludedType.Contains(documentType)) // OLD Test
            if (customerDocument)
            {
                var customer = CustomerProspectBL.GetCustomerProspectById(customerOrFirmInstitutionId.Value);
                if (customer.NbElectronicSafeDocument.HasValue)
                    customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                else
                    customer.NbElectronicSafeDocument = 1;
                CustomerProspectBL.Update(customer);
            }

            return electronicSafeDoc.idElectronicSafeDocument;
        }
        public static IList<ElectronicSafeDocument> GetDocumentsLite(Guid idCustomer)
        {
            using (var ctx = new UpsilabEntities())
            {
                var query = (from es in ctx.ElectronicSafeDocument
                    from dt in ctx.DocumentType.Where(x => x.idDocumentType == es.idDocumentType)
                    //from dc in ctx.DocumentCategory.Where(x => x.idDocumentCategory == es.idDocumentCategory)
                    where es.idCustomer == idCustomer
                    select new {es, dt}).ToList();

                IList<ElectronicSafeDocument> lst = new List<ElectronicSafeDocument>();
                if (query != null)
                {
                    query.ForEach(y =>
                    {
                        var md = new ElectronicSafeDocument();
                        md.idElectronicSafeDocument = y.es.idElectronicSafeDocument;
                        md.idDocumentCategory = y.es.idDocumentCategory;
                        if (y.es.idDocumentCategory.HasValue)
                        {
                            md.DocumentCategory = new DocumentCategory()
                            {
                                idDocumentCategory = y.es.idDocumentCategory.Value,
                            };
                            var entity2 = (from dc in ctx.DocumentCategory
                                           from dp in
                                               ctx.DocumentCategory.Where(x => x.idDocumentCategory == dc.IdDocumentCategoryParent)
                                           where dc.idDocumentCategory == y.es.idDocumentCategory.Value
                                           select dp).FirstOrDefault();
                            if (entity2 != null)
                            {
                                md.DocumentCategory.DocumentCategory2 = new DocumentCategory()
                                {
                                    idDocumentCategory = entity2.idDocumentCategory,
                                    Label = entity2.Label
                                };
                            }
                        }
                    
                        md.IdSubscriptionFile = y.es.IdSubscriptionFile;
                        md.DocumentType = new Data.Model.DocumentType()
                        {
                            idDocumentType = y.dt.idDocumentType,
                            DocumentNamePrefix = y.dt.DocumentNamePrefix
                        };
                        lst.Add(md);
                    });
                }
                return lst;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="electronicSafeDocument"></param>
        /// <param name="clientD3S">Set if D3S, null if DTP</param>
        public static void GenerateElectronicBufferPDF(ElectronicSafeDocument electronicSafeDocument, D3SClient clientD3S = null)
        {
            //Generate "Fichier d'intégrité" before save
            string pathBuffer = string.Format(@"{0}\tampon\", electronicSafeDocument.DocumentLocation);
            string filenameBuffer = string.Format(@"tampon_{0}.pdf", electronicSafeDocument.DocumentName.Split('.')[0]);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, pathBuffer);
            bool isExists = System.IO.Directory.Exists(fullPath);

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(fullPath);
            }

            bool D3S = true;
            if (electronicSafeDocument.Signed) //it's a DTP archive
            {
                D3S = false;
            }

            // Il se peut que ReadDeposit renvoie une exception, dans tel cas, générer le fichier d'attestation plus tard
            try
            {
                if (clientD3S == null)
                {
                    clientD3S = new D3SClient();
                }

                Deposit objDeposit = clientD3S.ReadDeposit(D3S, electronicSafeDocument.idDictao);
                ElectronicSafeDocumentBL.GenerateElectronicBufferPDF(objDeposit, fullPath, filenameBuffer);

                electronicSafeDocument.ElectronicBufferName = string.Concat(pathBuffer, filenameBuffer);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }
        }