source: consulta_publica/participacion/views.py @ bcf369a

constituyenteestudiantesgeneralplan_patriasala
Last change on this file since bcf369a was bcf369a, checked in by rudmanmrrod <rudman22@…>, 7 años ago

Agregados cambios para adaptar la consulta a la sala situacional

  • Propiedad mode establecida a 100644
File size: 19.3 KB
Línea 
1# -*- coding: utf-8 -*-
2"""
3Sistema de Consulta Pública
4
5Copyleft (@) 2017 CENDITEL nodo Mérida - https://planificacion.cenditel.gob.ve/trac/wiki/ModeladoTopicos_2017
6"""
7## @package participacion.views
8#
9# Vistas correspondientes a la aplicación participacion
10# @author Rodrigo Boet (rboet at cenditel.gob.ve)
11# @author <a href='http://www.cenditel.gob.ve'>Centro Nacional de Desarrollo e Investigación en Tecnologías Libres
12# (CENDITEL) nodo Mérida - Venezuela</a>
13# @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
14# @version 1.0
15import json
16from django.shortcuts import render, redirect
17from django.core.urlresolvers import reverse_lazy
18from django.http import JsonResponse
19from django.views.generic import FormView, TemplateView
20from django.contrib.auth.models import User
21from django.contrib.auth.mixins import LoginRequiredMixin
22from braces.views import GroupRequiredMixin
23from base.constant import OBJETIVOS_DEFINICION
24from .forms import ParticipacionSelectForm, ParticipacionSearchForm
25from .models import RespuestaAbierta, RespuestaOpciones, RespuestaSino
26from consulta.models import Pregunta, Opcion
27import requests
28
29class ParticipacionIndex(GroupRequiredMixin,LoginRequiredMixin,FormView):
30    """!
31    Clase que gestiona la vista principal de la participación
32
33    @author Rodrigo Boet (rboet at cenditel.gob.ve)
34    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
35    @date 22-02-2017
36    @version 1.0.0
37    """
38    template_name = "participacion.index.html"
39    form_class = ParticipacionSelectForm
40    group_required = u"Participante"
41   
42    def get_success_url(self):
43        """!
44        Metodo que permite definir la url de dirección al ser válido el formulario
45   
46        @author Rodrigo Boet (rboet at cenditel.gob.ve)
47        @copyright GNU/GPLv2
48        @date 22-02-2017
49        @param self <b>{object}</b> Objeto que instancia la clase
50        @return Retorna la url
51        """
52        consulta = self.request.POST['consultas']
53        if(consulta!="3"):
54            return reverse_lazy('participacion_busqueda',
55                            kwargs={'pk': consulta})
56        else:
57            return reverse_lazy('participacion_simple', kwargs={'pk': consulta})
58
59
60class ParticipacionSearch(GroupRequiredMixin,LoginRequiredMixin,FormView):
61    """!
62    Clase que gestiona la busqueda para la participación
63
64    @author Rodrigo Boet (rboet at cenditel.gob.ve)
65    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
66    @date 23-02-2017
67    @version 1.0.0
68    """
69    template_name = "participacion.search.html"
70    form_class = ParticipacionSearchForm
71    group_required = u"Participante"
72   
73    def get_success_url(self):
74        """!
75        Metodo que permite definir la url de dirección al ser válido el formulario
76   
77        @author Rodrigo Boet (rboet at cenditel.gob.ve)
78        @copyright GNU/GPLv2
79        @date 23-02-2017
80        @param self <b>{object}</b> Objeto que instancia la clase
81        @return Retorna la url
82        """
83        objetivo = self.request.POST['objetivo']
84        return reverse_lazy('participacion_consulta', kwargs={'pk': self.kwargs['pk'],'id_objetivo':objetivo})
85
86class ParticipacionCreate(GroupRequiredMixin,LoginRequiredMixin,TemplateView):
87    """!
88    Clase que gestiona la vista principal de la participación
89
90    @author Rodrigo Boet (rboet at cenditel.gob.ve)
91    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
92    @date 22-02-2017
93    @version 1.0.0
94    """
95    template_name = "participacion.create.html"
96    group_required = u"Participante"
97   
98    def get_context_data(self, **kwargs):
99        """!
100        Metodo que permite cargar de nuevo valores en los datos de contexto de la vista
101   
102        @author Rodrigo Boet (rboet at cenditel.gob.ve)
103        @copyright GNU/GPLv2
104        @date 23-02-2017
105        @param self <b>{object}</b> Objeto que instancia la clase
106        @param kwargs <b>{object}</b> Objeto que contiene los datos de contexto
107        @return Retorna los datos de contexto
108        """
109        valores = {}
110        for pregunta in Pregunta.objects.filter(consulta_id=kwargs['pk']).all():
111            label = '<label class="text-center">'+pregunta.texto_pregunta+'</label>'
112            campo = ''
113            if pregunta.tipo_pregunta.id == 1:
114                campo = ''
115                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
116                    campo += '<label for="'+kwargs['pk']+'">'+opcion.texto_opcion+'</label><input type="radio" name="consulta_respuesta_radio_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="'+str(opcion.id)+'" class="icheck">'
117            elif pregunta.tipo_pregunta.id == 2:
118                campo = ''
119                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
120                    campo += '<label for="'+kwargs['pk']+'">'+opcion.texto_opcion+'</label><input type="checkbox" name="consulta_respuesta_check_'+kwargs['pk']+'" id="'+kwargs['pk']+'"value="'+str(opcion.id)+'" class="icheck">'
121            elif pregunta.tipo_pregunta.id > 2 and pregunta.tipo_pregunta.id < 5:
122                if(pregunta.tipo_pregunta.id == 3):
123                    campo += '<label for="'+kwargs['pk']+'">Si</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="Si" class="icheck">'
124                    campo += '<label for="'+kwargs['pk']+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="No" class="icheck">'
125                else:
126                    campo += '<label for="'+kwargs['pk']+'">Si</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="Si" class="icheck need_justification">'
127                    campo += '<label for="'+kwargs['pk']+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="No" class="icheck">'
128                    campo += '<div id="div_justificar_'+kwargs['pk']+'" style="display:none;"><label>Indique con que instrumento legal en vigencia se relaciona su aporte</label>'
129                    campo += '<textarea class="form-control" id="respuesta_justificar_'+kwargs['pk']+'" name="consulta_respuesta_justificar_'+str(pregunta.id)+'">'
130                    campo += '</textarea></div>'
131            else:
132                campo += '<label class="text-center text-danger">La propuesta debe tener entre 700 y 5000 caracteres</label><br>'
133                campo += '<label class="pull-right" id="longitud"><span>0</span> caracteres escritos</label>'
134                campo += '<textarea class="form-control" name="consulta_respuesta_abierta_'+str(pregunta.id)+'" oninput="medir_caracters(this);"></textarea>'
135            valores[pregunta.id] = {'label':label,'field':campo}
136            kwargs['preguntas'] = valores
137            kwargs['objetivo'] = OBJETIVOS_DEFINICION[int(kwargs['id_objetivo'])-1][1]
138        return super(ParticipacionCreate, self).get_context_data(**kwargs)
139   
140    def post(self,request,pk,id_objetivo):
141        """!
142        Metodo que sobreescribe el post del formulario
143   
144        @author Rodrigo Boet (rboet at cenditel.gob.ve)
145        @copyright GNU/GPLv2
146        @date 20-03-2017
147        @param self <b>{object}</b> Objeto que instancia la clase
148        @param request <b>{object}</b> Objeto que instancia la petición
149        @param pk <b>{int}</b> Recibe el id de la consulta
150        @param id_ente <b>{int}</b> Recibe el id del ente
151        @return Retorna los datos de contexto
152        """
153        data = dict(request.POST)
154        del data['csrfmiddlewaretoken']
155        if self.request.is_ajax():
156            for key in data.keys():
157                parent_id = key.split("_")[-1]
158                if 'sino' in key:
159                    value = True if data[key][0] == 'Si' else False
160                    justify_id = 'consulta_respuesta_justificar_'+str(parent_id)
161                    self.crear_respuesta_sino(parent_id,value,id_objetivo,self.request.user.id)
162                    if(not value and justify_id in data.keys()):
163                        respuesta = data[justify_id][0]
164                        self.crear_respuesta_abierta(parent_id,respuesta,id_objetivo,self.request.user.id,True)
165                elif 'radio' in key or 'check' in key:
166                    for value in data[key]:
167                        self.crear_respuesta_opciones(value,id_objetivo,self.request.user.id)
168                elif 'abierta' in key:
169                    value = data[key][0]
170                    self.crear_respuesta_abierta(parent_id,value,id_objetivo,self.request.user.id)
171            return JsonResponse({"code":True})
172        return redirect(reverse_lazy('participacion_busqueda',kwargs={'pk':pk}))
173   
174    def crear_respuesta_sino(self,parent_id,value,id_objetivo,user_id):
175        """!
176        Metodo para crear una respuesta de si/no
177   
178        @author Rodrigo Boet (rboet at cenditel.gob.ve)
179        @copyright GNU/GPLv2
180        @date 27-03-2017
181        @param self <b>{object}</b> Objeto que instancia la clase
182        @param parent_id <b>{int}</b> Recibe el número del id del padre
183        @param value <b>{bool}</b> Recibe el valor de la respuesta
184        @param id_objetivo <b>{int}</b> Recibe el id del objetivo
185        @param user_id <b>{int}</b> Recibe el id del user
186        @return Retorna los datos de contexto
187        """
188        user = User.objects.get(id=user_id)
189        parent = Pregunta.objects.get(pk=parent_id)
190        respuesta = RespuestaSino()
191        respuesta.pregunta = parent
192        respuesta.respuesta = value
193        respuesta.user = user
194        respuesta.save()
195       
196    def crear_respuesta_opciones(self,parent_id,id_objetivo,user_id):
197        """!
198        Metodo para crear una respuesta de selección simple y múltiple
199   
200        @author Rodrigo Boet (rboet at cenditel.gob.ve)
201        @copyright GNU/GPLv2
202        @date 28-03-2017
203        @param self <b>{object}</b> Objeto que instancia la clase
204        @param parent_id <b>{int}</b> Recibe el número del id del padre
205        @param id_objetivo <b>{int}</b> Recibe el id del objetivo
206        @param user_id <b>{int}</b> Recibe el id del user
207        @return Retorna los datos de contexto
208        """
209        user = User.objects.get(id=user_id)
210        parent = Opcion.objects.get(pk=parent_id)
211        respuesta = RespuestaOpciones()
212        respuesta.opcion = parent
213        respuesta.user = user
214        respuesta.save()
215       
216    def crear_respuesta_abierta(self,parent_id,value,id_objetivo,user_id,es_justificacion = False):
217        """!
218        Metodo para crear una respuesta abierta
219   
220        @author Rodrigo Boet (rboet at cenditel.gob.ve)
221        @copyright GNU/GPLv2
222        @date 28-03-2017
223        @param self <b>{object}</b> Objeto que instancia la clase
224        @param parent_id <b>{int}</b> Recibe el número del id del padre
225        @param value <b>{str}</b> Recibe el valor de la respuesta
226        @param ente <b>{int}</b> Recibe el id del ente
227        @param user_id <b>{int}</b> Recibe el id del user
228        @param es_justificacion <b>{bool}</b> Recibe el párametro que indica si es una justifiación
229        @return Retorna los datos de contexto
230        """
231        user = User.objects.get(id=user_id)
232        parent = Pregunta.objects.get(pk=parent_id)
233        respuesta = RespuestaAbierta()
234        respuesta.pregunta = parent
235        respuesta.objetivo = id_objetivo
236        respuesta.texto_respuesta = value
237        respuesta.user = user
238        respuesta.es_justificacion = es_justificacion
239        respuesta.save()
240
241
242def validar_participacion(request):
243    """!
244    Función que valida si un usuario ya participó en la consulta con un ente en particular
245
246    @author Rodrigo Boet (rboet at cenditel.gob.ve)
247    @copyright GNU/GPLv2
248    @date 21-04-2017
249    @param request <b>{object}</b> Objeto que contiene la petición
250    @return Retorna un json con la respuesta
251    """
252    if not request.is_ajax():
253        return JsonResponse({'mensaje': False, 'error': str('La solicitud no es ajax')})
254    objetivo = request.GET.get('objetivo', None)
255    consulta = request.GET.get('consulta', None)
256    if(objetivo and consulta):
257        respuesta_sino = RespuestaSino.objects.filter(pregunta__consulta=consulta)
258        respuesta_abierta = RespuestaAbierta.objects.filter(pregunta__consulta=consulta,objetivo=objetivo)
259        respuesta_opciones = RespuestaOpciones.objects.filter(opcion__pregunta__consulta=consulta)
260        if(respuesta_sino or respuesta_abierta or respuesta_opciones):
261            return JsonResponse({'mensaje': True,'participacion':True})
262        return JsonResponse({'mensaje': True,'participacion':False})
263    else:
264        return JsonResponse({'mensaje': False, 'error': str('No envío el ente y/o el id de la consulta')})
265   
266   
267   
268class ParticipacionSimpleCreate(GroupRequiredMixin,LoginRequiredMixin,TemplateView):
269    """!
270    Clase que gestiona la vista principal de la participación simple
271
272    @author Rodrigo Boet (rboet at cenditel.gob.ve)
273    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
274    @date 18-07-2017
275    @version 1.0.0
276    """
277    template_name = "participacion.create.simple.html"
278    group_required = u"Participante"
279   
280    def get_context_data(self, **kwargs):
281        """!
282        Metodo que permite cargar de nuevo valores en los datos de contexto de la vista
283   
284        @author Rodrigo Boet (rboet at cenditel.gob.ve)
285        @copyright GNU/GPLv2
286        @date 23-02-2017
287        @param self <b>{object}</b> Objeto que instancia la clase
288        @param kwargs <b>{object}</b> Objeto que contiene los datos de contexto
289        @return Retorna los datos de contexto
290        """
291        valores = {}
292        for pregunta in Pregunta.objects.filter(consulta_id=kwargs['pk']).all():
293            label = '<label class="text-center">'+pregunta.texto_pregunta+'</label>'
294            campo = ''
295            if pregunta.tipo_pregunta.id == 1:
296                campo = ''
297                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
298                    campo += '<label for="'+kwargs['pk']+'">'+opcion.texto_opcion+'</label><input type="radio" name="consulta_respuesta_radio_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="'+str(opcion.id)+'" class="icheck">'
299            elif pregunta.tipo_pregunta.id == 2:
300                campo = ''
301                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
302                    campo += '<label for="'+kwargs['pk']+'">'+opcion.texto_opcion+'</label><input type="checkbox" name="consulta_respuesta_check_'+kwargs['pk']+'" id="'+kwargs['pk']+'"value="'+str(opcion.id)+'" class="icheck">'
303            elif pregunta.tipo_pregunta.id > 2 and pregunta.tipo_pregunta.id < 5:
304                if(pregunta.tipo_pregunta.id == 3):
305                    campo += '<label for="'+kwargs['pk']+'">Si</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="Si" class="icheck">'
306                    campo += '<label for="'+kwargs['pk']+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="No" class="icheck">'
307                else:
308                    campo += '<label for="'+kwargs['pk']+'">Si</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="Si" class="icheck need_justification">'
309                    campo += '<label for="'+kwargs['pk']+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="No" class="icheck">'
310                    campo += '<div id="div_justificar_'+kwargs['pk']+'" style="display:none;"><label>Indique con que instrumento legal en vigencia se relaciona su aporte</label>'
311                    campo += '<textarea class="form-control" id="respuesta_justificar_'+kwargs['pk']+'" name="consulta_respuesta_justificar_'+str(pregunta.id)+'">'
312                    campo += '</textarea></div>'
313            valores[pregunta.id] = {'label':label,'field':campo}
314            kwargs['preguntas'] = valores
315        return super(ParticipacionSimpleCreate, self).get_context_data(**kwargs)
316   
317    def post(self,request,pk,id_objetivo):
318        """!
319        Metodo que sobreescribe el post del formulario
320   
321        @author Rodrigo Boet (rboet at cenditel.gob.ve)
322        @copyright GNU/GPLv2
323        @date 20-03-2017
324        @param self <b>{object}</b> Objeto que instancia la clase
325        @param request <b>{object}</b> Objeto que instancia la petición
326        @param pk <b>{int}</b> Recibe el id de la consulta
327        @param id_ente <b>{int}</b> Recibe el id del ente
328        @return Retorna los datos de contexto
329        """
330        data = dict(request.POST)
331        del data['csrfmiddlewaretoken']
332        if self.request.is_ajax():
333            for key in data.keys():
334                parent_id = key.split("_")[-1]
335                if 'sino' in key:
336                    value = True if data[key][0] == 'Si' else False
337                    justify_id = 'consulta_respuesta_justificar_'+str(parent_id)
338                    self.crear_respuesta_sino(parent_id,value,id_objetivo,self.request.user.id)
339                    if(not value and justify_id in data.keys()):
340                        respuesta = data[justify_id][0]
341                        self.crear_respuesta_abierta(parent_id,respuesta,id_objetivo,self.request.user.id,True)
342                elif 'radio' in key or 'check' in key:
343                    for value in data[key]:
344                        self.crear_respuesta_opciones(value,id_objetivo,self.request.user.id)
345            return JsonResponse({"code":True})
346        return redirect(reverse_lazy('participacion_busqueda',kwargs={'pk':pk}))
347   
348    def crear_respuesta_sino(self,parent_id,value,id_objetivo,user_id):
349        """!
350        Metodo para crear una respuesta de si/no
351   
352        @author Rodrigo Boet (rboet at cenditel.gob.ve)
353        @copyright GNU/GPLv2
354        @date 27-03-2017
355        @param self <b>{object}</b> Objeto que instancia la clase
356        @param parent_id <b>{int}</b> Recibe el número del id del padre
357        @param value <b>{bool}</b> Recibe el valor de la respuesta
358        @param id_objetivo <b>{int}</b> Recibe el id del objetivo
359        @param user_id <b>{int}</b> Recibe el id del user
360        @return Retorna los datos de contexto
361        """
362        user = User.objects.get(id=user_id)
363        parent = Pregunta.objects.get(pk=parent_id)
364        respuesta = RespuestaSino()
365        respuesta.pregunta = parent
366        respuesta.respuesta = value
367        respuesta.user = user
368        respuesta.save()
369       
370    def crear_respuesta_opciones(self,parent_id,id_objetivo,user_id):
371        """!
372        Metodo para crear una respuesta de selección simple y múltiple
373   
374        @author Rodrigo Boet (rboet at cenditel.gob.ve)
375        @copyright GNU/GPLv2
376        @date 28-03-2017
377        @param self <b>{object}</b> Objeto que instancia la clase
378        @param parent_id <b>{int}</b> Recibe el número del id del padre
379        @param id_objetivo <b>{int}</b> Recibe el id del objetivo
380        @param user_id <b>{int}</b> Recibe el id del user
381        @return Retorna los datos de contexto
382        """
383        user = User.objects.get(id=user_id)
384        parent = Opcion.objects.get(pk=parent_id)
385        respuesta = RespuestaOpciones()
386        respuesta.opcion = parent
387        respuesta.user = user
388        respuesta.save()
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.