source: sapic/explicacion_situacional/views/genericEncuestasView.py @ 61114b7

Last change on this file since 61114b7 was 61114b7, checked in by ltroconis <ltroconis@…>, 6 años ago

Se insertó tabla para almacenar datos caracterización Social

  • Propiedad mode establecida a 100644
File size: 12.0 KB
Línea 
1# -*- coding: utf-8 -*-
2"""
3Sistema Automatizado de Planificación Integral Comunal SAPIC
4
5Copyleft (@) 2017 CENDITEL nodo Mérida - Copyleft (@) 2017 CENDITEL nodo Mérida - https://planificacion.cenditel.gob.ve/trac/wiki/WikiStart#a5.-SistemaAutomatizadodePlanificaciónIntegralComunalSAPIC
6"""
7## @package explicacion_situacional.views.genericEncuestasViews
8#
9# Vistas correspondientes a la explicacion situacional
10# @author Ing. Leonel Paolo Hernandez Macchiarulo (lhernandez 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
15
16from django.contrib import messages
17from django.contrib.auth.models import (
18    User
19)
20from django.shortcuts import render
21from django.views.generic.edit import (
22    FormView, UpdateView
23)
24from django.views.generic import (
25    TemplateView, ListView
26)
27from django.http import JsonResponse
28
29
30from explicacion_situacional.forms import (
31    ExplicacionForms, UbicacionForms
32    )
33from explicacion_situacional.modelsEncuestas.modelsConsultas import (
34    Pregunta, Consulta, Opcion
35    )
36from explicacion_situacional.modelsEncuestas.modelsParticipacion import (
37    RespuestaSino, RespuestaOpciones,
38    RespuestaAbierta, RespuestaUbicacion
39    )
40from explicacion_situacional.constantes import (
41    TIPOS_PREGUNTAS
42    )
43
44from utils.views import LoginRequeridoPerAuth
45
46
47
48class EncuestasParticiparView(LoginRequeridoPerAuth, TemplateView):
49    """!
50    Clase que gestiona la vista principal de la encuesta a la que va a participar
51
52    @author Ing. Leonel Paolo Hernandez Macchiarulo (lhernandez at cenditel.gob.ve)
53    @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a>
54    @date 20-09-2017
55    @version 1.0.0
56    """
57    template_name = "encuesta.participar.html"
58    #template_name = "caracterizacion.social.html"
59    group_required = [u"Administradores", u"Voceros", u"Integrantes"]
60
61    def get_context_data(self, **kwargs):
62        """!
63        Metodo que permite cargar de nuevo valores en los datos de contexto de la vista
64
65        @author Rodrigo Boet (rboet at cenditel.gob.ve)
66        @copyright GNU/GPLv2
67        @date 23-02-2017
68        @param self <b>{object}</b> Objeto que instancia la clase
69        @param kwargs <b>{object}</b> Objeto que contiene los datos de contexto
70        @return Retorna los datos de contexto
71        """
72        valores = {}
73        try:
74            consulta = Consulta.objects.select_related().get(pk=kwargs['pk'])
75        except:
76            consulta = ''
77
78        for pregunta in Pregunta.objects.filter(consulta_id=kwargs['pk']).all():
79            label = '<label>'+pregunta.texto_pregunta+'</label>'
80            campo = ''
81            if pregunta.tipo_pregunta.id == TIPOS_PREGUNTAS['SELECT_SIMPLE']:
82                campo = ''
83                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
84                    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">'
85            elif pregunta.tipo_pregunta.id == TIPOS_PREGUNTAS['SELECT_MULTIP']:
86                campo = ''
87                for opcion in Opcion.objects.filter(pregunta_id=pregunta.id).all():
88                    campo += '<label for="'+kwargs['pk']+'">'+opcion.texto_opcion+'</label><input type="checkbox" name="consulta_respuesta_check_'+str(pregunta.id)+'" id="'+kwargs['pk']+'"value="'+str(opcion.id)+'" class="icheck">'
89            elif pregunta.tipo_pregunta.id > TIPOS_PREGUNTAS['SELECT_MULTIP'] and pregunta.tipo_pregunta.id < TIPOS_PREGUNTAS['ABIERTA']:
90                campo += '<label for="'+str(pregunta.id)+'">Si</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+str(pregunta.id)+'"value="Si" class="icheck">'
91                if(pregunta.tipo_pregunta.id == TIPOS_PREGUNTAS['SI_NO']):
92                    campo += '<label for="'+str(pregunta.id)+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+str(pregunta.id)+'"value="No" class="icheck">'
93                else:
94                    campo += '<label for="'+str(pregunta.id)+'">No</label><input type="radio" name="consulta_respuesta_sino_'+str(pregunta.id)+'" id="'+str(pregunta.id)+'"value="No" class="icheck need_justification">'
95                    campo += '<div id="div_justificar_'+str(pregunta.id)+'" style="display:none;"><label>Justifique su Respuesta</label>'
96                    campo += '<textarea rows="20" cols="50" class="form-control" id="respuesta_justificar_'+str(pregunta.id)+'" name="consulta_respuesta_justificar_'+str(pregunta.id)+'">'
97                    campo += '</textarea></div>'
98            elif pregunta.tipo_pregunta.id == TIPOS_PREGUNTAS['UBICACION']:
99
100                    campo += '<tr><th><label for="id_ubicacion'+str(pregunta.id)+'">Ubicacion:</label></th><td><style type="text/css">\
101                                #id_ubicacion_map'+str(pregunta.id)+' { width: 600px; height: 400px; }\
102                                #id_ubicacion_map'+str(pregunta.id)+' .aligned label { float: inherit; }\
103                                #id_ubicacion_div_map'+str(pregunta.id)+' { position: relative; vertical-align: top; float: left; }\
104                                #id_ubicacion'+str(pregunta.id)+' { display: none; }\
105                                \
106                            </style>\
107                            \
108                            <div id="id_ubicacion_div_map'+str(pregunta.id)+'">\
109                                <div id="id_ubicacion_map'+str(pregunta.id)+'"></div>\
110                                <span class="clear_features"><a href="javascript:geodjango_ubicacion.clearFeatures()">Delete all Features</a></span>\
111                                \
112                                <textarea id="id_ubicacion'+str(pregunta.id)+'" class="vSerializedField required" cols="150" rows="10" name="consulta_respuesta_ubicacion_'+str(pregunta.id)+'"></textarea>\
113                                <script type="text/javascript">\
114                                    var map_options = {};\
115                                    \
116                            var base_layer = new ol.layer.Tile({source: new ol.source.OSM()});\
117                            \
118                                    var options = {\
119                                        base_layer: base_layer,\
120                                        geom_name: "Unknown",\
121                                        id: "id_ubicacion'+str(pregunta.id)+'",\
122                                        map_id: "id_ubicacion_map'+str(pregunta.id)+'",\
123                                        map_options: map_options,\
124                                        map_srid: 3857,\
125                                        name: "consulta_respuesta_ubicacion_'+str(pregunta.id)+'"\
126                                    };\
127                                    \
128                            options["default_lon"] = -66;\
129                            options["default_lat"] = 8;\
130                            options["default_zoom"] = 5.2;\
131                            \
132                                    var geodjango_ubicacion = new MapWidget(options);\
133                                </script>\
134                            </div></td></tr>'
135            else:
136                campo = '<textarea rows="10" cols="50" class="form-control" name="consulta_respuesta_abierta_'+str(pregunta.id)+'"></textarea>'
137            valores[pregunta.id] = {'label':label,'field':campo}
138            print (valores)
139            kwargs['preguntas'] = valores
140            kwargs['consulta'] = consulta
141        return super(EncuestasParticiparView, self).get_context_data(**kwargs)
142
143    def post(self, request, pk):
144        """!
145        Metodo que sobreescribe el post del formulario
146
147        @author Rodrigo Boet (rboet at cenditel.gob.ve)
148        @copyright GNU/GPLv2
149        @date 20-03-2017
150        @param self <b>{object}</b> Objeto que instancia la clase
151        @param request <b>{object}</b> Objeto que instancia la petición
152        @param pk <b>{int}</b> Recibe el id de la consulta
153        @return Retorna los datos de contexto
154        """
155        data = dict(request.POST)
156        del data['csrfmiddlewaretoken']
157        if self.request.is_ajax():
158            for key in data.keys():
159                parent_id = key.split("_")[-1]
160                if 'sino' in key:
161                    value = True if data[key][0] == 'Si' else False
162                    justify_id = 'consulta_respuesta_justificar_'+str(parent_id)
163                    self.crear_respuesta_sino(parent_id,value, self.request.user.id)
164                    if(not value and justify_id in data.keys()):
165                        respuesta = data[justify_id][0]
166                        self.crear_respuesta_abierta(parent_id, respuesta,self.request.user.id,True)
167                elif 'radio' in key or 'check' in key:
168                    for value in data[key]:
169                        self.crear_respuesta_opciones(value, self.request.user.id)
170                elif 'abierta' in key:
171                    value = data[key][0]
172                    self.crear_respuesta_abierta(parent_id, value, self.request.user.id)
173            return JsonResponse({"code":True})
174        return redirect(reverse_lazy('explicacions:condicion_suelos',kwargs={'pk':pk}))
175
176    def crear_respuesta_sino(self, parent_id, value, user_id):
177        """!
178        Metodo para crear una respuesta de si/no
179
180        @author Rodrigo Boet (rboet at cenditel.gob.ve)
181        @copyright GNU/GPLv2
182        @date 27-03-2017
183        @param self <b>{object}</b> Objeto que instancia la clase
184        @param parent_id <b>{int}</b> Recibe el número del id del padre
185        @param value <b>{bool}</b> Recibe el valor de la respuesta
186        @param user_id <b>{int}</b> Recibe el id del user
187        @return Retorna los datos de contexto
188        """
189        user = User.objects.get(id=user_id)
190        parent = Pregunta.objects.get(pk=parent_id)
191        respuesta = RespuestaSino()
192        respuesta.pregunta = parent
193        respuesta.respuesta = value
194        respuesta.user = user
195        respuesta.save()
196
197    def crear_respuesta_opciones(self, parent_id, user_id):
198        """!
199        Metodo para crear una respuesta de selección simple y múltiple
200
201        @author Rodrigo Boet (rboet at cenditel.gob.ve)
202        @copyright GNU/GPLv2
203        @date 28-03-2017
204        @param self <b>{object}</b> Objeto que instancia la clase
205        @param parent_id <b>{int}</b> Recibe el número del id del padre
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,
217                                user_id, es_justificacion=False):
218        """!
219        Metodo para crear una respuesta abierta
220
221        @author Rodrigo Boet (rboet at cenditel.gob.ve)
222        @copyright GNU/GPLv2
223        @date 28-03-2017
224        @param self <b>{object}</b> Objeto que instancia la clase
225        @param parent_id <b>{int}</b> Recibe el número del id del padre
226        @param value <b>{str}</b> Recibe el valor de la respuesta
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.texto_respuesta = value
236        respuesta.user = user
237        respuesta.es_justificacion = es_justificacion
238        respuesta.save()
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.