[a4764f9] | 1 | # -*- encoding: utf-8 -*- |
---|
| 2 | |
---|
| 3 | import os |
---|
| 4 | import requests |
---|
| 5 | from django.conf import settings |
---|
[94b3e3f] | 6 | from django.contrib import messages |
---|
[b8fffff] | 7 | from django.contrib.auth.mixins import LoginRequiredMixin |
---|
[a4764f9] | 8 | from django.core.files.base import ContentFile |
---|
| 9 | from django.core.files.storage import default_storage |
---|
[94b3e3f] | 10 | from django.core.urlresolvers import reverse_lazy |
---|
[5d88f36] | 11 | from django.http import JsonResponse |
---|
[452668a] | 12 | from django.utils.decorators import method_decorator |
---|
| 13 | from django.views.decorators.csrf import csrf_exempt |
---|
[94b3e3f] | 14 | from django.shortcuts import ( |
---|
[a4764f9] | 15 | redirect |
---|
[94b3e3f] | 16 | ) |
---|
[5d88f36] | 17 | from django.views import View |
---|
[27c0bd4] | 18 | from django.views.generic import ( |
---|
| 19 | ListView, FormView |
---|
| 20 | ) |
---|
| 21 | from django.views.generic.detail import DetailView |
---|
[8ec6ee3] | 22 | |
---|
[8fa24c3] | 23 | from multi_form_view import MultiModelFormView |
---|
[bf47591] | 24 | |
---|
[8fa24c3] | 25 | from .forms import * |
---|
| 26 | from participantes.forms import ( |
---|
| 27 | FormsetParticipanteEvento |
---|
| 28 | ) |
---|
[66158c7] | 29 | from .models import Evento |
---|
[b8fffff] | 30 | from participantes.models import ( |
---|
| 31 | Participante, ParticipanteEvento |
---|
| 32 | ) |
---|
[8fa24c3] | 33 | |
---|
[8ec6ee3] | 34 | |
---|
[a4764f9] | 35 | def handle_uploaded_file(file, name): |
---|
| 36 | with open('%s/%s' % (settings.TMP, name), 'wb+') as destination: |
---|
| 37 | for chunk in file.chunks(): |
---|
| 38 | destination.write(chunk) |
---|
| 39 | |
---|
[b8fffff] | 40 | class RegisterEvent(LoginRequiredMixin, FormView): |
---|
[8fa24c3] | 41 | """! |
---|
| 42 | Muestra el formulario de registro de usuarios |
---|
| 43 | |
---|
| 44 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
[5dea5ff] | 45 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
[8fa24c3] | 46 | @date 20-11-2017 |
---|
| 47 | @version 1.0.0 |
---|
| 48 | """ |
---|
[94b3e3f] | 49 | |
---|
[8fa24c3] | 50 | template_name = "register.event.html" |
---|
[94b3e3f] | 51 | form_class = EventoForm |
---|
| 52 | form_participante = FormsetParticipanteEvento |
---|
| 53 | success_url = reverse_lazy('base:inicio') |
---|
| 54 | |
---|
| 55 | def get_context_data(self, **kwargs): |
---|
| 56 | context = super(RegisterEvent, self).get_context_data(**kwargs) |
---|
| 57 | if 'form' not in context: |
---|
| 58 | context['form'] = self.form_class() |
---|
| 59 | if 'form2' not in context: |
---|
[45f784a] | 60 | context['form2'] = self.form_participante(queryset=Participante.objects.none()) |
---|
[94b3e3f] | 61 | return context |
---|
| 62 | |
---|
| 63 | def post(self, request, *args, **kwargs): |
---|
[eb2672b] | 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) |
---|
[52a0eb9] | 82 | messages.error(self.request, "Error al conectar al servidor y subir\ |
---|
[eb2672b] | 83 | el archivo a la api Murachi") |
---|
| 84 | return redirect(self.success_url) |
---|
[a4764f9] | 85 | try: |
---|
[eb2672b] | 86 | |
---|
[a4764f9] | 87 | if self.form_class(request.POST).is_valid() and nuevo_participante.is_valid(): |
---|
[d285c11] | 88 | nuevo_evento = self.form_class(request.POST, request.FILES).save(commit=False) |
---|
[a4764f9] | 89 | nuevo_evento.serial = consulta_api |
---|
| 90 | nuevo_evento.save() |
---|
| 91 | # Control para guardar y asignar participantes al evento |
---|
| 92 | for form in nuevo_participante: |
---|
| 93 | if form.cleaned_data.get('DELETE') and form.instance.pk: |
---|
| 94 | form.instance.delete() |
---|
| 95 | else: |
---|
| 96 | instance = form.save(commit=False) |
---|
| 97 | parametros = { |
---|
| 98 | 'nombres': instance.nombres, |
---|
| 99 | 'apellidos': instance.apellidos, |
---|
| 100 | 'correo': instance.correo |
---|
| 101 | } |
---|
| 102 | nuevo_participante, create = Participante.objects.update_or_create(pasaporte=instance.pasaporte, defaults=parametros) |
---|
| 103 | asigna_evento = ParticipanteEvento( |
---|
| 104 | fk_participante=nuevo_participante, |
---|
| 105 | fk_evento=nuevo_evento) |
---|
| 106 | asigna_evento.save() |
---|
[52a0eb9] | 107 | messages.success(self.request, "El usuario %s, ha creado con exito,\ |
---|
[eb2672b] | 108 | un nuevo evento %s" % |
---|
[a4764f9] | 109 | (str(self.request.user), |
---|
| 110 | str(nuevo_evento))) |
---|
| 111 | else: |
---|
| 112 | messages.error(self.request, "Existe un error en el\ |
---|
| 113 | Formualario %s %s" % |
---|
| 114 | (self.form_class(request.POST).errors, |
---|
| 115 | self.form_participante(request.POST).errors)) |
---|
| 116 | except Exception as e: |
---|
| 117 | print (e) |
---|
[52a0eb9] | 118 | messages.error(self.request, "Esta intentando realizar una\ |
---|
| 119 | acción incorrecta") |
---|
[a4764f9] | 120 | |
---|
[94b3e3f] | 121 | return redirect(self.success_url) |
---|
[66158c7] | 122 | |
---|
| 123 | |
---|
| 124 | class ListEvent(ListView): |
---|
| 125 | """! |
---|
| 126 | Muestra el listado de eventos |
---|
| 127 | |
---|
| 128 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
[5dea5ff] | 129 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
[66158c7] | 130 | @date 20-11-2017 |
---|
| 131 | @version 1.0.0 |
---|
| 132 | """ |
---|
| 133 | model = Evento |
---|
| 134 | template_name = "evento.list.html" |
---|
[248b1b4] | 135 | paginate_by = 5 |
---|
[5d88f36] | 136 | |
---|
| 137 | |
---|
[248b1b4] | 138 | class SignEvent(FormView): |
---|
| 139 | """! |
---|
| 140 | Muestra el formulario para buscar y luego firmar documento |
---|
| 141 | |
---|
| 142 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
[5dea5ff] | 143 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
[248b1b4] | 144 | @date 20-11-2017 |
---|
| 145 | @version 1.0.0 |
---|
| 146 | """ |
---|
| 147 | form_class = FirmaEventoForm |
---|
[ae65f8e] | 148 | template_name = "evento.firma.html" |
---|
[5d88f36] | 149 | |
---|
[ae65f8e] | 150 | def get_context_data(self, **kwargs): |
---|
| 151 | """! |
---|
| 152 | Metodo que permite cargar de nuevo valores en los datos de contexto de la vista |
---|
[5d88f36] | 153 | |
---|
[ae65f8e] | 154 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
| 155 | @copyright GNU/GPLv3 |
---|
| 156 | @date 20-11-2017 |
---|
| 157 | @param self <b>{object}</b> Objeto que instancia la clase |
---|
| 158 | @param kwargs <b>{object}</b> Objeto que contiene los datos de contexto |
---|
| 159 | @return Retorna los datos de contexto |
---|
| 160 | """ |
---|
| 161 | kwargs['nombre_evento'] = Evento.objects.get(pk=int(self.kwargs['pk'])) |
---|
[16cf088] | 162 | return super(SignEvent, self).get_context_data(**kwargs) |
---|
[27c0bd4] | 163 | |
---|
| 164 | |
---|
| 165 | class DetailEvent(DetailView): |
---|
| 166 | """! |
---|
| 167 | Muestra el detalle del evento |
---|
| 168 | |
---|
| 169 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
| 170 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
| 171 | @date 20-11-2017 |
---|
| 172 | @version 1.0.0 |
---|
| 173 | """ |
---|
| 174 | model = Evento |
---|
| 175 | template_name = "evento.detail.html" |
---|
| 176 | |
---|
| 177 | def get_context_data(self, **kwargs): |
---|
| 178 | evento = int(self.kwargs['pk']) |
---|
| 179 | context = super(DetailEvent, self).get_context_data(**kwargs) |
---|
| 180 | try: |
---|
| 181 | participante_evento = ParticipanteEvento.objects.select_related().filter(fk_evento=evento) |
---|
| 182 | falta_porfirma = participante_evento.filter(firma=False).count() |
---|
| 183 | except Exception as e: |
---|
| 184 | print(e) |
---|
| 185 | participante_evento = None |
---|
| 186 | falta_porfirma = None |
---|
| 187 | context['participantes'] = participante_evento |
---|
| 188 | context['num_firma'] = falta_porfirma |
---|
| 189 | return context |
---|
[5d88f36] | 190 | |
---|
[452668a] | 191 | @method_decorator(csrf_exempt, name='dispatch') |
---|
[5d88f36] | 192 | class EventoProcesado(View): |
---|
| 193 | """! |
---|
| 194 | Clase que permite consultar si el evento se encuentra disponible para firmar |
---|
| 195 | |
---|
| 196 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
| 197 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
| 198 | @date 27-11-2017 |
---|
| 199 | @version 1.0.0 |
---|
| 200 | """ |
---|
| 201 | model = Evento |
---|
| 202 | |
---|
[452668a] | 203 | def get(self, request, event_id): |
---|
[5d88f36] | 204 | """! |
---|
| 205 | Metodo que permite verificar si el documento esta procesado |
---|
| 206 | |
---|
| 207 | @author Leonel P. Hernandez M (lhernandez at cenditel.gob.ve) |
---|
| 208 | @copyright GNU/GPLv3 |
---|
| 209 | @date 27-11-2017 |
---|
| 210 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
| 211 | @return Retorna un Json con la respuesta |
---|
| 212 | """ |
---|
| 213 | mensaje = '' |
---|
| 214 | procesando = False |
---|
[452668a] | 215 | if event_id is not None: |
---|
[5d88f36] | 216 | try: |
---|
[452668a] | 217 | evento_pro = self.model.objects.get(pk=event_id) |
---|
[5d88f36] | 218 | except: |
---|
| 219 | print(e) |
---|
| 220 | procesando = True |
---|
| 221 | mensaje += 'No se encuentra un evento con ese serial' |
---|
| 222 | else: |
---|
| 223 | evento_pro = None |
---|
| 224 | procesando = True |
---|
| 225 | mensaje += 'No puedes enviar un evento vacio' |
---|
| 226 | |
---|
| 227 | if evento_pro.procesando: |
---|
| 228 | procesando = True |
---|
| 229 | mensaje += 'No puedes firmar el documento, en este momento\ |
---|
| 230 | se encuentra ocupado por otro Usuario' |
---|
| 231 | else: |
---|
| 232 | procesando = False |
---|
| 233 | mensaje += 'Puedes Firmar el Documento' |
---|
| 234 | data = {'validate': procesando, 'mensaje': mensaje} |
---|
| 235 | return JsonResponse(data, safe=False) |
---|
| 236 | |
---|
[452668a] | 237 | def post(self, request, event_id): |
---|
[5d88f36] | 238 | """! |
---|
| 239 | Metodo que permite cambiar el valor procesado al evento |
---|
| 240 | |
---|
| 241 | @author Leonel P. Hernandez M (lhernandez at cenditel.gob.ve) |
---|
| 242 | @copyright GNU/GPLv3 |
---|
| 243 | @date 27-11-2017 |
---|
| 244 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
| 245 | @return Retorna un Json con la respuesta |
---|
| 246 | """ |
---|
[452668a] | 247 | if event_id is not None: |
---|
[5d88f36] | 248 | try: |
---|
[452668a] | 249 | evento = self.model.objects.get(pk=event_id) |
---|
[5d88f36] | 250 | evento.procesando = not evento.procesando |
---|
| 251 | evento.save() |
---|
| 252 | validado = True |
---|
| 253 | except: |
---|
| 254 | print(e) |
---|
| 255 | validado = False |
---|
[d9b20e6] | 256 | |
---|
[5d88f36] | 257 | return JsonResponse(validado, safe=False) |
---|
[bc3aa92] | 258 | |
---|
| 259 | |
---|
[c152e07] | 260 | class UpdateFileEvent(LoginRequiredMixin, FormView): |
---|
[bc3aa92] | 261 | """! |
---|
| 262 | Clase que permite actualizar subir un archivo a un evento que no se haya cargado |
---|
| 263 | |
---|
| 264 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
| 265 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
| 266 | @date 27-11-2017 |
---|
| 267 | @version 1.0.0 |
---|
| 268 | """ |
---|
| 269 | model = Evento |
---|
| 270 | form_class = UpdateFileEventoForm |
---|
| 271 | template_name = 'evento.update.html' |
---|
[d9b20e6] | 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 |
---|
[bc3aa92] | 284 | |
---|
[d9b20e6] | 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\ |
---|
[83885cf] | 297 | esté evento") |
---|
[d9b20e6] | 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) |
---|
[52a0eb9] | 315 | messages.error(self.request, "Error al conectar al servidor y subir\ |
---|
[d9b20e6] | 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() |
---|
[52a0eb9] | 325 | messages.success(self.request, "El usuario %s, ha actualizado con exito,\ |
---|
[d9b20e6] | 326 | el evento %s" % |
---|
| 327 | (str(self.request.user), |
---|
| 328 | str(event))) |
---|
| 329 | else: |
---|
[52a0eb9] | 330 | messages.error(self.request, "Error al actualizar, debes llenar\ |
---|
| 331 | todos los campos, incluyendo la\ |
---|
| 332 | configuración de la firma") |
---|
[d9b20e6] | 333 | return redirect(self.success_url) |
---|