source: prototipo_portal_2018/prototipo/static/js/functions/firmarDocumentoPdf.js @ 025e022

Last change on this file since 025e022 was 025e022, checked in by José Sulbarán <jsulbaran@…>, 7 years ago

SE comenzo agregar la firma y se mejoro los reportes

  • Property mode set to 100644
File size: 7.9 KB
Line 
1
2function True_False(data){
3
4    if (data == "true" ){
5      return "Verdadero";
6    }
7    if (data ==  "false"){
8      return "Falso";
9    }
10
11}
12
13function SerealizeMyJson(data){
14  for (var i = 0; i < data.signatures.length; i++) {
15      data.signatures[i].integrityCheck = True_False(data.signatures[i].integrityCheck);
16      data.signatures[i].signerCertificateStillValid = True_False(data.signatures[i].signerCertificateStillValid);
17      data.signatures[i].signerCertificateValidAtTimeOfSigning = True_False(data.signatures[i].signerCertificateValidAtTimeOfSigning);
18      data.signatures[i].signatureCoversWholeDocument = True_False(data.signatures[i].signatureCoversWholeDocument);
19      data.signatures[i].certificatesVerifiedAgainstTheKeyStore = True_False(data.signatures[i].certificatesVerifiedAgainstTheKeyStore);         
20  }
21  return data;
22}
23
24
25//Obtenemos la  informacion de documento
26function InfoDocumentDataTablePDF(signedFileId){
27
28    $.ajax({
29        url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/"+signedFileId,
30        type: "get",
31        dataType: "json",       
32        headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
33        success: function(response) {
34               
35            INFO_DATATABLE = SerealizeMyJson(response);
36                       
37                        CONT += 1;
38                        if (CONT == 1){
39                                DATATABLE_SIGN_VISIBLE = DataTablePDF(response);       
40                        }
41                        if (CONT > 1){
42                                DATATABLE_SIGN_VISIBLE.destroy();
43                                DATATABLE_SIGN_VISIBLE = DataTablePDF(response);       
44                        }       
45
46                        $('#myJson_wrapper').show();
47        },
48        error: function(jqXHR, textStatus, errorThrown){
49                alert(textStatus+", "+ errorThrown+" el documento PDF para mostrar la info de la sign");     
50        }
51        });
52}
53
54
55// Cuarto paso (Se envia la información del token para terminar la firma)
56function FinalizarFirma(signature){
57
58        $.ajax({
59                type: 'POST',
60                contentType: 'application/json',
61                //url:"https://192.168.12.125:8443/Murachi/0.1/archivos/pdfs/resenas",
62                url:"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/pdfs/resenas",
63                dataType: 'json',
64                data: JSON.stringify({"signature":signature}),
65                xhrFields: {withCredentials: true},
66                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
67                success: function(data, textStatus, jqXHR){
68
69                        alert('Archivo firmado correctamente: ' + data['signedFileId']);
70                        var linkToDownload = "<a href=\"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/descargas/" + data['signedFileId'] +"\">descargar archivo firmado</a>";
71                        //alert(linkToDownload);
72                        document.getElementById("respuesta").innerHTML = linkToDownload;       
73                        $("#firmar-documento").hide();
74                        $("#pdf-main-container").hide();
75                       
76                        InfoDocumentDataTablePDF(data['signedFileId']);         
77
78                },
79                error: function(jqXHR, textStatus, errorThrown){
80                        alert('error en pdfs/resenas: ' + textStatus);
81                        $("#respuesta").html("error en pdfs/resenas: " + textStatus);
82                }
83        });
84
85}
86
87
88//Tercer paso (Obtenemos el hash de pdf enviado por el servidor y luego procesa la información en el token)
89function ObtenerHashPDFServer(parameters,cert){
90
91        $.ajax({
92                type: 'POST',
93                contentType: 'application/json',                               
94                //url:"https://192.168.12.125:8443/Murachi/0.1/archivos/pdfs",
95                url:"https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/pdfs",
96                dataType: "json",
97                data: parameters,               
98                xhrFields: {withCredentials: true},
99                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
100                success: function(data, textStatus, jqXHR){
101                        var json_x = data;
102                        var hash = json_x['hash']; 
103                        //alert("hash recibido del servidor "+hash);           
104                        var hashtype = "SHA-256";
105                        var lang = "eng";
106                       
107                        //Procesa la información
108                        window.hwcrypto.sign(cert, {type: hashtype, hex: hash}, {lang: lang}).then(
109                                function(signature) {
110                                        FinalizarFirma(signature.hex);
111                        }, 
112                        function(err) {
113                                log_text("sign() failed: " + err);
114                                        var error;
115                    log_text("sign() failed: " + err);
116                    if(err == "Error: user_cancel") {
117                        alert("sign() failed: El usuario cancelo la operación");
118                        error = "El usuario cancelo la operación"; 
119                     }     
120                     else if(err == "Error: no_certificates") {
121                         alert("sign() failed: No hay certificado disponible");
122                         error = "No hay certificado disponible";
123                     }
124                     else if(err == "Error: no_implementation") {
125                         alert("sign() failed: No hay soporte para el manejo del certificado");
126                         error = "No hay soporte para el manejo del certificado";
127                     }
128
129                                //alert("sign() failed: " + err);
130                                $("#respuesta").html("sign() failed: " + error);
131                });
132                       
133                },                                                             
134                error: function(jqXHR, textStatus, errorThrown){
135                        //alert('error: ' + textStatus);
136                        //var responseText = jQuery.parseJSON(jqXHR.responseText);
137                        alert('ajax error function: ' + jqXHR.responseText);
138                        $("#respuesta").html("error function: " + jqXHR.responseText);
139                }
140               
141        });
142               
143}
144
145
146//Segundo paso (Seleccionamos el Certificado Firmante)
147function ObtenerCertificadoFirmante(response){
148
149        // identificador del archivo en el servidor
150        var fileId = response.fileId.toString();
151        var cert;
152
153        window.hwcrypto.getCertificate({lang: "en"}).then(
154                function(response) {
155                        var cert = response;
156                        var parameters = "";
157
158                        if (FIRMA_VISIBLE == true){             
159                                parameters = JSON.stringify({
160                                        "fileId":fileId,
161                                        "certificate":cert.hex,
162                                        "reason":"Certificado",
163                                        "location":"CENDITEL",
164                                        "contact":"582746574336",
165                                        "signatureVisible":"true"
166                                        //"page": VALOR_PAGE,
167                                        //"coord_x": VALOR_X,
168                                        //"coord_y": VALOR_Y
169                                        });
170                        }
171                        else{
172                                parameters = JSON.stringify({
173                                        "fileId":fileId,
174                                        "certificate":cert.hex,
175                                        "reason":"Certificado",
176                                        "location":"CENDITEL",
177                                        "contact":"582746574336",
178                                        "signatureVisible":"true"
179                                        });                             
180                        }
181                        // ahora llamar al ajax de obtener la resena del pdf
182                        ObtenerHashPDFServer(parameters, cert); 
183
184                }, 
185                function(err) {
186                        log_text("getCertificate() failed: " + err);
187            var error;
188            if(err == "Error: user_cancel") {
189                alert("getCertificate() failed: El usuario cancelo la operación"    );
190                error = "El usuario cancelo la operación"; 
191             }     
192             else if(err == "Error: no_certificates") {
193                 alert("getCertificate() failed: No hay certificado disponible")    ;
194                 error = "No hay certificado disponible";
195             }
196             else if(err == "Error: no_implementation") {
197                 alert("getCertificate() failed: No hay soporte para el manejo del certificado");
198                 error = "No hay soporte para el manejo del certificado";
199                        }
200                        //alert("getCertificate() failed: " + err);
201                        $("#respuesta").html("getCertificate() failed: " + error);
202                }
203
204        );
205}
206
207
208
209
210// Primer paso (Subir el documento al servidor)
211function SubirDocumentServer(formData){
212
213    $.ajax({
214        //url: "https://192.168.12.125:8443/Murachi/0.1/archivos",               
215        url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos",
216        type: "post",
217        dataType: "json",
218        data: formData,
219        cache: false,
220        contentType: false,
221                processData: false,
222                xhrFields: {withCredentials: true},
223                headers: {"Authorization":"Basic YWRtaW46YWRtaW4="},
224                success: function(response) {
225
226                        document.getElementById("respuesta").innerHTML = manejoJsonPDF(JSON.stringify(response));       
227                        ObtenerCertificadoFirmante(response);
228        },
229        error: function(response) {
230                //Que se ejecuta cuando finalice la petición de con error
231                        $("#respuesta").html('Error, al subir el archivo al servidor...!!!');
232                alert("ocurrio un error, al subir el archivo al servidor")
233                }
234    });
235
236}
237
238
239$("#Form-Format-Visible").on('submit', function(event) {
240        event.preventDefault();
241
242        var formData = new FormData(); 
243    formData.append("upload", $("#file-sign-ft_Vble")[0].files[0]);     
244       
245        $('#myJson').hide();
246        FIRMA_VISIBLE = true;
247        SubirDocumentServer(formData);
248       
249});
Note: See TracBrowser for help on using the repository browser.