1 | # -*- encoding: utf-8 -*- |
---|
2 | |
---|
3 | import os |
---|
4 | import requests |
---|
5 | from django.conf import settings |
---|
6 | from django.contrib import messages |
---|
7 | from django.contrib.auth.mixins import LoginRequiredMixin |
---|
8 | from django.core.files.base import ContentFile |
---|
9 | from django.core.files.storage import default_storage |
---|
10 | from django.core.urlresolvers import reverse_lazy |
---|
11 | from django.http import JsonResponse |
---|
12 | from django.utils.decorators import method_decorator |
---|
13 | from django.views.decorators.csrf import csrf_exempt |
---|
14 | from django.shortcuts import ( |
---|
15 | redirect |
---|
16 | ) |
---|
17 | from django.views import View |
---|
18 | from django.views.generic import ( |
---|
19 | ListView, FormView |
---|
20 | ) |
---|
21 | from django.views.generic.detail import DetailView |
---|
22 | |
---|
23 | from multi_form_view import MultiModelFormView |
---|
24 | |
---|
25 | from .forms import * |
---|
26 | from participantes.forms import ( |
---|
27 | FormsetParticipanteEvento |
---|
28 | ) |
---|
29 | from .models import Evento |
---|
30 | from participantes.models import ( |
---|
31 | Participante, ParticipanteEvento |
---|
32 | ) |
---|
33 | |
---|
34 | |
---|
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 | |
---|
40 | class RegisterEvent(LoginRequiredMixin, FormView): |
---|
41 | """! |
---|
42 | Muestra el formulario de registro de usuarios |
---|
43 | |
---|
44 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
45 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
46 | @date 20-11-2017 |
---|
47 | @version 1.0.0 |
---|
48 | """ |
---|
49 | |
---|
50 | template_name = "register.event.html" |
---|
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: |
---|
60 | context['form2'] = self.form_participante(queryset=Participante.objects.none()) |
---|
61 | return context |
---|
62 | |
---|
63 | def post(self, request, *args, **kwargs): |
---|
64 | file = request.FILES['file'] |
---|
65 | handle_uploaded_file(request.FILES['file'], file) |
---|
66 | ruta = '%s/%s' % (settings.TMP, file) |
---|
67 | file = open(ruta, 'rb') |
---|
68 | files = {'file': file} |
---|
69 | try: |
---|
70 | r = requests.post('https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/cargar', verify=False, headers={'Authorization': 'Basic YWRtaW46YWRtaW4='}, files=files) |
---|
71 | nuevo_participante = self.form_participante(request.POST) |
---|
72 | consulta_api = r.json()['fileId'] |
---|
73 | # elimina el archivo si fue creado en la carpeta tmp |
---|
74 | file.close() |
---|
75 | os.unlink(ruta) |
---|
76 | except Exception as e: |
---|
77 | print (e) |
---|
78 | file.close() |
---|
79 | os.unlink(ruta) |
---|
80 | messages.error(self.request, "Error al concetar al servidor y subir\ |
---|
81 | el archivo a la api Murachi") |
---|
82 | return redirect(self.success_url) |
---|
83 | try: |
---|
84 | if self.form_class(request.POST).is_valid() and nuevo_participante.is_valid(): |
---|
85 | nuevo_evento = self.form_class(request.POST, request.FILES).save(commit=False) |
---|
86 | nuevo_evento.serial = consulta_api |
---|
87 | nuevo_evento.save() |
---|
88 | # Control para guardar y asignar participantes al evento |
---|
89 | for form in nuevo_participante: |
---|
90 | if form.cleaned_data.get('DELETE') and form.instance.pk: |
---|
91 | form.instance.delete() |
---|
92 | else: |
---|
93 | instance = form.save(commit=False) |
---|
94 | parametros = { |
---|
95 | 'nombres': instance.nombres, |
---|
96 | 'apellidos': instance.apellidos, |
---|
97 | 'correo': instance.correo |
---|
98 | } |
---|
99 | nuevo_participante, create = Participante.objects.update_or_create(pasaporte=instance.pasaporte, defaults=parametros) |
---|
100 | asigna_evento = ParticipanteEvento( |
---|
101 | fk_participante=nuevo_participante, |
---|
102 | fk_evento=nuevo_evento) |
---|
103 | asigna_evento.save() |
---|
104 | messages.success(self.request, "El usaurio %s, ha creado con exito,\ |
---|
105 | un nuevo envento %s" % |
---|
106 | (str(self.request.user), |
---|
107 | str(nuevo_evento))) |
---|
108 | else: |
---|
109 | messages.error(self.request, "Existe un error en el\ |
---|
110 | Formualario %s %s" % |
---|
111 | (self.form_class(request.POST).errors, |
---|
112 | self.form_participante(request.POST).errors)) |
---|
113 | except Exception as e: |
---|
114 | print (e) |
---|
115 | messages.error(self.request, "Esta intentado realizar una\ |
---|
116 | accion incorrecta") |
---|
117 | |
---|
118 | return redirect(self.success_url) |
---|
119 | |
---|
120 | |
---|
121 | class ListEvent(ListView): |
---|
122 | """! |
---|
123 | Muestra el listado de eventos |
---|
124 | |
---|
125 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
126 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
127 | @date 20-11-2017 |
---|
128 | @version 1.0.0 |
---|
129 | """ |
---|
130 | model = Evento |
---|
131 | template_name = "evento.list.html" |
---|
132 | paginate_by = 5 |
---|
133 | |
---|
134 | |
---|
135 | class SignEvent(FormView): |
---|
136 | """! |
---|
137 | Muestra el formulario para buscar y luego firmar documento |
---|
138 | |
---|
139 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
140 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
141 | @date 20-11-2017 |
---|
142 | @version 1.0.0 |
---|
143 | """ |
---|
144 | form_class = FirmaEventoForm |
---|
145 | template_name = "evento.firma.html" |
---|
146 | |
---|
147 | def get_context_data(self, **kwargs): |
---|
148 | """! |
---|
149 | Metodo que permite cargar de nuevo valores en los datos de contexto de la vista |
---|
150 | |
---|
151 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
152 | @copyright GNU/GPLv3 |
---|
153 | @date 20-11-2017 |
---|
154 | @param self <b>{object}</b> Objeto que instancia la clase |
---|
155 | @param kwargs <b>{object}</b> Objeto que contiene los datos de contexto |
---|
156 | @return Retorna los datos de contexto |
---|
157 | """ |
---|
158 | kwargs['nombre_evento'] = Evento.objects.get(pk=int(self.kwargs['pk'])) |
---|
159 | return super(SignEvent, self).get_context_data(**kwargs) |
---|
160 | |
---|
161 | |
---|
162 | class DetailEvent(DetailView): |
---|
163 | """! |
---|
164 | Muestra el detalle del evento |
---|
165 | |
---|
166 | @author Rodrigo Boet (rboet at cenditel.gob.ve) |
---|
167 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
168 | @date 20-11-2017 |
---|
169 | @version 1.0.0 |
---|
170 | """ |
---|
171 | model = Evento |
---|
172 | template_name = "evento.detail.html" |
---|
173 | |
---|
174 | def get_context_data(self, **kwargs): |
---|
175 | evento = int(self.kwargs['pk']) |
---|
176 | context = super(DetailEvent, self).get_context_data(**kwargs) |
---|
177 | try: |
---|
178 | participante_evento = ParticipanteEvento.objects.select_related().filter(fk_evento=evento) |
---|
179 | falta_porfirma = participante_evento.filter(firma=False).count() |
---|
180 | except Exception as e: |
---|
181 | print(e) |
---|
182 | participante_evento = None |
---|
183 | falta_porfirma = None |
---|
184 | context['participantes'] = participante_evento |
---|
185 | context['num_firma'] = falta_porfirma |
---|
186 | return context |
---|
187 | |
---|
188 | @method_decorator(csrf_exempt, name='dispatch') |
---|
189 | class EventoProcesado(View): |
---|
190 | """! |
---|
191 | Clase que permite consultar si el evento se encuentra disponible para firmar |
---|
192 | |
---|
193 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
194 | @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a> |
---|
195 | @date 27-11-2017 |
---|
196 | @version 1.0.0 |
---|
197 | """ |
---|
198 | model = Evento |
---|
199 | |
---|
200 | def get(self, request, event_id): |
---|
201 | """! |
---|
202 | Metodo que permite verificar si el documento esta procesado |
---|
203 | |
---|
204 | @author Leonel P. Hernandez M (lhernandez at cenditel.gob.ve) |
---|
205 | @copyright GNU/GPLv3 |
---|
206 | @date 27-11-2017 |
---|
207 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
208 | @return Retorna un Json con la respuesta |
---|
209 | """ |
---|
210 | mensaje = '' |
---|
211 | procesando = False |
---|
212 | if event_id is not None: |
---|
213 | try: |
---|
214 | evento_pro = self.model.objects.get(pk=event_id) |
---|
215 | except: |
---|
216 | print(e) |
---|
217 | procesando = True |
---|
218 | mensaje += 'No se encuentra un evento con ese serial' |
---|
219 | else: |
---|
220 | evento_pro = None |
---|
221 | procesando = True |
---|
222 | mensaje += 'No puedes enviar un evento vacio' |
---|
223 | |
---|
224 | if evento_pro.procesando: |
---|
225 | procesando = True |
---|
226 | mensaje += 'No puedes firmar el documento, en este momento\ |
---|
227 | se encuentra ocupado por otro Usuario' |
---|
228 | else: |
---|
229 | procesando = False |
---|
230 | mensaje += 'Puedes Firmar el Documento' |
---|
231 | data = {'validate': procesando, 'mensaje': mensaje} |
---|
232 | return JsonResponse(data, safe=False) |
---|
233 | |
---|
234 | def post(self, request, event_id): |
---|
235 | """! |
---|
236 | Metodo que permite cambiar el valor procesado al evento |
---|
237 | |
---|
238 | @author Leonel P. Hernandez M (lhernandez at cenditel.gob.ve) |
---|
239 | @copyright GNU/GPLv3 |
---|
240 | @date 27-11-2017 |
---|
241 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
242 | @return Retorna un Json con la respuesta |
---|
243 | """ |
---|
244 | if event_id is not None: |
---|
245 | try: |
---|
246 | evento = self.model.objects.get(pk=event_id) |
---|
247 | evento.procesando = not evento.procesando |
---|
248 | evento.save() |
---|
249 | validado = True |
---|
250 | except: |
---|
251 | print(e) |
---|
252 | validado = False |
---|
253 | return JsonResponse({'validate': validado}, safe=False) |
---|