예제 #1
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lstDocumentsToSign"></param>
        /// <returns></returns>
        private string BuildDocumentToSignJson(DTPData dtpData)
        {
            var lstDocumentsToSign = dtpData.DocumentsToSign;
            var signatoryRole = dtpData.SignatureRole;

            //Patterns
            var signatureFieldPattern = "%BEGIN% label:\"%SIGNATURE_FIELD_LABEL%\", layout:\"layoutHandwriting\" %END% ";
            var documentPattern = "%BEGIN% id: \"contract{0}\", type: \"{1}\", label: \"{2}\", description: \"{3}\", requirement: \"read\", signature_fields: [{4}] %END%"; //{ <=> %BEGIN% ; } <=> %END%
            
            var lstDocumentsOk = new List<string>();
           
            for (int i = 0; i<lstDocumentsToSign.Count; i++)
            {
                var documentToSign = lstDocumentsToSign[i];

                //json signatureFields for each document
                var lstSignatureFieldsOk = new List<string>();
                var lstSignatureFieldLabels = documentToSign.SignatureParameters.Where(sp => sp.SignatoryRole == signatoryRole).Select(sp => sp.SignatureFieldLabel).ToList();

                if (lstSignatureFieldLabels.Count == 0 || string.IsNullOrEmpty(signatoryRole))
                {
                    //prendre le FieldLabel donné dans dptData
                    lstSignatureFieldLabels = dtpData.SignatureFieldLabels;
                }

                foreach (var fieldLabel in lstSignatureFieldLabels)
                {
                    var itemLabel = signatureFieldPattern.Replace("%SIGNATURE_FIELD_LABEL%", fieldLabel);
                    lstSignatureFieldsOk.Add(itemLabel);
                }
                var signatureFieldsOk = string.Join(",", lstSignatureFieldsOk.ToArray());

                //json document
                var itemDoc = string.Format(documentPattern, i, documentToSign.Type, documentToSign.Label, string.Empty, signatureFieldsOk);
                lstDocumentsOk.Add(itemDoc);
            }

            var documentsOk = string.Join(",", lstDocumentsOk.ToArray());
            documentsOk = documentsOk.Replace("%BEGIN%", "{").Replace("%END%", "}");

            return documentsOk.ToString();
        }
예제 #2
0
        public void CreateUserSpace(DTPData dtpData)
        {
            //UserSpace filename
            string userSpaceFilename = "UserSpace.json";
            
            if (!string.IsNullOrEmpty(dtpData.Language) && dtpData.Language != "FR")
            {
                userSpaceFilename = string.Format("UserSpace_{0}.json", dtpData.Language.ToUpper()); //eg : UserSpace_EN.json
            }

            //Contact
            Contact contact = new Contact()
            {
                fullname = string.Format("{0} {1}", dtpData.UserLastname, dtpData.UserFirstname),
                mail = dtpData.UserEmail,
            };

            createUserSpaceRequest createUserSpaceRequest = new createUserSpaceRequest()
            {
                attributes = ConfigFileHelper.ReadFromFile(userSpaceFilename)
                                             .Replace("%USER_SPACE_LABEL%", dtpData.UserSpaceTitle),
                contact = contact,
                login = dtpData.Login,
                password = "******" ,
                tenant = _Tenant.TenantName,
            };
                        
            _UserSpacePortClient.create(createUserSpaceRequest);
        }
