Changes in / [bc3aa92:d9b20e6] in firmaeventos


Ignore:
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • base/templates/base.vars.javascript.html

    r5d88f36 r452668a  
    99    // URL para comprobar si el firmante es el último
    1010    var URL_ULTIMO_FIRMANTE = "{% url 'participantes:participante_restante_evento_nid' %}";
     11   
     12    // URL para comprobar si el documento esta siendo firmado
     13    var URL_COMPROBAR_FIRMA = "{% url 'events:comprobar_evento_nid' %}";
     14
    1115           
    1216</script>
  • eventos/forms.py

    rbc3aa92 rbc3aa92  
    3939             'readonly':
    4040             'readonly'})
    41         self.fields['archivo'].required = True
     41        self.fields['archivo'].required = False
    4242        self.fields['archivo'].widget.attrs.update(
    4343            {'class': 'file-path validate',
     
    4545             'accept': '.pdf'})
    4646        self.fields['pos_x'].widget = forms.HiddenInput()
     47        self.fields['pos_x'].required=False
    4748        self.fields['pos_y'].widget = forms.HiddenInput()
     49        self.fields['pos_y'].required=False
    4850        self.fields['pag'].widget = forms.HiddenInput()
     51        self.fields['pag'].required=False
     52
    4953
    5054class FirmaEventoForm(forms.Form):
  • eventos/models.py

    r5d88f36 reb2672b  
    1313    nombre_evento = models.CharField(max_length=128, unique=True)
    1414    fecha = models.DateField(null=False)
    15     serial = models.CharField(max_length=128)
    16     pos_x = models.CharField(max_length=32)
    17     pos_y = models.CharField(max_length=32)
    18     pag = models.CharField(max_length=4)
     15    serial = models.CharField(max_length=128,null=True)
     16    pos_x = models.CharField(max_length=32,null=True)
     17    pos_y = models.CharField(max_length=32,null=True)
     18    pag = models.CharField(max_length=4,null=True)
    1919    activo = models.BooleanField(default=True)
    2020    procesando = models.BooleanField(default=False)
  • eventos/templates/evento.detail.html

    r5d88f36 reb2672b  
    5252    </div>
    5353    <div class="center">
    54         <iframe width="700px" height="600px" src="https://192.168.12.154:8443/Murachi/0.1/archivos/listadopdf/{{object.serial}}">';
     54        {% if object.serial %}
     55        <iframe width="700px" height="600px" src="https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/listadopdf/{{object.serial}}">';
    5556        </iframe>
     57        {% else %}
     58            <h4 class="red-text">No cargó ningun documento</h4>
     59        {% endif %}
    5660    </div>
    5761    <div class="row">
  • eventos/templates/evento.list.html

    r5d88f36 r974a9c3  
    2424                    <i class="material-icons left">search</i> Detalle
    2525                </a>
     26                {% if evento.serial %}
    2627                <a type="button" class="btn waves-effect blue darken-1" href="{% url 'events:firma_events' evento.id %}">
    2728                    <i class="material-icons left">mode_edit</i> Firmar
    2829                </a>
     30                {% else %}
     31                <a type="button" class="btn waves-effect blue darken-1" href="{% url 'events:update_evento' evento.id %}">
     32                    <i class="material-icons left">backup</i> Cargar Documento
     33                </a>
     34                {% endif %}
    2935            </div>
    3036        </div>
  • eventos/templates/evento.update.html

    rbc3aa92 rbc3aa92  
    1515{% block content %}
    1616    <div class="content">
     17        {% if object.serial %}
     18        <div class="center">
     19          <h5 class="center">El evento {{object.nombre_evento}}, ya contiene un documento</h5><hr/><br>
     20          <iframe width="700px" height="600px" src="https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/listadopdf/{{object.serial}}">';
     21          </iframe>
     22        </div>
     23        {% else %}
    1724        <h5 class="center">Cargar Archivo al Evento</h5><hr/><br>
    1825        <form id="form" method="post" enctype="multipart/form-data">
     
    6572            </div>
    6673        </form>
     74        {% endif %}
    6775    </div>
    6876{% endblock %}
  • eventos/urls.py

    rbc3aa92 rbc3aa92  
    1414    url(r'^detail-evento/(?P<pk>\d+)$', DetailEvent.as_view(),
    1515        name='detail_event'),
     16    url(r'^comprobar-evento/(?P<event_id>\d+)$', EventoProcesado.as_view(),
     17        name='comprobar_evento'),
    1618    url(r'^comprobar-evento/$', EventoProcesado.as_view(),
    17         name='comprobar_evento'),
     19        name='comprobar_evento_nid'),
     20    url(r'^actualizar-evento/(?P<event_id>\d+)$', UpdateFileEvent.as_view(),
     21        name='update_evento'),
    1822]
  • eventos/views.py

    rbc3aa92 rbc3aa92  
    1010from django.core.urlresolvers import reverse_lazy
    1111from django.http import JsonResponse
     12from django.utils.decorators import method_decorator
     13from django.views.decorators.csrf import csrf_exempt
    1214from django.shortcuts import (
    1315    redirect
     
    6062
    6163    def post(self, request, *args, **kwargs):
    62         file =  request.FILES['file']
    63         handle_uploaded_file(request.FILES['file'], file)
    64         ruta = '%s/%s' % (settings.TMP, file)
    65         file = open(ruta, 'rb')
    66         files = {'file': file}
    67         try:
    68             r = requests.post('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/cargar', verify=False, headers={'Authorization': 'Basic YWRtaW46YWRtaW4='}, files=files)
    69             nuevo_participante = self.form_participante(request.POST)
    70             consulta_api = r.json()['fileId']
    71             # elimina el archivo si fue creado en la carpeta tmp
    72             file.close()
    73             os.unlink(ruta)
    74         except Exception as e:
    75             print (e)
    76             file.close()
    77             os.unlink(ruta)
    78             messages.error(self.request, "Error al concetar al servidor y subir\
    79                                           el archivo a la api Murachi")
    80             return redirect(self.success_url)
    81         try:
     64        nuevo_participante = self.form_participante(request.POST)
     65        consulta_api = None
     66        if len(request.FILES)>0:
     67            file =  request.FILES['file']
     68            handle_uploaded_file(request.FILES['file'], file)
     69            ruta = '%s/%s' % (settings.TMP, file)
     70            file = open(ruta, 'rb')
     71            files = {'file': file}
     72            try:
     73                r = requests.post('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/cargar', verify=False, headers={'Authorization': 'Basic YWRtaW46YWRtaW4='}, files=files)
     74                consulta_api = r.json()['fileId']
     75                # elimina el archivo si fue creado en la carpeta tmp
     76                file.close()
     77                os.unlink(ruta)
     78            except Exception as e:
     79                print (e)
     80                file.close()
     81                os.unlink(ruta)
     82                messages.error(self.request, "Error al concetar al servidor y subir\
     83                                              el archivo a la api Murachi")
     84                return redirect(self.success_url)
     85        try:
     86           
    8287            if self.form_class(request.POST).is_valid() and nuevo_participante.is_valid():
    8388                nuevo_evento = self.form_class(request.POST, request.FILES).save(commit=False)
     
    101106                        asigna_evento.save()
    102107                messages.success(self.request, "El usaurio %s, ha creado con exito,\
    103                                             un nuevo envento %s" %
     108                                            un nuevo evento %s" %
    104109                                 (str(self.request.user),
    105110                                  str(nuevo_evento)))
     
    184189        return context
    185190
    186 
     191@method_decorator(csrf_exempt, name='dispatch')
    187192class EventoProcesado(View):
    188193    """!
     
    196201    model = Evento
    197202
    198     def get(self, request):
     203    def get(self, request, event_id):
    199204        """!
    200205        Metodo que permite verificar si el documento esta procesado
     
    206211        @return Retorna un Json con la respuesta
    207212        """
    208         evento_id = request.GET.get('event_id', None)
    209213        mensaje = ''
    210214        procesando = False
    211         if evento_id is not None:
     215        if event_id is not None:
    212216            try:
    213                 evento_pro = self.model.objects.get(pk=evento_id)
     217                evento_pro = self.model.objects.get(pk=event_id)
    214218            except:
    215219                print(e)
     
    231235        return JsonResponse(data, safe=False)
    232236
    233     def post(self, request):
     237    def post(self, request, event_id):
    234238        """!
    235239        Metodo que permite cambiar el valor procesado al  evento
     
    241245        @return Retorna un Json con la respuesta
    242246        """
    243         evento_id = request.POST.get('event_id', None)
    244         if evento_id is not None:
     247        if event_id is not None:
    245248            try:
    246                 evento = self.model.objects.get(pk=evento_id)
     249                evento = self.model.objects.get(pk=event_id)
    247250                evento.procesando = not evento.procesando
    248251                evento.save()
     
    251254                print(e)
    252255                validado = False
     256
    253257        return JsonResponse(validado, safe=False)
    254258
     
    266270    form_class = UpdateFileEventoForm
    267271    template_name = 'evento.update.html'
    268 
    269     def form_valid(self, form, request):
    270         print(request)
     272    success_url = reverse_lazy('events:list_events')
     273
     274    def get_context_data(self, **kwargs):
     275        evento = int(self.kwargs['event_id'])
     276        context = super(UpdateFileEvent, self).get_context_data(**kwargs)
     277        try:
     278            evento = self.model.objects.select_related().get(pk=evento)
     279        except Exception as e:
     280            print(e)
     281            evento = None
     282        context['object'] = evento
     283        return context
     284
     285    def form_valid(self, form):
     286        print(form)
     287        file =  self.request.FILES['file']
     288        posx = form.cleaned_data['pos_x']
     289        posy = form.cleaned_data['pos_y']
     290        pag = form.cleaned_data['pag']
     291        consulta_api = None
     292        try:
     293            event = Evento.objects.get(pk=int(self.kwargs['event_id']))
     294        except Exception as e:
     295            print(e)
     296            messages.error(self.request, "Error, no se encuentra registrado\
     297                                          este evento")
     298            return redirect(self.success_url)
     299
     300        print(posx)
     301        handle_uploaded_file(self.request.FILES['file'], file)
     302        ruta = '%s/%s' % (settings.TMP, file)
     303        file = open(ruta, 'rb')
     304        files = {'file': file}
     305        try:
     306            r = requests.post('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/cargar', verify=False, headers={'Authorization': 'Basic YWRtaW46YWRtaW4='}, files=files)
     307            consulta_api = r.json()['fileId']
     308            # elimina el archivo si fue creado en la carpeta tmp
     309            file.close()
     310            os.unlink(ruta)
     311        except Exception as e:
     312            print (e)
     313            file.close()
     314            os.unlink(ruta)
     315            messages.error(self.request, "Error al concetar al servidor y subir\
     316                                          el archivo a la api Murachi")
     317            return redirect(self.success_url)
     318
     319        if event is not None and consulta_api is not None:
     320            event.serial = consulta_api
     321            event.pos_x = posx
     322            event.pos_y = posy
     323            event.pag = pag
     324            event.save()
     325            messages.success(self.request, "El usaurio %s, ha actualizado con exito,\
     326                                            el evento %s" %
     327                                 (str(self.request.user),
     328                                  str(event)))
     329        else:
     330            messages.error(self.request, "Error al actualizar, debes llanar\
     331                                          todos los campos incluyendo la\
     332                                          configuracion de la firma")
     333        return redirect(self.success_url)
  • static/js/funciones.js

    r5d88f36 r452668a  
    8080    }
    8181    else{
    82         html += '<a type="button" id="firmar" class="btn waves-effect blue darken-1" onclick="ObtenerCertificadoFirmanteMultiples(\''+data.documento+'\')">';
     82        html += '<a type="button" id="firmar" class="btn waves-effect blue darken-1" onclick="comprobarFirma(\''+data.documento+'\')">';
    8383        html += '<i class="material-icons left">mode_edit</i> Firmar</a>';   
    8484    }
     
    8787
    8888/**
     89 * Función para comprobar firma
     90 * @param fileId Recibe el id del documento
     91*/
     92function comprobarFirma(fileId){
     93    var routes = $(location).attr('pathname').split('/');
     94    var pk = routes[routes.length-1];
     95    $.ajax({
     96                type: 'GET',
     97        async: false,
     98                url:URL_COMPROBAR_FIRMA+pk,
     99                success: function(datos){
     100            if (datos.validate==true) {
     101                simple_modal(datos.mensaje);
     102            }
     103            else{
     104                $.ajax({
     105                    type: 'POST',
     106                    async: false,
     107                    url:URL_COMPROBAR_FIRMA+pk,
     108                    success: function(datos){
     109                        if (datos.validate==true) {
     110                            ObtenerCertificadoFirmanteMultiples(fileId,pk);
     111                        }
     112                        else{
     113                            simple_modal("Ocurrió un error al actualizar los datos");
     114                        }
     115                    },
     116                    error: function(jqXHR, textStatus, errorThrown){
     117                        console.log('error: ' + textStatus);
     118                    }
     119                });
     120            }
     121        },
     122                error: function(jqXHR, textStatus, errorThrown){
     123                        console.log('error: ' + textStatus);
     124                }
     125        });
     126}
     127
     128/**
    89129 * Función para obtener el certificado del participante
    90130 * @param fileId Recibe el id del documento
    91 */
    92 function ObtenerCertificadoFirmanteMultiples(fileId){
     131 * @param pk Recibe el id del evento
     132*/
     133function ObtenerCertificadoFirmanteMultiples(fileId,pk){
    93134    var xPos = yPos= signaturePage = "";
    94135    var lastSignature = false;
    95     var routes = $(location).attr('pathname').split('/');
    96     var pk = routes[routes.length-1];
    97136   
    98137    $.ajax({
     
    125164       
    126165                    // ahora llamar al ajax de obtener la resena del pdf
    127                     ObtenerHashPDFServerMultiples(parameters, cert);   
     166                    ObtenerHashPDFServerMultiples(parameters, cert, pk);       
    128167       
    129168                },
     
    139178                         error = "No hay soporte para el manejo del certificado";
    140179                    }
     180                    $.ajax({
     181                        type: 'POST',
     182                        async: false,
     183                        url:URL_COMPROBAR_FIRMA+pk,
     184                        success: function(datos){
     185                            console.log(datos);
     186                        },
     187                        error: function(jqXHR, textStatus, errorThrown){
     188                            console.log('error: ' + textStatus);
     189                        }
     190                    });
    141191                    simple_modal(error);
    142192                }
     
    155205 * @param parameters Recibe los parametros
    156206 * @param cert Recibe los certificados
    157 */
    158 function ObtenerHashPDFServerMultiples(parameters,cert){
     207 * @param pk Recibe el id del evento
     208*/
     209function ObtenerHashPDFServerMultiples(parameters,cert,pk){
    159210
    160211        $.ajax({
     
    175226                        window.hwcrypto.sign(cert, {type: hashtype, hex: hash}, {lang: lang}).then(
    176227                                function(signature) {
    177                                         FinalizarFirmaMultiples(signature.hex);
     228                                        FinalizarFirmaMultiples(signature.hex, pk);
    178229                        },
    179230                        function(err) {
     
    188239                         error = "No hay soporte para el manejo del certificado";
    189240                     }
     241                    $.ajax({
     242                        type: 'POST',
     243                        async: false,
     244                        url:URL_COMPROBAR_FIRMA+pk,
     245                        success: function(datos){
     246                            console.log(datos);
     247                        },
     248                        error: function(jqXHR, textStatus, errorThrown){
     249                            console.log('error: ' + textStatus);
     250                        }
     251                    });
    190252                    simple_modal(error);
    191253                });
     
    202264 * Función para enviar la firma al servidor
    203265 * @param signature Recibe la firma
    204 */
    205 function FinalizarFirmaMultiples(signature){
     266 * @param pk Recibe el id del evento
     267*/
     268function FinalizarFirmaMultiples(signature, pk){
    206269
    207270        $.ajax({
     
    215278                success: function(data, textStatus, jqXHR){
    216279            actualizar_participante(data['signedFileId']);
     280            $.ajax({
     281                type: 'POST',
     282                async: false,
     283                url:URL_COMPROBAR_FIRMA+pk,
     284                success: function(datos){
     285                    console.log(datos);
     286                },
     287                error: function(jqXHR, textStatus, errorThrown){
     288                    console.log('error: ' + textStatus);
     289                }
     290            });
    217291                },
    218292                error: function(jqXHR, textStatus, errorThrown){
    219293                        console.log('error en pdfs/resenas: ' + textStatus);
     294            $.ajax({
     295                type: 'POST',
     296                async: false,
     297                url:URL_COMPROBAR_FIRMA+pk,
     298                success: function(datos){
     299                    console.log(datos);
     300                },
     301                error: function(jqXHR, textStatus, errorThrown){
     302                    console.log('error: ' + textStatus);
     303                }
     304            });
    220305                }
    221306        });
Note: See TracChangeset for help on using the changeset viewer.