private static bool ArchiveDocument(Upsilab.Data.Model.SignatureTransaction signatureTransaction)
        {
            bool bOK = true; //TODO

            DTPClient dtpClient = new DTPClient(signatureTransaction.idDTPTransaction);

            //1- Update missionDocument table
            //signatoryTransaction.Status = ReportBL.Status.Completed.ToString(); //If signed by all signatories
            DocumentBL.Status docStatus = DocumentBL.Status.Completed;
            DocumentSignatureTransactionBL.UpdateTransactionStatus(signatureTransaction.idSignatureTransaction, docStatus);

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                //var firmSDG = Upsilab.Business.Configuration.FirmInstitutionBL.GetFirmInstitutionParentByIdUser(signatureTransaction.idUserCreated);
                var firmSDG = Configuration.FirmInstitutionBL.GetFirmInstitutionParentByIdFirm(signatureTransaction.idFirmInstitution.Value);

                CreditOperationBL.OperationType operationType = CreditOperationBL.OperationType.UNKNOWN;//TODO
                if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.CONVENTION.ToString())
                {
                    operationType = CreditOperationBL.OperationType.SIGNATURE_SDG_CONVENTION;
                }
                else if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT.ToString())
                {
                    operationType = CreditOperationBL.OperationType.SIGNATURE_SDG_AVENANT;
                }

                CreditOperationBL.SubstractCredit(firmSDG.idFirmInstitution, operationType.ToString(), signatureTransaction.idUserCreated);
            }
            catch { }

            //3- Save signed document to the server
            var docDocType = ElectronicSafeDocumentBL.DocumentType.DOC.ToString();
            var documentsToSign = (from doc in signatureTransaction.Document
                                   where doc.DocumentType != docDocType && doc.DocumentSignatory.Count > 0
                                   select doc).ToList();

            //TODO - TEST--------------------------------
            //documentsToSign = documentsToSign.Where(x => x.DocumentType == "CPART").ToList();
            //--------------------------------------------

            for (int i = 0; i < documentsToSign.Count; i++)
            {
                try
                {
                    var document = documentsToSign.ElementAt(i);

                    //Document to sign
                    var dtpDocType = (i == 0) ? DTPClient.DocumentTypes.CONTRACT.ToString() : string.Format("{0}{1}", DTPClient.APPENDIX, i);

                    var relativePath = string.Empty;
                    var documentName = ElectronicSafeDocumentBL.BuildDocumentName(document.DocumentType, document.idDocument);
                    var fullPath = ElectronicSafeDocumentBL.BuildSignatureDocumentPath(signatureTransaction.FirmInstitution.FirmInstitutionName, signatureTransaction.FirmInstitution.idFirmInstitution, document.DocumentType.ToDocumentTypeEnum(), false, out relativePath); //CF

                    Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(dtpDocType);

                    if (dtpDoc != null)
                    {
                        //Save physically
                        dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                        //TODO : Save document to ElectronicSafe table
                        var documentLabel = LanguageContentBL.Translate(document.DocumentType.ToLower());

                        //Particular case for "AVENANT"
                        if (signatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT.ToString())
                        {
                            documentLabel = document.Designation;
                        }

                        ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, document.DocumentType, documentLabel, relativePath, signatureTransaction.idFirmInstitution.Value, signatureTransaction.idDTPTransaction, null, false, null, null, signatureTransaction.idSignatureTransaction);
                    }
                }
                catch (Exception ex)
                {
                    Log.Log.AppendException(ex);
                }
            } 
      
            //4- Save to coffre document of type "DOC", doc not signed (documents de complétude)
            var clientD3S = new D3SClient();

            var documentsNotSigned = (from doc in signatureTransaction.Document
                                      where doc.DocumentType == docDocType
                                      select doc).ToList();

            foreach (var document in documentsNotSigned)
            {
                try
                {
                    //1- Copy to directory
                    var sourceFilePath = FileManager.GetFileFromUploadDirectory(document.Location, document.Name);

                    var relativePath = string.Empty;
                    var fullPath = ElectronicSafeDocumentBL.BuildSignatureDocumentPath(signatureTransaction.FirmInstitution.FirmInstitutionName, signatureTransaction.FirmInstitution.idFirmInstitution, ElectronicSafeDocumentBL.DocumentType.DOC, false, out relativePath); //CF
                    var destFileName = ElectronicSafeDocumentBL.BuildDocumentName(document.Label, document.idDocument);
                    var destFilePath = Path.Combine(fullPath, destFileName);

                    if (!System.IO.File.Exists(destFilePath))
                    {
                        System.IO.File.Copy(sourceFilePath, destFilePath);

                        //2- Send to dictao
                        var dictaoId = ElectronicSafeDocumentBL.SendToDictaoCoffreFort(sourceFilePath.Replace(document.Name, string.Empty),
                            document.Name, clientD3S);

                        if (!string.IsNullOrEmpty(dictaoId))
                        {
                            var documentLabel = document.DocumentCategory != null ? document.DocumentCategory.Label : document.Name.Split('.')[0];
                            ElectronicSafeDocumentBL.SaveDocumentToDB(destFileName, document.DocumentType, documentLabel, relativePath, signatureTransaction.idFirmInstitution.Value, dictaoId, clientD3S, false, document.IdDocumentCategory, null, signatureTransaction.idSignatureTransaction);
                        }

                    }

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


            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            IList<string> documentTypesToExcludeOnArchive = null; //TODO

            //6- Archive transaction : TODO : asynchrone ?
            try
            {
                string businessId = string.Format("{0}-{1}", DOCUMENT, signatureTransaction.idSignatureTransaction);
                dtpClient.ArchiveTransaction(string.Empty, string.Empty, string.Empty, businessId, documentTypesToExcludeOnArchive);
            }
            catch { }


            return bOK;
        }
        public static bool GetSignedDocumentFromDictao(string idDictao, string destFullPath, string destFileName, DTPClient.DocumentTypes dtpDocumentType)
        {
            var isOk = true;
            try
            {
                //1- Instanciate DTPClient
                DTPClient dtpClient = new DTPClient(idDictao);

                //2- Save signed document to the server 
                //NB : only for CONTRACT type
                Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(dtpDocumentType);
                dtpClient.SaveDocumentToFile(dtpDoc, destFullPath, destFileName);
            }
            catch (Exception ex)
            {
                isOk = false;
                Log.Log.AppendException(ex);
            }

            return isOk;
        }
        private static bool ArchiveSignedMissionDocument(Upsilab.Data.Model.MissionDocument missionDoc)
        {
            bool bOK = true; //TODO

            DTPClient dtpClient = new DTPClient(missionDoc.idDictao);

            //1- Update missionDocument table
            missionDoc.Status = ReportBL.Status.Completed.ToString(); //If signed by the 2 parts and saved to coffrefort
            missionDoc.Archived = true;
            missionDoc.IsOriginal = true;

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                CreditOperationBL.SubstractCredit(missionDoc.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_AUTOMATIQUE_DOCUMENT_MISSION.ToString(), missionDoc.CustomerProspect.idUserCreated, missionDoc.CustomerProspect.idCustomer);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }

            //3- Save signed document to the server 
            //a- CONTRACT
            ElectronicSafeDocumentBL.DocumentType docType = (missionDoc.IsLetter) ? ElectronicSafeDocumentBL.DocumentType.LM : ElectronicSafeDocumentBL.DocumentType.RM;
            string documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), missionDoc.idCustomerProspect);
            string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), missionDoc.CustomerProspect);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

            Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.CONTRACT);
            dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

            //4- Save document to ElectronicSafe table
            string missionDocLabel = (missionDoc.IsLetter) ? LanguageContentBL.Translate("lettre_de_mission") : LanguageContentBL.Translate("rapport_de_mission");
            string documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), missionDocLabel, (missionDoc.DateUpdated.HasValue) ? missionDoc.DateUpdated.Value.ToString("dd/MM/yyyy") : missionDoc.DateCreated.ToString("dd/MM/yyyy"));

            ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, missionDoc.idCustomerProspect, missionDoc.idDictao, null);

            //b- APPENDIX 1 : BS
            if (missionDoc.AttachPresentation)
            {
                docType = ElectronicSafeDocumentBL.DocumentType.BS;
                documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), missionDoc.idCustomerProspect);
                documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), missionDoc.CustomerProspect);
                fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.APPENDIX1);

                if (dtpDoc != null)
                {
                    dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                    //Save document to ElectronicSafe table
                    documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), LanguageContentBL.Translate("presentation_de_l_etab"), (missionDoc.DateUpdated.HasValue) ? missionDoc.DateUpdated.Value.ToString("dd/MM/yyyy") : missionDoc.DateCreated.ToString("dd/MM/yyyy"));

                    ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, missionDoc.idCustomerProspect, missionDoc.idDictao, null);
                }

            }

            //c- APPENDIX 2 : FIL => DER
            if (missionDoc.AttachInformationCard)
            {
                docType = ElectronicSafeDocumentBL.DocumentType.FIL;
                documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), missionDoc.idCustomerProspect);
                documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), missionDoc.CustomerProspect);
                fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.APPENDIX2);

                if (dtpDoc != null)
                {
                    dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                    //Save document to ElectronicSafe table
                    documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), LanguageContentBL.Translate("doc_entree_en_relation"), (missionDoc.DateUpdated.HasValue) ? missionDoc.DateUpdated.Value.ToString("dd/MM/yyyy") : missionDoc.DateCreated.ToString("dd/MM/yyyy"));

                    ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, missionDoc.idCustomerProspect, missionDoc.idDictao, null);
                }

            }

            // d- APPENDIX 3 : CRTO
            if (missionDoc.AttachConventionRTO.HasValue && missionDoc.AttachConventionRTO.Value)
            {
                docType = ElectronicSafeDocumentBL.DocumentType.CRTO;
                documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), missionDoc.idCustomerProspect);
                documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), missionDoc.CustomerProspect);
                fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.APPENDIX3);

                if (dtpDoc != null)
                {
                    dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                    //Save document to ElectronicSafe table
                    documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), LanguageContentBL.Translate("convention_de_rto"), (missionDoc.DateUpdated.HasValue) ? missionDoc.DateUpdated.Value.ToString("dd/MM/yyyy") : missionDoc.DateCreated.ToString("dd/MM/yyyy"));

                    ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, missionDoc.idCustomerProspect, missionDoc.idDictao, null);
                }
            }

            // e- APPENDIX >= 4
            //For RM
            if (!missionDoc.IsLetter && missionDoc.MissionDocumentAppendix.Count > 0)
            {
                List<MissionDocumentAppendix> lstAppendixDocs = missionDoc.MissionDocumentAppendix.OrderBy(app => app.DateCreated).ToList();
                int appendixNum = 4;
                foreach (var appendixDoc in lstAppendixDocs)
                {
                    docType = ElectronicSafeDocumentBL.DocumentType.AX;
                    documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), appendixDoc.idMissionDocumentAppendix);
                    documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), missionDoc.CustomerProspect);
                    fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                    string dtpDocType = string.Format("{0}{1}", DTPClient.APPENDIX, appendixNum);
                    dtpDoc = dtpClient.GetDocumentByType(dtpDocType);

                    appendixNum++;

                    if (dtpDoc != null)
                    {
                        dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                        //Save document to ElectronicSafe table
                        documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), appendixDoc.Designation, (missionDoc.DateUpdated.HasValue) ? missionDoc.DateUpdated.Value.ToString("dd/MM/yyyy") : missionDoc.DateCreated.ToString("dd/MM/yyyy"));

                        ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, missionDoc.idCustomerProspect, missionDoc.idDictao, null, true, appendixDoc.idDocumentCategory);
                    }
                }

            }

            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            IList<string> documentTypesToExcludeOnArchive = null; //TODO

            //6- Archive transaction : TODO : asynchrone ?
            try
            {
                string businessId = string.Format("{0}-{1}", (missionDoc.IsLetter) ? MISSION_LETTER : MISSION_REPORT, missionDoc.idMissionDocument);
                dtpClient.ArchiveTransaction(missionDoc.CustomerProspect.FirmInstitution.FirmInstitutionName, missionDoc.CustomerProspect.User.UserName, missionDoc.CustomerProspect.User.UserFirstName, businessId, documentTypesToExcludeOnArchive);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }

            return bOK;
        }
        private static bool ArchiveSignedDER(Upsilab.Data.Model.DER der)
        {
            bool bOK = true; //TODO

            DTPClient dtpClient = new DTPClient(der.idDictao);

            //1- Update missionDocument table
            der.Status = ReportBL.Status.Completed.ToString(); //If signed by the 2 parts and saved to coffrefort
            der.Archived = true;
            der.IsOriginal = true;

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                CreditOperationBL.SubstractCredit(der.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_AUTOMATIQUE_DER.ToString(), der.CustomerProspect.idUserCreated, der.CustomerProspect.idCustomer);
            }
            catch { }

            //3- Save signed document to the server 
            //a- CONTRACT
            ElectronicSafeDocumentBL.DocumentType docType = ElectronicSafeDocumentBL.DocumentType.FIL; //<=> DER
            string documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), der.idCustomerProspect);
            string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), der.CustomerProspect);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

            Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.CONTRACT);
            dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

            //4- Save document to ElectronicSafe table
            string docLabel = LanguageContentBL.Translate("der_title");
            string documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), docLabel, (der.DateUpdated.HasValue) ? der.DateUpdated.Value.ToString("dd/MM/yyyy") : der.DateCreated.ToString("dd/MM/yyyy"));

            ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, der.idCustomerProspect, der.idDictao, null);

            //b- APPENDIX 1 : BS
            if (der.AttachPresentation)
            {
                docType = ElectronicSafeDocumentBL.DocumentType.BS;
                documentName = ElectronicSafeDocumentBL.BuildDocumentName(docType.ToString(), der.idCustomerProspect);
                documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), der.CustomerProspect);
                fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.APPENDIX1);

                if (dtpDoc != null)
                {
                    dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

                    //Save document to ElectronicSafe table
                    documentLabel = string.Format(LanguageContentBL.Translate("signature_doc_title_on"), LanguageContentBL.Translate("der_bs_title"), (der.DateUpdated.HasValue) ? der.DateUpdated.Value.ToString("dd/MM/yyyy") : der.DateCreated.ToString("dd/MM/yyyy"));

                    ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, docType.ToString(), documentLabel, documentPath, der.idCustomerProspect, der.idDictao, null);
                }

            }

            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            IList<string> documentTypesToExcludeOnArchive = null; //TODO

            //6- Archive transaction : TODO : asynchrone ?
            try
            {
                string businessId = string.Format("DER-{0}", der.idDer);
                dtpClient.ArchiveTransaction(der.CustomerProspect.FirmInstitution.FirmInstitutionName, der.CustomerProspect.User.UserName, der.CustomerProspect.User.UserFirstName, businessId, documentTypesToExcludeOnArchive);
            }
            catch { }


            return bOK;
        }
        private static bool ArchiveReportSignedDocument(Upsilab.Data.Model.Report report)
        {
            bool bOK = true; //TODO
           
            DTPClient dtpClient = new DTPClient(report.idDictao);

            //1- Update report table
            report.Status = ReportBL.Status.Completed.ToString(); //If signed by the 2 parts and saved to coffrefort
            report.Archived = true;
            report.IsOriginal = true;

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                CreditOperationBL.SubstractCredit(report.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_RECUEIL.ToString(), report.CustomerProspect.idUserCreated, report.CustomerProspect.idCustomer);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }

            //3- Save signed document to the server
            string documentName = ElectronicSafeDocumentBL.BuildDocumentName(ElectronicSafeDocumentBL.DocumentType.RC.ToString(), report.idCustomerProspect);
            string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.RC.ToString(), report.CustomerProspect);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

            Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.CONTRACT);
            dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

            //4- Save document to ElectronicSafe table
            string documentLabel = string.Format(LanguageContentBL.Translate("signature_report_on"), (report.DateUpdated.HasValue) ? report.DateUpdated.Value.ToString("dd/MM/yyyy") : report.DateCreated.ToString("dd/MM/yyyy"));

            ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, ElectronicSafeDocumentBL.DocumentType.RC.ToString(), documentLabel, documentPath, report.idCustomerProspect, report.idDictao, null);

            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            IList<string> documentTypesToExcludeOnArchive = null; //TODO

            //6- Archive transaction : TODO : asynchrone ?
            try
            {
                string businessId = string.Format("{0}-{1}", REPORT, report.idReport);
                dtpClient.ArchiveTransaction(report.CustomerProspect.FirmInstitution.FirmInstitutionName, report.CustomerProspect.User.UserName, report.CustomerProspect.User.UserFirstName, businessId, documentTypesToExcludeOnArchive);
            }
            catch { }

            return bOK;
        }
        private static bool ArchiveCRTOSignedDocument(Upsilab.Data.Model.CustomerProspect customer)
        {
            bool bOK = true; //TODO

            Upsilab.Data.Model.ConventionRTO crto = customer.ConventionRTO;

            DTPClient dtpClient = new DTPClient(crto.idDictao);

            //1- Update ConfidentialityAgreement table
            crto.Status = ReportBL.Status.Completed.ToString(); //If signed by the 2 parts and saved to coffrefort
            crto.Archived = true;

            //2- Reduice firm credit after signature + mise au coffre
            //TODO : don't archive, sign doc if credit is not sufficient
            try
            {
                CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.MISE_AU_COFFRE_AUTOMATIQUE_CRTO.ToString(), customer.idUserCreated, customer.idCustomer);
            }
            catch (Exception ex)
            {
                Log.Log.AppendException(ex);
            }

            //3- Save signed document to the server
            string documentName = ElectronicSafeDocumentBL.BuildDocumentName(ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), customer.idCustomer);
            string documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), customer);
            string fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

            Upsilab.Infrastructure.DictaoDTPCoreServiceReference.Document dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.CONTRACT);
            dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);

            //4- Save document to ElectronicSafe table
            string documentLabel = LanguageContentBL.Translate("signature_crto_title");
            ElectronicSafeDocumentBL.SaveDocumentToDB(documentName, ElectronicSafeDocumentBL.DocumentType.CRTO.ToString(), documentLabel, documentPath, customer.idCustomer, crto.idDictao, null);

            //5- If all is ok, finish / close transaction
            dtpClient.FinishTransaction();

            //6- Archive transaction : TODO : asynchrone ?
            IList<string> documentTypesToExcludeOnArchive = null; //TODO
            try
            {
                string businessId = string.Format("{0}-{1}", CONVENTION_RTO, customer.idCustomer);
                dtpClient.ArchiveTransaction(customer.FirmInstitution.FirmInstitutionName, customer.User.UserName, customer.User.UserFirstName, businessId, documentTypesToExcludeOnArchive);
            }
            catch { }

            return bOK;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="dtpData"></param>
        /// <returns></returns>
        private static DTPData SignByFirstUser(Upsilab.Data.Model.User user, DTPData dtpData)
        {
            //User infos
            dtpData = GetUserInfos(user, dtpData);

            DTPClient dtpClient = new DTPClient();

            //If idDictao has value, cancel this transaction and create a new one
            if (!string.IsNullOrEmpty(dtpData.TransactionId))
            {
                dtpClient.TransactionId = dtpData.TransactionId;
                try
                {
                    dtpClient.CancelTransaction();
                }
                catch { }
            }

            //#1 : Init transaction
            dtpClient.InitTransaction(dtpData.BusinessId);

            //#2 : Provide document
            dtpClient.ProvideDocuments(dtpData.DocumentsToSign);

            //#3 : create access user
            //TODO : where to put ?
            //string termAndConditionsFileName = "termsAndConditions_fr.pdf";
            //string termAndConditionsFileName = "convention_preuve.pdf";
            //string termAndConditionsUrl = string.Format("{0}/Client/Documents/{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), termAndConditionsFileName);

            dtpData.UserAccessId = dtpClient.CreateUserAccess(string.Empty, user.UserName, user.UserFirstName, user.UserMobilePhone, dtpData.BackUrl);
            
            //#4 : create user space
            dtpClient.CreateUserSpace(dtpData);

            //#5 : create user space content
            dtpClient.CreateUserSpaceContent(dtpData);

            //#5' : send OTP by sms to user
            //dtpClient.SendOtp(accessId); TODO

            //#6 : build urlIhm
            dtpData.IHM_Url = dtpClient.BuildUserInterfaceUrl(dtpData);

            dtpData.TransactionId = dtpClient.TransactionId;

            return dtpData;
        }
        public ActionResult GetSignedDocument(string idTransaction, string documentType)
        {
            var dtpClient = new DTPClient(idTransaction);
            var documentName = ElectronicSafeDocumentBL.BuildDocumentName(documentType, Guid.NewGuid());

            //Get document from dictao
            var dtpDoc = dtpClient.GetDocumentByType(documentType);
            
            //Download file if exists
            if (dtpDoc.content != null)
            {
                var contentDisposition = new System.Net.Mime.ContentDisposition
                {
                    FileName = documentName,
                    // always prompt the user for downloading, set to true if you want 
                    Inline = false,
                };

                Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

                return File(dtpDoc.content, "application/octet-stream");
            }

            return RedirectToAction("RetourSignature", new { success = false, doc = documentType });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="txid"></param>
        /// <param name="aid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool BackFromCustomerCRTOSignature(string status, string login, string offer, out string error)
        {
            bool isOk = true;
            error = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.ConventionRTO crto = (from conf in context.ConventionRTO
                                                                                    .Include("User")
                                                                                    .Include("CustomerProspect_1")
                                                                                    .Include("CustomerProspect_1.User")
                                                                                    .Include("CustomerProspect_1.User1")
                                                                                    .Include("CustomerProspect_1.FirmInstitution")

                                                            where conf.idDTPUserAccess == idUserAccess
                                                            select conf).FirstOrDefault();

                    if (crto == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(crto.idConventionRTO, null, crto.idDictao, crto.idDTPUserAccess, status, ElectronicSafeDocumentBL.DocumentType.CRTO.ToString());

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(crto.idDictao);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }

                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {

                            Upsilab.Data.Model.CustomerProspect customer = crto.CustomerProspect_1;

                            customer.CustomersUsingSameAccount = CustomerProspect.CustomerProspectBL.GetCustomersByEmail(customer.User.UserEmail);

                            //Check if already signed by customer
                            if (crto.SignedByCustomer)
                            {
                                error = LanguageContentBL.Translate("signature_crto_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update database
                                crto.SignedByCustomer = true;
                                crto.DateSignatureCustomer = DateTime.Now;

                                //Update customer.idCRTO = latest signed CRTO
                                customer.idConventionRTO = crto.idConventionRTO;

                                //Archive signed document (send to coffre fort)
                                SignatureDocumentBL.ArchiveCRTOSignedDocument(customer);

                                // Send mail informing adviser that client has signed the "Confidentiality agreement"
                                SignatureDocumentBL.SendCRTOMailToAdviser(customer, false); //TODO : if customer sign "Second", template mail ?
                                
                                context.SaveChanges();

                                //Update session user
                                SessionManager.SetCustomerProspectSession(customer);
                            } //End signed
                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }
                    }

                } //end using                
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Log.Log.AppendException(ex);
                isOk = false;
            }

            return isOk;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="txid"></param>
        /// <param name="aid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool BackFromDocumentSignature(string status, string login, string offer, out string error, out string transactionType)
        {
            bool isOk = true;
            error = string.Empty;
            transactionType = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.Signatory signatory = (from sign in context.Signatory
                                                                                  .Include("SignatureTransaction")
                                                                                  .Include("SignatureTransaction.FirmInstitution")
                                                                                  .Include("SignatureTransaction.Signatory")
                                                                                  .Include("SignatureTransaction.Document")
                                                              where sign.idDTPUserAccess == idUserAccess
                                                              select sign).FirstOrDefault();

                    if (signatory == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, ElectronicSafeDocumentBL.DocumentType.SIGN.ToString());
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(signatory.idSignatory, null, null, signatory.idDTPUserAccess, status, ElectronicSafeDocumentBL.DocumentType.SIGN.ToString());
                        
                        transactionType = signatory.SignatureTransaction.SignatureTransactionType;

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(signatory.SignatureTransaction.idDTPTransaction);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }


                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {
                            //Check if already signed by customer
                            if (signatory.DateSignature.HasValue)
                            {
                                error = LanguageContentBL.Translate("signature_doc_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update database
                                signatory.DateSignature = DateTime.Now;

                                // If already signed by other signatories, archive document
                                var signatoriesHaveNotSigned = signatory.SignatureTransaction.Signatory.Where(sign => !sign.DateSignature.HasValue).ToList();

                                if (signatoriesHaveNotSigned.Count > 0) //some signatories haven't sign
                                {
                                    DocumentBL.Status docStatus = DocumentBL.Status.InProgress;
                                    if (signatory.Role == SignatoryBL.Roles.SDG.ToString())
                                    {
                                        docStatus = DocumentBL.Status.WaitingForClientSignature; //TODO
                                    }

                                    DocumentSignatureTransactionBL.UpdateTransactionStatus(signatory.idSignatureTransaction.Value, docStatus);

                                    //TODO : Soustraire le credit
                                    try
                                    {
                                        //CreditOperationBL.SubstractCredit(report.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_RECUEIL.ToString(), report.CustomerProspect.idUserCreated, report.CustomerProspect.idCustomer);
                                    }
                                    catch { }

                                    //Send mail inviting CGP to sign
                                    if (signatory.Role == SignatoryBL.Roles.SDG.ToString())
                                    {
                                        //UpsideoSignature
                                        bool isConvention = signatory.SignatureTransaction.SignatureTransactionType == DocumentSignatureTransactionBL.SignatureTransactionType.CONVENTION.ToString();
                                        SignatureDocumentBL.SendConventionMailToCGP(signatory.SignatureTransaction, isConvention);
                                    }
                                    else
                                    { 
                                        //TODO : send mail for other application ?
                                    }
                                   
                                }
                                else
                                {
                                    //Archive signed document (send to coffre fort)
                                    SignatureDocumentBL.ArchiveDocument(signatory.SignatureTransaction);

                                    //TODO : Send mail informing adviser that client has signed the "Report"
                                    //SignatureDocumentBL.SendReportMailToAdviser(report, false);
                                }

                                context.SaveChanges();
                            }
                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }

                    }

                } //End using
            } //End try
            catch (Exception ex)
            {
                error = ex.Message;
                Log.Log.AppendException(ex);
                isOk = false;
            }

            return isOk;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="txid"></param>
        /// <param name="aid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool BackFromAdviserDERSignature(string status, string login, string offer, out string error)
        {
            bool isOk = true;
            error = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.DER derDoc = (from der in context.DER
                                                            .Include("User")
                                                            .Include("CustomerProspect")
                                                            .Include("CustomerProspect.FirmInstitution")
                                                            .Include("CustomerProspect.User")
                                                            .Include("CustomerProspect.User1")
                                                    where der.idDTPUserAccess == idUserAccess
                                                    select der).FirstOrDefault();
                    if (derDoc == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, ElectronicSafeDocumentBL.DocumentType.FIL.ToString());
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(derDoc.idDer, derDoc.idCustomerProspect, derDoc.idDictao, derDoc.idDTPUserAccess, status, ElectronicSafeDocumentBL.DocumentType.FIL.ToString());

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(derDoc.idDictao);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }

                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {
                            //Check if already signed by adviser
                            if (derDoc.SignedByAdviser)
                            {
                                error = LanguageContentBL.Translate("signature_doc_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update report table
                                derDoc.SignedByAdviser = true;
                                derDoc.DateAdviserSignature = DateTime.Now;

                                // If already signed by customer, archive document
                                if (!derDoc.SignedByCustomer)
                                {
                                    derDoc.Status = ReportBL.Status.WaitingForClientSignature.ToString();
                                    //mettre à jour le current status du customer
                                    Upsilab.Data.Model.CustomerProspect cust = derDoc.CustomerProspect;
                                    cust.DerStatus = ReportBL.Status.WaitingForClientSignature.ToString();

                                    //Soustraire le credit
                                    try
                                    {
                                        CreditOperationBL.SubstractCredit(derDoc.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_DER.ToString(), derDoc.CustomerProspect.idUserCreated, derDoc.CustomerProspect.idCustomer);
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Log.AppendException(ex);
                                    }

                                    // Send mail inviting client to sign
                                    SignatureDocumentBL.SendDERMailToClient(derDoc, true);
                                }
                                else
                                {
                                    //Achive the signed document : send to coffre-fort
                                    SignatureDocumentBL.ArchiveSignedDER(derDoc);

                                    //Update table CustomerProspect : DateLastUpdatedMission
                                    Upsilab.Data.Model.CustomerProspect customer = derDoc.CustomerProspect;
                                    customer.DateLastUpdateDer = DateTime.Now;
                                    customer.DerStatus = Upsilab.Business.Report.ReportBL.Status.Completed.ToString();
                                    customer.IsDerOriginal = true;

                                    if (customer.NbElectronicSafeDocument.HasValue)
                                        customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                                    else
                                        customer.NbElectronicSafeDocument = 1;

                                    // Send mail informing client that Adviser has signed the "Report"
                                    SignatureDocumentBL.SendDERMailToClient(derDoc, false);
                                }

                                context.SaveChanges();
                            }
                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }

                    }

                }//End using
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Log.Log.AppendException(ex);
                isOk = false;
            }

            return isOk;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="txid"></param>
        /// <param name="aid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool BackFromCustomerMissionDocumentSignature(string status, string login, string offer, out string error)
        {
            bool isOk = true;
            error = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.MissionDocument missionDoc = (from md in context.MissionDocument
                                                                            .Include("User")
                                                                            .Include("CustomerProspect")
                                                                            .Include("CustomerProspect.FirmInstitution")
                                                                            .Include("CustomerProspect.User")
                                                                            .Include("CustomerProspect.User1")
                                                                     where md.idDTPUserAccess == idUserAccess
                                                                     select md).FirstOrDefault();

                    if (missionDoc == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, "LM/RM");
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(missionDoc.idMissionDocument, missionDoc.idCustomerProspect, missionDoc.idDictao, missionDoc.idDTPUserAccess, status, (missionDoc.IsLetter) ? ElectronicSafeDocumentBL.DocumentType.LM.ToString() : ElectronicSafeDocumentBL.DocumentType.RM.ToString());

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(missionDoc.idDictao);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }

                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {
                            //Check if already signed by customer
                            if (missionDoc.SignedByCustomer)
                            {
                                error = LanguageContentBL.Translate("signature_doc_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update database
                                missionDoc.SignedByCustomer = true;
                                missionDoc.DateCustomerSignature = DateTime.Now;

                                // If already signed by adviser, archive document
                                if (!missionDoc.SignedByAdviser)
                                {
                                    missionDoc.Status = ReportBL.Status.WaitingForAdviserSignature.ToString();
                                    //mettre à jour le current status du customer
                                    Upsilab.Data.Model.CustomerProspect cust = missionDoc.CustomerProspect;
                                    if (missionDoc.IsLetter)
                                        cust.LetterStatus = ReportBL.Status.WaitingForAdviserSignature.ToString();
                                    else
                                        cust.MissionStatus = ReportBL.Status.WaitingForAdviserSignature.ToString();
                                    //Upsilab.Business.CustomerProspect.CustomerProspectBL.Update(cust);

                                    //Soustraire le credit
                                    try
                                    {
                                        CreditOperationBL.SubstractCredit(missionDoc.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_DOCUMENT_MISSION.ToString(), missionDoc.CustomerProspect.idUserCreated, missionDoc.CustomerProspect.idCustomer);
                                    }
                                    catch(Exception ex)
                                    {
                                        Log.Log.AppendException(ex);
                                    }

                                    // Send mail inviting adviser to sign
                                    SignatureDocumentBL.SendMissionDocumentMailToAdviser(missionDoc, true);
                                }
                                else
                                {
                                    //Archive signed document (send to coffre fort)
                                    SignatureDocumentBL.ArchiveSignedMissionDocument(missionDoc);

                                    //Update table CustomerProspect : DateLastUpdatedMission
                                    Upsilab.Data.Model.CustomerProspect customer = missionDoc.CustomerProspect;

                                    if (missionDoc.IsLetter)
                                    {
                                        customer.DateLastUpdateLetter = DateTime.Now;
                                        customer.LetterStatus = Upsilab.Business.Report.ReportBL.Status.Completed.ToString();
                                        customer.IsLetterOriginal = true;
                                    }
                                    else
                                    {
                                        customer.DateLastUpdateMission = DateTime.Now;
                                        customer.MissionStatus = Upsilab.Business.Report.ReportBL.Status.Completed.ToString();
                                        customer.IsMissionOriginal = true;
                                    }

                                    if (customer.NbElectronicSafeDocument.HasValue)
                                        customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                                    else
                                        customer.NbElectronicSafeDocument = 1;

                                    //If DER (FIL) is attached to LM/RM
                                    if (missionDoc.AttachInformationCard)
                                    {
                                        customer.DerStatus = Upsilab.Business.Report.ReportBL.Status.Completed.ToString();
                                        customer.IsDerOriginal = true;
                                        customer.DateLastUpdateDer = DateTime.Now;
                                    }

                                    //If CRTO is attached to LM/RM
                                    if (missionDoc.AttachConventionRTO.HasValue && missionDoc.AttachConventionRTO.Value)
                                    {
                                        var convention = Business.ConventionRTO.ConventionRTOBL.CreateCRTOFromMissionDocument(missionDoc);

                                        //Mise à jour idConventionRTO du client
                                        if (convention != null)
                                        {
                                            customer.idConventionRTO = convention.idConventionRTO;
                                        }
                                    }
                                   
                                    // Send mail informing adviser that client has signed the "Lettre de mission / Rapport de mission"
                                    SignatureDocumentBL.SendMissionDocumentMailToAdviser(missionDoc, false);
                                }

                                context.SaveChanges();
                            } //end else
                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }

                    }

                } //end using
            }
            catch (Exception ex)
            {
                error = ex.Message;
                isOk = false;
                Log.Log.AppendException(ex);
            }

            return isOk;
        }
        public string SaveSignedDERToCoffreFort()
        {
            using (var db = new UpsilabEntities())
            {
                var dateStart = new DateTime(2015, 4, 9);

                var query = from lm in db.MissionDocument.Include("CustomerProspect")
                            from rm in db.MissionDocument.Where(r => lm.idCustomerProspect == r.idCustomerProspect
                                                                    && lm.IsLetter && !r.IsLetter
                                                                    && lm.AttachInformationCard && r.AttachInformationCard
                                                                    && lm.Status == "Completed" && r.Status == "Completed"
                                                                    && lm.idDTPUserAccess != null && r.idDTPUserAccess != null)
                            where lm.DateCustomerSignature.Value.Year == rm.DateCustomerSignature.Value.Year
                                 && lm.DateCustomerSignature.Value.Month == rm.DateCustomerSignature.Value.Month
                                 && lm.DateCustomerSignature.Value.Day == rm.DateCustomerSignature.Value.Day
                                 && rm.DateCustomerSignature >= dateStart
                            select new
                            {
                                LM_DateCustomerSignature = lm.DateCustomerSignature,
                                RM_DateCustomerSignature = rm.DateCustomerSignature,
                                IdCustomerProspect = lm.idCustomerProspect,
                                IdDictao = (lm.DateCustomerSignature < rm.DateCustomerSignature) ? lm.idDictao : rm.idDictao,
                                CustomerProspect = lm.CustomerProspect
                            };

                var list = query.ToList();

                //Get signed DER : from LM or RM => which signed first
                var count = 0;
                foreach (var item in list)
                {
                    try
                    {
                        DTPClient dtpClient = new DTPClient(item.IdDictao);

                        var docType = ElectronicSafeDocumentBL.DocumentType.FIL;
                        var documentName = string.Format("{0}_{1}_{2}.pdf", docType.ToString(), item.IdCustomerProspect.ToString(), item.LM_DateCustomerSignature.Value.ToString("ddMMyyyy"));
                        var documentPath = ElectronicSafeDocumentBL.BuildClientDocumentPath(docType.ToString(), item.CustomerProspect);
                        var fullPath = System.IO.Path.Combine(Upsilab.Business.Utility.ConfigurationManager.CoffreFortRootPath, documentPath);

                        var dtpDoc = dtpClient.GetDocumentByType(DTPClient.DocumentTypes.APPENDIX2);

                        if (dtpDoc != null)
                        {
                            dtpClient.SaveDocumentToFile(dtpDoc, fullPath, documentName);
                            count++;
                        }
                    }
                    catch { }


                }

                return count.ToString();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        /// <param name="login"></param>
        /// <param name="offer"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool BackFromAdviserReportSignature(string status, string login, string offer, out string error)
        {
            bool isOk = true;
            error = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.Report report = (from rep in context.Report
                                                                .Include("CustomerProspect")
                                                                .Include("CustomerProspect.FirmInstitution")
                                                                .Include("CustomerProspect.User")
                                                                .Include("CustomerProspect.User1")
                                                        where rep.idDTPUserAccess == idUserAccess
                                                        select rep).FirstOrDefault();

                    if (report == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, ElectronicSafeDocumentBL.DocumentType.RC.ToString());
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(report.idReport, report.idCustomerProspect, report.idDictao, report.idDTPUserAccess, status, ElectronicSafeDocumentBL.DocumentType.RC.ToString());

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(report.idDictao);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }


                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {
                            //Check if already signed by adviser
                            if (report.SignedByAdviser)
                            {
                                error = LanguageContentBL.Translate("signature_doc_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update report table
                                report.SignedByAdviser = true;
                                report.DateAdviserSignature = DateTime.Now;

                                // If already signed by customer, archive document
                                if (!report.SignedByCustomer)
                                {
                                    report.Status = ReportBL.Status.WaitingForClientSignature.ToString();
                                    //mettre à jour le current status du customer
                                    report.CustomerProspect.CurrentReportStatus = ReportBL.Status.WaitingForClientSignature.ToString();
                                    //Upsilab.Business.CustomerProspect.CustomerProspectBL.Update(report.CustomerProspect);

                                    //Soustraire le credit
                                    try
                                    {
                                        CreditOperationBL.SubstractCredit(report.CustomerProspect.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_RECUEIL.ToString(), report.CustomerProspect.idUserCreated, report.CustomerProspect.idCustomer);
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Log.AppendException(ex);
                                    }

                                    // Send mail inviting client to sign
                                    SignatureDocumentBL.SendReportMailToClient(report, true);
                                }
                                else
                                {
                                    //Achive the signed document : send to coffre-fort
                                    SignatureDocumentBL.ArchiveReportSignedDocument(report);

                                    //Update table CustomerProspect : DateShiftLabLast & DateShiftLabNext & Profil

                                    Upsilab.Data.Model.CustomerProspect customer = report.CustomerProspect;
                                    customer.DateUpdatedLast = DateTime.Now;
                                    customer.DateUpdatedNext = DateTime.Now.AddYears(1);
                                    customer.CurrentReportStatus = Upsilab.Business.Report.ReportBL.Status.Completed.ToString();
                                    customer.HasCompletedReport = true;
                                    customer.IsReportOriginal = true;
                                    
                                    if (customer.NbElectronicSafeDocument.HasValue)
                                    {
                                        customer.NbElectronicSafeDocument = customer.NbElectronicSafeDocument.Value + 1;
                                    }
                                    else
                                    {
                                        customer.NbElectronicSafeDocument = 1;
                                    }

                                    customer.RiskProfile = (customer.IsCorporation.HasValue && customer.IsCorporation.Value) ? CustomerProspectBL.GetCustomerPMProfil(report) : CustomerProspectBL.GetCustomerPPProfil(report);

                                    // Send mail informing client that Adviser has signed the "Report"
                                    SignatureDocumentBL.SendReportMailToClient(report, false);
                                }

                                context.SaveChanges();
                            }

                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Log.Log.AppendException(ex);
                isOk = false;
            }

            return isOk;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="dtpData"></param>
        /// <returns></returns>
        private static DTPData SignBySecondUser(Upsilab.Data.Model.User user, DTPData dtpData)
        {
            //User infos
            dtpData = GetUserInfos(user, dtpData);

            if (string.IsNullOrEmpty(dtpData.TransactionId))
            {
                //throw new Exception(SignatureExceptionCode.TransactionIdMissing.ToString());
                throw new Exception("La transaction de cette signature est expirée.");
            }

            //#1 : Continue transaction
            DTPClient dtpClient = new DTPClient(dtpData.TransactionId);

            //Check if all users have signed the transaction
            if (dtpClient.IsTransactionSignedByAll())
            //if (true)
            {
                dtpData.IHM_Url = dtpData.BackUrl.Replace("%3F", "?").Replace("%3D", "=").Replace("%7B", "{").Replace("%7D", "}").Replace("%26", "&")
                                                 .Replace("{STATUS}", ALREADY_SIGNED).Replace("{LOGIN}", dtpData.Login).Replace("{OFFER}", dtpData.OfferId); //Exec back url;
            }
            else
            {

                //#2 : Create access user for second user
                dtpData.UserAccessId = dtpClient.CreateUserAccess(string.Empty, user.UserName, user.UserFirstName, user.UserMobilePhone, dtpData.BackUrl);

                //#3 : create user space
                dtpClient.CreateUserSpace(dtpData);

                //#4 : create user space content
                dtpClient.CreateUserSpaceContent(dtpData);

                //#4' : Send OTP by sms to user
                //dtpClient.SendOtp(accessId); TODO

                //#5 : IHM_url
                dtpData.IHM_Url = dtpClient.BuildUserInterfaceUrl(dtpData);
            }

            return dtpData;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="txid"></param>
        /// <param name="aid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool BackFromAdviserConfidentialityAgreementSignature(string status, string login, string offer, out string error)
        {
            bool isOk = true;
            error = string.Empty;

            try
            {
                using (UpsilabEntities context = new UpsilabEntities())
                {
                    string idUserAccess = DTPData.GetUserAccessIdByLogin(login);

                    Upsilab.Data.Model.ConfidentialityAgreement confident = (from conf in context.ConfidentialityAgreement
                                                                             where conf.idDTPUserAccess == idUserAccess
                                                                             select conf).FirstOrDefault();

                    if (confident == null)
                    {
                        error = LanguageContentBL.Translate("signature_user_access_id_not_ok");
                        isOk = false;
                        SignatureLogBL.Save(null, null, null, login, status, ElectronicSafeDocumentBL.DocumentType.EC.ToString());
                    }
                    else
                    {
                        //Log signature
                        SignatureLogBL.Save(confident.idConfidentialityAgreement, null, confident.idDictao, confident.idDTPUserAccess, status, ElectronicSafeDocumentBL.DocumentType.EC.ToString());

                        //Finish user access and delete userspace
                        try
                        {
                            DTPClient dtpClient = new DTPClient(confident.idDictao);

                            dtpClient.FinishUserAccess(idUserAccess);
                            dtpClient.DeleteUserSpace(login);
                        }
                        catch { }

                        //Check status
                        if (status.ToUpper() == ALREADY_SIGNED)
                        {
                            error = GetDTPError(ALREADY_SIGNED);
                            isOk = false;
                        }

                        //If OK or ALREADY_SIGNED, do database update
                        if (status.ToUpper() == OK || status.ToUpper() == ALREADY_SIGNED)
                        {

                            Upsilab.Data.Model.CustomerProspect customer = (from cust in context.CustomerProspect
                                                                                    .Include("ConfidentialityAgreement.User")
                                                                                    .Include("FirmInstitution")
                                                                                    .Include("User")
                                                                                    .Include("User1")
                                                                            where cust.idConfidentialityAgreement == confident.idConfidentialityAgreement
                                                                            select cust).FirstOrDefault();

                            //Check if already signed by adviser
                            if (confident.SignedByAdviser)
                            {
                                error = LanguageContentBL.Translate("signature_ec_signed");
                                isOk = false;
                            }
                            else
                            {
                                //Update report table
                                confident.SignedByAdviser = true;
                                confident.DateAdviserSignature = DateTime.Now;

                                // If already signed by customer, archive document
                                if (!confident.SignedByCustomer)
                                {
                                    confident.Status = ReportBL.Status.WaitingForClientSignature.ToString();

                                    //Soustraire le credit
                                    try
                                    {
                                        CreditOperationBL.SubstractCredit(customer.idFirmInstitution, CreditOperationBL.OperationType.SIGNATURE_ENGAGEMENT_CONFIDENTIALITE.ToString(), customer.idUserCreated, customer.idCustomer);
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Log.AppendException(ex);
                                    }

                                    // Send mail inviting client to sign
                                    SignatureDocumentBL.SendAgreementMailToClient(customer, true);
                                }
                                else
                                {
                                    //Achive the signed document : send to coffre-fort
                                    SignatureDocumentBL.ArchiveConfidentialityAgreementSignedDocument(customer);

                                    // Send mail informing client that Adviser has signed the "Report"
                                    SignatureDocumentBL.SendAgreementMailToClient(customer, false);
                                }

                                context.SaveChanges();
                            } //end signed
                        }
                        else
                        {
                            //error = string.Format("Erreur lors de la signature (status {0})", status);
                            error = GetDTPError(status);
                            isOk = false;
                        }
                    }

                } //End using
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Log.Log.AppendException(ex);
                isOk = false;
            }

            return isOk;
        }
        public string GetTransactionFileLog(string idTransaction)
        {
            string retValue = string.Empty;
            idTransaction = Url.Encode(idTransaction);
            try
            {
                DTPClient dtpClient = new DTPClient(idTransaction);
                dtpClient.GetTransactionData();

                retValue = dtpClient.TransactionData;
            }
            catch (Exception ex)
            {
                retValue = ex.Message;
            }

            return retValue;
        }