예제 #3
0
        public void CreateUserSpaceContent(DTPData dtpData)
        {
            string contentFilename = "Content.json";

            //Language ?
            if (!string.IsNullOrEmpty(dtpData.Language) && dtpData.Language != "FR")
            {
                contentFilename = string.Format("Content_{0}.json", dtpData.Language.ToUpper()); //eg : Content_EN.json
            }
            
            //Json for documents is generated dynamically
            string documentsToSignStruct = BuildDocumentToSignJson(dtpData);

            createContentRequest createContentRequest = new createContentRequest()
            {
                attributes = ConfigFileHelper.ReadFromFile(contentFilename)
                                             .Replace("%DOCUMENTS_TO_SIGN_STRUCT%", documentsToSignStruct)
                                             .Replace("%USER_ACCESS_ID%", dtpData.UserAccessId)
                                             //.Replace("%SIGNATURE_FIELD_LABEL%", dtpData.SignatureFieldLabel) //TODO
                                             .Replace("%CG_FILE_NAME%", dtpData.CGFileName)
                                             .Replace("%OTP_USER_MOBILE%", dtpData.UserMobile),
                id = dtpData.OfferId,
                login = dtpData.Login,
                tenant = _Tenant.TenantName,
            };
                 
            _ContentPortClient.create(createContentRequest);        
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignConfidentialityAgreementByAdviser(Guid idCustomer, string docToSignPathFileName, Upsilab.Data.Model.User userAdviser)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.CustomerProspect customer = (from cust in context.CustomerProspect.Include("ConfidentialityAgreement").Include("User").Include("User1")
                                                                where cust.idCustomer == idCustomer
                                                                select cust).FirstOrDefault();

                if (customer == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_customer"));
                }

                Upsilab.Data.Model.ConfidentialityAgreement confident = customer.ConfidentialityAgreement;

                if (confident == null)
                {
                    confident = new Upsilab.Data.Model.ConfidentialityAgreement()
                    {
                        idConfidentialityAgreement = Upsilab.Business.Utility.GuidHelper.GenerateGuid(),
                        Status = ReportBL.Status.InProgress.ToString(),
                        DateCreated = DateTime.Now,
                        SignedByCustomer = false,
                        SignedByAdviser = false,
                        Archived = false
                    };

                    context.ConfidentialityAgreement.Attach(confident);
                    context.ObjectStateManager.ChangeObjectState(confident, System.Data.EntityState.Added);

                    customer.idConfidentialityAgreement = confident.idConfidentialityAgreement;
                }

                //Check if already signed by adviser
                if (confident.SignedByAdviser)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_ec_signed"));
                }

                // Data needed
                string businessId = string.Format("{0}-{1}", CONFIDENTIALITY_AGREEMENT, idCustomer);
                string backUrl = string.Format("{0}/User/Signature/RetourSignatureEngagementParConseiller{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 8,
                        X = 28,
                        Y = 85,
                    }
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 8,
                        X = 114,
                        Y = 85,
                    }
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_ec_title"),
                    Description = LanguageContentBL.Translate("signature_ec_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = confident.idDictao,
                    UserAccessId = confident.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_ADVISER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_ec_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // Check if already signed by customer, if not, the adviser signs the doc first.
                if (!confident.SignedByCustomer)
                {
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(userAdviser, dtpData);

                    //Save transaction Id to table
                    confident.idDictao = dtpData.TransactionId;
                    confident.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(userAdviser, dtpData);

                    confident.idDTPUserAccess = dtpData.UserAccessId;
                }

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
예제 #5
0
        /// <summary>
        /// Send OTP
        /// </summary>
        /// <param name="accessId"></param>
        /*public void SendOtp(string accessId)
        {            
            sendOtp s = new sendOtp()
            {
                accessId = accessId
            };

            _TransactionPortClient.sendOtp(s);
        }*/

        /// <summary>
        /// Build the user interface url : to access the IHM sign page
        /// </summary>
        /// <param name="accessId"></param>
        /// <returns></returns>
        public string BuildUserInterfaceUrl(DTPData dtpData)
        {
            string urlIHM = _Tenant.DTPwcs_euapp_Url;
            urlIHM = string.Format("{0}offre/{1}/convention?login={2}&url={3}", urlIHM, dtpData.OfferId, dtpData.Login, dtpData.BackUrl); //Multioffre ?
            //urlIHM = string.Format("{0}?login={2}&url={3}", urlIHM, offerId, login, backUrl);

            return urlIHM;
        }
        private static DTPData GetUserInfos(Upsilab.Data.Model.User user, DTPData dtpData)
        {
            //User info
            dtpData.UserEmail = user.UserEmail;
            dtpData.UserLastname = user.UserName;
            dtpData.UserFirstname = user.UserFirstName;
            dtpData.UserMobile = user.UserMobilePhone;
            dtpData.IsEndUser = user.IsEndUser();

            //CG file
            dtpData.CGFileName = (dtpData.IsEndUser) ? "CG_client_final.pdf" : "CG_conseiller.pdf";

            if (ConfigurationManager.ExtranetHostCode == "BE")
            {
                dtpData.CGFileName = string.Format("BE_{0}", dtpData.CGFileName);
            }

            return dtpData;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignReportByCustomer(Guid idReport, string docToSignPathFileName, int pageCount)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.Report report = (from rep in context.Report.Include("CustomerProspect")
                                                    where rep.idReport == idReport
                                                    select rep).FirstOrDefault();

                if (report == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_doc"));
                }

                // Check if already signed by customer
                if (report.SignedByCustomer)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_doc_signed_by_customer"));
                }

                // Check if Firm has sufficient credit to send doc to coffre fort
                

                // Data needed
                string businessId = string.Format("{0}-{1}", REPORT, idReport);
                Upsilab.Data.Model.CustomerProspect customer = report.CustomerProspect;
                string backUrl = string.Format("{0}/Client/Signature/RetourSignatureRecueilParClient{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                bool isPP = (customer.IsCorporation.HasValue) ? ((customer.IsCorporation.Value) ? false : true) : false;
                
                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,
                    SignaturePosition = new SignaturePosition(pageCount, true)
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,
                    SignaturePosition = new SignaturePosition(pageCount, false)
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_report_title"),
                    Description = LanguageContentBL.Translate("signature_report_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = report.idDictao,
                    UserAccessId = report.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string>() { DTPClient.USER_CUSTOMER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_report_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // Check if already signed by adviser, if not, the customer signs the doc first.
                if (!report.SignedByAdviser)
                {                    
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(customer.User, dtpData);

                    //Save transaction Id to table
                    report.idDictao = dtpData.TransactionId;
                    report.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(customer.User, dtpData);
                    
                    //Save userAccess Id to table                    
                    report.idDTPUserAccess = dtpData.UserAccessId;
                }

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <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;
        }
        /// <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;
        }
        public static string SignDocument(Guid idSignatory)
        {
            using (UpsilabEntities db = new UpsilabEntities())
            {
                var currentSignatory = (from sign in db.Signatory//.Include("User")
                                        where sign.idSignatory == idSignatory
                                        select sign).FirstOrDefault();

                var lstFieldLabelsCurrentSignatory = new List<string>();

                if (currentSignatory == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_not_allowed_to_sign"));
                }

                // Check if already signed by user
                if (currentSignatory.DateSignature.HasValue)
                {
                    throw new Exception(string.Format(LanguageContentBL.Translate("signature_doc_signed_on"), currentSignatory.DateSignature.Value.ToShortDateString()));
                }

                //Liste des signataires
                SignatureTransaction signatureTransaction = (from signTrans in db.SignatureTransaction
                                                                                //.Include("Signatory")
                                                                                //.Include("Document")
                                                                                //.Include("Document.DocumentSignatory")
                                                                                //.Include("Document.DocumentModel")
                                                                  where signTrans.idSignatureTransaction == currentSignatory.idSignatureTransaction
                                                                  select signTrans).FirstOrDefault();
              
                // Data needed
                //1- Business Id
                string businessId = string.Format("{0}-{1}", DOCUMENT, currentSignatory.idSignatureTransaction);
                
                //2- back Url
                string backUrl = string.Format("{0}/Signature/RetourSignatureDocument{1}", Upsilab.Business.Utility.UrlHelper.GetSiteUrl(), DTPClient.GET_Variables); //TODO : User ??
                
                //3- List of documents to sign
                var documentsToSign = new List<DocumentToSign>();

                // Document different from documentType = DOC (This type of document is only to send to "coffre fort" not to sign)
                // And document which have config signatory : page, x, y...
                var docDocType = ElectronicSafeDocumentBL.DocumentType.DOC.ToString();

                var documents = (from doc in signatureTransaction.Document
                                 where doc.DocumentType != docDocType && doc.DocumentSignatory.Count > 0
                                 select doc).ToList();

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

                // Check if there is a document to sign
                if (documents.Count == 0)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_no_doc"));
                }

                for (int i = 0; i < documents.Count; i++)
                {
                    List<SignatureParameter> signatureParameters = new List<SignatureParameter>();
                    bool isSignParamsFromFile = false;
                    var document = documents.ElementAt(i);
                    var documentModel = document.DocumentModel;

                    if (document.GeneratedFromModel) //Doc generated from model
                    {
                        //Dans certains cas, les parametres de signature sont donnés sur un fichier json par rapport au modele de document
                        if (documentModel != null)
                        {
                            var jsonSignParams = Upsilab.Business.Sdg.DocumentModelFileBL.GetSignatureParametersContentFromFile(documentModel);
                            signatureParameters = SignatureParameter.JsonToSignatureParameters(jsonSignParams);

                            if (signatureParameters.Count > 0)
                            {
                                isSignParamsFromFile = true;
                            }
                        }
                    }

                    //Position de la zone de signature de chaque signataire sur le document
                    foreach (var signataire in signatureTransaction.Signatory)
                    {

                        //Signature fieldLabel
                        var signatureFieldLabel = string.Format("{0}-{1}", DTPClient.USER, signataire.idSignatory);

                        if (isSignParamsFromFile) //just update "SignatureFieldLabel"
                        {
                            var signatoryRole = signataire.Role;
                            var j = 0;
                            signatureParameters.Where(sp => sp.SignatoryRole == signatoryRole).ToList().ForEach(sp =>
                                {
                                    //Differencier par un compteur les fieldLabes
                                    sp.SignatureFieldLabel = string.Format("{0}-{1}", signatureFieldLabel, j);
                                    j++;
                                });
                        }
                        else //Create the signatureParameter //TODO : if many fields for defined manually
                        {
                            var documentSignatories = signataire.DocumentSignatory.Where(ds => ds.idDocument == document.idDocument).ToList(); //Liste des zones de signature du signataire
                            var j = 0;

                            documentSignatories.ForEach(documentSignatory =>
                            {
                                var x = documentSignatory.X;
                                var y = documentSignatory.Y;
                                var height = documentSignatory.Height;
                                var width = documentSignatory.Width;

                                //NB : les valeurs provenant de la BD est en "pixel", convertir en "mm" pour dictao ? 
                                //=> pour les documents dont on a defini manuellement les zones
                                //=> pas de conversion pour les documents automatiques
                                if (!document.GeneratedFromModel) //zones de signature definies manuellement
                                {
                                    x = ConverPixelToMillimeter(x);
                                    y = 297 - ConverPixelToMillimeter(height) - ConverPixelToMillimeter(y); //297 <=> height A4 ?
                                    width = ConverPixelToMillimeter(width);
                                    height = ConverPixelToMillimeter(height);
                                }

                                SignatureParameter signatureParameter = new SignatureParameter()
                                {
                                    //SignatureFieldLabel = signatureFieldLabel,
                                    SignatureFieldLabel = string.Format("{0}-{1}", signatureFieldLabel, j),
                                    SignatoryRole = signataire.Role,

                                    SignaturePosition = new SignaturePosition()
                                    {
                                        Page = documentSignatory.Page,
                                        X = x,
                                        Y = y,
                                        Width = width,
                                        Height = height
                                    }
                                };

                                signatureParameters.Add(signatureParameter);
                                j++;
                            }
                            );
                        }

                    }
                    

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

                    //Label of the document to send to DICTAO ?
                    //Particular case for AVENANT : get the document name
                    var label = (string.IsNullOrEmpty(document.Status)) ? LanguageContentBL.Translate("signature_doc_title") : LanguageContentBL.Translate(document.DocumentType.ToLower());

                    var avenantDocumentTypes = DocumentSignatureTransactionBL.GetDocumentTypes(DocumentSignatureTransactionBL.SignatureTransactionType.AVENANT);

                    if (avenantDocumentTypes.Contains(document.DocumentType))
                    {
                        label = document.Designation;
                    }
                  
                    DocumentToSign doc = new DocumentToSign()
                    {
                        Label = label,
                        Description = label,
                        PathFilename = FileManager.GetFileFromUploadDirectory(document.Location, document.Name),
                        Type = dtpDocType,
                        SignatureParameters = signatureParameters
                    };

                    documentsToSign.Add(doc);

                    //List des signatureFields for currentSignatory
                    signatureParameters.ForEach(sp => 
                    {
                        if (sp.SignatoryRole == currentSignatory.Role)
                        {
                            if (!lstFieldLabelsCurrentSignatory.Contains(sp.SignatureFieldLabel))
                            {
                                lstFieldLabelsCurrentSignatory.Add(sp.SignatureFieldLabel);
                            }
                        }
                    });

                }
                                                
                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = currentSignatory.SignatureTransaction.idDTPTransaction,
                    UserAccessId = currentSignatory.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = lstFieldLabelsCurrentSignatory,//new List<string> { string.Format("{0}-{1}", DTPClient.USER, currentSignatory.idSignatory) }, //Exemple : USER-00000-00000-...
                    SignatureRole = currentSignatory.Role,
                    UserSpaceTitle = LanguageContentBL.Translate("signature_doc_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

               //User info ?
                var user = currentSignatory.User;
                if (user == null)
                {
                    user = new Data.Model.User()
                    {
                        UserName = currentSignatory.Name,
                        UserFirstName = !string.IsNullOrEmpty(currentSignatory.Firstname) ? currentSignatory.Firstname : " ", //TODO : test
                        UserMobilePhone = currentSignatory.Mobile,
                        UserEmail = currentSignatory.Email,

                        idUser = Guid.Empty,
                        idUserProfile = 7,
                        UserPassword = string.Empty,
                        DateCreated = DateTime.Now,
                    };
                }

                // Check if any users has signed first. if not, he signs first
                var anySignatoryHasSigned = signatureTransaction.Signatory.Where(sign => sign.DateSignature.HasValue).FirstOrDefault();

                if (anySignatoryHasSigned == null)
                {
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(user, dtpData);

                    //Save transaction Id to table
                    signatureTransaction.idDTPTransaction = dtpData.TransactionId;
                    currentSignatory.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(user, dtpData);

                    //Save userAccess Id to table                    
                    currentSignatory.idDTPUserAccess = dtpData.UserAccessId;
                }

                db.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idReport"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignCRTOByAdviser(Guid idCustomer, string docToSignPathFileName, Upsilab.Data.Model.User userAdviser)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                var customer = context.CustomerProspect.FirstOrDefault(x => x.idCustomer == idCustomer);

                //Add new CRTO
                var crto = new Upsilab.Data.Model.ConventionRTO()
                {
                    idConventionRTO = Upsilab.Business.Utility.GuidHelper.GenerateGuid(),
                    IdCustomerProspect = idCustomer,
                    Status = ReportBL.Status.InProgress.ToString(),
                    SignedByCustomer = false,
                    SignedByAdviser = false,
                    Archived = false,
                    DatesSendMailToCustomer = DateTime.Now.ToString("dd/MM/yyyy"),
                    DateCreated = DateTime.Now,
                    DateUpdated = DateTime.Now,
                };

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

                //Update idConvention customer
                customer.idConventionRTO = crto.idConventionRTO;

                // Data needed
                string businessId = string.Format("{0}-{1}", CONVENTION_RTO, idCustomer);
                string backUrl = string.Format("{0}/User/Signature/RetourSignatureCRTOParConseiller{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                SignatureParameter signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_ADVISER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 4, //TODO
                        X = 34,
                        Y = 178,
                    }
                };

                signatureParameters.Add(signatureParameter);

                signatureParameter = new SignatureParameter()
                {
                    SignatureFieldLabel = DTPClient.USER_CUSTOMER,

                    SignaturePosition = new SignaturePosition()
                    {
                        Page = 4, //TODO
                        X = 120,
                        Y = 178,
                    }
                };

                signatureParameters.Add(signatureParameter);

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_crto_title"),
                    Description = LanguageContentBL.Translate("signature_crto_title"),
                    PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = crto.idDictao,
                    UserAccessId = crto.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_ADVISER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_crto_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                //Sign document :  adviser always sign first
                dtpData = SignatureDocumentBL.SignByFirstUser(userAdviser, dtpData);

                //Save transaction Id to table
                crto.idDictao = dtpData.TransactionId;
                crto.idDTPUserAccess = dtpData.UserAccessId;

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idCustomer"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignCRTOByCustomer(Guid idCustomer)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                var latestCRTO = (from crto in context.ConventionRTO.Include("CustomerProspect_1.User")
                                 where crto.IdCustomerProspect == idCustomer && crto.SignedByAdviser && !crto.Archived
                                 orderby crto.DateUpdated descending
                                 select crto).FirstOrDefault();

                if (latestCRTO == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_customer"));
                }

                // Check if already signed by customer
                if (latestCRTO.SignedByCustomer)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_crto_signed"));
                }

                // Data needed
                string businessId = string.Format("{0}-{1}", CONVENTION_RTO, latestCRTO.idConventionRTO);
                string backUrl = string.Format("{0}/Client/Signature/RetourSignatureCRTOParClient{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                List<SignatureParameter> signatureParameters = new List<SignatureParameter>();

                //Document to sign
                DocumentToSign doc = new DocumentToSign()
                {
                    Label = LanguageContentBL.Translate("signature_crto_title"),
                    Description = LanguageContentBL.Translate("signature_crto_title"),
                    //PathFilename = docToSignPathFileName,
                    Type = DTPClient.DocumentTypes.CONTRACT.ToString(),
                    SignatureParameters = signatureParameters
                };

                List<DocumentToSign> documentsToSign = new List<DocumentToSign>() { doc };

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = latestCRTO.idDictao,
                    UserAccessId = latestCRTO.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_CUSTOMER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_crto_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // CRTO is signed secondly by customer
                dtpData = SignatureDocumentBL.SignBySecondUser(latestCRTO.CustomerProspect_1.User, dtpData);
                latestCRTO.idDTPUserAccess = dtpData.UserAccessId;
                
                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idDER"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <param name="userAdviser"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignDERByAdviser(Guid idDER, List<DocumentToSign> documentsToSign, Upsilab.Data.Model.User userAdviser)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.DER derDoc = (from der in context.DER.Include("CustomerProspect.FirmInstitution")
                                                where der.idDer == idDER
                                                select der).FirstOrDefault();

                if (derDoc == null)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_select_doc"));
                }

                //Check if already signed by adviser
                if (derDoc.SignedByAdviser)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_doc_signed_by_adviser"));
                }

                // Data needed
                string businessId = string.Format("DER-{0}", derDoc.idDer);
                string backUrl = string.Format("{0}/User/Signature/RetourSignatureDERParConseiller{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = derDoc.idDictao,
                    UserAccessId = derDoc.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_ADVISER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_der_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                // Check if already signed by customer, if not, the adviser signs the doc first.
                if (!derDoc.SignedByCustomer)
                {
                    //Sign document
                    dtpData = SignatureDocumentBL.SignByFirstUser(userAdviser, dtpData);

                    //Save transaction Id to table
                    derDoc.idDictao = dtpData.TransactionId;
                    derDoc.idDTPUserAccess = dtpData.UserAccessId;
                }
                else
                {
                    dtpData = SignatureDocumentBL.SignBySecondUser(userAdviser, dtpData);
                    derDoc.idDTPUserAccess = dtpData.UserAccessId;
                }

                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idDER"></param>
        /// <param name="docToSignPathFileName"></param>
        /// <returns>The url to access the signature page</returns>
        public static string SignDERByCustomer(Guid idDER, List<DocumentToSign> documentsToSign, int pageCount = 0)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                Upsilab.Data.Model.DER derDoc = (from der in context.DER.Include("CustomerProspect")
                                                 where der.idDer == idDER
                                                 select der).FirstOrDefault();

                if (derDoc == null)
                {
                    //throw new Exception(SignatureExceptionCode.DataMissingInDB.ToString());
                    throw new Exception(LanguageContentBL.Translate("signature_select_doc"));
                }

                // Check if already signed by customer
                if (derDoc.SignedByCustomer)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_doc_signed_by_customer"));
                }

                // Check if already signed by adviser : client signs secondly
                if (!derDoc.SignedByAdviser)
                {
                    throw new Exception(LanguageContentBL.Translate("signature_doc_notyet_signed_by_adviser"));
                }

                // Data needed
                string businessId = string.Format("DER-{0}", idDER);
                Upsilab.Data.Model.CustomerProspect customer = derDoc.CustomerProspect;
                string backUrl = string.Format("{0}/Client/Signature/RetourSignatureDERParClient{1}", Upsilab.Business.Utility.UrlHelper.GetHost(), DTPClient.GET_Variables);

                //DTP Data
                DTPData dtpData = new DTPData()
                {
                    TransactionId = derDoc.idDictao,
                    UserAccessId = derDoc.idDTPUserAccess,
                    BusinessId = businessId,
                    BackUrl = backUrl,
                    DocumentsToSign = documentsToSign,
                    SignatureFieldLabels = new List<string> { DTPClient.USER_CUSTOMER },
                    UserSpaceTitle = LanguageContentBL.Translate("signature_der_sign_title"),
                    Language = SessionManager.GetCurrentLanguage().LanguageTypeName,
                };

                dtpData = SignatureDocumentBL.SignBySecondUser(customer.User, dtpData);

                //Save userAccess Id to table                    
                derDoc.idDTPUserAccess = dtpData.UserAccessId;
                context.SaveChanges();

                return dtpData.IHM_Url;
            }
        }